220 lines
6.3 KiB
TypeScript
220 lines
6.3 KiB
TypeScript
import {
|
||
dummy,
|
||
getProductos,
|
||
getPrices,
|
||
getPricesByCustomer,
|
||
getStocks,
|
||
getCustomers,
|
||
order,
|
||
OrderDto,
|
||
TipoDeDocumento,
|
||
Customer,
|
||
Producto,
|
||
Precio,
|
||
getPublications,
|
||
getPriceLists,
|
||
} from "../index.js";
|
||
|
||
// TODO: hacerlo input
|
||
const HOST = "http://sutty.vm:4001";
|
||
|
||
const tokenInput = document.querySelector<HTMLInputElement>("#token-input")!;
|
||
|
||
if (localStorage.token) {
|
||
tokenInput.value = localStorage.token;
|
||
}
|
||
|
||
function token() {
|
||
return tokenInput.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", () => dummy(HOST, token()));
|
||
setupForm("#save-token", async () => {
|
||
localStorage.token = token();
|
||
});
|
||
setupForm("#productos", () => getProductos(HOST, token(), {}));
|
||
setupForm("#publicaciones", () => getPublications(HOST, token(), {}));
|
||
setupForm("#price", (event) =>
|
||
getPrices(HOST, token(), {
|
||
filter: (event.target! as any).filter.value,
|
||
})
|
||
);
|
||
setupForm("#stock", (event) =>
|
||
getStocks(HOST, token(), {
|
||
filter: (event.target! as any).filter.value,
|
||
warehouseCode: (event.target! as any).warehouseCode.value,
|
||
})
|
||
);
|
||
setupForm("#price-by-customer", (event) =>
|
||
getPricesByCustomer(HOST, token(), {
|
||
filter: (event.target! as any).filter.value,
|
||
})
|
||
);
|
||
setupForm("#price-list", (event) =>
|
||
getPriceLists(HOST, token(), {
|
||
filter: (event.target! as any).filter.value,
|
||
})
|
||
);
|
||
setupForm("#customers", () => getCustomers(HOST, token(), {}));
|
||
|
||
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, token(), {
|
||
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, token(), { filter: sku });
|
||
if (productosResponse.Data.length !== 1)
|
||
throw new Error("Encontré más de un producto.");
|
||
|
||
const preciosDelClienteResponse = await getPricesByCustomer(HOST, token(), {
|
||
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, token(), orderJson);
|
||
});
|