@carlosdiazz/lottodiz-shared 4.2.3 → 5.1.0

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.
@@ -124,6 +124,8 @@ export declare class MethodValid {
124
124
  static PLATFORM_DEVICE_FIND_ALL: string;
125
125
  static PLATFORM_DEVICE_UPDATE: string;
126
126
  static PLATFORM_DEVICE_REMOVE: string;
127
+ static PLATFORM_DEVICE_STATS: string;
128
+ static PLATFORM_DEVICE_SUMMARIZE: string;
127
129
  static PLATFORM_MESSAGE_CREATE: string;
128
130
  static PLATFORM_MESSAGE_AUTO_CREATE: string;
129
131
  static PLATFORM_MESSAGE_SEND: string;
@@ -151,6 +151,8 @@ MethodValid.PLATFORM_DEVICE_FIND_ONE = "PLATFORM_DEVICE_FIND_ONE";
151
151
  MethodValid.PLATFORM_DEVICE_FIND_ALL = "PLATFORM_DEVICE_FIND_ALL";
152
152
  MethodValid.PLATFORM_DEVICE_UPDATE = "PLATFORM_DEVICE_UPDATE";
153
153
  MethodValid.PLATFORM_DEVICE_REMOVE = "PLATFORM_DEVICE_REMOVE";
154
+ MethodValid.PLATFORM_DEVICE_STATS = "PLATFORM_DEVICE_STATS";
155
+ MethodValid.PLATFORM_DEVICE_SUMMARIZE = "PLATFORM_DEVICE_SUMMARIZE";
154
156
  //PLATFORM MESSAGE
155
157
  MethodValid.PLATFORM_MESSAGE_CREATE = "PLATFORM_MESSAGE_CREATE";
156
158
  MethodValid.PLATFORM_MESSAGE_AUTO_CREATE = "PLATFORM_MESSAGE_AUTO_CREATE";
@@ -8,9 +8,18 @@ export interface DrawInterface {
8
8
  imagen?: string;
9
9
  preference: number;
10
10
  draw_code: string;
11
+ /** Fecha de negocio (00:00 UTC) en la zona de la lotería. Filtrar por esta columna. */
11
12
  date: Date;
13
+ /** Hora local de la lotería (zona `time_zone`), sin convertir. */
12
14
  time_start: string;
15
+ /** Hora local de la lotería (zona `time_zone`), sin convertir. */
13
16
  time_end: string;
17
+ /** Zona IANA de la lotería (copiada del template al crear el sorteo). */
18
+ time_zone: string;
19
+ /** Instante UTC de apertura. Los clientes lo muestran en la zona del dispositivo. */
20
+ open_at: Date;
21
+ /** Instante UTC de cierre. Los clientes lo muestran en la zona del dispositivo. */
22
+ close_at: Date;
14
23
  is_open: boolean;
15
24
  is_express: boolean;
16
25
  message: string;
@@ -4,4 +4,6 @@ export interface ParamsLeaderLinesInterface {
4
4
  owner_id: string;
5
5
  date_from?: Date | null;
6
6
  date_to?: Date | null;
7
+ /** Zona IANA para interpretar date_from/date_to. Por defecto la zona de la app. */
8
+ time_zone?: string | null;
7
9
  }
@@ -7,4 +7,6 @@ export interface ParamsOperationInterface {
7
7
  id_pos_user?: string | null;
8
8
  date_from?: Date | null;
9
9
  date_to?: Date | null;
10
+ /** Zona IANA para interpretar date_from/date_to. Por defecto la zona de la app. */
11
+ time_zone?: string | null;
10
12
  }
@@ -7,3 +7,4 @@ export * from "./platform-device.service";
7
7
  export * from "./response-platform-device.base";
8
8
  export * from "./update-platform-device.base";
9
9
  export * from "./params-platform-device.base";
10
+ export * from "./platform-device-stats.base";
@@ -23,3 +23,4 @@ __exportStar(require("./platform-device.service"), exports);
23
23
  __exportStar(require("./response-platform-device.base"), exports);
24
24
  __exportStar(require("./update-platform-device.base"), exports);
25
25
  __exportStar(require("./params-platform-device.base"), exports);
26
+ __exportStar(require("./platform-device-stats.base"), exports);
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Estadísticas de uso de la app (dispositivos).
3
+ *
4
+ * - Un dispositivo = una instalación de la app (`device_uuid`).
5
+ * - Activo en un día = abrió la app al menos una vez ese día (zona APP_TIME_ZONE).
6
+ * - El resumen diario se calcula a medianoche (job) y se guarda en `platform_device_stat`.
7
+ */
8
+ /** Fila del resumen diario por plataforma (tabla `platform_device_stat`). */
9
+ export interface PlatformDeviceStatInterface {
10
+ id: string;
11
+ /** Día de negocio YYYY-MM-DD. */
12
+ date: string;
13
+ /** null = dispositivos sin plataforma asignada. */
14
+ id_platform?: string | null;
15
+ /** Dispositivos que abrieron la app ese día. */
16
+ active_devices: number;
17
+ /** Dispositivos registrados por primera vez ese día. */
18
+ new_devices: number;
19
+ /** Total de dispositivos registrados al final del día. */
20
+ total_devices: number;
21
+ create_at: Date;
22
+ }
23
+ /** Actividad de un dispositivo en un día (tabla `platform_device_activity`). */
24
+ export interface PlatformDeviceActivityInterface {
25
+ id: string;
26
+ date: string;
27
+ id_platform_device: string;
28
+ id_platform?: string | null;
29
+ create_at: Date;
30
+ }
31
+ export interface ParamsPlatformDeviceStatsInterface {
32
+ /** YYYY-MM-DD (inclusive). */
33
+ date_from: string;
34
+ /** YYYY-MM-DD (inclusive). */
35
+ date_to: string;
36
+ /** Sin valor = total general de todas las plataformas. */
37
+ id_platform?: string | null;
38
+ }
39
+ /** Punto diario de la serie (sumado si no se filtra por plataforma). */
40
+ export interface PlatformDeviceDailyStatInterface {
41
+ date: string;
42
+ active_devices: number;
43
+ new_devices: number;
44
+ total_devices: number;
45
+ /** true = hoy, calculado en vivo (aún no resumido por el job). */
46
+ is_live: boolean;
47
+ }
48
+ export interface PlatformDeviceStatsSummaryInterface {
49
+ /** Total de dispositivos registrados (en vivo). */
50
+ total_devices: number;
51
+ /** Dispositivos activos hoy (en vivo). */
52
+ active_today: number;
53
+ /** Dispositivos nuevos hoy (en vivo). */
54
+ new_today: number;
55
+ /** Promedio diario de activos en el rango consultado. */
56
+ average_active: number;
57
+ /** Día con más activos en el rango. */
58
+ peak_active: number;
59
+ peak_date?: string | null;
60
+ }
61
+ export interface PlatformDevicePlatformStatInterface {
62
+ id_platform?: string | null;
63
+ name: string;
64
+ total_devices: number;
65
+ active_today: number;
66
+ }
67
+ export interface ResponsePlatformDeviceStatsInterface {
68
+ summary: PlatformDeviceStatsSummaryInterface;
69
+ daily: PlatformDeviceDailyStatInterface[];
70
+ by_platform: PlatformDevicePlatformStatInterface[];
71
+ }
72
+ export interface SummarizePlatformDeviceStatsInterface {
73
+ /** YYYY-MM-DD (inclusive). */
74
+ date_from: string;
75
+ /** YYYY-MM-DD (inclusive). */
76
+ date_to: string;
77
+ }
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ /**
3
+ * Estadísticas de uso de la app (dispositivos).
4
+ *
5
+ * - Un dispositivo = una instalación de la app (`device_uuid`).
6
+ * - Activo en un día = abrió la app al menos una vez ese día (zona APP_TIME_ZONE).
7
+ * - El resumen diario se calcula a medianoche (job) y se guarda en `platform_device_stat`.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -7,6 +7,8 @@ export interface PlatformDeviceInterface {
7
7
  app_version: string;
8
8
  device_model: string;
9
9
  topic_platform: string;
10
+ /** Última vez que el dispositivo abrió la app. */
11
+ last_seen_at?: Date | null;
10
12
  platform?: PlatformInterface;
11
13
  create_at: Date;
12
14
  update_at: Date;
@@ -2,8 +2,10 @@ import { ParamsPlatformDevicesInterface } from "./params-platform-device.base";
2
2
  import { PlatformDeviceInterface } from "./platform-device.base";
3
3
  import { ResponsePlatformDeviceInterface } from "./response-platform-device.base";
4
4
  import { ResponseInterface } from "../common";
5
+ import { ParamsPlatformDeviceStatsInterface, ResponsePlatformDeviceStatsInterface } from "./platform-device-stats.base";
5
6
  export interface PlatformDeviceDatasourceInterface {
6
7
  findAll(pagination: ParamsPlatformDevicesInterface): Promise<ResponsePlatformDeviceInterface>;
7
8
  findOne(id: string): Promise<PlatformDeviceInterface>;
8
9
  remove(id: string): Promise<ResponseInterface>;
10
+ stats(params: ParamsPlatformDeviceStatsInterface): Promise<ResponsePlatformDeviceStatsInterface>;
9
11
  }
@@ -3,8 +3,11 @@ import { PlatformDeviceInterface } from "./platform-device.base";
3
3
  import { ResponsePlatformDeviceInterface } from "./response-platform-device.base";
4
4
  import { ResponseInterface } from "../common";
5
5
  import { UserInterface } from "../user";
6
+ import { ParamsPlatformDeviceStatsInterface, ResponsePlatformDeviceStatsInterface, SummarizePlatformDeviceStatsInterface } from "./platform-device-stats.base";
6
7
  export interface PlatformDeviceResolverInterface {
7
8
  findAll(pagination: ParamsPlatformDevicesInterface, user?: UserInterface): Promise<ResponsePlatformDeviceInterface>;
8
9
  findOne(id: string, user?: UserInterface): Promise<PlatformDeviceInterface>;
9
10
  remove(id: string, user?: UserInterface): Promise<ResponseInterface>;
11
+ stats(params: ParamsPlatformDeviceStatsInterface, user?: UserInterface): Promise<ResponsePlatformDeviceStatsInterface>;
12
+ summarize(dto: SummarizePlatformDeviceStatsInterface, user?: UserInterface): Promise<ResponseInterface>;
10
13
  }
@@ -2,4 +2,6 @@ import { ConfigObsInterface } from "../config_obs";
2
2
  export interface CreateJobsObsDtoInterface {
3
3
  configObs: ConfigObsInterface[];
4
4
  date: string;
5
+ /** Zona IANA en la que se interpretan `date` y `hour`. */
6
+ time_zone: string;
5
7
  }
@@ -13,6 +13,8 @@ export interface ParamsTicketInterface {
13
13
  date_sale_to?: Date | null;
14
14
  date_paid_at_from?: Date | null;
15
15
  date_paid_at_to?: Date | null;
16
+ /** Zona IANA para interpretar los rangos de fecha. Por defecto la zona de la app. */
17
+ time_zone?: string | null;
16
18
  total_amount?: number | null;
17
19
  prize_amount?: number | null;
18
20
  filter_sale?: FilterTicketType | null;
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const utils_1 = require("../utils");
3
4
  const main = async () => {
4
- const date = new Date("2025-12-03");
5
- const time_end = "11:40";
6
- //const time = getDelayFromDateTime(date, time_end);
5
+ const { open_at, close_at } = (0, utils_1.buildDrawSchedule)("2025-12-03", "09:00:00", "11:40:00", "America/Santo_Domingo");
6
+ console.log(open_at.toISOString(), close_at.toISOString());
7
+ console.log((0, utils_1.getDelayUntil)(close_at));
7
8
  };
8
9
  main();
@@ -0,0 +1,36 @@
1
+ import * as joi from "joi";
2
+ export declare const isValidTimeZone: (timeZone: string) => boolean;
3
+ export declare const timeZoneValidator: joi.CustomValidator<string>;
4
+ /**
5
+ * Convierte la fecha de negocio a "YYYY-MM-DD".
6
+ * Si recibe un Date, se toma su parte UTC (convención: la fecha de negocio se guarda a las 00:00 UTC).
7
+ */
8
+ export declare const toBusinessDateString: (date: Date | string) => string;
9
+ /** Fecha de negocio (00:00 UTC) que se guarda en la columna `date`. */
10
+ export declare const toBusinessDate: (date: Date | string) => Date;
11
+ /**
12
+ * Convierte fecha de negocio + hora local de una zona en un instante UTC.
13
+ * Usa el offset real de ESA fecha (soporta DST).
14
+ */
15
+ export declare const toInstant: (date: Date | string, time: string, timeZone: string) => Date;
16
+ export interface DrawScheduleInterface {
17
+ open_at: Date;
18
+ close_at: Date;
19
+ }
20
+ /**
21
+ * Calcula apertura y cierre de un sorteo.
22
+ * Si el cierre es menor o igual a la apertura, el sorteo cruza medianoche y cierra al día siguiente.
23
+ */
24
+ export declare const buildDrawSchedule: (date: Date | string, time_start: string, time_end: string, timeZone: string) => DrawScheduleInterface;
25
+ /** Milisegundos desde ahora hasta el instante (0 si ya pasó). */
26
+ export declare const getDelayUntil: (instant: Date | string, now?: number) => number;
27
+ /** Fecha actual (YYYY-MM-DD) en una zona horaria. */
28
+ export declare const todayInTimeZone: (timeZone: string) => string;
29
+ /**
30
+ * Rango UTC [inicio, fin] de un rango de días locales (inclusive) en una zona.
31
+ * Útil para filtrar reportes por "día" del usuario.
32
+ */
33
+ export declare const localDateRangeToUtc: (date_from: string, date_to: string, timeZone: string) => {
34
+ start: Date;
35
+ end: Date;
36
+ };
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.localDateRangeToUtc = exports.todayInTimeZone = exports.getDelayUntil = exports.buildDrawSchedule = exports.toInstant = exports.toBusinessDate = exports.toBusinessDateString = exports.timeZoneValidator = exports.isValidTimeZone = void 0;
4
+ const luxon_1 = require("luxon");
5
+ /**
6
+ * Utilidades de fecha/hora independientes de la zona horaria del proceso.
7
+ *
8
+ * Reglas:
9
+ * - Los instantes (open_at, close_at, create_at...) siempre son UTC (Date / timestamptz).
10
+ * - `date` de un sorteo es la FECHA DE NEGOCIO (YYYY-MM-DD) en la zona de la lotería.
11
+ * - `time_start` / `time_end` son la hora local de la lotería (time_zone del template), sin convertir.
12
+ * - Los clientes muestran los instantes en la zona del dispositivo.
13
+ */
14
+ const TIME_REGEX = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/;
15
+ const DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/;
16
+ const isValidTimeZone = (timeZone) => typeof timeZone === "string" &&
17
+ timeZone.length > 0 &&
18
+ luxon_1.DateTime.now().setZone(timeZone).isValid;
19
+ exports.isValidTimeZone = isValidTimeZone;
20
+ const timeZoneValidator = (value, helpers) => {
21
+ if (!(0, exports.isValidTimeZone)(value)) {
22
+ return helpers.error("any.invalid", { value });
23
+ }
24
+ return value;
25
+ };
26
+ exports.timeZoneValidator = timeZoneValidator;
27
+ /**
28
+ * Convierte la fecha de negocio a "YYYY-MM-DD".
29
+ * Si recibe un Date, se toma su parte UTC (convención: la fecha de negocio se guarda a las 00:00 UTC).
30
+ */
31
+ const toBusinessDateString = (date) => {
32
+ if (typeof date === "string") {
33
+ const only = date.substring(0, 10);
34
+ if (!DATE_REGEX.test(only))
35
+ throw new Error(`Invalid date: "${date}"`);
36
+ return only;
37
+ }
38
+ const dt = luxon_1.DateTime.fromJSDate(date, { zone: "utc" });
39
+ if (!dt.isValid)
40
+ throw new Error(`Invalid date: "${String(date)}"`);
41
+ return dt.toFormat("yyyy-MM-dd");
42
+ };
43
+ exports.toBusinessDateString = toBusinessDateString;
44
+ /** Fecha de negocio (00:00 UTC) que se guarda en la columna `date`. */
45
+ const toBusinessDate = (date) => new Date(`${(0, exports.toBusinessDateString)(date)}T00:00:00.000Z`);
46
+ exports.toBusinessDate = toBusinessDate;
47
+ /**
48
+ * Convierte fecha de negocio + hora local de una zona en un instante UTC.
49
+ * Usa el offset real de ESA fecha (soporta DST).
50
+ */
51
+ const toInstant = (date, time, timeZone) => {
52
+ if (!TIME_REGEX.test(time))
53
+ throw new Error(`Invalid time: "${time}"`);
54
+ if (!(0, exports.isValidTimeZone)(timeZone)) {
55
+ throw new Error(`Invalid time zone: "${timeZone}"`);
56
+ }
57
+ const [hour, minute, second = 0] = time.split(":").map(Number);
58
+ const [year, month, day] = (0, exports.toBusinessDateString)(date).split("-").map(Number);
59
+ const dt = luxon_1.DateTime.fromObject({ year, month, day, hour, minute, second, millisecond: 0 }, { zone: timeZone });
60
+ if (!dt.isValid) {
61
+ throw new Error(`Invalid date/time: ${String(date)} ${time} ${timeZone}`);
62
+ }
63
+ return dt.toUTC().toJSDate();
64
+ };
65
+ exports.toInstant = toInstant;
66
+ /**
67
+ * Calcula apertura y cierre de un sorteo.
68
+ * Si el cierre es menor o igual a la apertura, el sorteo cruza medianoche y cierra al día siguiente.
69
+ */
70
+ const buildDrawSchedule = (date, time_start, time_end, timeZone) => {
71
+ const open_at = (0, exports.toInstant)(date, time_start, timeZone);
72
+ let close_at = (0, exports.toInstant)(date, time_end, timeZone);
73
+ if (close_at.getTime() <= open_at.getTime()) {
74
+ const next = luxon_1.DateTime.fromISO((0, exports.toBusinessDateString)(date), { zone: "utc" })
75
+ .plus({ days: 1 })
76
+ .toFormat("yyyy-MM-dd");
77
+ close_at = (0, exports.toInstant)(next, time_end, timeZone);
78
+ }
79
+ return { open_at, close_at };
80
+ };
81
+ exports.buildDrawSchedule = buildDrawSchedule;
82
+ /** Milisegundos desde ahora hasta el instante (0 si ya pasó). */
83
+ const getDelayUntil = (instant, now = Date.now()) => {
84
+ const target = new Date(instant).getTime();
85
+ if (Number.isNaN(target))
86
+ throw new Error(`Invalid instant: "${instant}"`);
87
+ return Math.max(0, target - now);
88
+ };
89
+ exports.getDelayUntil = getDelayUntil;
90
+ /** Fecha actual (YYYY-MM-DD) en una zona horaria. */
91
+ const todayInTimeZone = (timeZone) => {
92
+ if (!(0, exports.isValidTimeZone)(timeZone)) {
93
+ throw new Error(`Invalid time zone: "${timeZone}"`);
94
+ }
95
+ return luxon_1.DateTime.now().setZone(timeZone).toFormat("yyyy-MM-dd");
96
+ };
97
+ exports.todayInTimeZone = todayInTimeZone;
98
+ /**
99
+ * Rango UTC [inicio, fin] de un rango de días locales (inclusive) en una zona.
100
+ * Útil para filtrar reportes por "día" del usuario.
101
+ */
102
+ const localDateRangeToUtc = (date_from, date_to, timeZone) => {
103
+ if (!(0, exports.isValidTimeZone)(timeZone)) {
104
+ throw new Error(`Invalid time zone: "${timeZone}"`);
105
+ }
106
+ const start = luxon_1.DateTime.fromISO((0, exports.toBusinessDateString)(date_from), {
107
+ zone: timeZone,
108
+ }).startOf("day");
109
+ const end = luxon_1.DateTime.fromISO((0, exports.toBusinessDateString)(date_to), {
110
+ zone: timeZone,
111
+ }).endOf("day");
112
+ return { start: start.toUTC().toJSDate(), end: end.toUTC().toJSDate() };
113
+ };
114
+ exports.localDateRangeToUtc = localDateRangeToUtc;
@@ -1,14 +1,11 @@
1
1
  export * from "./convert-array-to-record";
2
2
  export * from "./convert-date-to-string";
3
- export * from "./convert-time-zone";
4
3
  export * from "./convert-to-number-array";
5
4
  export * from "./create-interval-array";
5
+ export * from "./date-time";
6
6
  export * from "./deep-partial";
7
- export * from "./diff-minutes-from-dates";
8
7
  export * from "./exect-function";
9
8
  export * from "./get-day-number-of-day";
10
- export * from "./get-delay-from-date-time";
11
- export * from "./get-delay-from-time";
12
9
  export * from "./mapper-api-result-v2";
13
10
  export * from "./normalize-time";
14
11
  export * from "./sleep";
@@ -16,15 +16,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./convert-array-to-record"), exports);
18
18
  __exportStar(require("./convert-date-to-string"), exports);
19
- __exportStar(require("./convert-time-zone"), exports);
20
19
  __exportStar(require("./convert-to-number-array"), exports);
21
20
  __exportStar(require("./create-interval-array"), exports);
21
+ __exportStar(require("./date-time"), exports);
22
22
  __exportStar(require("./deep-partial"), exports);
23
- __exportStar(require("./diff-minutes-from-dates"), exports);
24
23
  __exportStar(require("./exect-function"), exports);
25
24
  __exportStar(require("./get-day-number-of-day"), exports);
26
- __exportStar(require("./get-delay-from-date-time"), exports);
27
- __exportStar(require("./get-delay-from-time"), exports);
28
25
  __exportStar(require("./mapper-api-result-v2"), exports);
29
26
  __exportStar(require("./normalize-time"), exports);
30
27
  __exportStar(require("./sleep"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@carlosdiazz/lottodiz-shared",
3
- "version": "4.2.3",
3
+ "version": "5.1.0",
4
4
  "description": "Shared Dtos, models, constants and utils",
5
5
  "main": "dist/index.js",
6
6
  "private": false,