@grapadigital/shared-schemas 1.0.242 → 1.1.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.
Files changed (150) hide show
  1. package/dist/index.d.ts +42 -42
  2. package/dist/schemas/action.schema.d.ts +9 -34
  3. package/dist/schemas/action.schema.js +81 -64
  4. package/dist/schemas/assignment.schema.d.ts +3 -28
  5. package/dist/schemas/assignment.schema.js +44 -44
  6. package/dist/schemas/attachment.schema.d.ts +13 -0
  7. package/dist/schemas/attachment.schema.js +28 -0
  8. package/dist/schemas/benchmark.schema.d.ts +3 -28
  9. package/dist/schemas/benchmark.schema.js +11 -6
  10. package/dist/schemas/campaign.schema.d.ts +2 -27
  11. package/dist/schemas/campaign.schema.js +4 -4
  12. package/dist/schemas/client.schema.d.ts +18 -79
  13. package/dist/schemas/client.schema.js +73 -71
  14. package/dist/schemas/comment.schema.d.ts +5 -30
  15. package/dist/schemas/comment.schema.js +42 -37
  16. package/dist/schemas/commission.schema.d.ts +5 -30
  17. package/dist/schemas/commission.schema.js +10 -10
  18. package/dist/schemas/content-capture-process.schema.d.ts +6 -31
  19. package/dist/schemas/content-capture-process.schema.js +24 -17
  20. package/dist/schemas/content-draft.schema.d.ts +2 -27
  21. package/dist/schemas/content-draft.schema.js +5 -5
  22. package/dist/schemas/content.schema.d.ts +6 -31
  23. package/dist/schemas/content.schema.js +84 -74
  24. package/dist/schemas/contract.schema.d.ts +3 -28
  25. package/dist/schemas/contract.schema.js +5 -5
  26. package/dist/schemas/creative.schema.d.ts +6 -31
  27. package/dist/schemas/creative.schema.js +22 -31
  28. package/dist/schemas/export-comments-job.schema.d.ts +2 -27
  29. package/dist/schemas/export-comments-job.schema.js +6 -6
  30. package/dist/schemas/group.schema.d.ts +1 -26
  31. package/dist/schemas/group.schema.js +5 -5
  32. package/dist/schemas/influencer.schema.d.ts +6 -31
  33. package/dist/schemas/influencer.schema.js +16 -18
  34. package/dist/schemas/invoice.schema.d.ts +4 -29
  35. package/dist/schemas/invoice.schema.js +42 -32
  36. package/dist/schemas/job.schema.d.ts +2 -27
  37. package/dist/schemas/job.schema.js +14 -14
  38. package/dist/schemas/lead.schema.d.ts +1 -26
  39. package/dist/schemas/lead.schema.js +67 -64
  40. package/dist/schemas/log.schema.d.ts +1 -26
  41. package/dist/schemas/log.schema.js +24 -24
  42. package/dist/schemas/note.schema.d.ts +1 -26
  43. package/dist/schemas/note.schema.js +9 -9
  44. package/dist/schemas/notifications.schema.d.ts +1 -26
  45. package/dist/schemas/notifications.schema.js +8 -8
  46. package/dist/schemas/organization.schema.d.ts +2 -26
  47. package/dist/schemas/organization.schema.js +8 -4
  48. package/dist/schemas/party.schema.d.ts +1 -26
  49. package/dist/schemas/party.schema.js +11 -11
  50. package/dist/schemas/payment.schema.d.ts +12 -49
  51. package/dist/schemas/payment.schema.js +66 -69
  52. package/dist/schemas/profile.schema.d.ts +3 -28
  53. package/dist/schemas/profile.schema.js +6 -6
  54. package/dist/schemas/project.schema.d.ts +4 -29
  55. package/dist/schemas/project.schema.js +13 -13
  56. package/dist/schemas/prospect.schema.d.ts +3 -28
  57. package/dist/schemas/prospect.schema.js +9 -9
  58. package/dist/schemas/recruitment.schema.d.ts +5 -30
  59. package/dist/schemas/recruitment.schema.js +36 -36
  60. package/dist/schemas/responsible.schema.d.ts +0 -26
  61. package/dist/schemas/responsible.schema.js +6 -6
  62. package/dist/schemas/sale.schema.d.ts +31 -46
  63. package/dist/schemas/sale.schema.js +66 -62
  64. package/dist/schemas/script.schema.d.ts +6 -31
  65. package/dist/schemas/script.schema.js +21 -30
  66. package/dist/schemas/snapshot.schema.d.ts +3 -28
  67. package/dist/schemas/snapshot.schema.js +6 -6
  68. package/dist/schemas/store-visit.schema.d.ts +2 -27
  69. package/dist/schemas/store-visit.schema.js +21 -17
  70. package/dist/schemas/store.schema.d.ts +3 -28
  71. package/dist/schemas/store.schema.js +8 -8
  72. package/dist/schemas/supplier.schema.d.ts +2 -27
  73. package/dist/schemas/supplier.schema.js +3 -3
  74. package/dist/schemas/tag.schema.d.ts +1 -26
  75. package/dist/schemas/tag.schema.js +5 -5
  76. package/dist/schemas/task.schema.d.ts +9 -34
  77. package/dist/schemas/task.schema.js +67 -67
  78. package/dist/schemas/token.schema.d.ts +1 -26
  79. package/dist/schemas/token.schema.js +3 -3
  80. package/dist/schemas/trigger.schema.d.ts +2 -27
  81. package/dist/schemas/trigger.schema.js +5 -5
  82. package/dist/schemas/user.schema.d.ts +2 -27
  83. package/dist/schemas/user.schema.js +7 -7
  84. package/dist/schemas/webhook.schema.d.ts +1 -26
  85. package/dist/schemas/webhook.schema.js +10 -10
  86. package/dist/utils/merge-metrics-breakdown.util.d.ts +1 -1
  87. package/dist/utils/merge-metrics-breakdown.util.js +7 -2
  88. package/dist/utils/normalize-content-link.util.js +7 -7
  89. package/package.json +22 -10
  90. package/.eslintrc.json +0 -28
  91. package/.prettierrc +0 -4
  92. package/dist/schemas/profile-followers-snapshot.schema.d.ts +0 -67
  93. package/dist/schemas/profile-followers-snapshot.schema.js +0 -65
  94. package/dist/schemas/schedule.schema.d.ts +0 -73
  95. package/dist/schemas/schedule.schema.js +0 -116
  96. package/dist/utils/cost-per-impact.util.d.ts +0 -37
  97. package/dist/utils/cost-per-impact.util.js +0 -72
  98. package/dist/utils/influencer-contract.util.d.ts +0 -32
  99. package/dist/utils/influencer-contract.util.js +0 -77
  100. package/docs/code-review.md +0 -27
  101. package/docs/constitution.md +0 -75
  102. package/docs/specs/GD-692.md +0 -112
  103. package/docs/specs/GD-761.md +0 -94
  104. package/index.d.ts +0 -3
  105. package/src/index.ts +0 -42
  106. package/src/schemas/action.schema.ts +0 -328
  107. package/src/schemas/assignment.schema.ts +0 -154
  108. package/src/schemas/benchmark.schema.ts +0 -39
  109. package/src/schemas/campaign.schema.ts +0 -38
  110. package/src/schemas/client.schema.ts +0 -319
  111. package/src/schemas/comment.schema.ts +0 -216
  112. package/src/schemas/commission.schema.ts +0 -108
  113. package/src/schemas/content-capture-process.schema.ts +0 -195
  114. package/src/schemas/content-draft.schema.ts +0 -49
  115. package/src/schemas/content.schema.ts +0 -688
  116. package/src/schemas/contract.schema.ts +0 -44
  117. package/src/schemas/creative.schema.ts +0 -256
  118. package/src/schemas/export-comments-job.schema.ts +0 -59
  119. package/src/schemas/group.schema.ts +0 -23
  120. package/src/schemas/influencer.schema.ts +0 -184
  121. package/src/schemas/invoice.schema.ts +0 -164
  122. package/src/schemas/job.schema.ts +0 -111
  123. package/src/schemas/lead.schema.ts +0 -372
  124. package/src/schemas/log.schema.ts +0 -91
  125. package/src/schemas/note.schema.ts +0 -34
  126. package/src/schemas/notifications.schema.ts +0 -61
  127. package/src/schemas/organization.schema.ts +0 -29
  128. package/src/schemas/party.schema.ts +0 -65
  129. package/src/schemas/payment.schema.ts +0 -275
  130. package/src/schemas/profile.schema.ts +0 -77
  131. package/src/schemas/project.schema.ts +0 -116
  132. package/src/schemas/prospect.schema.ts +0 -62
  133. package/src/schemas/recruitment.schema.ts +0 -277
  134. package/src/schemas/responsible.schema.ts +0 -27
  135. package/src/schemas/sale.schema.ts +0 -297
  136. package/src/schemas/script.schema.ts +0 -235
  137. package/src/schemas/snapshot.schema.ts +0 -55
  138. package/src/schemas/store-visit.schema.ts +0 -68
  139. package/src/schemas/store.schema.ts +0 -52
  140. package/src/schemas/supplier.schema.ts +0 -12
  141. package/src/schemas/tag.schema.ts +0 -26
  142. package/src/schemas/task.schema.ts +0 -205
  143. package/src/schemas/token.schema.ts +0 -42
  144. package/src/schemas/trigger.schema.ts +0 -48
  145. package/src/schemas/user.schema.ts +0 -59
  146. package/src/schemas/webhook.schema.ts +0 -81
  147. package/src/utils/merge-metrics-breakdown.util.ts +0 -51
  148. package/src/utils/normalize-content-link.util.ts +0 -31
  149. package/tsconfig.build.json +0 -5
  150. package/tsconfig.json +0 -29
