Compare commits

...

1 commit

Author SHA1 Message Date
fc20a8bec2 WIP: Order 2021-11-01 17:50:33 -03:00
4 changed files with 280 additions and 3 deletions

View file

@ -4,7 +4,14 @@ import {
getPrices, getPrices,
getPricesByCustomer, getPricesByCustomer,
getCustomers, getCustomers,
order,
OrderDto,
TipoDeDocumento,
Customer,
Producto,
Precio,
getPublications, getPublications,
Publication,
} from "../index.js"; } from "../index.js";
const tokenInput = document.querySelector<HTMLInputElement>("#token-input")!; const tokenInput = document.querySelector<HTMLInputElement>("#token-input")!;
@ -83,4 +90,113 @@ setupForm("#price", () => getPrices(token(), {}));
setupForm("#price-by-customer", (event) => setupForm("#price-by-customer", (event) =>
getPricesByCustomer(token(), { filter: (event.target! as any).filter.value }) getPricesByCustomer(token(), { filter: (event.target! as any).filter.value })
); );
setupForm("#customer", () => getCustomers(token(), {})); setupForm("#customers", () => getCustomers(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(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;
publicacion: Publication;
}[] = [];
function renderProductosEl() {
clear(productosEl);
for (const { producto, precio, publicacion } of productos) {
const itemEl = document.createElement("li");
itemEl.append(
`${producto.Description} (precio de cliente: $${precio.Price}, ProductCode: ${publicacion.ProductCode})`
);
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(token(), { filter: sku });
if (productosResponse.Data.length !== 1)
throw new Error("Encontré más de un producto.");
const preciosDelClienteResponse = await getPricesByCustomer(token(), {
SKUCode: sku,
customer: {
type: customer.DocumentType,
number: customer.DocumentNumber,
},
});
if (preciosDelClienteResponse.Data.length !== 1)
throw new Error("Encontré más de un producto.");
// TODO: puede haber varias publicaciones que serían varias variantes... ¿creo?
const publicacionesResponse = await getPublications(token(), {
skuCode: sku,
});
if (publicacionesResponse.Data.length !== 1)
throw new Error("Encontré más de un producto.");
productos.push({
producto: productosResponse.Data[0],
precio: preciosDelClienteResponse.Data[0],
publicacion: publicacionesResponse.Data[0],
});
renderProductosEl();
return productosResponse;
});
setupForm("#pedido", async (event) => {
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, publicacion }) => ({
Description: producto.Description,
UnitPrice: precio.Price,
Quantity: 1,
ProductCode: publicacion.ProductCode,
})),
Customer: {
CustomerID: 9999999999, // TODO: CustomerID
User: "Prueba", // TODO: User
IVACategoryCode: customer.IvaCategoryCode,
Email: customer.Email,
ProvinceCode: customer.ProvinceCode,
},
};
return await order(token(), orderJson);
});

View file

@ -5,6 +5,11 @@
form { form {
border: solid 2px black; border: solid 2px black;
padding: 0.2em; padding: 0.2em;
margin: 1em 0;
}
section {
border: solid 2px blue;
padding: 0.2em;
margin-bottom: 1em; margin-bottom: 1em;
} }
@ -54,9 +59,27 @@
<p class="status"></p> <p class="status"></p>
</form> </form>
<form id="customer"> <form id="customers">
<button>Conseguir clientes</button>
<p class="status"></p> <p class="status"></p>
<button>Conseguir clientes</button>
</form> </form>
<section>
<form id="pedido-customer">
<p class="status"></p>
<input type="text" name="cuit" placeholder="CUIT" />
<button>Setear cliente</button>
</form>
<form id="pedido-item">
<p class="status"></p>
<input type="text" name="sku" placeholder="SKU" />
<button>+</button>
<ul class="productos"></ul>
</form>
<form id="pedido">
<p class="status"></p>
<button>Hacer pedido</button>
</form>
</section>
<script type="module" src="../build/demo/demo.js"></script> <script type="module" src="../build/demo/demo.js"></script>

View file

