@floristcloud/api-lib 1.2.107 → 1.2.109

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.
Files changed (83) hide show
  1. package/build/commands/client/create-client.command.js +2 -0
  2. package/build/commands/client/get-client-list.query.js +8 -0
  3. package/build/commands/client/index.js +1 -0
  4. package/build/commands/client/update-client-contract-data.command.js +22 -0
  5. package/build/commands/client/update-client.command.js +2 -0
  6. package/build/commands/money-account/get-money-account-by-criteria.query.js +7 -2
  7. package/build/commands/money-account/get-money-account-list.query.js +5 -1
  8. package/build/commands/report/export-inventory-stock.query.js +4 -17
  9. package/build/commands/report/export-inventory-turnover.query.js +4 -27
  10. package/build/commands/report/export-sales-by-client.query.js +3 -0
  11. package/build/commands/report/export-sales-by-position.query.js +3 -0
  12. package/build/commands/report/export-sales-revenue.query.js +3 -0
  13. package/build/commands/report/get-inventory-stock.query.js +34 -0
  14. package/build/commands/report/get-inventory-turnover.query.js +43 -0
  15. package/build/commands/report/get-report-by-client-weeks.query.js +19 -0
  16. package/build/commands/report/get-report-group-by-client.query.js +25 -2
  17. package/build/commands/report/get-report-group-by-position.query.js +21 -2
  18. package/build/commands/report/get-sales-by-client.query.js +48 -0
  19. package/build/commands/report/get-sales-summary.query.js +4 -0
  20. package/build/commands/report/index.js +3 -0
  21. package/build/commands/settings/get-company-profile.query.js +24 -0
  22. package/build/commands/settings/index.js +1 -0
  23. package/build/constant/index.js +1 -0
  24. package/build/constant/report.constant.js +9 -0
  25. package/build/enum/client-contract-status.enum.js +13 -0
  26. package/build/enum/index.js +4 -0
  27. package/build/enum/report-order-date-basis.enum.js +18 -0
  28. package/build/enum/report-sort-by.enum.js +13 -0
  29. package/build/helpers/index.js +2 -0
  30. package/build/helpers/pagination.helper.js +12 -0
  31. package/build/helpers/query-boolean.helper.js +16 -0
  32. package/build/schemas/client/client.schema.js +2 -0
  33. package/build/schemas/index.js +8 -0
  34. package/build/schemas/money-account/money-account-with-balance.schema.js +13 -0
  35. package/build/schemas/report/inventory-stock-category-item.schema.js +10 -0
  36. package/build/schemas/report/inventory-stock-detailed-item.schema.js +14 -0
  37. package/build/schemas/report/inventory-turnover-category-item.schema.js +15 -0
  38. package/build/schemas/report/inventory-turnover-detailed-item.schema.js +19 -0
  39. package/build/schemas/report/report-order-filter.schema.js +28 -0
  40. package/build/schemas/report/sales-by-client-row.schema.js +45 -0
  41. package/build/schemas/report/sales-by-client-top-item.schema.js +9 -0
  42. package/commands/client/create-client.command.ts +2 -0
  43. package/commands/client/get-client-list.query.ts +8 -0
  44. package/commands/client/index.ts +1 -0
  45. package/commands/client/update-client-contract-data.command.ts +24 -0
  46. package/commands/client/update-client.command.ts +2 -0
  47. package/commands/money-account/get-money-account-by-criteria.query.ts +10 -3
  48. package/commands/money-account/get-money-account-list.query.ts +8 -2
  49. package/commands/report/export-inventory-stock.query.ts +4 -19
  50. package/commands/report/export-inventory-turnover.query.ts +4 -29
  51. package/commands/report/export-sales-by-client.query.ts +3 -0
  52. package/commands/report/export-sales-by-position.query.ts +3 -0
  53. package/commands/report/export-sales-revenue.query.ts +3 -0
  54. package/commands/report/get-inventory-stock.query.ts +36 -0
  55. package/commands/report/get-inventory-turnover.query.ts +45 -0
  56. package/commands/report/get-report-by-client-weeks.query.ts +20 -1
  57. package/commands/report/get-report-group-by-client.query.ts +26 -3
  58. package/commands/report/get-report-group-by-position.query.ts +23 -4
  59. package/commands/report/get-sales-by-client.query.ts +50 -0
  60. package/commands/report/get-sales-summary.query.ts +4 -0
  61. package/commands/report/index.ts +3 -0
  62. package/commands/settings/get-company-profile.query.ts +24 -0
  63. package/commands/settings/index.ts +1 -0
  64. package/constant/index.ts +1 -0
  65. package/constant/report.constant.ts +6 -0
  66. package/enum/client-contract-status.enum.ts +9 -0
  67. package/enum/index.ts +4 -0
  68. package/enum/report-order-date-basis.enum.ts +14 -0
  69. package/enum/report-sort-by.enum.ts +9 -0
  70. package/helpers/index.ts +2 -0
  71. package/helpers/pagination.helper.ts +9 -0
  72. package/helpers/query-boolean.helper.ts +14 -0
  73. package/package.json +1 -1
  74. package/schemas/client/client.schema.ts +2 -0
  75. package/schemas/index.ts +8 -0
  76. package/schemas/money-account/money-account-with-balance.schema.ts +11 -0
  77. package/schemas/report/inventory-stock-category-item.schema.ts +8 -0
  78. package/schemas/report/inventory-stock-detailed-item.schema.ts +12 -0
  79. package/schemas/report/inventory-turnover-category-item.schema.ts +13 -0
  80. package/schemas/report/inventory-turnover-detailed-item.schema.ts +17 -0
  81. package/schemas/report/report-order-filter.schema.ts +26 -0
  82. package/schemas/report/sales-by-client-row.schema.ts +43 -0
  83. package/schemas/report/sales-by-client-top-item.schema.ts +7 -0
