cardus 0.0.11 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -9,18 +9,23 @@ import {
9
9
  InsertParams,
10
10
  CountriesService,
11
11
  AddressesService,
12
+ ConfigurationsService,
13
+ UsersService,
12
14
  IntegrationsService,
13
15
  Type,
14
16
  SellerAddress,
15
17
  OriginalOrder,
16
18
  ModifiedOrder,
17
- ShipmentType
19
+ ShipmentType,
20
+ UserDefaultConfigurationContent
18
21
  } from './types';
19
22
 
20
23
  interface Services {
21
24
  integrationsService: IntegrationsService;
22
25
  addressesService: AddressesService;
23
26
  countriesService: CountriesService;
27
+ configurationsService: ConfigurationsService;
28
+ usersService: UsersService;
24
29
  }
25
30
 
26
31
  export class IntegrationManager {
@@ -34,6 +39,8 @@ export class IntegrationManager {
34
39
  integrationsService: IntegrationsService;
35
40
  addressesService: AddressesService;
36
41
  countriesService: CountriesService;
42
+ configurationService: ConfigurationsService;
43
+ userService: UsersService;
37
44
  type: Type;
38
45
  shipmentType: ShipmentType;
39
46
  executionManager: ExecutionManager;
@@ -42,7 +49,9 @@ export class IntegrationManager {
42
49
  this.services = {
43
50
  integrationsService: params.integrationsService,
44
51
  addressesService: params.addressesService,
45
- countriesService: params.countriesService
52
+ countriesService: params.countriesService,
53
+ configurationsService: params.configurationService,
54
+ usersService: params.userService
46
55
  };
47
56
  this.shipmentType = params.shipmentType;
48
57
  this.type = params.type;
@@ -111,9 +120,64 @@ export class IntegrationManager {
111
120
  estaAgrupado
112
121
  });
113
122
 
123
+ await this.insertUserDefaultConfigurationContent({
124
+ idUsuario,
125
+ tempShimpmentIds: successfullShipments.map(
126
+ (successfullShipment) => successfullShipment.idEnvioTemporal
127
+ )
128
+ });
129
+
114
130
  return filteredOrders;
115
131
  }
116
132
 
133
+ async insertUserDefaultConfigurationContent({
134
+ idUsuario,
135
+ tempShimpmentIds
136
+ }: {
137
+ idUsuario: number;
138
+ tempShimpmentIds: number[];
139
+ }) {
140
+ const { usersService, configurationsService, integrationsService } =
141
+ this.services;
142
+ const insert = async (
143
+ data: UserDefaultConfigurationContent[],
144
+ tempShimpmentId: number
145
+ ) => {
146
+ return Promise.allSettled(
147
+ data.map(async (tempContent) => {
148
+ await integrationsService.insertTempContent({
149
+ ...tempContent,
150
+ id_envio: tempShimpmentId
151
+ });
152
+ })
153
+ );
154
+ };
155
+ const insertOrdersResult = await new this.executionManager({
156
+ arrayParams: tempShimpmentIds,
157
+ executable: async (order: any) => {
158
+ const userSavedData =
159
+ (await configurationsService.getDefaultProformaConfiguration(
160
+ idUsuario
161
+ )) || [];
162
+
163
+ if (userSavedData.length > 0) {
164
+ await insert(userSavedData, order);
165
+ } else {
166
+ const user = await usersService.obtenerUsuarioId(idUsuario);
167
+ const userFakeData =
168
+ configurationsService.getFakeDefaultProformaConfiguration(
169
+ idUsuario,
170
+ user.dni
171
+ );
172
+
173
+ await insert(userFakeData, order);
174
+ }
175
+ },
176
+ regularExecutionTime: 100, // ms
177
+ initialBatchQuantity: 5 // de cinco en cinco
178
+ }).upload();
179
+ }
180
+
117
181
  insertOrder = async ({
118
182
  order,
119
183
  agencyId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cardus",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "description": "an integration manager",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
package/types/index.ts CHANGED
@@ -70,6 +70,10 @@ export type Bulto = {
70
70
  alto: number;
71
71
  ancho: number;
72
72
  largo: number;
73
+ sku_producto: string | null;
74
+ id_producto: number | null;
75
+ url_imagen: string | null;
76
+ nombre_producto: string | null;
73
77
  };
74
78
  cantidad: number;
75
79
  };
@@ -152,12 +156,15 @@ export type IntegrationsService = {
152
156
  }) => number | false;
153
157
  insertTempShipmentLines: (params: {
154
158
  id_envio: number;
155
- bulto: Bulto['bulto'];
159
+ bulto: Pick<Bulto['bulto'], 'peso' | 'alto' | 'ancho' | 'largo'>;
156
160
  }) => Promise<undefined>;
157
161
  insertTempDetailsShipment: (params: {
158
162
  id_envio: number;
159
163
  bulto: Bulto['bulto'];
160
164
  }) => Promise<undefined>;
165
+ insertTempContent: (
166
+ params: UserDefaultConfigurationContent & { id_envio: number }
167
+ ) => Promise<number | false>;
161
168
  };