@ -5,4 +5,5 @@ export * from "./product.js";
export * from "./price.js"; export * from "./price.js";
export * from "./priceByCustomer.js"; export * from "./priceByCustomer.js";
export * from "./customer.js"; export * from "./customer.js";
export * from "./order.js";
export * from "./publications.js"; export * from "./publications.js";

137
order.ts Normal file
View file

@ -0,0 +1,137 @@
import {
HOST,
Paginacion,
paginacionToSearchParams,
Paging,
} from "./common.js";
export interface OrderDto {
SituacionOrden?: null | string;
Date: string;
Total: number;
TotalDiscount?: number;
PaidTotal?: number;
FinancialSurcharge?: number;
WarehouseCode?: null | string;
SellerCode?: null | string;
TransportCode?: null | string;
SaleConditionCode?: number;
InvoiceCounterfoil?: number;
PriceListNumber?: number;
AgreedWithSeller?: boolean;
IvaIncluded?: boolean;
InternalTaxIncluded?: boolean;
OrderID: string;
OrderNumber: string;
ValidateTotalWithPaidTotal?: boolean;
Comment?: null | string;
Customer: CustomerDto;
CancelOrder?: boolean;
OrderItems: OrderItemDto[];
Shipping?: null | ShippingDto;
CashPayment?: null | CashPaymentDto;
CashPayments?: CashPaymentDto[] | null;
Payments?: PaymentDto[] | null;
}
export interface CustomerDto {
CustomerID: number;
Code?: null | string;
DocumentType?: null | string;
DocumentNumber?: null | string;
IVACategoryCode: string;
PayInternalTax?: boolean;
User: string;
Email: string;
FirstName?: null | string;
LastName?: null | string;
BusinessName?: null | string;
Street?: null | string;
HouseNumber?: null | string;
Floor?: null | string;
Apartment?: null | string;
City?: null | string;
ProvinceCode: string;
PostalCode?: null | string;
PhoneNumber1?: null | string;
PhoneNumber2?: null | string;
Bonus?: number;
MobilePhoneNumber?: null | string;
WebPage?: null | string;
BusinessAddress?: null | string;
Comments?: null | string;
NumberListPrice?: number;
Removed?: boolean;
DateUpdate?: string;
Disable?: string;
}
export interface OrderItemDto {
ProductCode: string;
SKUCode?: null | string;
VariantCode?: null | string;
Description: string;
VariantDescription?: null | string;
Quantity: number;
UnitPrice: number;
DiscountPercentage?: number;
}
export interface ShippingDto {
ShippingID: number;
ShippingCode?: null | string;
Street?: null | string;
HouseNumber?: null | string;
Floor?: null | string;
Apartment?: null | string;
City?: null | string;
ProvinceCode?: null | string;
PostalCode?: null | string;
PhoneNumber1?: null | string;
PhoneNumber2?: null | string;
ShippingCost?: number;
DeliversMonday?: null | string;
DeliversTuesday?: null | string;
DeliversWednesday?: null | string;
DeliversThursday?: null | string;
DeliversFriday?: null | string;
DeliversSaturday?: null | string;
DeliversSunday?: null | string;
DeliveryHours?: null | string;
}
export interface CashPaymentDto {
PaymentID?: number;
PaymentMethod: string;
PaymentTotal?: number;
}
export interface PaymentDto {
PaymentId: number;
TransactionDate: string;
AuthorizationCode?: null | string;
TransactionNumber?: null | string;
Installments: number;
InstallmentAmount: number;
Total: number;
CardCode: string;
CardPlanCode: string;
VoucherNo: number;
CardPromotionCode?: null | string;
}
export interface OrderResponse {}
export async function order(
token: string,
order: OrderDto
): Promise<OrderResponse> {
const res = await fetch(`${HOST}/api/Aperture/order`, {
method: "POST",
headers: {
accesstoken: token,
"content-type": "application/json",
},
});
const json = await res.json();
console.debug(json);
if (json.Message) {
throw new Error(`Tango: ${json.Message}`);
}
return json;
}