@@ -0,0 +1,45 @@
1
+ import { z } from 'zod';
2
+ import { dateRangeCheck } from '../../helpers/date.helper';
3
+ import { isPageAccompaniedByCount } from '../../helpers/pagination.helper';
4
+ import { queryBooleanSchema } from '../../helpers/query-boolean.helper';
5
+ import { InventoryTurnoverCategoryItemSchema } from '../../schemas/report/inventory-turnover-category-item.schema';
6
+ import { InventoryTurnoverDetailedItemSchema } from '../../schemas/report/inventory-turnover-detailed-item.schema';
7
+
8
+ const GetInventoryTurnoverRequestSchema = z
9
+ .object({
10
+ // Даты обязательны: без периода оборачиваемость не считается (в отличие от export/*, где
11
+ // отсутствие дат приводило к ошибке уже внутри сервиса).
12
+ startDate: z.coerce.date(),
13
+ endDate: z.coerce.date(),
14
+ categoryUUID: z.uuid().optional().describe('Keep only the products of this category.'),
15
+ detailed: queryBooleanSchema.describe('Pass "true" to group rows by product name / size / grower instead of by category only.'),
16
+ // Пагинация по строкам отчёта. Без count лимит не накладывается — отдаём весь отчёт,
17
+ // а page без count отклоняется: иначе листание молча возвращало бы одну и ту же выдачу.
18
+ page: z.coerce.number().int().positive().optional().describe('1-based page number, requires "count".'),
19
+ count: z.coerce.number().int().positive().optional().describe('Rows per page. Without it the whole report is returned.'),
20
+ })
21
+ .refine(value => dateRangeCheck(value.startDate, value.endDate), {
22
+ message: 'validation.dateRange',
23
+ path: ['endDate', 'startDate'],
24
+ })
25
+ .refine(isPageAccompaniedByCount, {
26
+ message: 'validation.pageRequiresCount',
27
+ path: ['page'],
28
+ });
29
+
30
+ const GetInventoryTurnoverResponseSchema = z.object({
31
+ message: z.string().optional(),
32
+ data: z.object({
33
+ list: z.array(z.union([InventoryTurnoverCategoryItemSchema, InventoryTurnoverDetailedItemSchema])),
34
+ // Число строк во всём отчёте — не размер страницы.
35
+ total: z.number(),
36
+ }),
37
+ });
38
+
39
+ export namespace GetInventoryTurnoverContractQuery {
40
+ export const RequestSchema = GetInventoryTurnoverRequestSchema;
41
+ export type Request = z.infer<typeof RequestSchema>;
42
+
43
+ export const ResponseSchema = GetInventoryTurnoverResponseSchema;
44
+ export type Response = z.infer<typeof ResponseSchema>;
45
+ }
@@ -1,5 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { dateRangeCheck } from '../../helpers/date.helper';
3
+ import { isPageAccompaniedByCount } from '../../helpers/pagination.helper';
4
+ import { queryBooleanSchema } from '../../helpers/query-boolean.helper';
3
5
  import { ClientByWeeksSchema } from '../../schemas';
4
6
 
5
7
  const GetReportByClientWeeksRequestSchema = z
@@ -7,6 +9,15 @@ const GetReportByClientWeeksRequestSchema = z
7
9
  startDate: z.coerce.date(),
8
10
  endDate: z.coerce.date(),
9
11
  responsibleUserUUID: z.string().optional(),