162
169
 
163
170
  export type SellerAddress = {
@@ -198,6 +205,39 @@ export type CountriesService = {
198
205
  ) => Promise<Zone>;
199
206
  };
200
207
 
208
+ export type UserDefaultConfigurationContent = {
209
+ id_usuario: number;
210
+ contenido: string;
211
+ valor: number;
212
+ dni: string;
213
+ taric: string;
214
+ eori_importacion: string;
215
+ eori_exportacion: string;
216
+ peso_bruto: number;
217
+ peso_neto: number;
218
+ origen: number;
219
+ cantidad: number;
220
+ reason_export: '1' | '2' | '3' | '4' | '5';
221
+ };
222
+
223
+ type User = {
224
+ dni: string;
225
+ };
226
+
227
+ export type ConfigurationsService = {
228
+ getDefaultProformaConfiguration: (
229
+ id_usuario: number
230
+ ) => Promise<UserDefaultConfigurationContent[] | false>;
231
+ getFakeDefaultProformaConfiguration: (
232
+ id_usuario: number,
233
+ dni: string
234
+ ) => UserDefaultConfigurationContent[];
235
+ };
236
+
237
+ export type UsersService = {
238
+ obtenerUsuarioId: (id_usuario: number) => Promise<User>;
239
+ };
240
+
201
241
  export type FindNextPickupDate = (params: {
202
242
  fecha?: string;
203
243
  cp_salida: string;
package/dist/index.js DELETED
@@ -1,181 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.IntegrationManager = void 0;
16
- const moment_1 = __importDefault(require("moment"));
17
- const insertTempShipment_1 = require("./insertTempShipment");
18
- class IntegrationManager {
19
- constructor(params) {
20
- this.insertOrder = (_a) => __awaiter(this, [_a], void 0, function* ({ order, agencyId, warehouseId, sellerAddress, idUsuario, group }) {
21
- const idEnvioTemporal = yield this.insertTempShipment({
22
- order,
23
- agencyId,
24
- warehouseId,
25
- sellerAddress,
26
- idUsuario
27
- });
28
- if (!idEnvioTemporal)
29
- throw new Error('Temp shipments could not be created');
30
- yield this.insertExternalShipment({
31
- idUsuario,
32
- order,
33
- idEnvioTemporal
34
- });
35
- const grouped = Number((group === null || group === void 0 ? void 0 : group.grouped) === 1);
36
- if (grouped)
37
- yield this.insertTempShipmentLines({ idEnvioTemporal, group });
38
- return Object.assign(order, { idEnvioTemporal });
39
- });
40
- this.insertTempShipment = (_b) => __awaiter(this, [_b], void 0, function* ({ order, agencyId, warehouseId, sellerAddress, idUsuario }) {
41
- const tempShipmentData = yield (0, insertTempShipment_1.cookTempShipment)({
42
- order,
43
- shipmentType: this.shipmentType,
44
- agencyId,
45
- warehouseId,
46
- sellerAddress,
47
- idUsuario,
48
- findNextPickupDate: this.findNextPickupDate,
49
- countriesService: this.services.countriesService
50
- });
51
- return yield this.services.integrationsService.insertTempShipment(tempShipmentData);
52
- });
53
- this.insertExternalShipment = (_c) => __awaiter(this, [_c], void 0, function* ({ idUsuario, order, idEnvioTemporal }) {
54
- const idEnvioExterno = yield this.services.integrationsService.insertExternalShipment({
55
- id_envio_temporal_usuario: idEnvioTemporal,
56
- codigo_envio_externo: order.codigoEnvioExterno,
57
- id_usuario: idUsuario,
58
- fecha_hora_creacion: (0, moment_1.default)().format('YYYY-MM-DD HH:mm:ss'),
59
- servicio: this.type,
60
- id_interno_shopify: order.idInternoShopify
61
- });
62
- return idEnvioExterno;
63
- });
64
- this.insertTempShipmentLines = (_d) => __awaiter(this, [_d], void 0, function* ({ idEnvioTemporal, group }) {
65
- const grouped = group.grouped === 1 || group.grouped === '1';
66
- if (grouped)
67
- yield this.services.integrationsService.insertTempShipmentLines({
68
- id_envio: idEnvioTemporal,
69
- bulto: {
70
- peso: group.weight,
71
- alto: group.height,
72
- ancho: group.width,
73
- largo: group.length
74
- }
75
- });
76
- });
77
- this.services = {
78
- integrationsService: params.integrationsService,
79
- addressesService: params.addressesService,
80
- countriesService: params.countriesService
81
- };
82
- this.shipmentType = params.shipmentType;
83
- this.type = params.type;
84
- this.executionManager = params.executionManager;
85
- this.findNextPickupDate = params.findNextPickupDate;
86
- }
87
- insertTempShipments(_a) {
88
- return __awaiter(this, arguments, void 0, function* ({ payload: { idUsuario, agencyId, addressId, warehouseId, group }, fetchAllOrders, crearBulto, modificarOrdenOriginal }) {
89
- const estaAgrupado = Number(group === null || group === void 0 ? void 0 : group.grouped) === 1;
90
- const { integrationsService, addressesService } = this.services;
91
- // esto hay que pasarlo ya en los parametros
92
- const sellerAddress = warehouseId > 0
93
- ? yield addressesService.getWarehouseAddress(idUsuario)
94
- : yield addressesService.getAddress(addressId, idUsuario);
95
- const allOrders = yield fetchAllOrders();
96
- const filteredOrders = yield integrationsService.filterExternalDuplicatedOrders({
97
- idUsuario,
98
- orders: allOrders,
99
- type: this.type
100
- });
101
- const insertOrdersResult = yield new this.executionManager({
102
- arrayParams: allOrders,
103
- executable: (order) => __awaiter(this, void 0, void 0, function* () {
104
- const parsedOrder = yield modificarOrdenOriginal({ originalOrder: order });
105
- const duplicatedTempShipment = yield integrationsService.checkDuplicateTempShipment(parsedOrder.codigoEnvioExterno, idUsuario);
106
- if (duplicatedTempShipment)
107
- throw new Error('Envio Duplicado');
108
- return this.insertOrder({
109
- order: parsedOrder,
110
- agencyId,
111
- warehouseId,
112
- sellerAddress,
113
- idUsuario,
114
- group
115
- });
116
- }),
117
- regularExecutionTime: 100, // ms
118
- initialBatchQuantity: 5 // de cinco en cinco
119
- }).upload();
120
- const successfullShipments = insertOrdersResult
121
- .filter(Boolean)
122
- .filter((each) => each.status === 'fulfilled')
123
- .map((each) => each.value);
124
- yield this.insertQuantityRelatedLines({
125
- orders: successfullShipments,
126
- idUsuario,
127
- crearBulto,
128
- estaAgrupado
129
- });
130
- return filteredOrders;
131
- });
132
- }
133
- insertQuantityRelatedLines(_a) {
134
- return __awaiter(this, arguments, void 0, function* ({ orders, idUsuario, crearBulto, estaAgrupado }) {
135
- const { integrationsService } = this.services;
136
- const quantityRelatedFunctions = [];
137
- const obtenerBultosYCantidades = orders.map((_b) => __awaiter(this, [_b], void 0, function* ({ idEnvioTemporal, lineas }) {
138
- if (!idEnvioTemporal)
139
- return null;
140
- return yield Promise.all(lineas.map((line) => __awaiter(this, void 0, void 0, function* () {
141
- const { bulto, cantidad = 0 } = yield crearBulto({
142
- lineItems: { idEnvioTemporal, line },
143
- idUsuario
144
- });
145
- if (cantidad === 0)
146
- return null;
147
- return { bulto, cantidad, idEnvioTemporal };
148
- })));
149
- }));
150
- const bultosYCantidades = (yield new Promise((res) => __awaiter(this, void 0, void 0, function* () {
151
- const bultosYCantidadesAnidados = yield Promise.all(obtenerBultosYCantidades);
152
- const bultosYCantidades = bultosYCantidadesAnidados
153
- .flat()
154
- .filter(Boolean);
155
- res(bultosYCantidades);
156
- })));
157
- bultosYCantidades.forEach(({ bulto, cantidad, idEnvioTemporal }) => {
158
- try {
159
- const arrayFake = Array.from({ length: Number(cantidad) });
160
- arrayFake.forEach(() => {
161
- if (!estaAgrupado) {
162
- quantityRelatedFunctions.push(integrationsService.insertTempShipmentLines({
163
- id_envio: idEnvioTemporal,
164
- bulto
165
- }));
166
- }
167
- quantityRelatedFunctions.push(integrationsService.insertTempDetailsShipment({
168
- id_envio: idEnvioTemporal,
169
- bulto
170
- }));
171
- });
172
- }
173
- catch (e) {
174
- console.log(e);
175
- }
176
- });
177
- yield Promise.allSettled(quantityRelatedFunctions);
178
- });
179
- }
180
- }
181
- exports.IntegrationManager = IntegrationManager;
@@ -1,123 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.cookTempShipment = void 0;
16
- const moment_1 = __importDefault(require("moment"));
17
- const cookTempShipment = (_a) => __awaiter(void 0, [_a], void 0, function* ({ order, shipmentType, agencyId, warehouseId, sellerAddress, idUsuario, findNextPickupDate, countriesService }) {
18
- let zonaLLegada = {};
19
- if (order.codigoPaisLLegada)
20
- zonaLLegada = yield countriesService.getCountryFromCountryCode(order.codigoPaisLLegada);
21
- const setDatosVendedor = () => ({
22
- id_usuario: idUsuario,
23
- id_agencia: agencyId,
24
- nom_ape_salida: sellerAddress.nombre,
25
- direccion_salida: sellerAddress.direccion,
26
- cod_pos_salida: sellerAddress.codigo_postal,
27
- poblacion_salida: sellerAddress.poblacion,
28
- provincia_salida: sellerAddress.provincia,
29
- id_zona_salida: sellerAddress.id_zona,
30
- pais_salida: sellerAddress.nombre_pais,
31
- tlf_salida: sellerAddress.telefono,
32
- observaciones_salida: sellerAddress.observaciones,
33
- contacto_salida: sellerAddress.nombre,
34
- mail_salida: sellerAddress.mail
35
- });
36
- const setUbicacionComprador = (order) => __awaiter(void 0, void 0, void 0, function* () {
37
- const compradorLocation = {
38
- pais_llegada: null,
39
- provincia_llegada: null,
40
- id_zona_llegada: null
41
- };
42
- if (order.codigoPaisLLegada) {
43
- const _zonaLLegada = zonaLLegada;
44
- compradorLocation.pais_llegada = (_zonaLLegada === null || _zonaLLegada === void 0 ? void 0 : _zonaLLegada.nombre_pais) || null;
45
- if ((_zonaLLegada === null || _zonaLLegada === void 0 ? void 0 : _zonaLLegada.id_pais) && order.codigoPostalLLegada) {
46
- const oTempShipmentProvincia = yield countriesService.getProvinceByCountryIdAndPostalCode(_zonaLLegada.id_pais, order.codigoPostalLLegada);
47
- compradorLocation.provincia_llegada =
48
- (oTempShipmentProvincia === null || oTempShipmentProvincia === void 0 ? void 0 : oTempShipmentProvincia.nombre_provincia) || null;
49
- compradorLocation.id_zona_llegada =
50
- yield countriesService.getZoneIdByCountryIdAndPostalCode(_zonaLLegada.id_pais, order.codigoPostalLLegada);
51
- }
52
- }
53
- return compradorLocation;
54
- });
55
- const setDatosComprador = (order) => __awaiter(void 0, void 0, void 0, function* () {
56
- return ({
57
- nom_ape_llegada: order.primerApellidoLLegada
58
- ? order.nombreLLegada + ' ' + order.primerApellidoLLegada
59
- : order.nombreLLegada,
60
- contacto_llegada: order.primerApellidoLLegada
61
- ? order.nombreLLegada + ' ' + order.primerApellidoLLegada
62
- : order.nombreLLegada,
63
- direccion_llegada: order.direccionLLegada2
64
- ? order.direccionLLegada1 + ' ' + order.direccionLLegada2
65
- : order.direccionLLegada1,
66
- cod_pos_llegada: order.codigoPostalLLegada,
67
- poblacion_llegada: order.ciudadLLegada,
68
- tlf_llegada: order.telefonoLLegada || 'no informado',
69
- mail_llegada: order.emailLLegada || 'no informado'
70
- });
71
- });
72
- const setReembolso = (order) => {
73
- return { cantidad_contrareembolso: order.cantidadContrareembolso };
74
- };
75
- const setFechas = (order) => __awaiter(void 0, void 0, void 0, function* () {
76
- const date = (0, moment_1.default)().format('YYYY-MM-DD');
77
- const beginHour = '09:00';
78
- const afterHour = '13:00';
79
- if (order.codigoPaisLLegada) {
80
- const _zonaLLegada = zonaLLegada;
81
- const oDeliveryDate = yield findNextPickupDate({
82
- cp_salida: sellerAddress.codigo_postal,
83
- id_pais_origen: sellerAddress.id_pais,
84
- id_pais_destino: _zonaLLegada.id_pais,
85
- idAgencia: agencyId
86
- });
87
- if (oDeliveryDate) {
88
- const deliveryDateFramgents = oDeliveryDate.fecha_recogida_horas.split(',');
89
- return {
90
- fecha_recogida: deliveryDateFramgents[0],
91
- hora_desde: deliveryDateFramgents[1],
92
- hora_hasta: deliveryDateFramgents[2]
93
- };
94
- }
95
- }
96
- return {
97
- fecha_recogida: date,
98
- hora_desde: beginHour,
99
- hora_hasta: afterHour
100
- };
101
- });
102
- const setBultos = (order) => ({
103
- num_bultos: warehouseId ? 0 : order.lineas.length,
104
- tipo_envio: shipmentType,
105
- codigo_envio_externo: order.codigoEnvioExterno,
106
- id_almacen: warehouseId
107
- });
108
- const setters = [
109
- setDatosVendedor,
110
- setDatosComprador,
111
- setUbicacionComprador,
112
- setReembolso,
113
- setFechas,
114
- setBultos
115
- ];
116
- const dataInsert = (yield setters.reduce((acc, curr) => __awaiter(void 0, void 0, void 0, function* () {
117
- const accumulated = yield acc;
118
- const stepResult = yield curr(Object.assign(Object.assign({}, order), accumulated));
119
- return Object.assign(Object.assign({}, accumulated), stepResult);
120
- }), {}));
121
- return dataInsert;
122
- });
123
- exports.cookTempShipment = cookTempShipment;
@@ -1,26 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const shipmentTypes = {
4
- NORMAL: 1,
5
- EXCEL: 7,
6
- RECTIFICATIVO: 8,
7
- PRESTASHOP_MODULE: 15,
8
- API: 16,
9
- EBAY: 17,
10
- ABONO: 18,
11
- WOOCOMMERCE: 19,
12
- ALIEXPRESS: 22,
13
- SHOPIFY: 23,
14
- ECWID: 31,
15
- CARGOS: 40,
16
- DAILY_PICKUP: 50,
17
- FLASH_SHIPMENT: 51,
18
- WITHDRAWALL: 52,
19
- SHIPMENT_SCHEME: 53,
20
- PRESTASHOP: 115,
21
- AMAZON: 118,
22
- JOOM: 119,
23
- HOLDED: 120,
24
- ETSY: 121,
25
- NORMAL_V2: 122
26
- };