@@ -1,116 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.ScheduleModel = exports.ScheduleSchema = exports.Schedule = void 0;
13
- const mongoose_1 = require("@nestjs/mongoose");
14
- const swagger_1 = require("@nestjs/swagger");
15
- const mongoose_2 = require("mongoose");
16
- let Schedule = class Schedule {
17
- };
18
- __decorate([
19
- (0, swagger_1.ApiProperty)({ example: '64bfc3a78d3f1e2a12345670' }),
20
- (0, mongoose_1.Prop)({ type: mongoose_2.Schema.Types.ObjectId, auto: true, required: false }),
21
- __metadata("design:type", mongoose_2.Types.ObjectId)
22
- ], Schedule.prototype, "_id", void 0);
23
- __decorate([
24
- (0, swagger_1.ApiProperty)({ example: '64bfc3a78d3f1e2a12345678' }),
25
- (0, mongoose_1.Prop)({ type: mongoose_2.Schema.Types.ObjectId, ref: 'Recruitment', required: true }),
26
- __metadata("design:type", Object)
27
- ], Schedule.prototype, "recruitment", void 0);
28
- __decorate([
29
- (0, swagger_1.ApiProperty)({ example: '64bfc3a78d3f1e2a12345679' }),
30
- (0, mongoose_1.Prop)({ type: mongoose_2.Schema.Types.ObjectId, ref: 'Profile', required: true }),
31
- __metadata("design:type", Object)
32
- ], Schedule.prototype, "profile", void 0);
33
- __decorate([
34
- (0, swagger_1.ApiProperty)({ example: '64bfc3a78d3f1e2a12345683' }),
35
- (0, mongoose_1.Prop)({ type: mongoose_2.Schema.Types.ObjectId, ref: 'Influencer', required: true }),
36
- __metadata("design:type", Object)
37
- ], Schedule.prototype, "influencer", void 0);
38
- __decorate([
39
- (0, swagger_1.ApiProperty)({ example: 'instagram' }),
40
- (0, mongoose_1.Prop)({ type: String, required: true }),
41
- __metadata("design:type", String)
42
- ], Schedule.prototype, "socialnetwork", void 0);
43
- __decorate([
44
- (0, swagger_1.ApiProperty)({ enum: ['post', 'task'], example: 'post' }),
45
- (0, mongoose_1.Prop)({ type: String, enum: ['post', 'task'], required: true }),
46
- __metadata("design:type", String)
47
- ], Schedule.prototype, "type", void 0);
48
- __decorate([
49
- (0, swagger_1.ApiProperty)({ example: 'reel', required: false }),
50
- (0, mongoose_1.Prop)({
51
- type: String,
52
- required: function () {
53
- return this.type === 'post';
54
- },
55
- }),
56
- __metadata("design:type", String)
57
- ], Schedule.prototype, "format", void 0);
58
- __decorate([
59
- (0, swagger_1.ApiProperty)({ example: 'Mostrar o produto em uso, destacar a promoção', required: false }),
60
- (0, mongoose_1.Prop)({ type: String, required: false }),
61
- __metadata("design:type", String)
62
- ], Schedule.prototype, "briefing", void 0);
63
- __decorate([
64
- (0, swagger_1.ApiProperty)({ example: '@marca, #publi, #ad', required: false }),
65
- (0, mongoose_1.Prop)({ type: String, required: false }),
66
- __metadata("design:type", String)
67
- ], Schedule.prototype, "requiredTags", void 0);
68
- __decorate([
69
- (0, swagger_1.ApiProperty)({ example: 'https://drive.google.com/...', required: false }),
70
- (0, mongoose_1.Prop)({ type: String, required: false }),
71
- __metadata("design:type", String)
72
- ], Schedule.prototype, "referenceLink", void 0);
73
- __decorate([
74
- (0, swagger_1.ApiProperty)({ example: 'Confirmar com o cliente antes de publicar', required: false }),
75
- (0, mongoose_1.Prop)({ type: String, required: false }),
76
- __metadata("design:type", String)
77
- ], Schedule.prototype, "observation", void 0);
78
- __decorate([
79
- (0, swagger_1.ApiProperty)({ example: '2025-11-05T14:00:00.000Z' }),
80
- (0, mongoose_1.Prop)({ type: Date, required: true }),
81
- __metadata("design:type", Date)
82
- ], Schedule.prototype, "scheduledAt", void 0);
83
- __decorate([
84
- (0, swagger_1.ApiProperty)({ enum: ['scheduled', 'published', 'late', 'cancelled'], example: 'scheduled' }),
85
- (0, mongoose_1.Prop)({
86
- type: String,
87
- enum: ['scheduled', 'published', 'late', 'cancelled'],
88
- required: true,
89
- }),
90
- __metadata("design:type", String)
91
- ], Schedule.prototype, "status", void 0);
92
- __decorate([
93
- (0, swagger_1.ApiProperty)({ example: '64bfc3a78d3f1e2a12345680', required: false }),
94
- (0, mongoose_1.Prop)({ type: mongoose_2.Schema.Types.ObjectId, ref: 'Content', required: false }),
95
- __metadata("design:type", Object)
96
- ], Schedule.prototype, "contentId", void 0);
97
- __decorate([
98
- (0, swagger_1.ApiProperty)({ example: '64bfc3a78d3f1e2a12345681' }),
99
- (0, mongoose_1.Prop)({ type: mongoose_2.Schema.Types.ObjectId, ref: 'Action', required: true }),
100
- __metadata("design:type", Object)
101
- ], Schedule.prototype, "action", void 0);
102
- __decorate([
103
- (0, swagger_1.ApiProperty)({ example: '64bfc3a78d3f1e2a12345682' }),
104
- (0, mongoose_1.Prop)({ type: mongoose_2.Schema.Types.ObjectId, ref: 'Client', required: true }),
105
- __metadata("design:type", Object)
106
- ], Schedule.prototype, "client", void 0);
107
- Schedule = __decorate([
108
- (0, mongoose_1.Schema)({ timestamps: true })
109
- ], Schedule);
110
- exports.Schedule = Schedule;
111
- exports.ScheduleSchema = mongoose_1.SchemaFactory.createForClass(Schedule);
112
- exports.ScheduleSchema.index({ action: 1, scheduledAt: 1 });
113
- exports.ScheduleSchema.index({ client: 1 });
114
- exports.ScheduleSchema.index({ recruitment: 1 });
115
- exports.ScheduleSchema.index({ influencer: 1 });
116
- exports.ScheduleModel = (0, mongoose_2.model)('Schedule', exports.ScheduleSchema);
@@ -1,37 +0,0 @@
1
- import { InfluencerContract } from '../schemas/influencer.schema';
2
- export declare const getEngagementRatePercent: (totals: {
3
- engagement: number;
4
- potentialReach: number;
5
- }) => number | null;
6
- export declare const getCostPerImpact: (input: {
7
- value: number;
8
- engagementRatePercent: number | null;
9
- impressions: number;
10
- posts: number;
11
- }) => number | null;
12
- export interface ContractMonthTotals {
13
- year: number;
14
- month: number;
15
- posts: number;
16
- impressions: number;
17
- engagement: number;
18
- potentialReach: number;
19
- }
20
- export interface MonthlyCostPerImpact extends ContractMonthTotals {
21
- monthlyValue: number;
22
- monthlyCostPerImpact: number | null;
23
- engagementRatePercent: number | null;
24
- elapsedMonths: number;
25
- accumulatedSpend: number;
26
- }
27
- /**
28
- * Série mensal acumulada desde o mês de início até `untilMonth` (inclusive):
29
- * gasto acumulado = valor mensal × meses decorridos; métricas somadas desde o
30
- * início. `monthlyTotals` traz os totais de cada mês (não acumulados).
31
- */
32
- export declare const getMonthlyCostPerImpactSeries: (contract: Pick<InfluencerContract, 'value' | 'productsValue' | 'startDate' | 'endDate' | 'amendments' | 'status' | 'isActive'>, monthlyTotals: ContractMonthTotals[], until: {
33
- year: number;
34
- month: number;
35
- }) => MonthlyCostPerImpact[];
36
- /** Média dos CPIs mensais não nulos. */
37
- export declare const getAverageMonthlyCostPerImpact: (series: MonthlyCostPerImpact[]) => number | null;
@@ -1,72 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAverageMonthlyCostPerImpact = exports.getMonthlyCostPerImpactSeries = exports.getCostPerImpact = exports.getEngagementRatePercent = void 0;
4
- const influencer_contract_util_1 = require("./influencer-contract.util");
5
- /**
6
- * CPI (Custo por Impacto), como no genc (`TB_Contratos_Influencer_Cliente` e
7
- * `TB_CPI_Mensal_Contrato`). Ver GD-715.
8
- * CPI = valor ÷ ((E/R% ÷ 100) × impressões × posts), E/R% = engajamento ÷ alcance potencial × 100.
9
- */
10
- const round = (value, places) => Math.round(value * 10 ** places) / 10 ** places;
11
- const getEngagementRatePercent = (totals) => totals.potentialReach > 0 ? (totals.engagement / totals.potentialReach) * 100 : null;
12
- exports.getEngagementRatePercent = getEngagementRatePercent;
13
- const getCostPerImpact = (input) => {
14
- const { value, engagementRatePercent, impressions, posts } = input;
15
- if (!engagementRatePercent || engagementRatePercent <= 0 || value <= 0)
16
- return null;
17
- const divisor = (engagementRatePercent / 100) * impressions * posts;
18
- return divisor > 0 ? round(value / divisor, 6) : null;
19
- };
20
- exports.getCostPerImpact = getCostPerImpact;
21
- /**
22
- * Série mensal acumulada desde o mês de início até `untilMonth` (inclusive):
23
- * gasto acumulado = valor mensal × meses decorridos; métricas somadas desde o
24
- * início. `monthlyTotals` traz os totais de cada mês (não acumulados).
25
- */
26
- const getMonthlyCostPerImpactSeries = (contract, monthlyTotals, until) => {
27
- const brt = new Date(new Date(contract.startDate).getTime() - 3 * 60 * 60 * 1000);
28
- let year = brt.getUTCFullYear();
29
- let month = brt.getUTCMonth() + 1;
30
- const monthlyValue = (0, influencer_contract_util_1.getContractMonthlyValue)(contract);
31
- const byMonth = new Map(monthlyTotals.map((t) => [`${t.year}-${t.month}`, t]));
32
- const acc = { posts: 0, impressions: 0, engagement: 0, potentialReach: 0 };
33
- const series = [];
34
- let elapsedMonths = 0;
35
- while (year < until.year || (year === until.year && month <= until.month)) {
36
- elapsedMonths += 1;
37
- const totals = byMonth.get(`${year}-${month}`);
38
- if (totals) {
39
- acc.posts += totals.posts;
40
- acc.impressions += totals.impressions;
41
- acc.engagement += totals.engagement;
42
- acc.potentialReach += totals.potentialReach;
43
- }
44
- const accumulatedSpend = round(monthlyValue * elapsedMonths, 2);
45
- const engagementRatePercent = acc.posts > 0 ? (0, exports.getEngagementRatePercent)(acc) : null;
46
- series.push({
47
- year,
48
- month,
49
- ...acc,
50
- monthlyValue,
51
- elapsedMonths,
52
- accumulatedSpend,
53
- engagementRatePercent: engagementRatePercent == null ? null : round(engagementRatePercent, 4),
54
- monthlyCostPerImpact: acc.posts > 0 && acc.engagement > 0
55
- ? (0, exports.getCostPerImpact)({ value: accumulatedSpend, engagementRatePercent, impressions: acc.impressions, posts: acc.posts })
56
- : null,
57
- });
58
- month += 1;
59
- if (month > 12) {
60
- month = 1;
61
- year += 1;
62
- }
63
- }
64
- return series;
65
- };
66
- exports.getMonthlyCostPerImpactSeries = getMonthlyCostPerImpactSeries;
67
- /** Média dos CPIs mensais não nulos. */
68
- const getAverageMonthlyCostPerImpact = (series) => {
69
- const values = series.map((row) => row.monthlyCostPerImpact).filter((v) => v != null);
70
- return values.length > 0 ? round(values.reduce((a, b) => a + b, 0) / values.length, 6) : null;
71
- };
72
- exports.getAverageMonthlyCostPerImpact = getAverageMonthlyCostPerImpact;
@@ -1,32 +0,0 @@
1
- import { InfluencerContract } from '../schemas/influencer.schema';
2
- type ContractLike = Pick<InfluencerContract, 'value' | 'productsValue' | 'startDate' | 'endDate' | 'amendments' | 'status' | 'isActive'> & {
3
- client?: unknown;
4
- };
5
- /**
6
- * Fim efetivo da vigência: o maior entre o fim do Contrato e o fim dos Aditivos
7
- * ativos (o Aditivo estende a vigência). null = Contrato em aberto, mesmo com
8
- * Aditivo. Ver GD-715.
9
- */
10
- export declare const getContractEndDate: (contract: ContractLike) => Date | null;
11
- /**
12
- * Início do dia seguinte ao fim da vigência em São Paulo (limite exclusivo):
13
- * o último dia conta inteiro. null = Contrato em aberto.
14
- */
15
- export declare const getContractEndExclusive: (contract: ContractLike) => Date | null;
16
- /**
17
- * Meses de vigência como no genc (`calcular_meses_vigencia`): anos × 12 + meses
18
- * e mais 1 se sobrar dia; mínimo 1. Sem fim, conta até `now`.
19
- * Ex.: 10/06/2025 a 11/02/2027 = 21; 15/03 a 14/09 = 6.
20
- */
21
- export declare const getContractMonths: (contract: ContractLike, now?: Date) => number;
22
- /** Cachê + produtos + Aditivos ativos. */
23
- export declare const getContractTotalValue: (contract: ContractLike) => number;
24
- /** Total ÷ meses de vigência, 2 casas (428.392,93 ÷ 21 = 20.399,66). */
25
- export declare const getContractMonthlyValue: (contract: ContractLike, now?: Date) => number;
26
- /** Ativo e assinado (status ausente conta como assinado). */
27
- export declare const isContractUsable: (contract: ContractLike) => boolean;
28
- /** Contrato usável do cliente vigente em `at`, com o último dia inteiro (sem fim = em aberto). */
29
- export declare const getActiveContract: <T extends ContractLike>(influencer: {
30
- contracts?: T[] | null | undefined;
31
- } | null | undefined, clientId: unknown, at: Date) => T | null;
32
- export {};
@@ -1,77 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getActiveContract = exports.isContractUsable = exports.getContractMonthlyValue = exports.getContractTotalValue = exports.getContractMonths = exports.getContractEndExclusive = exports.getContractEndDate = void 0;
4
- const BRT_OFFSET_MS = 3 * 60 * 60 * 1000;
5
- /** Data no calendário de São Paulo (as datas do Flow são gravadas à meia-noite BRT = 03:00Z). */
6
- const brtParts = (date) => {
7
- const d = new Date(new Date(date).getTime() - BRT_OFFSET_MS);
8
- return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate() };
9
- };
10
- const round2 = (value) => Math.round(value * 100) / 100;
11
- const activeAmendments = (contract) => (contract.amendments ?? []).filter((amendment) => amendment.isActive !== false);
12
- /**
13
- * Fim efetivo da vigência: o maior entre o fim do Contrato e o fim dos Aditivos
14
- * ativos (o Aditivo estende a vigência). null = Contrato em aberto, mesmo com
15
- * Aditivo. Ver GD-715.
16
- */
17
- const getContractEndDate = (contract) => {
18
- if (!contract.endDate)
19
- return null;
20
- const ends = [contract.endDate, ...activeAmendments(contract).map((a) => a.endDate)]
21
- .filter((date) => !!date)
22
- .map((date) => new Date(date).getTime());
23
- return new Date(Math.max(...ends));
24
- };
25
- exports.getContractEndDate = getContractEndDate;
26
- /**
27
- * Início do dia seguinte ao fim da vigência em São Paulo (limite exclusivo):
28
- * o último dia conta inteiro. null = Contrato em aberto.
29
- */
30
- const getContractEndExclusive = (contract) => {
31
- const end = (0, exports.getContractEndDate)(contract);
32
- if (!end)
33
- return null;
34
- const { year, month, day } = brtParts(end);
35
- return new Date(Date.UTC(year, month - 1, day + 1) + BRT_OFFSET_MS);
36
- };
37
- exports.getContractEndExclusive = getContractEndExclusive;
38
- /**
39
- * Meses de vigência como no genc (`calcular_meses_vigencia`): anos × 12 + meses
40
- * e mais 1 se sobrar dia; mínimo 1. Sem fim, conta até `now`.
41
- * Ex.: 10/06/2025 a 11/02/2027 = 21; 15/03 a 14/09 = 6.
42
- */
43
- const getContractMonths = (contract, now = new Date()) => {
44
- const start = brtParts(contract.startDate);
45
- const end = brtParts((0, exports.getContractEndDate)(contract) ?? now);
46
- let months = (end.year - start.year) * 12 + (end.month - start.month);
47
- // relativedelta: dia do fim menor tira um mês e sobra dia, que devolve o mês.
48
- if (end.day > start.day)
49
- months += 1;
50
- return Math.max(1, months);
51
- };
52
- exports.getContractMonths = getContractMonths;
53
- /** Cachê + produtos + Aditivos ativos. */
54
- const getContractTotalValue = (contract) => round2((contract.value ?? 0) +
55
- (contract.productsValue ?? 0) +
56
- activeAmendments(contract).reduce((sum, a) => sum + (a.value ?? 0), 0));
57
- exports.getContractTotalValue = getContractTotalValue;
58
- /** Total ÷ meses de vigência, 2 casas (428.392,93 ÷ 21 = 20.399,66). */
59
- const getContractMonthlyValue = (contract, now) => round2((0, exports.getContractTotalValue)(contract) / (0, exports.getContractMonths)(contract, now));
60
- exports.getContractMonthlyValue = getContractMonthlyValue;
61
- /** Ativo e assinado (status ausente conta como assinado). */
62
- const isContractUsable = (contract) => contract.isActive !== false && (contract.status ?? 'signed') === 'signed';
63
- exports.isContractUsable = isContractUsable;
64
- /** Contrato usável do cliente vigente em `at`, com o último dia inteiro (sem fim = em aberto). */
65
- const getActiveContract = (influencer, clientId, at) => {
66
- const time = new Date(at).getTime();
67
- return ((influencer?.contracts ?? []).find((contract) => {
68
- if (!(0, exports.isContractUsable)(contract))
69
- return false;
70
- const client = contract.client?._id ?? contract.client;
71
- if (String(client) !== String(clientId))
72
- return false;
73
- const end = (0, exports.getContractEndExclusive)(contract);
74
- return new Date(contract.startDate).getTime() <= time && (!end || time < end.getTime());
75
- }) ?? null);
76
- };
77
- exports.getActiveContract = getActiveContract;
@@ -1,27 +0,0 @@
1
- # Code Review: shared-schemas
2
-
3
- Checklist de cada PR, junto da spec da Task e da `docs/constitution.md`. Usado pela skill `gd-code-review`.
4
-
5
- ## 1. Spec e commits
6
-
7
- - [ ] A spec existe em `docs/specs/` (ou na API que consome) com `**Feature:** GD-xxx`?
8
- - [ ] O schema bate com o contrato da spec?
9
- - [ ] Cada commit segue a seção Commits da constitution? Para cada desvio, anotar como foi feito e como deveria ser.
10
-
11
- ## 2. Compatibilidade
12
-
13
- - [ ] Campo novo é opcional no tipo e tem `default`? Documento antigo continua válido?
14
- - [ ] Nenhum campo foi removido, renomeado ou mudou de tipo sem migração e sem a lista de repos afetados?
15
- - [ ] Enum novo segue o padrão `*_VALUES as const` + tipo derivado e está no barrel?
16
- - [ ] Índice novo faz sentido para as queries de quem consome?
17
-
18
- ## 3. Padrões
19
-
20
- - [ ] `@ApiProperty` em todo campo exposto?
21
- - [ ] JSDoc em português nos campos com regra?
22
- - [ ] Sem helper de regra de negócio de uma API só?
23
-
24
- ## 4. Publicação
25
-
26
- - [ ] A versão no `package.json` é a próxima livre no npm?
27
- - [ ] `npm run build` passa?
@@ -1,75 +0,0 @@
1
- # Constitution: shared-schemas
2
-
3
- Regras do pacote `@grapadigital/shared-schemas`: os schemas Mongoose de todas as entidades, consumidos pelas APIs e pelos workers. Os fronts não dependem deste pacote (ele carrega mongoose e decorators do Nest); os tipos do front ficam no `@grapadigital/shared-app-modules`.
4
-
5
- ## Stack
6
-
7
- - TypeScript compilado com `tsc` para CommonJS (`dist/`)
8
- - Mongoose 8 + `@nestjs/mongoose` (`@Schema`, `@Prop`, `SchemaFactory`) e `@nestjs/swagger` (`@ApiProperty`)
9
- - npm para publicar (`prepublishOnly` roda o build); sem lint nem testes configurados
10
- - Prettier (`singleQuote: true`, `trailingComma: 'all'`)
11
-
12
- ## Estrutura
13
-
14
- - Um arquivo por entidade em `src/schemas/<entidade>.schema.ts`, com a classe, o `<Entidade>Schema`, os índices e o model.
15
- - Barrel em `src/index.ts`, com `export * from './schemas/<entidade>.schema'`. Nome que conflita entre arquivos é exportado nominalmente (ex.: `note.schema`).
16
- - Subdocumento é uma classe com `@Schema({ _id: false })` no mesmo arquivo da entidade dona. Usar `@Schema()` (com `_id`) só quando outro documento aponta para ele (ex.: `ActionPhase`).
17
-
18
- ## Regras dos schemas
19
-
20
- - **Enum** é uma constante `as const` exportada com o tipo derivado, usada no `@Prop` e no `@ApiProperty`:
21
- ```ts
22
- export const ENTIDADE_STATUS_VALUES = ['a', 'b'] as const;
23
- export type EntidadeStatus = (typeof ENTIDADE_STATUS_VALUES)[number];
24
- ```
25
- - **Campo novo** é opcional no tipo (`campo?: T`) e tem `default` no `@Prop` (vazio ou `null`). Documento que já existe no banco não pode ficar inválido, e código que monta a entidade sem o campo não pode quebrar.
26
- - **Todo campo exposto** tem `@ApiProperty`, para aparecer no Swagger das APIs.
27
- - **JSDoc em português** em campo cuja regra não é óbvia: o que é, o que vazio significa e a Task (`Ver GD-xxx`).
28
- - **Percentual** é gravado como fração (0,10 = 10%).
29
- - **Nada de helper com regra de negócio** de uma API só: o pacote tem schemas, enums, tipos e constantes. Helper puro, sem I/O, usado por mais de um backend pode entrar.
30
- - **Índice** novo é declarado no schema (`<Entidade>Schema.index(...)`); os serviços sobem com `autoIndex`.
31
-
32
- ## Versão e publicação
33
-
34
- 1. Subir a versão no `package.json` (conferir a última no npm: `npm view @grapadigital/shared-schemas version`).
35
- 2. `npm run build` e checar o `dist`.
36
- 3. Publicar (`npm publish`) e só então subir a dependência nas APIs e nos workers.
37
-
38
- Mudança que quebra quem consome (remover ou renomear campo, mudar tipo) precisa de migração de dados e da lista de repos afetados na spec.
39
-
40
- ## Spec antes do código
41
-
42
- Nenhuma implementação começa sem spec. A spec fica em `docs/specs/<slice>.md`, com `**Feature:** GD-xxx`, e segue o formato da seção 6 do `AGENTS.md` da raiz do workspace (fluxo `gd-spec-task` → `gd-execute-spec` → `gd-code-review`).
43
-
44
- ## Commits
45
-
46
- Formato Conventional Commits: `<tipo>(<escopo>): <descrição>`.
47
-
48
- | Tipo | Quando usar |
49
- |---|---|
50
- | `feat` | Nova feature ou novo slice |
51
- | `fix` | Correção de bug |
52
- | `refactor` | Refatoração sem mudança de comportamento |
53
- | `docs` | Documentação (`docs/`, `AGENTS.md`, `README`) |
54
- | `test` | Testes |
55
- | `chore` | Dependências, configs, scripts |
56
- | `perf` | Performance |
57
-
58
- - Descrição em inglês, no imperativo, em minúsculas, numa linha só de até 72 caracteres.
59
- - O escopo é a entidade ou o módulo afetado (ex.: `feat(client): add create-client slice`).
60
- - Um commit é uma mudança coesa. Commitar só os arquivos da Task.
61
- - Sem trailer de co-autoria.
62
- - Nunca commitar `console.log`, `debugger`, código comentado, `.env` ou segredo.
63
-
64
- ## Branch, PR e push
65
-
66
- - Task de feature ou bug: branch a partir da `main` atualizada, no formato `<tipo>/GD-xxx-<descricao-curta>` (kebab-case, sem acento), e PR para a `main` com título e descrição em português e o link da Task.
67
- - Antes do push:
68
-
69
- - [ ] `npm run build` (tsc) compila sem erro
70
- - [ ] campo novo é opcional ou tem default, e documentos antigos continuam válidos (`validateSync` com o `dist`)
71
- - [ ] constante e tipo novos exportados pelo barrel (`src/index.ts`)
72
- - [ ] versão nova no `package.json`, conferida no npm antes de publicar
73
- - [ ] a spec existe em `docs/specs/` e bate com o que foi feito
74
- - [ ] os commits seguem a seção Commits
75
- - [ ] sem conflito com a `main`
@@ -1,112 +0,0 @@
1
- # Spec: action + content: Orgânico, Fases e Metas da Ação
2
-
3
- **Feature:** GD-692 (Story GD-691)
4
- **Consumido por:** api-campaigns (GD-693), content-capture-trigger e content-capture-worker (GD-693), web-campaigns (GD-694, via shared-app-modules)
5
-
6
- ---
7
-
8
- ## Descrição
9
-
10
- A Ação da Samsung passa a guardar a hashtag de Orgânico, as Fases (antigo briefing do genc) e as
11
- Metas da Ação. O Conteúdo passa a guardar as próprias hashtags e o Tipo (Orgânico ou Pago) e a Fase
12
- sugeridos, cada um com a origem (`auto` = regra da captura, `manual` = quem revisou).
13
-
14
- Todos os campos são opcionais e têm default vazio: Ações e Conteúdos existentes não mudam.
15
-
16
- **Nome:** "Orgânico" aqui é o Tipo do Conteúdo (fora do escopo contratado). Não confundir com
17
- `metricsSource: 'organic'` (Métrica pública) nem com `isBoosted` (mídia paga, GD-707).
18
-
19
- ## Schema
20
-
21
- ### `action.schema.ts`
22
-
23
- ```ts
24
- @Schema() // com _id: o Conteúdo aponta para a Fase
25
- export class ActionPhase {
26
- _id: Types.ObjectId;
27
- name: string;
28
- color: string; // hex #rrggbb (paleta do cpanel)
29
- order: number; // 0..n, define a prioridade quando Fases se sobrepõem
30
- startDate?: Date | null; // inclusivo
31
- endDate?: Date | null; // inclusivo (dia inteiro)
32
- hashtags: string[]; // normalizadas, default []
33
- }
34
-
35
- Action.organicHashtags: string[] // normalizadas, default []
36
- Action.phases: ActionPhase[] // default []
37
- Action.goals: ClientMetricGoal[] // default []; mesmo { metric, value } e catálogo dos Tiers (GD-688)
38
- ```
39
-
40
- ### `content.schema.ts`
41
-
42
- ```ts
43
- export const CONTENT_CLASSIFICATION_SOURCE_VALUES = ['auto', 'manual'] as const;
44
-
45
- Content.hashtags: string[] // normalizadas, default []
46
- Content.isOrganic: boolean | null // default null (Ação sem hashtag de Orgânico)
47
- Content.isOrganicSource: 'auto' | 'manual' | null // default null
48
- Content.phase: Types.ObjectId | null // _id de Action.phases; default null
49
- Content.phaseSource: 'auto' | 'manual' | null // default null
50
- ```
51
-
52
- Índices novos: `ContentSchema.index({ action: 1, phase: 1 })` e `ContentSchema.index({ action: 1, isOrganic: 1 })`.
53
-
54
- ### Catálogo de métricas (`client.schema.ts`)
55
-
56
- `CLIENT_GOAL_METRIC_VALUES` ganha as métricas do relatório Samsung que faltavam, com a unidade em
57
- `CLIENT_GOAL_METRIC_UNITS`:
58
-
59
- | métrica | unidade |
60
- |---|---|
61
- | `savedCount` | count |
62
- | `sharesCount` | count |
63
- | `vcr` | rate (a métrica entra no Content na GD-707) |
64
-
65
- O mesmo vale no espelho do shared-app-modules (`CLIENT_GOAL_METRIC_VALUES` com label): "Salvamentos",
66
- "Compartilhamentos", "VCR".
67
-
68
- ## Normalização de hashtag
69
-
70
- Regra única, implementada **localmente em cada repo que usa** (decisão da Story): api-campaigns,
71
- content-capture-worker e web-campaigns. Não vai para o shared-schemas.
72
-
73
- `normalizeHashtag(value)`: tira espaços e `#` do começo, remove acentos (NFD), passa para
74
- minúsculas e remove o que não for `[a-z0-9_]`.
75
-
76
- - `"#GalaxyMoments"` → `"galaxymoments"`
77
- - `"#VerãoSamsung"` → `"veraosamsung"`
78
-
79
- ---
80
-
81
- ## Arquivos
82
-
83
- - Alterar `src/schemas/action.schema.ts` (ActionPhase + 3 campos).
84
- - Alterar `src/schemas/content.schema.ts` (5 campos, enum de origem, 2 índices).
85
- - Alterar `src/schemas/client.schema.ts` (3 métricas no catálogo).
86
- - Alterar `package.json` (1.0.220).
87
- - shared-app-modules: `src/app/constants/values.constant.ts` (3 métricas com label) e
88
- `src/app/interfaces/action/action.interface.ts` (`organicHashtags`, `phases`, `goals`, mais
89
- `ActionPhaseInterface`); interface de Content usada no web-campaigns, se houver no pacote.
90
-
91
- ## Passos
92
-
93
- 1. `ActionPhase` com `_id` (subdocumento com id) e os três campos novos na Action, com JSDoc em PT e "Ver GD-691".
94
- 2. Campos e índices do Content.
95
- 3. Métricas novas no catálogo do client.
96
- 4. `npm run build` e conferir no `dist` os campos e exports; checar com `validateSync` que uma Action e um Content antigos (sem os campos) continuam válidos e que `phases[0]._id` é gerado.
97
- 5. shared-app-modules: catálogo e interfaces; `pnpm run build`.
98
- 6. Publicar os dois pacotes (José).
99
-
100
- ## Dependências
101
-
102
- - GD-688 (catálogo de métricas) já em produção.
103
- - Esta Task vem antes da GD-693 e da GD-694.
104
-
105
- ## Validação
106
-
107
- - `npm run build` no shared-schemas; `pnpm run build` no shared-app-modules.
108
- - `validateSync` de documentos antigos e novos (script rápido com o `dist`).
109
-
110
- ## Pontos abertos
111
-
112
- - `vcr` entra no catálogo antes de existir no Content (chega na GD-707). Até lá a meta pode ser cadastrada, mas o Hub mostra o realizado como indisponível.
@@ -1,94 +0,0 @@
1
- # Spec: log: acesso ao Hub e troca de cliente
2
-
3
- **Feature:** GD-761 (Story GD-760)
4
- **Consumido por:** api-entities (GD-762)
5
-
6
- ---
7
-
8
- ## Descrição
9
-
10
- O Log passa a guardar três coisas novas do Hub de Relatórios:
11
-
12
- - alteração de acesso (criar, editar, remover), feita pela tela do Cliente no web-entities;
13
- - troca de cliente (`POST /auth/select-client`);
14
- - acesso bloqueado (conta de fora da Grapa com role diferente de `client`).
15
-
16
- Hoje o Log só sabe quem fez (`updatedBy`). Aqui ele precisa saber também **quem foi afetado**, que é uma conta do Firebase do Hub e não um documento do Mongo. Isso vira o campo `target`.
17
-
18
- `referenceId` continua sendo ObjectId e recebe o `clientId` do Cliente envolvido.
19
-
20
- Os campos novos são opcionais e têm default `null`. Logs que já existem não mudam.
21
-
22
- ## Schema
23
-
24
- ### `log.schema.ts`
25
-
26
- ```ts
27
- export const LOG_REFERENCE_VALUES = [
28
- 'action', 'recruitment', 'content', 'contract', 'sale',
29
- 'invoice', 'payment', 'assignment', 'commission',
30
- 'hub-access', // novo
31
- ] as const;
32
- export type LogReference = (typeof LOG_REFERENCE_VALUES)[number];
33
-
34
- export const LOG_TYPE_VALUES = [
35
- 'created', 'updated', 'deleted', 'email',
36
- 'client-selected', // novo: troca de cliente no Hub
37
- 'access-blocked', // novo: conta externa barrada pelo guard
38
- ] as const;
39
- export type LogType = (typeof LOG_TYPE_VALUES)[number];
40
-
41
- @Schema({ _id: false })
42
- export class LogTarget {
43
- uid: string; // uid no Firebase do Hub (projeto hub-grapa)
44
- email: string;
45
- }
46
-
47
- Log.reference: LogReference // @Prop com enum LOG_REFERENCE_VALUES
48
- Log.type: LogType // @Prop com enum LOG_TYPE_VALUES
49
- Log.target?: LogTarget | null // default null; preenchido só em reference 'hub-access'
50
- ```
51
-
52
- - `@ApiProperty` em `target` e nos dois enums.
53
- - JSDoc em português no `target`: "Conta do Hub afetada pela ação. Vazio fora de `hub-access`. Ver GD-760."
54
-
55
- Índice novo, para buscar o histórico de uma pessoa e para a trava de um alerta por hora da GD-762:
56
-
57
- ```ts
58
- LogSchema.index({ reference: 1, 'target.uid': 1, updatedAt: -1 });
59
- ```
60
-
61
- Os índices atuais (`{ referenceId: 1, reference: 1 }` e `{ reference: 1, updatedAt: -1 }`) ficam.
62
-
63
- ---
64
-
65
- ## Arquivos
66
-
67
- - Alterar `src/schemas/log.schema.ts`: as duas constantes `as const` com o tipo derivado, a classe `LogTarget`, o campo `target` e o índice.
68
- - Alterar `package.json`: versão nova (a última publicada hoje é a 1.0.236; conferir no npm antes).
69
-
70
- ## Passos
71
-
72
- 1. Trocar os enums inline de `reference` e `type` pelas constantes `LOG_REFERENCE_VALUES` e `LOG_TYPE_VALUES`, com os valores novos. Os valores antigos continuam, na mesma ordem.
73
- 2. Criar `LogTarget` (`@Schema({ _id: false })`) e o campo `target` (`@Prop({ type: LogTarget, default: null })`), com `@ApiProperty` e o JSDoc.
74
- 3. Declarar o índice `{ reference: 1, 'target.uid': 1, updatedAt: -1 }`.
75
- 4. `npm run build` e conferir no `dist` as constantes, `LogTarget` e o índice, exportados pelo barrel (`src/index.ts` já faz `export *` do arquivo).
76
- 5. Checar com `validateSync`, usando o `dist`:
77
- - um Log antigo, sem `target`, continua válido;
78
- - um Log com `reference: 'hub-access'`, `type: 'client-selected'` e `target` preenchido é válido;
79
- - `type: 'qualquer'` continua inválido.
80
- 6. Subir a versão no `package.json` e publicar (José).
81
-
82
- ## Dependências
83
-
84
- - Nenhuma. Esta Task vem antes da GD-762.
85
-
86
- ## Validação
87
-
88
- - `npm run build`.
89
- - Script rápido de `validateSync` com o `dist` (passo 5).
90
- - `npm view @grapadigital/shared-schemas version` antes de publicar.
91
-
92
- ## Pontos abertos
93
-
94
- - O DTO da api-logs (`create-log.dto.ts`) já aceita referências que o schema não tem (`influencer`, `profile`, `curation`, `prospect`). Isso não muda aqui: a GD-762 grava o Log direto pelo model e não passa pela api-logs.
package/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- declare module '@grapadigital/shared-schemas' {
2
- export * from './dist/index';
3
- }