12
+ // Отчёт — это матрица «неделя × клиент», поэтому по умолчанию отдаёт строку и на нулевые недели.
13
+ // Флаг оставляет только недели с заказами: то, что обычно и нужно, и на порядок меньше данных.
14
+ onlyWithOrders: queryBooleanSchema,
15
+ // Фильтр по группе клиента (client."group") — дешёвый, применяется до CROSS JOIN недель.
16
+ clientGroup: z.string().optional(),
17
+ // Пагинация по строкам матрицы. Без count лимит не накладывается — поведение по умолчанию
18
+ // прежнее, а page без count отклоняется: иначе листание молча возвращало бы одну и ту же выдачу.
19
+ page: z.coerce.number().int().positive().optional(),
20
+ count: z.coerce.number().int().positive().optional(),
10
21
  })
11
22
  .refine(
12
23
  value => {
@@ -20,11 +31,19 @@ const GetReportByClientWeeksRequestSchema = z
20
31
  message: 'validation.dateRange',
21
32
  path: ['endDate', 'startDate'],
22
33
  },
23
- );
34
+ )
35
+ .refine(isPageAccompaniedByCount, {
36
+ message: 'validation.pageRequiresCount',
37
+ path: ['page'],
38
+ });
24
39
 
25
40
  const GetReportGroupByClientResponseSchema = z.object({
26
41
  message: z.string().optional(),
27
42
  data: z.array(ClientByWeeksSchema),
43
+ // `total` лежит РЯДОМ с data, а не внутри неё: панель читает `data` как плоский массив строк,
44
+ // и обёртка `{ list, total }` (как в остальных пагинируемых отчётах) сломала бы ей рендер.
45
+ // Без total последняя страница неотличима от полной выдачи.
46
+ total: z.number().describe('Rows in the whole report, before "page"/"count" are applied.'),
28
47
  });
29
48
 
30
49
  export namespace GetReportByClientWeeksContractQuery {
@@ -1,11 +1,30 @@
1
1
  import { z } from 'zod';
2
- import { dateRangeCheck, setEndDay, setStartDay } from '../../helpers/date.helper';
2
+ import { OrderByEnum, ReportSortByEnum } from '../../enum';
3
+ import { dateRangeCheck } from '../../helpers/date.helper';
4
+ import { ReportOrderFilterSchema } from '../../schemas/report/report-order-filter.schema';
3
5
 
4
6
  const GetReportGroupByClientRequestSchema = z
5
7
  .object({
6
- startDate: z.coerce.date().transform(val => (val ? setStartDay(val) : val)),
7
- endDate: z.coerce.date().transform(val => (val ? setEndDay(val) : val)),
8
+ // Даты приходят «сырым» днём — раскладку в полуинтервал [start, endExclusive) делает сервис
9
+ // в таймзоне компании, как в cash-flow. Прежний setStartDay/setEndDay в UTC разворачивал день
10
+ // второй раз, и в таймзоне с плюсовым сдвигом конец периода уезжал на сутки вперёд.
11
+ startDate: z.coerce.date(),
12
+ endDate: z.coerce.date(),
13
+ // Сортировка НЕ имеет значения по умолчанию: без явного sortBy/sortOrder строки отдаются
14
+ // в том порядке, в каком их вернул отчёт (панель рендерит map в порядке ключей, и тихая
15
+ // пересортировка меняла бы ей вид таблицы). Исключение — limit: он срезает хвост, что без
16
+ // сортировки бессмысленно, поэтому при limit применяется порядок «по прибыли, убывание».
17
+ sortBy: z
18
+ .nativeEnum(ReportSortByEnum)
19
+ .optional()
20
+ .describe('Sort metric. Without it (and without "limit") rows keep the report order.'),
21
+ sortOrder: z.nativeEnum(OrderByEnum).optional().describe('Sort direction. Defaults to "desc" once sorting applies.'),
22
+ // Без значения — ограничения нет: панель по-прежнему получает все строки.
23
+ limit: z.coerce.number().int().positive().optional().describe('Keep only the top N rows; implies sorting by gross profit desc.'),
8
24
  })
25
+ // dateBasis / excludeClientUUID общие с sales/summary: обе цифры живут на одном экране и должны
26
+ // сужаться одинаково.
27
+ .merge(ReportOrderFilterSchema)
9
28
  .refine(
10
29
  value => {
11
30
  const { startDate, endDate } = value;
@@ -43,6 +62,10 @@ const GetReportGroupByClientResponseSchema = z.object({
43
62
  marginality: z.number(),
44
63
  }),
45
64
  ),
65
+ // Аддитивно к прежней форме: число клиентов во ВСЁМ отчёте до усечения и применённый limit.
66
+ // Без них усечённый ответ неотличим от полного.
67
+ total: z.number().describe('Client rows in the whole report, before "limit".'),
68
+ limit: z.number().optional().describe('Row limit that actually cut rows off. Absent when the response is complete.'),
46
69
  }),
