@asumano/worklip-typeorm-db 1.1.72 → 1.1.74

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.
@@ -0,0 +1,100 @@
1
+ export type TEntityType = "natural" | "juridica";
2
+ export interface ICountryDocumentType {
3
+ code: string;
4
+ label: string;
5
+ regex?: string;
6
+ }
7
+ export interface ICountryLegalOption {
8
+ value: string;
9
+ label: string;
10
+ no_tax?: boolean;
11
+ }
12
+ export interface ICountryLegalField {
13
+ key: string;
14
+ label: string;
15
+ type: "text" | "select" | "multiselect" | "boolean";
16
+ options?: ICountryLegalOption[];
17
+ required_for?: TEntityType[];
18
+ help?: string;
19
+ }
20
+ export interface ICountryLegalProfile {
21
+ tax_id_label: string;
22
+ uses_dv: boolean;
23
+ document_types: Record<TEntityType, ICountryDocumentType[]>;
24
+ company_kinds?: string[];
25
+ registry_required_for?: TEntityType[];
26
+ postal_code_required?: boolean;
27
+ fields: ICountryLegalField[];
28
+ }
29
+ export interface ICompanyLegalAddress {
30
+ line1: string;
31
+ city: number | null;
32
+ region: number | null;
33
+ postal_code?: string | null;
34
+ }
35
+ export interface ICompanyLegalRegistry {
36
+ number: string;
37
+ chamber?: string | null;
38
+ incorporated_at?: string | null;
39
+ company_kind?: string | null;
40
+ }
41
+ export interface ICompanyLegalRepresentative {
42
+ same_as_owner: boolean;
43
+ document_type: string;
44
+ document: string;
45
+ name: string;
46
+ surname: string;
47
+ position?: string | null;
48
+ email: string;
49
+ phone?: string | null;
50
+ }
51
+ export type TLegalVerificationStatus = "pending" | "verified" | "rejected";
52
+ export interface ICompanyLegalVerification {
53
+ status: Exclude<TLegalVerificationStatus, "pending">;
54
+ at: string;
55
+ by: number | null;
56
+ by_name: string | null;
57
+ note?: string | null;
58
+ }
59
+ export interface ICompanyLegal {
60
+ schema_version: number;
61
+ entity_type: TEntityType;
62
+ legal_name: string;
63
+ tax_id_type: string;
64
+ tax_id: string;
65
+ tax_id_dv?: string | null;
66
+ address: ICompanyLegalAddress;
67
+ billing_email: string;
68
+ billing_phone?: string | null;
69
+ registry?: ICompanyLegalRegistry | null;
70
+ representative?: ICompanyLegalRepresentative | null;
71
+ country_fields: Record<string, unknown>;
72
+ verification?: ICompanyLegalVerification | null;
73
+ updated_at?: string | null;
74
+ updated_by?: number | null;
75
+ }
76
+ export interface ICompanyLegalReminder {
77
+ sent_at: string;
78
+ count: number;
79
+ }
80
+ export interface ICompanyDetails {
81
+ legal?: ICompanyLegal;
82
+ legal_reminder?: ICompanyLegalReminder;
83
+ logo?: {
84
+ key?: string | null;
85
+ } | null;
86
+ tax_percentage?: number;
87
+ is_tax_included?: boolean;
88
+ is_evidence_retention_enabled?: boolean;
89
+ evidence_retention_months?: number;
90
+ [key: string]: unknown;
91
+ }
92
+ export declare const COMPANY_LEGAL_SCHEMA_VERSION = 1;
93
+ export declare const getLegalVerificationStatus: (details: unknown) => TLegalVerificationStatus;
94
+ export declare const normalizeTaxId: (value: unknown) => string;
95
+ export declare const calculateNitCheckDigit: (taxId: unknown) => string | null;
96
+ export declare const hasCompanyLegal: (details: unknown) => boolean;
97
+ export declare const getMissingLegalFields: (details: unknown, profile?: ICountryLegalProfile | null) => string[];
98
+ export declare const isCompanyLegalComplete: (details: unknown, profile?: ICountryLegalProfile | null) => boolean;
99
+ export declare const getCountryLegalProfile: (countryDetails: unknown) => ICountryLegalProfile | null;
100
+ export declare const legalPreventsTaxCollection: (details: unknown, profile?: ICountryLegalProfile | null) => boolean;
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ // DOC: Datos legales y fiscales de la empresa (`company.details.legal`) y el catálogo por
3
+ // país que decide qué se le pide (`country.details.legal_profile`).
4
+ //
5
+ // Vive en la librería compartida porque los tres lados tienen que estar de acuerdo en qué
6
+ // significa "estar completo": el panel pinta la pastilla, el portal muestra el aviso y el
7
+ // job decide a quién le manda el correo. Duplicada, una empresa podría salir completa en
8
+ // pantalla e incompleta en el correo del día siguiente.
9
+ //
10
+ // Son funciones puras sobre el JSON: no tocan la base de datos ni dependen de TypeORM.
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.legalPreventsTaxCollection = exports.getCountryLegalProfile = exports.isCompanyLegalComplete = exports.getMissingLegalFields = exports.hasCompanyLegal = exports.calculateNitCheckDigit = exports.normalizeTaxId = exports.getLegalVerificationStatus = exports.COMPANY_LEGAL_SCHEMA_VERSION = void 0;
13
+ // DOC: Versión del formato. Se sube cuando cambie la forma del bloque, para poder migrar
14
+ // después sin adivinar qué empresas quedaron con el viejo.
15
+ exports.COMPANY_LEGAL_SCHEMA_VERSION = 1;
16
+ // DOC: En qué estado de revisión está la empresa. Sin bloque `verification` es
17
+ // "pendiente", que es lo que le pasa a toda empresa hasta que alguien de Worklip la mira.
18
+ const getLegalVerificationStatus = (details) => details?.legal?.verification?.status ?? "pending";
19
+ exports.getLegalVerificationStatus = getLegalVerificationStatus;
20
+ // ─── Dígito de verificación ──────────────────────────────────────────────────
21
+ // DOC: Pesos del DV del NIT (DIAN), aplicados de derecha a izquierda. Cuando entre otro
22
+ // país con DV (RUT chileno, RUC peruano) su algoritmo va acá al lado, elegido por
23
+ // `country.code`: los pesos y el módulo son distintos en cada uno.
24
+ const NIT_WEIGHTS = [3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71];
25
+ // DOC: Deja solo los dígitos. El NIT se digita con puntos y guion de mil formas y todas
26
+ // tienen que comparar igual contra el índice único.
27
+ const normalizeTaxId = (value) => String(value ?? "").replace(/\D/g, "");
28
+ exports.normalizeTaxId = normalizeTaxId;
29
+ // DOC: Calcula el dígito de verificación del NIT. Devuelve null si el número no sirve,
30
+ // para que quien llame decida si es un error del usuario o un campo todavía vacío.
31
+ const calculateNitCheckDigit = (taxId) => {
32
+ const digits = (0, exports.normalizeTaxId)(taxId);
33
+ if (!digits || digits.length > NIT_WEIGHTS.length)
34
+ return null;
35
+ const total = digits
36
+ .split("")
37
+ .reverse()
38
+ .reduce((sum, digit, index) => sum + Number(digit) * NIT_WEIGHTS[index], 0);
39
+ const rest = total % 11;
40
+ return String(rest > 1 ? 11 - rest : rest);
41
+ };
42
+ exports.calculateNitCheckDigit = calculateNitCheckDigit;
43
+ // ─── Completitud ─────────────────────────────────────────────────────────────
44
+ // DOC: Hay bloque legal guardado. Es lo que bloquea el cambio de país: sin datos legales
45
+ // no hay nada que invalidar y el país sigue libre.
46
+ const hasCompanyLegal = (details) => !!details?.legal?.tax_id;
47
+ exports.hasCompanyLegal = hasCompanyLegal;
48
+ const isEmpty = (value) => value === null ||
49
+ value === undefined ||
50
+ (typeof value === "string" && !value.trim()) ||
51
+ (Array.isArray(value) && !value.length);
52
+ // DOC: Qué le falta a la empresa para poder facturarle, como rutas del JSON
53
+ // ("legal_name", "address.city", "representative.document"). Quien llame las traduce: el
54
+ // front las pinta en el formulario y el correo del aviso las lista.
55
+ //
56
+ // Sin catálogo del país solo se puede exigir el núcleo común; los campos tributarios
57
+ // propios de ese país no se conocen y se dan por buenos.
58
+ const getMissingLegalFields = (details, profile) => {
59
+ const legal = details?.legal;
60
+ if (!legal)
61
+ return ["legal"];
62
+ const missing = [];
63
+ const requireValue = (key, value) => {
64
+ if (isEmpty(value))
65
+ missing.push(key);
66
+ };
67
+ requireValue("entity_type", legal.entity_type);
68
+ requireValue("legal_name", legal.legal_name);
69
+ requireValue("tax_id_type", legal.tax_id_type);
70
+ requireValue("tax_id", legal.tax_id);
71
+ requireValue("billing_email", legal.billing_email);
72
+ requireValue("address.line1", legal.address?.line1);
73
+ requireValue("address.city", legal.address?.city);
74
+ requireValue("address.region", legal.address?.region);
75
+ // DOC: El DV es de los documentos NUMÉRICOS. Un pasaporte o una cédula de extranjería
76
+ // con letras no lo tiene, y exigírselo dejaría a esa empresa incompleta para siempre.
77
+ if (profile?.uses_dv && !/\D/.test(String(legal.tax_id ?? ""))) {
78
+ requireValue("tax_id_dv", legal.tax_id_dv);
79
+ }
80
+ if (profile?.postal_code_required) {
81
+ requireValue("address.postal_code", legal.address?.postal_code);
82
+ }
83
+ const entityType = legal.entity_type;
84
+ // DOC: El representante legal solo se le pide a la jurídica. En persona natural es el
85
+ // titular mismo, y pedirlo dos veces es una forma de que quede mal la segunda.
86
+ if (entityType === "juridica") {
87
+ requireValue("representative", legal.representative);
88
+ if (legal.representative) {
89
+ requireValue("representative.document_type", legal.representative.document_type);
90
+ requireValue("representative.document", legal.representative.document);
91
+ requireValue("representative.name", legal.representative.name);
92
+ requireValue("representative.surname", legal.representative.surname);
93
+ requireValue("representative.email", legal.representative.email);
94
+ }
95
+ }
96
+ if (profile?.registry_required_for?.includes(entityType)) {
97
+ requireValue("registry.number", legal.registry?.number);
98
+ }
99
+ if (profile?.company_kinds?.length && entityType === "juridica") {
100
+ requireValue("registry.company_kind", legal.registry?.company_kind);
101
+ }
102
+ for (const field of profile?.fields ?? []) {
103
+ if (field.required_for?.includes(entityType)) {
104
+ requireValue(`country_fields.${field.key}`, legal.country_fields?.[field.key]);
105
+ }
106
+ }
107
+ return missing;
108
+ };
109
+ exports.getMissingLegalFields = getMissingLegalFields;
110
+ // DOC: La empresa tiene todo lo necesario para facturarle. Es la MISMA definición que usan
111
+ // la pastilla del panel, el aviso del portal y el job del correo.
112
+ const isCompanyLegalComplete = (details, profile) => !(0, exports.getMissingLegalFields)(details, profile).length;
113
+ exports.isCompanyLegalComplete = isCompanyLegalComplete;
114
+ // DOC: El catálogo legal del país, si lo tiene cargado. `country.details` es JSON libre,
115
+ // así que puede venir nulo o sin el bloque mientras no se le cargue.
116
+ const getCountryLegalProfile = (countryDetails) => countryDetails?.legal_profile ?? null;
117
+ exports.getCountryLegalProfile = getCountryLegalProfile;
118
+ // DOC: ¿Lo que la empresa declaró ante la DIAN le PROHÍBE cobrar impuesto? Es la única
119
+ // relación real entre los datos legales y la configuración de impuesto de las visitas: un
120
+ // "no responsable de IVA" no puede cobrar IVA, y hoy la plataforma deja tener las dos
121
+ // cosas al tiempo.
122
+ //
123
+ // Devuelve solo el hecho; qué hacer con él lo decide quien llama. Las pantallas AVISAN en
124
+ // vez de apagar el impuesto: el bloque legal es opcional y puede estar a medias, y apagarlo
125
+ // solo cambiaría en silencio lo que se le cobra al cliente del taller.
126
+ const legalPreventsTaxCollection = (details, profile) => {
127
+ const countryFields = details?.legal?.country_fields;
128
+ if (!countryFields || !profile?.fields?.length)
129
+ return false;
130
+ return profile.fields.some((field) => {
131
+ const value = countryFields[field.key];
132
+ if (value === undefined || value === null || value === "")
133
+ return false;
134
+ const chosen = Array.isArray(value) ? value.map(String) : [String(value)];
135
+ return (field.options ?? []).some((option) => option.no_tax && chosen.includes(option.value));
136
+ });
137
+ };
138
+ exports.legalPreventsTaxCollection = legalPreventsTaxCollection;
@@ -7,6 +7,15 @@ export declare class BillingUsageSnapshot {
7
7
  storage_bytes: string;
8
8
  whatsapp_messages: number;
9
9
  emails_sent: number;
10
+ /**
11
+ * DOC: Segundos de audio COBRADOS (`voice_note_log.billed_seconds`) del mes.
12
+ *
13
+ * En segundos y no en minutos aunque el plan se venda por minutos: el proveedor factura por
14
+ * segundos y con un mínimo por petición, así que guardar minutos obligaría a redondear acá y
15
+ * la foto del consumo dejaría de cuadrar con lo que se pagó. Se divide entre 60 solo al
16
+ * mostrarlo.
17
+ */
18
+ voice_note_seconds: number;
10
19
  users_count: number;
11
20
  workshops_count: number;
12
21
  created: Date;
@@ -70,6 +70,14 @@ __decorate([
70
70
  }),
71
71
  __metadata("design:type", Number)
72
72
  ], BillingUsageSnapshot.prototype, "emails_sent", void 0);
