hyperpop.js/demo/demo.ts

239 lines
6.7 KiB
TypeScript
Raw Permalink Normal View History

import {
dummy,
getProductos,
getPrices,
getPricesByCustomer,
2022-06-16 21:59:47 +00:00
getStocks,
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";
2022-11-01 17:23:48 +00:00
const hostInput = document.querySelector<HTMLInputElement>("#host")!;
const userInput = document.querySelector<HTMLInputElement>("#user")!;
const passInput = document.querySelector<HTMLInputElement>("#pass")!;
2021-11-15 21:57:36 +00:00
const tokenInput = document.querySelector<HTMLInputElement>("#token-input")!;
2022-11-01 17:23:48 +00:00
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;
}
2022-11-01 17:23:48 +00:00
function host() {
return hostInput.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));
});
}
2022-11-01 17:23:48 +00:00
setupForm("#token", () => {
console.log(headers());
return dummy(host(), headers());
});
2022-11-01 17:23:48 +00:00
setupForm("#productos", () => getProductos(host(), headers(), {}));
setupForm("#publicaciones", () => getPublications(host(), headers(), {}));
setupForm("#price", (event) =>
2022-11-01 17:23:48 +00:00
getPrices(host(), headers(), {
filter: (event.target! as any).filter.value,
})
);
2022-06-16 21:59:47 +00:00
setupForm("#stock", (event) =>
2022-11-01 17:23:48 +00:00
getStocks(host(), headers(), {
2022-06-16 21:59:47 +00:00
filter: (event.target! as any).filter.value,
warehouseCode: (event.target! as any).warehouseCode.value,
})
);
2021-10-12 22:57:24 +00:00
setupForm("#price-by-customer", (event) =>
2022-11-01 17:23:48 +00:00
getPricesByCustomer(host(), headers(), {
2021-11-15 21:57:36 +00:00
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) =>
2022-11-01 17:23:48 +00:00
getPriceLists(host(), headers(), {
2021-11-18 15:07:35 +00:00
filter: (event.target! as any).filter.value,
})
);
2022-11-01 17:23:48 +00:00
setupForm("#customers", () => getCustomers(host(), headers(), {}));
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.");
2022-11-01 17:23:48 +00:00
const customers = await getCustomers(host(), headers(), {
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.");
2022-11-01 17:23:48 +00:00
const productosResponse = await getProductos(host(), headers(), {
filter: sku,
});
2021-11-15 21:48:48 +00:00
if (productosResponse.Data.length !== 1)
throw new Error("Encontré más de un producto.");
2022-11-01 17:23:48 +00:00
const preciosDelClienteResponse = await getPricesByCustomer(
host(),
headers(),
{
SKUCode: sku,
customer: {
type: customer.DocumentType,
number: customer.DocumentNumber,
},
}
);
2021-11-15 21:48:48 +00:00
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,
})),
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,
},
};
2022-11-01 17:23:48 +00:00
return await order(host(), headers(), orderJson);
2021-11-15 21:48:48 +00:00
});