47
70
  });
48
71
 
@@ -1,13 +1,27 @@
1
1
  import { z } from 'zod';
2
- import { PositionReportTypeEnum } from '../../enum';
3
- import { dateRangeCheck, setEndDay, setStartDay } from '../../helpers/date.helper';
2
+ import { OrderByEnum, PositionReportTypeEnum, ReportSortByEnum } from '../../enum';
3
+ import { dateRangeCheck } from '../../helpers/date.helper';
4
4
 
5
5
  const GetReportGroupByPositionRequestSchema = z
6
6
  .object({
7
7
  type: z.nativeEnum(PositionReportTypeEnum).default(PositionReportTypeEnum.PRODUCT),
8
8
  categoryUUID: z.string().optional(),
9
- startDate: z.coerce.date().transform(val => (val ? setStartDay(val) : val)),
10
- endDate: z.coerce.date().transform(val => (val ? setEndDay(val) : val)),
9
+ // Даты приходят «сырым» днём — раскладку в полуинтервал [start, endExclusive) делает сервис
10
+ // в таймзоне компании, как в cash-flow. Прежний setStartDay/setEndDay в UTC разворачивал день
11
+ // второй раз, и в таймзоне с плюсовым сдвигом конец периода уезжал на сутки вперёд.
12
+ startDate: z.coerce.date(),
13
+ endDate: z.coerce.date(),
14
+ // Сортировка НЕ имеет значения по умолчанию: без явного sortBy/sortOrder строки отдаются
15
+ // в том порядке, в каком их вернул отчёт (панель рендерит map в порядке ключей, и тихая
16
+ // пересортировка меняла бы ей вид таблицы). Исключение — limit: он срезает хвост, что без
17
+ // сортировки бессмысленно, поэтому при limit применяется порядок «по прибыли, убывание».
18
+ sortBy: z
19
+ .nativeEnum(ReportSortByEnum)
20
+ .optional()
21
+ .describe('Sort metric. Without it (and without "limit") rows keep the report order.'),
22
+ sortOrder: z.nativeEnum(OrderByEnum).optional().describe('Sort direction. Defaults to "desc" once sorting applies.'),
23
+ // Без значения — ограничения нет: панель по-прежнему получает все строки.
24
+ limit: z.coerce.number().int().positive().optional().describe('Keep only the top N rows; implies sorting by gross profit desc.'),
11
25
  })
12
26
  .refine(
13
27
  value => {
@@ -67,6 +81,11 @@ const GetReportGroupByPositionResponseSchema = z.object({
67
81
  }),
68
82
  )
69
83
  .optional(),
84
+ // Аддитивно к прежней форме: отчёт отдаёт ЛИБО категории, ЛИБО товары (при categoryUUID),
85
+ // поэтому total относится к той группировке, что вернулась. Вместе с limit это единственный
86
+ // способ отличить усечённый ответ от полного.
87
+ total: z.number().describe('Rows in the whole report (of the returned grouping), before "limit".'),
88
+ limit: z.number().optional().describe('Row limit that actually cut rows off. Absent when the response is complete.'),
70
89
  }),
71
90
  });
72
91
 