73
+ __decorate([
74
+ (0, typeorm_1.Column)({
75
+ type: "int",
76
+ default: 0,
77
+ comment: "Cuántos segundos de audio cobrados (voice_note_log) consumió la empresa para el mes y año.",
78
+ }),
79
+ __metadata("design:type", Number)
80
+ ], BillingUsageSnapshot.prototype, "voice_note_seconds", void 0);
73
81
  __decorate([
74
82
  (0, typeorm_1.Column)({
75
83
  type: "int",
@@ -9,6 +9,7 @@ export declare class Company {
9
9
  code: string;
10
10
  name: string;
11
11
  details: any | null;
12
+ tax_id_norm: string | null;
12
13
  created: Date;
13
14
  updated: Date | null;
14
15
  status: number;
@@ -56,6 +56,20 @@ __decorate([
56
56
  }),
57
57
  __metadata("design:type", Object)
58
58
  ], Company.prototype, "details", void 0);
59
+ __decorate([
60
+ (0, typeorm_1.Column)({
61
+ type: "varchar",
62
+ length: 20,
63
+ nullable: true,
64
+ select: false,
65
+ insert: false,
66
+ update: false,
67
+ generatedType: "STORED",
68
+ asExpression: "json_unquote(json_extract(`details`,'$.legal.tax_id'))",
69
+ comment: "Documento fiscal (NIT) extraído de details.legal.tax_id. Columna generada, existe para el índice único.",
70
+ }),
71
+ __metadata("design:type", Object)
72
+ ], Company.prototype, "tax_id_norm", void 0);
59
73
  __decorate([
60
74
  (0, typeorm_1.Column)({
61
75
  type: "datetime",
@@ -158,4 +172,8 @@ __decorate([
158
172
  ], Company.prototype, "company_subscriptions", void 0);
159
173
  exports.Company = Company = __decorate([
160
174
  (0, typeorm_1.Entity)({ comment: "Empresas registradas en la plataforma." })
175
+ // DOC: Dos empresas no pueden compartir documento fiscal. UNIQUE en MySQL admite varios
176
+ // NULL, así que las que todavía no cargaron sus datos legales conviven sin chocar.
177
+ ,
178
+ (0, typeorm_1.Index)("UQ_company_tax_id", ["tax_id_norm"], { unique: true })
161
179
  ], Company);
@@ -34,7 +34,7 @@ __decorate([
34
34
  __decorate([
35
35
  (0, typeorm_1.Column)({
36
36
  type: "int",
37
- comment: "Tipo de recurso:\r\n1. STORAGE_GB.\r\n2. WHATSAPP_MESSAGES.\r\n3. EMAIL_MESSAGES.\r\n4. USERS.\r\n5. WORKSHOPS.",
37
+ comment: "Tipo de recurso:\r\n1. STORAGE_GB.\r\n2. WHATSAPP_MESSAGES.\r\n3. EMAIL_MESSAGES.\r\n4. USERS.\r\n5. WORKSHOPS.\r\n6. VOICE_NOTE_SECONDS.",
38
38
  }),
39
39
  __metadata("design:type", Number)
40
40
  ], UsageAlert.prototype, "resource_type", void 0);
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ import { DataSource, EntityTarget, ObjectLiteral, Repository } from "typeorm";
2
2
  import { IBasicFilter } from "./types";
3
3
  export * from "./entities.views.routes";
4
4
  export * from "./visit.summary";
5
+ export * from "./company.legal";
5
6
  export declare function createDataBaseSource(): DataSource;
6
7
  export declare function showEntityName<T extends ObjectLiteral>(entity: EntityTarget<T>): Promise<Repository<T>>;
7
8
  export declare function callStoredProcedureName(storedProcedure: any, elements: any): Promise<any>;
package/dist/index.js CHANGED
@@ -51,6 +51,9 @@ __exportStar(require("./entities.views.routes"), exports);
51
51
  // DOC: Cálculo del resumen de la visita. Lo consumen el front (en vivo) y el API
52
52
  // (al guardar), y tiene que ser la MISMA implementación en los dos.
53
53
  __exportStar(require("./visit.summary"), exports);
54
+ // DOC: Datos legales/fiscales de la empresa y el catálogo por país. Lo consumen el panel,
55
+ // el portal y el job del aviso, y "estar completo" tiene que significar lo mismo en los tres.
56
+ __exportStar(require("./company.legal"), exports);
54
57
  let connection = null;
55
58
  // DOC: Inicialización en curso. Se memoriza la PROMESA y no el resultado porque el patrón
56
59
  // "si no está inicializada, inicialízala" tiene una carrera en el arranque en frío: dos
@@ -7,6 +7,7 @@ export declare class SubscriptionPlans {
7
7
  included_storage_gb: number;
8
8
  included_whatsapp_messages: number;
9
9
  included_emails: number;
10
+ included_voice_note_minutes: number;
10
11
  max_workshops: number;
11
12
  max_users: number;
12
13
  retention_days: number | null;
@@ -46,6 +46,10 @@ __decorate([
46
46
  (0, typeorm_1.ViewColumn)(),
47
47
  __metadata("design:type", Number)
48
48
  ], SubscriptionPlans.prototype, "included_emails", void 0);
49
+ __decorate([
50
+ (0, typeorm_1.ViewColumn)(),
51
+ __metadata("design:type", Number)
52
+ ], SubscriptionPlans.prototype, "included_voice_note_minutes", void 0);
49
53
  __decorate([
50
54
  (0, typeorm_1.ViewColumn)(),
51
55
  __metadata("design:type", Number)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asumano/worklip-typeorm-db",
3
- "version": "1.1.72",
3
+ "version": "1.1.74",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },