238 lines
6.7 KiB
TypeScript
238 lines
6.7 KiB
TypeScript
import {
|
||
dummy,
|
||
getProductos,
|
||
getPrices,
|
||
getPricesByCustomer,
|
||
getStocks,
|
||
getCustomers,
|
||
order,
|
||
OrderDto,
|
||
TipoDeDocumento,
|
||
Customer,
|
||
Producto,
|
||
Precio,
|
||
getPublications,
|
||
getPriceLists,
|
||
} from "../index.js";
|
||
|
||
const hostInput = document.querySelector<HTMLInputElement>("#host")!;
|
||
const userInput = document.querySelector<HTMLInputElement>("#user")!;
|
||
const passInput = document.querySelector<HTMLInputElement>("#pass")!;
|
||
|
||
const tokenInput = document.querySelector<HTMLInputElement>("#token-input")!;
|
||
|
||
function headers() {
|
||
const h = new Headers();
|
||
|
||
h.set("content-type", "application/json");
|
||
|
||
if (tokenInput.value) {
|
||
h.set("accesstoken", tokenInput.value);
|
||
} else {
|
||
const basic = btoa(`${userInput.value}:${passInput.value}`);
|
||
h.set("authorization", `Basic ${basic}`);
|
||
}
|
||
|
||
return h;
|
||
}
|
||
|
||
function host() {
|
||
return hostInput.value;
|
||
}
|
||
|
||
function clear(el: Node) {
|
||
while (el.firstChild) {
|
||
el.firstChild.remove();
|
||
}
|
||
}
|
||
|
||
function objectToDom(object: any) {
|
||
const detailsEl = document.createElement("details");
|
||
const summaryEl = document.createElement("summary");
|
||
summaryEl.append("JSON");
|
||
detailsEl.open = true;
|
||
detailsEl.append(summaryEl);
|
||
const preEl = document.createElement("pre");
|
||
const codeEl = document.createElement("code");
|
||
if (typeof object === "string") {
|
||
codeEl.append(JSON.stringify(JSON.parse(object), null, 2));
|
||
} else if (Object.keys(object).length > 0) {
|
||
codeEl.append(JSON.stringify(object, null, 2));
|
||
} else {
|
||
codeEl.append(object);
|
||
}
|
||
preEl.append(codeEl);
|
||
detailsEl.append(preEl);
|
||
return detailsEl;
|
||
}
|
||
|
||
async function showResponse(statusEl: Element | null, promise: Promise<any>) {
|
||
try {
|
||
const response = await promise;
|
||
if (statusEl) {
|
||
clear(statusEl);
|
||
statusEl.append("¡Funcionó!");
|
||
if (response) {
|
||
statusEl.append(" Respuesta:", objectToDom(response));
|
||
}
|
||
} else alert(`¡Funcionó!${response ? ` Respuesta: ${response}` : ""}`);
|
||
} catch (error) {
|
||
if (statusEl) {
|
||
clear(statusEl);
|
||
statusEl.append("Hubo un error :(", objectToDom(error));
|
||
} else {
|
||
alert(`Hubo un error: ${error}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
function setupForm(selector: string, listener: (event: Event) => Promise<any>) {
|
||
const formEl = document.querySelector<HTMLFormElement>(selector);
|
||
if (!formEl) throw new Error(`No existe el formulario ${selector}`);
|
||
const statusEl = formEl.querySelector<HTMLElement>(".status");
|
||
if (!statusEl)
|
||
console.error(
|
||
`El formulario ${selector} no tiene un .status, voy a reportar los errores con alert()`
|
||
);
|
||
formEl.addEventListener("submit", async (event) => {
|
||
event.preventDefault();
|
||
showResponse(statusEl, listener(event));
|
||
});
|
||
}
|
||
|
||
setupForm("#token", () => {
|
||
console.log(headers());
|
||
return dummy(host(), headers());
|
||
});
|
||
setupForm("#productos", () => getProductos(host(), headers(), {}));
|
||
setupForm("#publicaciones", () => getPublications(host(), headers(), {}));
|
||
setupForm("#price", (event) =>
|
||
getPrices(host(), headers(), {
|
||
filter: (event.target! as any).filter.value,
|
||
})
|
||
);
|
||
setupForm("#stock", (event) =>
|
||
getStocks(host(), headers(), {
|
||
filter: (event.target! as any).filter.value,
|
||
warehouseCode: (event.target! as any).warehouseCode.value,
|
||
})
|
||
);
|
||
setupForm("#price-by-customer", (event) =>
|
||
getPricesByCustomer(host(), headers(), {
|
||
filter: (event.target! as any).filter.value,
|
||
})
|
||
);
|
||
setupForm("#price-list", (event) =>
|
||
getPriceLists(host(), headers(), {
|
||
filter: (event.target! as any).filter.value,
|
||
})
|
||
);
|
||
setupForm("#customers", () => getCustomers(host(), headers(), {}));
|
||
|
||
let customer: Customer | null = null;
|
||
|
||
setupForm("#pedido-customer", async (event) => {
|
||
const cuit = (event.target! as any).cuit.value;
|
||
if (cuit.length === 0) throw new Error("No pusiste un CUIT.");
|
||
|
||
const customers = await getCustomers(host(), headers(), {
|
||
customer: {
|
||
type: TipoDeDocumento.CUIT,
|
||
number: cuit,
|
||
},
|
||
});
|
||
if (customers.Data.length !== 1)
|
||
throw new Error("Encontré más de unx cliente.");
|
||
customer = customers.Data[0];
|
||
|
||
return customers;
|
||
});
|
||
|
||
const productosEl = document.querySelector<HTMLUListElement>(
|
||
"#pedido-item > .productos"
|
||
)!;
|
||
let productos: {
|
||
producto: Producto;
|
||
precio: Precio;
|
||
}[] = [];
|
||
function renderProductosEl() {
|
||
clear(productosEl);
|
||
|
||
for (const { producto, precio } of productos) {
|
||
const itemEl = document.createElement("li");
|
||
itemEl.append(
|
||
`${producto.Description} (precio de cliente: $${precio.Price}, SKUCode: ${producto.SKUCode})`
|
||
);
|
||
productosEl.append(itemEl);
|
||
}
|
||
}
|
||
|
||
setupForm("#pedido-item", async (event) => {
|
||
if (!customer) throw new Error("No seteaste lx cliente todavía.");
|
||
const sku = (event.target! as any).sku.value;
|
||
if (sku.length === 0) throw new Error("No pusiste un SKU.");
|
||
|
||
const productosResponse = await getProductos(host(), headers(), {
|
||
filter: sku,
|
||
});
|
||
if (productosResponse.Data.length !== 1)
|
||
throw new Error("Encontré más de un producto.");
|
||
|
||
const preciosDelClienteResponse = await getPricesByCustomer(
|
||
host(),
|
||
headers(),
|
||
{
|
||
SKUCode: sku,
|
||
customer: {
|
||
type: customer.DocumentType,
|
||
number: customer.DocumentNumber,
|
||
},
|
||
}
|
||
);
|
||
if (preciosDelClienteResponse.Data.length !== 1)
|
||
throw new Error("Encontré más de un producto.");
|
||
|
||
productos.push({
|
||
producto: productosResponse.Data[0],
|
||
precio: preciosDelClienteResponse.Data[0],
|
||
});
|
||
renderProductosEl();
|
||
|
||
return productosResponse;
|
||
});
|
||
|
||
setupForm("#pedido", async () => {
|
||
if (!customer) throw new Error("No seteaste lx cliente todavía.");
|
||
|
||
// Se supone que Total es:
|
||
// >=0 ∑[(OrderItems.Quantity x OrderItems.UnitPrice) – OrderItems.DiscountPorcentage)] + Shipping.ShippingCost + Principal.FinancialSurcharge – Principal.TotalDiscount
|
||
// Pero no tenemos la mayoría de las variables.
|
||
const total = productos.reduce((total, curr) => total + curr.precio.Price, 0);
|
||
|
||
// Se supone que es único ¡pero lo tenemos que generar nosotrxs! wtf
|
||
const id = Math.floor(Math.random() * 100000).toString();
|
||
|
||
const orderJson: OrderDto = {
|
||
Date: new Date().toISOString(),
|
||
Total: total,
|
||
OrderID: id,
|
||
OrderNumber: id,
|
||
OrderItems: productos.map(({ producto, precio }) => ({
|
||
Description: producto.Description,
|
||
UnitPrice: precio.Price,
|
||
Quantity: 1,
|
||
ProductCode: producto.SKUCode,
|
||
})),
|
||
Customer: {
|
||
CustomerID: 1,
|
||
User: customer.BusinessName,
|
||
IVACategoryCode: customer.IvaCategoryCode,
|
||
Email: "api@axoft.com", // En prod: customer.Email, tenemos que usar esto porque el usuario de prueba no tiene Email
|
||
ProvinceCode: customer.ProvinceCode,
|
||
DocumentNumber: customer.DocumentNumber,
|
||
DocumentType: customer.DocumentType,
|
||
},
|
||
};
|
||
|
||
return await order(host(), headers(), orderJson);
|
||
});
|