@@ -0,0 +1,50 @@
1
+ import { z } from 'zod';
2
+ import { OrderByEnum, ReportSortByEnum } from '../../enum';
3
+ import { dateRangeCheck, isStatementPeriodWithinLimit } from '../../helpers/date.helper';
4
+ import { isPageAccompaniedByCount } from '../../helpers/pagination.helper';
5
+ import { SalesByClientRowSchema } from '../../schemas/report/sales-by-client-row.schema';
6
+ import { ReportOrderFilterSchema } from '../../schemas/report/report-order-filter.schema';
7
+
8
+ const GetSalesByClientRequestSchema = z
9
+ .object({
10
+ startDate: z.coerce.date(),
11
+ endDate: z.coerce.date(),
12
+ // По умолчанию самые прибыльные клиенты сверху, чтобы count срезал хвост, а не топ.
13
+ sortBy: z.nativeEnum(ReportSortByEnum).optional().default(ReportSortByEnum.GROSS_PROFIT),
14
+ sortOrder: z.nativeEnum(OrderByEnum).optional().default(OrderByEnum.DESC),
15
+ // Пагинация по строкам отчёта. Без count лимит не накладывается — отдаём всех клиентов,
16
+ // а page без count отклоняется: иначе листание молча возвращало бы одну и ту же выдачу.
17
+ page: z.coerce.number().int().positive().optional().describe('1-based page number, requires "count".'),
18
+ count: z.coerce.number().int().positive().optional().describe('Rows per page. Without it every client row is returned.'),
19
+ })
20
+ // dateBasis / excludeClientUUID — те же, что у JSON-эндпоинтов отчётов по заказам.
21
+ .merge(ReportOrderFilterSchema)
22
+ .refine(value => dateRangeCheck(value.startDate, value.endDate), {
23
+ message: 'validation.dateRange',
24
+ path: ['endDate', 'startDate'],
25
+ })
26
+ .refine(value => isStatementPeriodWithinLimit(value.startDate, value.endDate), {
27
+ message: 'validation.reportPeriodMax',
28
+ path: ['endDate', 'startDate'],
29
+ })
30
+ .refine(isPageAccompaniedByCount, {
31
+ message: 'validation.pageRequiresCount',
32
+ path: ['page'],
33
+ });
34
+
35
+ const GetSalesByClientResponseSchema = z.object({
36
+ message: z.string().optional(),
37
+ data: z.object({
38
+ list: z.array(SalesByClientRowSchema),
39
+ // Число клиентов во всём отчёте — не размер страницы.
40
+ total: z.number(),
41
+ }),
42
+ });
43
+
44
+ export namespace GetSalesByClientContractQuery {
45
+ export const RequestSchema = GetSalesByClientRequestSchema;
46
+ export type Request = z.infer<typeof RequestSchema>;
47
+
48
+ export const ResponseSchema = GetSalesByClientResponseSchema;
49
+ export type Response = z.infer<typeof ResponseSchema>;
50
+ }
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { dateRangeCheck } from '../../helpers/date.helper';
3
3
  import { ReportPeriodTypeEnum } from '../../enum/report-period-type.enum';
4
+ import { ReportOrderFilterSchema } from '../../schemas/report/report-order-filter.schema';
4
5
 
5
6
  const GetSalesSummaryRequestSchema = z
6
7
  .object({
@@ -8,6 +9,9 @@ const GetSalesSummaryRequestSchema = z
8
9
  endDate: z.coerce.date().optional(),
9
10
  periodType: z.nativeEnum(ReportPeriodTypeEnum).default(ReportPeriodTypeEnum.DAY),
10
11
  })
