cardus 0.0.1

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 ADDED
@@ -0,0 +1,224 @@
1
+ import moment from "moment"
2
+ import { cookTempShipment } from "./insertTempShipment";
3
+ import { ModifiedOrderExtended, CrearBulto, Group, FindNextPickupDate, ExecutionManager, InsertParams, CountriesService, AddressesService, IntegrationsService, Type, SellerAddress, OriginalOrder, ModifiedOrder } from './types'
4
+
5
+ interface Services {
6
+ integrationsService: IntegrationsService
7
+ addressesService: AddressesService
8
+ countriesService: CountriesService
9
+ }
10
+
11
+ export class IntegrationManager {
12
+ services: Services
13
+ type: Type
14
+ executionManager: ExecutionManager
15
+ findNextPickupDate: FindNextPickupDate
16
+
17
+ constructor(params: {
18
+ integrationsService: IntegrationsService,
19
+ addressesService: AddressesService,
20
+ countriesService: CountriesService,
21
+ type: Type,
22
+ executionManager: ExecutionManager,
23
+ findNextPickupDate: FindNextPickupDate,
24
+ }) {
25
+ this.services = {
26
+ integrationsService: params.integrationsService,
27
+ addressesService: params.addressesService,
28
+ countriesService: params.countriesService,
29
+ };
30
+ this.type = params.type;
31
+ this.executionManager = params.executionManager;
32
+ this.findNextPickupDate = params.findNextPickupDate;
33
+ }
34
+
35
+ async insertTempShipments({
36
+ payload: { idUsuario, agencyId, addressId, warehouseId, group },
37
+ fetchAllOrders,
38
+ crearBulto,
39
+ modificarOrdenOriginal,
40
+ }: InsertParams) {
41
+ try {
42
+ const estaAgrupado = Number(group?.grouped) === 1;
43
+ const { integrationsService, addressesService } = this.services;
44
+ // esto hay que pasarlo ya en los parametros
45
+ const sellerAddress =
46
+ warehouseId > 0
47
+ ? await addressesService.getWarehouseAddress(idUsuario)
48
+ : await addressesService.getAddress(addressId, idUsuario);
49
+
50
+ const allShopifyOrders = await fetchAllOrders();
51
+
52
+ const filteredOrders = await integrationsService.filterExternalDuplicatedOrders({
53
+ idUsuario,
54
+ orders: allShopifyOrders,
55
+ type: this.type,
56
+ });
57
+
58
+ const insertOrdersResult = await new this.executionManager({
59
+ arrayParams: allShopifyOrders,
60
+ executable: async (order: OriginalOrder) => {
61
+ const parsedOrder = modificarOrdenOriginal({ originalOrder: order })
62
+ const duplicatedTempShipment = await integrationsService.checkDuplicateTempShipment(
63
+ parsedOrder.codigoEnvioExterno,
64
+ idUsuario,
65
+ );
66
+ if (duplicatedTempShipment) return;
67
+
68
+ return this.insertOrder({
69
+ order: parsedOrder,
70
+ agencyId,
71
+ warehouseId,
72
+ sellerAddress,
73
+ idUsuario,
74
+ group,
75
+ });
76
+ },
77
+ regularExecutionTime: 100, // ms
78
+ initialBatchQuantity: 1, // de uno en uno
79
+ }).upload();
80
+
81
+ const successfullShipments = insertOrdersResult
82
+ .filter(Boolean)
83
+ .filter((each) => each.status === "fulfilled")
84
+ .map((each) => each.value)
85
+
86
+ await this.insertQuantityRelatedLines({
87
+ orders: successfullShipments,
88
+ idUsuario,
89
+ crearBulto,
90
+ estaAgrupado,
91
+ });
92
+
93
+ return filteredOrders;
94
+ } catch (e) {
95
+ console.log(e)
96
+ }
97
+ }
98
+
99
+ insertOrder = async (
100
+ { order, agencyId, warehouseId, sellerAddress, idUsuario, group }:
101
+ { order: ModifiedOrder, agencyId: number, warehouseId: number, sellerAddress: SellerAddress, idUsuario: number, group: Group }): Promise<ModifiedOrderExtended> => {
102
+
103
+ const idEnvioTemporal = await this.insertTempShipment({
104
+ order,
105
+ agencyId,
106
+ warehouseId,
107
+ sellerAddress,
108
+ idUsuario,
109
+ });
110
+
111
+ if (!idEnvioTemporal) throw new Error('Temp shipments could not be created')
112
+
113
+ await this.insertExternalShipment({
114
+ idUsuario,
115
+ order,
116
+ idEnvioTemporal,
117
+ });
118
+
119
+ const grouped = Number(group?.grouped === 1);
120
+
121
+ if (grouped) await this.insertTempShipmentLines({ idEnvioTemporal, group });
122
+
123
+ return Object.assign(order, { idEnvioTemporal });
124
+ };
125
+
126
+ insertTempShipment = async ({ order, agencyId, warehouseId, sellerAddress, idUsuario }:
127
+ { order: ModifiedOrder, agencyId: number, warehouseId: number, sellerAddress: SellerAddress, idUsuario: number }
128
+ ) => {
129
+ const tempShipmentData = await cookTempShipment({
130
+ order,
131
+ type: this.type,
132
+ agencyId,
133
+ warehouseId,
134
+ sellerAddress,
135
+ idUsuario,
136
+ findNextPickupDate: this.findNextPickupDate,
137
+ countriesService: this.services.countriesService,
138
+ });
139
+ return await this.services.integrationsService.insertTempShipment(tempShipmentData);
140
+ };
141
+
142
+ insertExternalShipment = async ({ idUsuario, order, idEnvioTemporal }:
143
+ { idUsuario: number, order: ModifiedOrder, idEnvioTemporal: number }
144
+ ): Promise<number | false> => {
145
+ const idEnvioExterno = await this.services.integrationsService.insertExternalShipment({
146
+ id_envio_temporal_usuario: idEnvioTemporal,
147
+ codigo_envio_externo: order.codigoEnvioExterno,
148
+ id_usuario: idUsuario,
149
+ fecha_hora_creacion: moment().format("YYYY-MM-DD HH:mm:ss"),
150
+ servicio: this.type,
151
+ id_interno_shopify: order.idInternoShopify,
152
+ });
153
+
154
+ return idEnvioExterno;
155
+ };
156
+
157
+ insertTempShipmentLines = async ({ idEnvioTemporal, group }: {
158
+ idEnvioTemporal: number, group: Group
159
+ }) => {
160
+ const grouped = group.grouped === 1 || group.grouped === '1';
161
+ if (grouped)
162
+ await this.services.integrationsService.insertTempShipmentLines({
163
+ id_envio: idEnvioTemporal,
164
+ bulto: {
165
+ peso: group.weight,
166
+ alto: group.height,
167
+ ancho: group.width,
168
+ largo: group.length,
169
+ },
170
+ });
171
+ };
172
+
173
+ async insertQuantityRelatedLines({ orders, idUsuario, crearBulto, estaAgrupado }:
174
+ {
175
+ orders: ModifiedOrderExtended[], idUsuario: number, crearBulto: CrearBulto, estaAgrupado: boolean
176
+ }
177
+ ) {
178
+ const { integrationsService } = this.services;
179
+ const quantityRelatedFunctions: Array<Promise<undefined>> = [];
180
+
181
+ const obtenerBultosYCantidades = orders.map(async ({ idEnvioTemporal, lineas }) => {
182
+ if (!idEnvioTemporal) return null;
183
+ return await Promise.all(
184
+ lineas.map(async (line) => {
185
+ const { bulto, cantidad = 0 } = await crearBulto({
186
+ lineItems: { idEnvioTemporal, line },
187
+ idUsuario,
188
+ });
189
+
190
+ if (cantidad === 0) return null;
191
+
192
+ return { bulto, cantidad, idEnvioTemporal };
193
+ }),
194
+ );
195
+ });
196
+
197
+ const bultosYCantidades = await new Promise(async (res) => {
198
+ const bultosYCantidadesAnidados = await Promise.all(obtenerBultosYCantidades);
199
+ const bultosYCantidades = bultosYCantidadesAnidados.flat().filter(Boolean);
200
+ res(bultosYCantidades);
201
+ }) as Array<any>;
202
+
203
+ bultosYCantidades.forEach(({ bulto, cantidad, idEnvioTemporal }) => {
204
+ try {
205
+ const arrayFake = Array.from({ length: Number(cantidad) });
206
+ arrayFake.forEach(() => {
207
+ if (!estaAgrupado) {
208
+ quantityRelatedFunctions.push(
209
+ integrationsService.insertTempShipmentLines({ id_envio: idEnvioTemporal, bulto }),
210
+ );
211
+ }
212
+
213
+ quantityRelatedFunctions.push(
214
+ integrationsService.insertTempDetailsShipment({ id_envio: idEnvioTemporal, bulto }),
215
+ );
216
+ });
217
+ } catch (e) {
218
+ console.log(e);
219
+ }
220
+ });
221
+
222
+ await Promise.allSettled(quantityRelatedFunctions);
223
+ }
224
+ }
@@ -0,0 +1,154 @@
1
+ import moment from "moment";
2
+ import { Type, Shipment, ModifiedOrder, CountriesService, FindNextPickupDate, SellerAddress } from "types";
3
+
4
+ type ZonaLLegada = { nombre_pais: string, id_pais: number }
5
+
6
+ export const cookTempShipment = async ({
7
+ order,
8
+ type,
9
+ agencyId,
10
+ warehouseId,
11
+ sellerAddress,
12
+ idUsuario,
13
+ findNextPickupDate,
14
+ countriesService,
15
+ }: {
16
+ order: ModifiedOrder,
17
+ type: Type,
18
+ agencyId: number,
19
+ warehouseId: number,
20
+ sellerAddress: SellerAddress,
21
+ idUsuario: number,
22
+ findNextPickupDate: FindNextPickupDate,
23
+ countriesService: CountriesService,
24
+ }): Promise<Shipment> => {
25
+
26
+ let zonaLLegada = {}
27
+
28
+ if (order.codigoPaisLLegada) zonaLLegada = await countriesService.getCountryFromCountryCode(
29
+ order.codigoPaisLLegada,
30
+ );
31
+
32
+ const setDatosVendedor = () => ({
33
+ id_usuario: idUsuario,
34
+ id_agencia: agencyId,
35
+ nom_ape_salida: sellerAddress.nombre,
36
+ direccion_salida: sellerAddress.direccion,
37
+ cod_pos_salida: sellerAddress.codigo_postal,
38
+ poblacion_salida: sellerAddress.poblacion,
39
+ provincia_salida: sellerAddress.provincia,
40
+ id_zona_salida: sellerAddress.id_zona,
41
+ pais_salida: sellerAddress.nombre_pais,
42
+ tlf_salida: sellerAddress.telefono,
43
+ observaciones_salida: sellerAddress.observaciones,
44
+ contacto_salida: sellerAddress.nombre,
45
+ mail_salida: sellerAddress.mail,
46
+ });
47
+
48
+ const setUbicacionComprador = async (order: ModifiedOrder) => {
49
+ type CompradorLocation = {
50
+ pais_llegada: string | null,
51
+ provincia_llegada: string | null,
52
+ id_zona_llegada: string | null,
53
+ }
54
+
55
+ const compradorLocation: CompradorLocation = {
56
+ pais_llegada: null,
57
+ provincia_llegada: null,
58
+ id_zona_llegada: null,
59
+ };
60
+ if (order.codigoPaisLLegada) {
61
+ const _zonaLLegada = zonaLLegada as ZonaLLegada
62
+ compradorLocation.pais_llegada = _zonaLLegada?.nombre_pais || null;
63
+
64
+ if (_zonaLLegada?.id_pais && order.codigoPostalLLegada) {
65
+ const oTempShipmentProvincia = await countriesService.getProvinceByCountryIdAndPostalCode(
66
+ _zonaLLegada.id_pais,
67
+ order.codigoPostalLLegada,
68
+ );
69
+
70
+ compradorLocation.provincia_llegada = oTempShipmentProvincia?.nombre_provincia || null;
71
+
72
+ compradorLocation.id_zona_llegada = await countriesService.getZoneIdByCountryIdAndPostalCode(
73
+ _zonaLLegada.id_pais,
74
+ order.codigoPostalLLegada,
75
+ );
76
+ }
77
+ }
78
+ return compradorLocation;
79
+ };
80
+
81
+ const setDatosComprador = async (order: ModifiedOrder) => ({
82
+ nom_ape_llegada: order.primerApellidoLLegada
83
+ ? order.nombreLLegada + " " + order.primerApellidoLLegada
84
+ : order.nombreLLegada,
85
+ contacto_llegada: order.primerApellidoLLegada
86
+ ? order.nombreLLegada + " " + order.primerApellidoLLegada
87
+ : order.nombreLLegada,
88
+ direccion: order.direccionLLegada2
89
+ ? order.direccionLLegada1 + " " + order.direccionLLegada2
90
+ : order.direccionLLegada1,
91
+ cod_pos_llegada: order.codigoPostalLLegada,
92
+ poblacion_llegada: order.ciudadLLegada,
93
+ tlf_llegada: order.telefonoLLegada || "no informado",
94
+ mail_llegada: order.emailLLegada || "no informado",
95
+ });
96
+
97
+ const setReembolso = (order: ModifiedOrder) => {
98
+ return { cantidad_contrareembolso: order.cantidadContrareembolso };
99
+ };
100
+
101
+ const setFechas = async (order: ModifiedOrder) => {
102
+ const date = moment().format("YYYY-MM-DD");
103
+ const beginHour = "09:00";
104
+ const afterHour = "13:00";
105
+
106
+ if (order.codigoPaisLLegada) {
107
+ const _zonaLLegada = zonaLLegada as ZonaLLegada
108
+ const oDeliveryDate = await findNextPickupDate({
109
+ cp_salida: sellerAddress.codigo_postal,
110
+ id_pais_origen: sellerAddress.id_pais,
111
+ id_pais_destino: _zonaLLegada.id_pais,
112
+ idAgencia: agencyId
113
+ });
114
+
115
+ if (oDeliveryDate) {
116
+ const deliveryDateFramgents = oDeliveryDate.fecha_recogida_horas.split(",");
117
+ return {
118
+ fecha_recogida: deliveryDateFramgents[0],
119
+ hora_desde: deliveryDateFramgents[1],
120
+ hora_hasta: deliveryDateFramgents[2],
121
+ };
122
+ }
123
+ }
124
+
125
+ return {
126
+ fecha_recogida: date,
127
+ hora_desde: beginHour,
128
+ hora_hasta: afterHour,
129
+ };
130
+ };
131
+
132
+ const setBultos = (order: ModifiedOrder) => ({
133
+ num_bultos: warehouseId ? 0 : order.lineas.length,
134
+ tipo_envio: type,
135
+ codigo_envio_externo: order.codigoEnvioExterno,
136
+ id_almacen: warehouseId,
137
+ });
138
+
139
+ const setters = [setDatosVendedor, setDatosComprador, setUbicacionComprador, setReembolso, setFechas, setBultos];
140
+
141
+ const dataInsert = await setters.reduce(async (acc, curr) => {
142
+ const accumulated = await acc;
143
+ const stepResult = await curr({
144
+ ...order,
145
+ ...accumulated,
146
+ });
147
+ return {
148
+ ...accumulated,
149
+ ...stepResult,
150
+ };
151
+ }, {}) as Shipment;
152
+
153
+ return dataInsert;
154
+ };
package/package.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "cardus",
3
+ "version": "0.0.1",
4
+ "description": "an integration manager",
5
+ "main": "index.js",
6
+ "module": "dist/index.mjs",
7
+ "scripts": {
8
+ "build": "rm -rf dist && tsc --build",
9
+ "test": "npm run test"
10
+ },
11
+ "author": "sergio ibanez",
12
+ "license": "ISC",
13
+ "devDependencies": {
14
+ "@types/node": "^20.12.7",
15
+ "typescript": "^5.4.5"
16
+ },
17
+ "dependencies": {
18
+ "moment": "^2.30.1"
19
+ }
20
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,109 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
+
27
+ /* Modules */
28
+ "module": "commonjs", /* Specify what module code is generated. */
29
+ "rootDir": "./", /* Specify the root folder within your source files. */
30
+ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
+ "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
+ // "resolveJsonModule": true, /* Enable importing .json files. */
43
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45
+
46
+ /* JavaScript Support */
47
+ "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50
+
51
+ /* Emit */
52
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
59
+ // "removeComments": true, /* Disable emitting comments. */
60
+ // "noEmit": true, /* Disable emitting files from a compilation. */
61
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
69
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75
+
76
+ /* Interop Constraints */
77
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83
+
84
+ /* Type Checking */
85
+ "strict": true, /* Enable all strict type-checking options. */
86
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104
+
105
+ /* Completeness */
106
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
108
+ }
109
+ }
package/types/index.ts ADDED
@@ -0,0 +1,173 @@
1
+ export type AnyObject = Record<string, any> // Object with whichever properties
2
+
3
+ export type OriginalOrder = AnyObject
4
+
5
+ export type Shipment = {
6
+ id_usuario: number
7
+ id_agencia: number
8
+ nom_ape_salida: string
9
+ direccion_salida: string
10
+ cod_pos_salida: string
11
+ poblacion_salida: string
12
+ provincia_salida: string
13
+ id_zona_salida: string
14
+ pais_salida: string
15
+ tlf_salida: string
16
+ observaciones_salida: string
17
+ contacto_salida: string
18
+ mail_salida: string
19
+ pais_llegada: string | null
20
+ provincia_llegada: string | null
21
+ id_zona_llegada: string | null
22
+ nom_ape_llegada: string
23
+ contacto_llegada: string
24
+ direccion_llegada: string
25
+ cod_pos_llegada: string
26
+ poblacion_llegada: string
27
+ tlf_llegada: string
28
+ mail_llegada: string
29
+ cantidad_contrareembolso: number | null
30
+ fecha_recogida: string
31
+ hora_desde: string
32
+ hora_hasta: string
33
+ num_bultos: number,
34
+ tipo_envio: Type,
35
+ codigo_envio_externo: string,
36
+ id_almacen: number,
37
+ }
38
+
39
+ export type Bulto = {
40
+ id_envio: number,
41
+ bulto: {
42
+ peso: number,
43
+ alto: number,
44
+ ancho: number,
45
+ largo: number,
46
+ },
47
+ cantidad: number,
48
+ }
49
+
50
+ export type ModifiedOrder = {
51
+ lineas: Array<AnyObject>,
52
+ codigoPaisLLegada: string | undefined
53
+ codigoPostalLLegada: string | undefined
54
+ primerApellidoLLegada: string | undefined
55
+ nombreLLegada: string | undefined
56
+ direccionLLegada2: string | undefined
57
+ direccionLLegada1: string | undefined
58
+ ciudadLLegada: string | undefined
59
+ telefonoLLegada: string | undefined
60
+ emailLLegada: string | undefined
61
+ cantidadContrareembolso: number | null
62
+ codigoEnvioExterno: string
63
+ idInternoShopify?: string
64
+ precio: number | null
65
+ }
66
+
67
+ export interface ModifiedOrderExtended extends ModifiedOrder {
68
+ idEnvioTemporal: number
69
+ }
70
+
71
+ type FetchAllOrders = () => Promise<OriginalOrder[]>
72
+ export type CrearBulto = (params: { lineItems: { idEnvioTemporal: number, line: AnyObject }, idUsuario: number }) => Promise<Bulto>
73
+ type ModificarOrdenOriginal = (param: { originalOrder: OriginalOrder }) => ModifiedOrder
74
+
75
+ type GroupNotGrouped = {
76
+ grouped?: 0 | '0'
77
+ }
78
+
79
+ type GroupGrouped = {
80
+ grouped?: 1 | '1'
81
+ weight: number
82
+ height: number
83
+ width: number
84
+ length: number
85
+ }
86
+
87
+ export type Group = GroupNotGrouped | GroupGrouped
88
+
89
+ export interface InsertParams {
90
+ payload: {
91
+ idUsuario: number,
92
+ agencyId: number,
93
+ addressId: number,
94
+ warehouseId: number,
95
+ group: Group
96
+ },
97
+ fetchAllOrders: FetchAllOrders,
98
+ crearBulto: CrearBulto,
99
+ modificarOrdenOriginal: ModificarOrdenOriginal,
100
+ }
101
+
102
+ export type IntegrationsService = {
103
+ filterExternalDuplicatedOrders: (params: { idUsuario: number, orders: OriginalOrder[], type: Type }) => Promise<OriginalOrder[]>
104
+ checkDuplicateTempShipment: (codigoEnvioExterno: string, idUsuario: number) => Promise<boolean>
105
+ insertTempShipment: (params: Shipment) => number | false,
106
+ insertExternalShipment: (params: {
107
+ id_envio_temporal_usuario: number,
108
+ codigo_envio_externo: string,
109
+ id_usuario: number,
110
+ fecha_hora_creacion: string,
111
+ servicio: Type,
112
+ id_interno_shopify?: string,
113
+ }) => number | false
114
+ insertTempShipmentLines: (params: { id_envio: number, bulto: Bulto['bulto'] }) => Promise<undefined>
115
+ insertTempDetailsShipment: (params: { id_envio: number, bulto: Bulto['bulto'] }) => Promise<undefined>
116
+ }
117
+
118
+ export type SellerAddress = {
119
+ id_pais: number,
120
+ codigo_postal: string,
121
+ nombre: string,
122
+ direccion: string,
123
+ poblacion: string,
124
+ provincia: string,
125
+ id_zona: number,
126
+ nombre_pais: string,
127
+ telefono: string,
128
+ observaciones: string,
129
+ mail: string,
130
+ country_code_unico: string
131
+ }
132
+
133
+ export type AddressesService = {
134
+ getWarehouseAddress: (idUsuario: number) => Promise<SellerAddress>
135
+ getAddress: (addressId: number, idUsuario: number) => Promise<SellerAddress>
136
+ }
137
+
138
+ type Country = { nombre_pais: string, id_pais?: number }
139
+ type Provincia = { nombre_provincia?: string }
140
+ type Zone = string
141
+
142
+ export type CountriesService = {
143
+ getCountryFromCountryCode: (countryCode: string) => Promise<{ nombre_pais: string, id_pais?: number }>
144
+ getProvinceByCountryIdAndPostalCode: (id_pais: Country["id_pais"], zipCode: string) => Promise<Provincia>
145
+ getZoneIdByCountryIdAndPostalCode: (id_pais: Country["id_pais"], zipCode: string) => Promise<Zone>
146
+ }
147
+
148
+ export type FindNextPickupDate = (params: {
149
+ fecha?: string,
150
+ cp_salida: string,
151
+ id_pais_origen?: number,
152
+ id_pais_destino?: number,
153
+ idAgencia?: number | null,
154
+ }) => { fecha_recogida_horas: `${string},${string},${string}` }
155
+
156
+ export type Type = 'shopify' | 'amazon' | 'odoo'
157
+
158
+ type ExecutionManagerConstructorParams = {
159
+ arrayParams: Array<any>
160
+ executable: (params?: any) => any
161
+ regularExecutionTime: number,
162
+ initialBatchQuantity: number
163
+ }
164
+
165
+ type ExecutionManagerUploadReturn = {
166
+ status: "fulfilled" | "rejected"
167
+ value: any
168
+ }
169
+
170
+ export type ExecutionManager = {
171
+ upload(): ExecutionManagerUploadReturn[]
172
+ new(params: ExecutionManagerConstructorParams): ExecutionManager
173
+ }