hyperpop.js/demo/demo.ts

215 lines
6.1 KiB
TypeScript
Raw Permalink Normal View History

import {
dummy,
getProductos,
getPrices,
getPricesByCustomer,
getCustomers,
2021-11-15 21:48:48 +00:00
order,
OrderDto,
TipoDeDocumento,
Customer,
Producto,
Precio,
2021-11-01 20:48:42 +00:00
getPublications,
2021-11-18 15:07:35 +00:00
getPriceLists,
} from "../index.js";
2021-11-15 21:57:36 +00:00
// 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) {
2021-10-12 22:38:51 +00:00
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);
2021-10-12 22:38:51 +00:00
detailsEl.append(preEl);
return detailsEl;
}
async function showResponse(statusEl: Element | null, promise: Promise<any>) {
try {
const response = await promise;
if (statusEl) {
2021-11-18 15:08:27 +00:00
clear(statusEl);
statusEl.append("¡Funcionó!");
if (response) {
statusEl.append(" Respuesta:", objectToDom(response));
}
} else alert(`¡Funcionó!${response ? ` Respuesta: ${response}` : ""}`);
} catch (error) {
2021-11-18 15:08:27 +00:00
if (statusEl) {
clear(statusEl);
statusEl.append("Hubo un error :(", objectToDom(error));
} else {
alert(`Hubo un error: ${error}`);
}
}
}
2021-10-12 22:57:24 +00:00
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();
2021-10-12 22:57:24 +00:00
showResponse(statusEl, listener(event));
});
}
2021-11-15 21:57:36 +00:00
setupForm("#token", () => dummy(HOST, token()));
setupForm("#save-token", async () => {
localStorage.token = token();
});
2021-11-15 21:57:36 +00:00
setupForm("#productos", () => getProductos(HOST, token(), {}));
setupForm("#publicaciones", () => getPublications(HOST, token(), {}));
setupForm("#price", (event) =>
getPrices(HOST, token(), {
filter: (event.target! as any).filter.value,
})
);
2021-10-12 22:57:24 +00:00
setupForm("#price-by-customer", (event) =>
2021-11-15 21:57:36 +00:00
getPricesByCustomer(HOST, token(), {
filter: (event.target! as any).filter.value,
})
2021-10-12 22:57:24 +00:00
);
2021-11-18 15:07:35 +00:00
setupForm("#price-list", (event) =>
getPriceLists(HOST, token(), {
filter: (event.target! as any).filter.value,
})
);
2021-11-15 21:57:36 +00:00
setupForm("#customers", () => getCustomers(HOST, token(), {}));
2021-11-15 21:48:48 +00:00
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.");
2021-11-15 21:57:36 +00:00
const customers = await getCustomers(HOST, token(), {
2021-11-15 21:48:48 +00:00
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.");
2021-11-15 21:57:36 +00:00
const productosResponse = await getProductos(HOST, token(), { filter: sku });
2021-11-15 21:48:48 +00:00
if (productosResponse.Data.length !== 1)
throw new Error("Encontré más de un producto.");
2021-11-15 21:57:36 +00:00
const preciosDelClienteResponse = await getPricesByCustomer(HOST, token(), {
2021-11-15 21:48:48 +00:00
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;
});
2021-11-15 21:58:56 +00:00
setupForm("#pedido", async () => {
2021-11-15 21:48:48 +00:00
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,
SKUCode: producto.SKUCode,
2021-11-15 21:48:48 +00:00
})),
Customer: {
CustomerID: 1,
User: customer.BusinessName,
2021-11-15 21:48:48 +00:00
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,
},
};
2021-11-15 21:57:36 +00:00
return await order(HOST, token(), orderJson);
2021-11-15 21:48:48 +00:00
});