12
+ // dateBasis / excludeClientUUID общие с group-client: обе цифры живут на одном экране и должны
13
+ // сужаться одинаково.
14
+ .merge(ReportOrderFilterSchema)
11
15
  .refine(
12
16
  value => {
13
17
  const { startDate, endDate } = value;
@@ -12,3 +12,6 @@ export * from './export-client-statement.query';
12
12
  export * from './get-report-by-client-weeks.query';
13
13
  export * from './get-daily-orders-summary.query';
14
14
  export * from './get-cash-flow.query';
15
+ export * from './get-inventory-stock.query';
16
+ export * from './get-inventory-turnover.query';
17
+ export * from './get-sales-by-client.query';
@@ -0,0 +1,24 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Company-level facts every panel role may read: who the company is, how it is named, which time
5
+ * zone its calendar days are counted in and which currency its figures are in. `companyUUID` is
6
+ * echoed so a caller can prove the profile belongs to its own tenant — the ADMIN-only
7
+ * `settings/for-admin` answer carries no such marker and cannot be cross-checked.
8
+ */
9
+ const CompanyProfileSchema = z.object({
10
+ companyUUID: z.string(),
11
+ companyName: z.string().nullable(),
12
+ timeZone: z.string().nullable(),
13
+ currency: z.string().nullable(),
14
+ });
15
+
16
+ const GetCompanyProfileResponseSchema = z.object({
17
+ message: z.string().optional(),
18
+ data: CompanyProfileSchema,
19
+ });
20
+
21
+ export namespace GetCompanyProfileContractQuery {
22
+ export const ResponseSchema = GetCompanyProfileResponseSchema;
23
+ export type Response = z.infer<typeof ResponseSchema>;
24
+ }
@@ -1,3 +1,4 @@
1
1
  export * from './get-settings.query';
2
2
  export * from './update-settings.command';
3
3
  export * from './get-settings-for-admin.query';
4
+ export * from './get-company-profile.query';
package/constant/index.ts CHANGED
@@ -4,3 +4,4 @@ export * from './error-i18n-key';
4
4
  export * from './import.constant';
5
5
  export * from './validation-i18n-key';
6
6
  export * from './validation-i18n-message';
7
+ export * from './report.constant';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Потолок списка исключаемых из отчёта клиентов. Список едет в query-строке и дальше в SQL
3
+ * как `= ANY($n::text[])`, поэтому ограничение защищает и от переполнения URL, и от запроса
4
+ * с массивом в тысячи элементов.
5
+ */
6
+ export const REPORT_EXCLUDE_CLIENT_LIMIT = 500;
@@ -0,0 +1,9 @@
1
+ export enum ClientContractStatusEnum {
2
+ NONE = 'NONE',
3
+ REQUIRED = 'REQUIRED',
4
+ PREPARED = 'PREPARED',
5
+ SENT = 'SENT',
6
+ SIGNED = 'SIGNED',
7
+ EXPIRED = 'EXPIRED',
8
+ TERMINATED = 'TERMINATED',
9
+ }
package/enum/index.ts CHANGED
@@ -36,6 +36,7 @@ export * from './order-distribute-status-list';
36
36
  export * from './order-active-status-list';
37
37
  export * from './order-price-correction-skipped-status-list';
38
38
  export * from './client-status.enum';
39
+ export * from './client-contract-status.enum';
39
40
  export * from './client-type.enum';
40
41
  export * from './consignment-distribution-validation-status.enum';
41
42
  export * from './consignment-distribution-validation-type.enum';
@@ -95,3 +96,6 @@ export * from './legal-identifier-field.enum';
95
96
  export * from './permission-key.enum';
96
97
  export * from './cash-flow-item-status.enum';
97
98
  export * from './payment-invoice-status.enum';
99
+ export * from './order-by.enum';
100
+ export * from './report-sort-by.enum';
101
+ export * from './report-order-date-basis.enum';
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Ось периода для отчётов по заказам — ровно одна дата на отчёт.
3
+ *
4
+ * CREATED_AT — по дате создания заказа (историческое поведение всех отчётов).
5
+ * COMPLETED_AT — по дате отгрузки (завершения); заказ, созданный в июне и отгруженный в июле,
6
+ * попадёт в июль.
7
+ *
8
+ * Дизъюнкции («любая из дат») здесь намеренно нет: заказ, созданный в июне и отгруженный в июле,
9
+ * попал бы в оба месяца, сумма отчётов по месяцам перестала бы сходиться с отчётом за квартал.
10
+ */
11
+ export enum ReportOrderDateBasisEnum {
12
+ CREATED_AT = 'CREATED_AT',
13
+ COMPLETED_AT = 'COMPLETED_AT',
14
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Метрика сортировки для отчётов-группировок (по позициям и по клиентам).
3
+ * Значения совпадают с именами полей ответа, чтобы клиент мог сортировать «по тому, что видит».
4
+ */
5
+ export enum ReportSortByEnum {
6
+ GROSS_PROFIT = 'grossProfit',
7
+ TOTAL_SALES = 'totalSales',
8
+ SOLD_UNITS = 'soldUnits',
9
+ }
package/helpers/index.ts CHANGED
@@ -1 +1,3 @@
1
1
  export * from './date.helper';
2
+ export * from './pagination.helper';
3
+ export * from './query-boolean.helper';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `page` имеет смысл только вместе с `count`.
3
+ *
4
+ * Раньше `page` без `count` молча игнорировался и отчёт отдавался целиком: агент, листающий
5
+ * страницы, бесконечно получал одну и ту же выдачу и не мог отличить это от «страниц больше нет».
6
+ * Поэтому неполная пара отклоняется валидацией — единообразно во всех постраничных отчётах.
7
+ */
8
+ export const isPageAccompaniedByCount = (value: { page?: number; count?: number }): boolean =>
9
+ value.page === undefined || value.count !== undefined;
@@ -0,0 +1,14 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Boolean-флаг, приходящий в query-строке.
5
+ *
6
+ * Не `z.coerce.boolean()`: в query всегда приходит текст, а `Boolean('false') === true` —
7
+ * такой флаг невозможно выключить явным значением. Принимаем `true` / `1` как включение,
8
+ * всё остальное — выключение. По умолчанию флаг выключен, чтобы поведение без параметра не менялось.
9
+ */
10
+ export const queryBooleanSchema = z
11
+ .union([z.boolean(), z.string()])
12
+ .optional()
13
+ .default(false)
14
+ .transform(value => (typeof value === 'boolean' ? value : value === 'true' || value === '1'));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floristcloud/api-lib",
3
- "version": "1.2.107",
3
+ "version": "1.2.109",
4
4
  "description": "",
5
5
  "main": "./build/index.js",
6
6
  "scripts": {
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { ClientStatusEnum } from '../../enum/client-status.enum';
3
+ import { ClientContractStatusEnum } from '../../enum/client-contract-status.enum';
3
4
  import { ClientTypeEnum } from '../../enum/client-type.enum';
4
5
  import { UserSchema } from '../user/user.schema';
5
6
  import { ClientIndividualProfileSchema } from './client-individual-profile.schema';
@@ -17,6 +18,7 @@ export const ClientSchema = z.object({
17
18
  isCommon: z.boolean(),
18
19
  contractNumber: z.string().nullable(),
19
20
  contractDate: z.date().nullable(),
21
+ contractStatus: z.nativeEnum(ClientContractStatusEnum),
20
22
  address: z.string().nullable(),
21
23
  city: z.string().nullable(),
22
24
  code: z.string().nullable(),
package/schemas/index.ts CHANGED
@@ -22,6 +22,7 @@ export * from './product-image/product-image.schema';
22
22
  export * from './settings/settings.schema';
23
23
  export * from './payment-invoice/payment-invoice.schema';
24
24
  export * from './money-account/money-account.schema';
25
+ export * from './money-account/money-account-with-balance.schema';
25
26
  export * from './domain/domain.schema';
26
27
  export * from './category/category.schema';
27
28
  export * from './branch/branch.schema';
@@ -52,6 +53,12 @@ export * from './consignment/consignment-distribution-validation.schema';
52
53
  export * from './product-image-template/product-image-template.schema';
53
54
  export * from './report/client-statement.schema';
54
55
  export * from './report/client-by-weeks.schema';
56
+ export * from './report/inventory-stock-category-item.schema';
57
+ export * from './report/inventory-stock-detailed-item.schema';
58
+ export * from './report/inventory-turnover-category-item.schema';
59
+ export * from './report/inventory-turnover-detailed-item.schema';
60
+ export * from './report/sales-by-client-top-item.schema';
61
+ export * from './report/sales-by-client-row.schema';
55
62
  export * from './action-log/index';
56
63
  export * from './delivery-route/delivery-route.schema';
57
64
  export * from './product/product-multiplicity-option.schema';
@@ -70,3 +77,4 @@ export * from './account-deletion-request/account-deletion-request.schema';
70
77
  export * from './consignment-transfer';
71
78
  export * from './api-error.schema';
72
79
  export * from './access-policy';
80
+ export * from './report/report-order-filter.schema';
@@ -0,0 +1,11 @@
1
+ import { z } from 'zod';
2
+ import { MoneyAccountSchema } from './money-account.schema';
3
+
4
+ /**
5
+ * Денежный счёт в ответах списков. `balance` — текущий остаток счёта (приход минус расход),
6
+ * приходит только при `?withBalance=true`: поле аддитивное, клиенты без этого параметра
7
+ * получают ровно прежнюю форму ответа.
8
+ */
9
+ export const MoneyAccountWithBalanceSchema = MoneyAccountSchema.extend({
10
+ balance: z.number().optional(),
11
+ });
@@ -0,0 +1,8 @@
1
+ import { z } from 'zod';
2
+
3
+ /** Строка отчёта об остатках в разрезе категорий (`detailed=false`). */
4
+ export const InventoryStockCategoryItemSchema = z.object({
5
+ categoryUUID: z.string(),
6
+ categoryName: z.string(),
7
+ balance: z.number(),
8
+ });
@@ -0,0 +1,12 @@
1
+ import { z } from 'zod';
2
+
3
+ /** Строка отчёта об остатках с детализацией по name/size/grower (`detailed=true`). */
4
+ export const InventoryStockDetailedItemSchema = z.object({
5
+ categoryUUID: z.string(),
6
+ categoryName: z.string(),
7
+ name: z.string(),
8
+ color: z.string().nullable(),
9
+ size: z.string().nullable(),
10
+ grower: z.string().nullable(),
11
+ balance: z.number(),
12
+ });
@@ -0,0 +1,13 @@
1
+ import { z } from 'zod';
2
+
3
+ /** Строка отчёта об оборачиваемости в разрезе категорий (`detailed=false`). */
4
+ export const InventoryTurnoverCategoryItemSchema = z.object({
5
+ categoryUUID: z.string(),
6
+ categoryName: z.string(),
7
+ initialBalance: z.number(), // начальный остаток
8
+ receipts: z.number(), // приходы
9
+ sales: z.number(), // продажи
10
+ currentBalance: z.number(), // текущий остаток
11
+ daysInStock: z.number(), // дни в наличии на складе
12
+ turnoverRate: z.number(), // коэффициент оборачиваемости
13
+ });
@@ -0,0 +1,17 @@
1
+ import { z } from 'zod';
2
+
3
+ /** Строка отчёта об оборачиваемости с детализацией по name/size/grower (`detailed=true`). */
4
+ export const InventoryTurnoverDetailedItemSchema = z.object({
5
+ categoryUUID: z.string(),
6
+ categoryName: z.string(),
7
+ name: z.string(),
8
+ color: z.string().nullable(),
9
+ size: z.string().nullable(),
10
+ grower: z.string().nullable(), // производитель
11
+ initialBalance: z.number(), // начальный остаток
12
+ receipts: z.number(), // приходы
13
+ sales: z.number(), // продажи
14
+ currentBalance: z.number(), // текущий остаток
15
+ daysInStock: z.number(), // дни в наличии на складе
16
+ turnoverRate: z.number(), // коэффициент оборачиваемости
17
+ });
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod';
2
+ import { ReportOrderDateBasisEnum } from '../../enum';
3
+ import { REPORT_EXCLUDE_CLIENT_LIMIT } from '../../constant/report.constant';
4
+
5
+ /**
6
+ * Общие фильтры отчётов, построенных на заказах: по какой дате заказ попадает в период и каких
7
+ * клиентов из него выкинуть. Схема одна на все такие отчёты — иначе `sales/summary` и
8
+ * `group-client` на одном экране разошлись бы в семантике при первой же правке.
9
+ *
10
+ * `excludeClientUUID` — типовой случай «отгружаем по себестоимости, в прибыли не учитываем».
11
+ * Принимается и CSV (`?excludeClientUUID=uuid1,uuid2`, как в get-notifications-status), и повтор
12
+ * параметра (`?excludeClientUUID=uuid1&excludeClientUUID=uuid2`) — Express отдаёт второй вариант
13
+ * массивом, и требовать от фронта именно CSV незачем.
14
+ */
15
+ export const ReportOrderFilterSchema = z.object({
16
+ dateBasis: z
17
+ .nativeEnum(ReportOrderDateBasisEnum)
18
+ .default(ReportOrderDateBasisEnum.CREATED_AT)
19
+ .describe('Which order date puts the order into the period. Defaults to the order creation date.'),
20
+ excludeClientUUID: z
21
+ .union([z.string(), z.array(z.string())])
22
+ .transform(value => (Array.isArray(value) ? value : value.split(',')).map(item => item.trim()).filter(Boolean))
23
+ .pipe(z.array(z.string().uuid()).max(REPORT_EXCLUDE_CLIENT_LIMIT))
24
+ .optional()
25
+ .describe('Clients to drop from the report entirely — their orders, revenue and cost.'),
26
+ });
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+ import { SalesByClientTopItemSchema } from './sales-by-client-top-item.schema';
3
+
4
+ /**
5
+ * Строка отчёта «продажи по клиентам» — те же данные, что уходят в Excel из `export/sales/clients`.
6
+ * Опциональные поля отсутствуют в ответе, когда у клиента нет соответствующего значения.
7
+ */
8
+ export const SalesByClientRowSchema = z.object({
9
+ uuid: z.string(),
10
+ clientName: z.string(),
11
+ responsibleUserName: z.string().optional(),
12
+ totalOrders: z.number(),
13
+ soldUnits: z.number(),
14
+ soldUnitsByUnit: z.object({
15
+ PIECE: z.number(),
16
+ PACK: z.number(),
17
+ BOX: z.number(),
18
+ }),
19
+ totalSales: z.number(),
20
+ avgCheck: z.number(),
21
+ totalWriteOff: z.number(),
22
+ grossProfit: z.number(),
23
+ marginality: z.number(),
24
+ // Оплаты (INCOME) и предоплаты (PREPAYMENT) клиента за период
25
+ totalPayments: z.number(),
26
+ totalPrepayments: z.number(),
27
+ // Сумма услуг (order_service_line) за период — отдельно, вне товарных sales/margin
28
+ totalServiceAmount: z.number(),
29
+ // Текущий баланс клиента (на момент формирования отчёта)
30
+ balance: z.number(),
31
+ lastOrderDate: z.coerce.date().optional(),
32
+ // Топ-5 по сумме выручки за период
33
+ topCategories: z.array(SalesByClientTopItemSchema),
34
+ topProducts: z.array(SalesByClientTopItemSchema),
35
+ // Статическая информация о клиенте
36
+ code: z.string().optional(),
37
+ city: z.string().optional(),
38
+ contactName: z.string().optional(),
39
+ phone: z.string().optional(),
40
+ clientType: z.string().optional(),
41
+ status: z.string().optional(),
42
+ group: z.string().optional(),
43
+ });
@@ -0,0 +1,7 @@
1
+ import { z } from 'zod';
2
+
3
+ /** Элемент топа (категория или товар) внутри строки отчёта «продажи по клиентам». */
4
+ export const SalesByClientTopItemSchema = z.object({
5
+ name: z.string(),
6
+ amount: z.number(),
7
+ });