Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(tiny): Updating with https://github.com/ecomplus/app-tiny-erp #218

Merged
merged 11 commits into from
Oct 3, 2023
25 changes: 25 additions & 0 deletions packages/apps/tiny-erp/src/integration/export-order-to-tiny.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,37 @@ export default async (apiDoc, queueEntry, appData, canCreateNew) => {
logger.info(`${orderId} skipped with status "${tinyStatus}"`);
return null;
}

if (appData.ready_for_shipping_only) {
switch (tinyStatus) {
case 'aberto':
case 'cancelado':
case 'aprovado':
case 'preparando_envio':
case 'faturado':
if (!order.fulfillment_status || order.fulfillment_status.current !== 'ready_for_shipping') {
logger.info(`${orderId} skipped with status "${tinyStatus}"`);
return null;
}
break;
default:
break;
}
}

const tinyOrder = parseOrder(order, appData);
logger.info(`${orderId} ${JSON.stringify(tinyOrder)}`);
return postTiny('/pedido.incluir.php', {
pedido: {
pedido: tinyOrder,
},
}).then((response) => {
// https://github.com/ecomplus/app-tiny-erp/blob/d5eef0c6be83485805ec94ba801a8cf111d24ed6/functions/lib/integration/export-order.js#L91
const updateTrackingCode = global.$tinyErpUpdateTrackingCode;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Além do tempo verbal no nome das funções, na verdade isso aqui nem necessariamente é pra tracking code inclusive, talvez global.$tinyErpOnNewOrder ?

if (updateTrackingCode && typeof updateTrackingCode === 'function') {
return updateTrackingCode({ response, order, postTiny });
}
return response;
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default (d: Date) => {
/* eslint-disable prefer-template */
export default (date: Date) => {
const d = new Date(date.getTime() - (3 * 60 * 60 * 1000));
return d.getDate().toString().padStart(2, '0') + '/'
+ (d.getMonth() + 1).toString().padStart(2, '0') + '/'
+ d.getFullYear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,16 @@ export default async (apiDoc, queueEntry) => {
? { numeroEcommerce: tinyOrderNumber.substring(5) }
: { numero: tinyOrderNumber };
return postTiny('/pedidos.pesquisa.php', filter).then(({ pedidos }) => {
let prop = 'numero';
let tinyOrderNumberSearch = tinyOrderNumber;
if (filter && filter.numeroEcommerce) {
prop = 'numero_ecommerce';
tinyOrderNumberSearch = tinyOrderNumber.substring(5);
}
const tinyOrder = pedidos.find(({ pedido }) => {
return Number(tinyOrderNumber) === Number(pedido.numero);
return Number(tinyOrderNumberSearch) === Number(pedido[prop]);
});

if (tinyOrder) {
return getTinyOrder(tinyOrder.pedido.id);
}
Expand Down
22 changes: 17 additions & 5 deletions packages/apps/tiny-erp/src/integration/import-product-from-tiny.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,26 +60,34 @@ export default async (apiDoc, queueEntry, appData, canCreateNew, isHiddenQueue)
}
return null;
}

if (!product && tinyProduct && tipo === 'produto') {
return parseProduct(tinyProduct, tipo, true)
.then((bodyProduct) => {
return api.post('products', bodyProduct);
});
}

if (!tinyProduct) {
return null;
}

return postTiny('/produto.obter.php', { id: tinyProduct.id })
return postTiny('/produto.obter.php', { id: (tinyProduct.id || produtoSaldo.id) })
.then(({ produto }) => {
let method;
let endpoint;
let productId = product && product._id;
if (productId) {
method = 'PATCH';
endpoint = `products/${productId}`;
} else if (tipo === 'produto' || !tipo) {
} else if (tipo === 'produto' || appData.import_all_products) {
method = 'POST';
endpoint = 'products';
} else {
return null;
}
// @ts-ignore
return parseProduct(produto, method === 'POST').then((parsedProduct: Products) => {
return parseProduct(produto, tipo, method === 'POST').then((parsedProduct: Products) => {
if (!Number.isNaN(quantity)) {
parsedProduct.quantity = quantity >= 0 ? quantity : 0;
}
Expand Down Expand Up @@ -137,9 +145,13 @@ export default async (apiDoc, queueEntry, appData, canCreateNew, isHiddenQueue)
variationId,
}));
const { tinyStockUpdate } = queueEntry;
if (tinyStockUpdate && isHiddenQueue && queueProductId) {
return handleTinyStock(tinyStockUpdate as any);
if (tinyStockUpdate && isHiddenQueue && (queueProductId || (product && product._id))) {
return handleTinyStock(tinyStockUpdate as any, tinyStockUpdate.produto);
}
if (tinyStockUpdate.tipo === 'produto' && !queueProductId) {
return handleTinyStock({ produto: {}, tipo: 'produto' }, tinyStockUpdate.produto);
}

return postTiny('/produtos.pesquisa.php', { pesquisa: queueSku })
.then(({ produtos }) => {
if (Array.isArray(produtos)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,23 @@ export default (tinyOrder, shippingLines) => new Promise((resolve, reject) => {
postTiny('/nota.fiscal.obter.php', { id: tinyOrder.id_nota_fiscal })
.then((tinyInvoice) => {
const number = String(tinyInvoice.nota_fiscal.numero);
if (number && !shippingLine.invoices.find((invoice) => invoice.number === number)) {
const indexFromInvoice = shippingLine.invoices
.findIndex((invoice) => invoice.number === number);

if (number && !(indexFromInvoice > -1)) {
shippingLine.invoices.push({
number,
serial_number: String(tinyInvoice.nota_fiscal.serie),
access_key: String(tinyInvoice.nota_fiscal.chave_acesso),
});
} else if (number && (indexFromInvoice > -1)) {
Object.assign(
shippingLine.invoices[indexFromInvoice],
{
access_key: String(tinyInvoice.nota_fiscal.chave_acesso),
serial_number: String(tinyInvoice.nota_fiscal.serie),
},
);
}
partialOrder.shipping_lines = shippingLines;
resolve(partialOrder);
Expand Down
17 changes: 11 additions & 6 deletions packages/apps/tiny-erp/src/integration/parsers/order-to-tiny.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ export default (order: Orders, appData) => {
if (buyer.doc_number && buyer.doc_number.length <= 18) {
tinyCustomer.cpf_cnpj = buyer.doc_number;
}
if (buyer.inscription_number && buyer.inscription_number.length <= 18) {
if (
buyer.inscription_number && buyer.inscription_number.length <= 18
&& buyer.inscription_type !== 'Municipal'
) {
tinyCustomer.ie = buyer.inscription_number;
}
if (buyer.main_email && buyer.main_email.length <= 50) {
Expand All @@ -72,7 +75,7 @@ export default (order: Orders, appData) => {
};
}

if (shippingAddress && billingAddress) {
if (shippingAddress) {
tinyOrder.endereco_entrega = {};
parseAddress(shippingAddress, tinyOrder.endereco_entrega);
if (shippingAddress.name) {
Expand All @@ -83,7 +86,7 @@ export default (order: Orders, appData) => {
if (order.items) {
order.items.forEach((item) => {
if (item.quantity) {
const itemRef = (item.sku || item._id || Math.random().toString()).substring(0, 30);
const itemRef = (item.sku || item._id || Math.random().toString()).substring(0, 60);
tinyOrder.itens.push({
item: {
codigo: itemRef,
Expand Down Expand Up @@ -124,6 +127,11 @@ export default (order: Orders, appData) => {
}
}

const middlewareOrderParser = global.$tinyErpOrderParser;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Um middleware tá nomeado no imperativo (UpdateTrackingCode) e outro não, é bom tentar manter o padrões...

if (middlewareOrderParser && typeof middlewareOrderParser === 'function') {
middlewareOrderParser({ tinyOrder, order });
}

if (order.shipping_method_label) {
tinyOrder.forma_frete = order.shipping_method_label;
}
Expand Down Expand Up @@ -163,9 +171,6 @@ export default (order: Orders, appData) => {
if (amount.tax) {
tinyOrder.valor_frete += amount.tax;
}
if (amount.extra) {
tinyOrder.valor_frete += amount.extra;
}
}
if (amount.discount) {
tinyOrder.valor_desconto = amount.discount;
Expand Down
Loading
Loading