@adatechnology/content-module 0.3.0 → 0.4.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.
package/dist/index.js CHANGED
@@ -11,13 +11,18 @@ var __dirname = /* @__PURE__ */ getDirname();
11
11
  // src/ContentModule.ts
12
12
  import { ConfigMissingError } from "@adatechnology/content-contracts";
13
13
 
14
- // src/repositories/PostRepository.ts
15
- import { and as and2, asc, desc, eq as eq2, inArray as inArray2, sql as sql3 } from "drizzle-orm";
16
- import { POST_STATUS as POST_STATUS2 } from "@adatechnology/content-contracts";
14
+ // src/repositories/CommunityRepository.ts
15
+ import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, ne, sql as sql2 } from "drizzle-orm";
16
+ import { COMMUNITY_MODERATIONS, DEFAULT_CONTENT_SETTINGS, POST_ORIGIN, POST_STATUS } from "@adatechnology/content-contracts";
17
17
 
18
18
  // src/schema/schema.ts
19
19
  import { sql } from "drizzle-orm";
20
- import { boolean, index, integer, jsonb, primaryKey, pgSchema, text, timestamp, uniqueIndex, uuid, varchar } from "drizzle-orm/pg-core";
20
+ import { boolean, customType, index, integer, jsonb, primaryKey, pgSchema, text, timestamp, uniqueIndex, uuid, varchar } from "drizzle-orm/pg-core";
21
+ var jsonbObject = /* @__PURE__ */ __name((name) => customType({
22
+ dataType: /* @__PURE__ */ __name(() => "jsonb", "dataType"),
23
+ toDriver: /* @__PURE__ */ __name((value) => sql`${JSON.stringify(value)}::text::jsonb`, "toDriver"),
24
+ fromDriver: /* @__PURE__ */ __name((value) => typeof value === "string" ? JSON.parse(value) : value, "fromDriver")
25
+ })(name), "jsonbObject");
21
26
  var contentSchema = pgSchema("content");
22
27
  var posts = contentSchema.table("posts", {
23
28
  id: uuid("id").primaryKey().defaultRandom(),
@@ -44,7 +49,7 @@ var posts = contentSchema.table("posts", {
44
49
  tags: text("tags").array().notNull().default([]),
45
50
  tagLabels: jsonb("tag_labels").$type().notNull().default({}),
46
51
  status: varchar("status", {
47
- length: 12
52
+ length: 16
48
53
  }).notNull().default("draft"),
49
54
  isTemplate: boolean("is_template").notNull().default(false),
50
55
  publishedAt: timestamp("published_at", {
@@ -68,7 +73,33 @@ var posts = contentSchema.table("posts", {
68
73
  }).notNull().defaultNow(),
69
74
  updatedAt: timestamp("updated_at", {
70
75
  withTimezone: true
71
- }).notNull().defaultNow()
76
+ }).notNull().defaultNow(),
77
+ // Comunidade: linhas antigas leem `staff`. Valores de `origin` espelham `POST_ORIGIN`.
78
+ origin: varchar("origin", {
79
+ length: 12
80
+ }).notNull().default("staff"),
81
+ authorAccountId: varchar("author_account_id", {
82
+ length: 64
83
+ }),
84
+ authorDisplayName: varchar("author_display_name", {
85
+ length: 80
86
+ }),
87
+ // `YYYY-MM`, retrato da porta no primeiro envio.
88
+ authorReferenceMonth: varchar("author_reference_month", {
89
+ length: 7
90
+ }),
91
+ reviewNote: varchar("review_note", {
92
+ length: 500
93
+ }),
94
+ termsAcceptedAt: timestamp("terms_accepted_at", {
95
+ withTimezone: true
96
+ }),
97
+ // Ordem da fila de moderação.
98
+ submittedAt: timestamp("submitted_at", {
99
+ withTimezone: true
100
+ }),
101
+ // Edição de post publicado, à parte até a aprovação; forma validada por `communityRevisionSchema`.
102
+ pendingRevision: jsonbObject("pending_revision")
72
103
  }, (table) => [
73
104
  // Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo
74
105
  // faria um link antigo (já compartilhado) abrir outro post.
@@ -76,6 +107,10 @@ var posts = contentSchema.table("posts", {
76
107
  uniqueIndex("idx_posts_company_short_id").on(table.companyId, table.shortId),
77
108
  // Serve a listagem pública: empresa + status + ordem por data.
78
109
  index("idx_posts_company_status_published").on(table.companyId, table.status, table.publishedAt),
110
+ index("idx_posts_company_origin_status_published").on(table.companyId, table.origin, table.status, table.publishedAt),
111
+ // Serve o limite diário: posts do autor na janela de 24 h.
112
+ index("idx_posts_community_author_created").on(table.companyId, table.authorAccountId, table.createdAt).where(sql`"origin" = 'community'`),
113
+ index("idx_posts_moderation_queue").on(table.companyId, table.submittedAt).where(sql`"status" = 'pending_review' OR "pending_revision" IS NOT NULL`),
79
114
  index("idx_posts_tags").using("gin", table.tags),
80
115
  // Serve o `publishDue`: só linha agendada entra, então o índice fica minúsculo.
81
116
  index("idx_posts_due").on(table.publishedAt).where(sql`"status" = 'scheduled'`)
@@ -121,78 +156,306 @@ var postFormerSlugs = contentSchema.table("post_former_slugs", {
121
156
  ]
122
157
  })
123
158
  ]);
159
+ var contentSettings = contentSchema.table("content_settings", {
160
+ companyId: uuid("company_id").primaryKey(),
161
+ communityModeration: varchar("community_moderation", {
162
+ length: 8
163
+ }).notNull().default("before"),
164
+ communityDailyLimit: integer("community_daily_limit").notNull().default(3),
165
+ maxImagesPerPost: integer("max_images_per_post").notNull().default(12),
166
+ updatedAt: timestamp("updated_at", {
167
+ withTimezone: true
168
+ }).notNull().defaultNow()
169
+ });
170
+ var postReports = contentSchema.table("post_reports", {
171
+ id: uuid("id").primaryKey().defaultRandom(),
172
+ companyId: uuid("company_id").notNull(),
173
+ postId: uuid("post_id").notNull().references(() => posts.id),
174
+ reason: varchar("reason", {
175
+ length: 300
176
+ }).notNull(),
177
+ createdAt: timestamp("created_at", {
178
+ withTimezone: true
179
+ }).notNull().defaultNow(),
180
+ resolvedAt: timestamp("resolved_at", {
181
+ withTimezone: true
182
+ }),
183
+ resolvedBy: varchar("resolved_by", {
184
+ length: 64
185
+ })
186
+ }, (table) => [
187
+ index("idx_post_reports_open").on(table.companyId, table.createdAt).where(sql`"resolved_at" IS NULL`)
188
+ ]);
189
+ var communityImages = contentSchema.table("community_images", {
190
+ id: uuid("id").primaryKey().defaultRandom(),
191
+ companyId: uuid("company_id").notNull(),
192
+ accountId: varchar("account_id", {
193
+ length: 64
194
+ }).notNull(),
195
+ storageKey: varchar("storage_key", {
196
+ length: 512
197
+ }).notNull(),
198
+ url: varchar("url", {
199
+ length: 2048
200
+ }).notNull(),
201
+ createdAt: timestamp("created_at", {
202
+ withTimezone: true
203
+ }).notNull().defaultNow()
204
+ }, (table) => [
205
+ uniqueIndex("idx_community_images_company_url").on(table.companyId, table.url),
206
+ index("idx_community_images_account").on(table.companyId, table.accountId, table.createdAt)
207
+ ]);
208
+
209
+ // src/shared/community.constant.ts
210
+ var COMMUNITY_WINDOW_MS = 24 * 60 * 60 * 1e3;
211
+ var COMMUNITY_IMAGE_KEY_PREFIX = "content/community";
212
+ var ANONYMIZED_TITLE = "\u2014";
213
+ var COMMUNITY_ACTION = {
214
+ SUBMIT: "submit",
215
+ APPROVE: "approve",
216
+ REJECT: "reject",
217
+ UNPUBLISH: "unpublish"
218
+ };
219
+ var BULK_UNEXPECTED_FAILURE = {
220
+ code: "CONTENT_UNEXPECTED",
221
+ message: "N\xE3o foi poss\xEDvel concluir esta a\xE7\xE3o."
222
+ };
223
+
224
+ // src/repositories/CommunityRepository.ts
225
+ function toModeration(value) {
226
+ return COMMUNITY_MODERATIONS.includes(value) ? value : DEFAULT_CONTENT_SETTINGS.communityModeration;
227
+ }
228
+ __name(toModeration, "toModeration");
229
+ var CommunityRepository = class {
230
+ static {
231
+ __name(this, "CommunityRepository");
232
+ }
233
+ db;
234
+ constructor(db) {
235
+ this.db = db;
236
+ }
237
+ async createWithDailyLimit(params) {
238
+ const { values, accountId, limit, now } = params;
239
+ const windowStart = new Date(now.getTime() - COMMUNITY_WINDOW_MS);
240
+ const lockKey = `${values.companyId}:${accountId}`;
241
+ return this.db.transaction(async (tx) => {
242
+ await tx.execute(sql2`select pg_advisory_xact_lock(hashtext(${lockKey}))`);
243
+ const recent = await tx.select({
244
+ createdAt: posts.createdAt
245
+ }).from(posts).where(and(eq(posts.companyId, values.companyId), eq(posts.origin, POST_ORIGIN.COMMUNITY), eq(posts.authorAccountId, accountId), gt(posts.createdAt, windowStart))).orderBy(asc(posts.createdAt));
246
+ const blocking = recent[recent.length - limit];
247
+ if (recent.length >= limit && blocking) {
248
+ return {
249
+ isLimited: true,
250
+ freesUpAt: new Date(blocking.createdAt.getTime() + COMMUNITY_WINDOW_MS)
251
+ };
252
+ }
253
+ const [row] = await tx.insert(posts).values(values).returning();
254
+ if (!row) throw new Error("content-module: insert em posts n\xE3o retornou linha");
255
+ return {
256
+ isLimited: false,
257
+ row
258
+ };
259
+ });
260
+ }
261
+ async listByAuthor(params) {
262
+ const where = and(eq(posts.companyId, params.companyId), eq(posts.origin, POST_ORIGIN.COMMUNITY), eq(posts.authorAccountId, params.accountId), ne(posts.status, POST_STATUS.ARCHIVED));
263
+ const [rows, [counted]] = await Promise.all([
264
+ this.db.select().from(posts).where(where).orderBy(desc(posts.updatedAt), asc(posts.id)).limit(params.pageSize).offset((params.page - 1) * params.pageSize),
265
+ this.db.select({
266
+ value: sql2`count(*)::int`
267
+ }).from(posts).where(where)
268
+ ]);
269
+ return {
270
+ rows,
271
+ total: counted?.value ?? 0
272
+ };
273
+ }
274
+ async getSettings(params) {
275
+ const [row] = await this.db.select().from(contentSettings).where(eq(contentSettings.companyId, params.companyId)).limit(1);
276
+ if (!row) return DEFAULT_CONTENT_SETTINGS;
277
+ return {
278
+ communityModeration: toModeration(row.communityModeration),
279
+ communityDailyLimit: row.communityDailyLimit,
280
+ maxImagesPerPost: row.maxImagesPerPost
281
+ };
282
+ }
283
+ async findOwnedImageUrls(params) {
284
+ if (params.urls.length === 0) return [];
285
+ const rows = await this.db.select({
286
+ url: communityImages.url
287
+ }).from(communityImages).where(and(eq(communityImages.companyId, params.companyId), eq(communityImages.accountId, params.accountId), inArray(communityImages.url, [
288
+ ...params.urls
289
+ ])));
290
+ return rows.map((row) => row.url);
291
+ }
292
+ async recordImage(params) {
293
+ await this.db.insert(communityImages).values(params);
294
+ }
295
+ async listRecentImageDates(params) {
296
+ const rows = await this.db.select({
297
+ createdAt: communityImages.createdAt
298
+ }).from(communityImages).where(and(eq(communityImages.companyId, params.companyId), eq(communityImages.accountId, params.accountId), gt(communityImages.createdAt, params.since))).orderBy(asc(communityImages.createdAt));
299
+ return rows.map((row) => row.createdAt);
300
+ }
301
+ async upsertSettings(params) {
302
+ const { companyId, settings, now } = params;
303
+ const values = {
304
+ ...settings,
305
+ updatedAt: now
306
+ };
307
+ await this.db.insert(contentSettings).values({
308
+ companyId,
309
+ ...values
310
+ }).onConflictDoUpdate({
311
+ target: contentSettings.companyId,
312
+ set: values
313
+ });
314
+ return settings;
315
+ }
316
+ async createReport(params) {
317
+ const { now, ...values } = params;
318
+ const [row] = await this.db.insert(postReports).values({
319
+ ...values,
320
+ createdAt: now
321
+ }).returning();
322
+ if (!row) throw new Error("content-module: insert em post_reports n\xE3o retornou linha");
323
+ return row;
324
+ }
325
+ async listReports(params) {
326
+ const where = and(eq(postReports.companyId, params.companyId), params.status === "open" ? isNull(postReports.resolvedAt) : isNotNull(postReports.resolvedAt));
327
+ const [rows, [counted]] = await Promise.all([
328
+ this.db.select().from(postReports).where(where).orderBy(desc(postReports.createdAt), asc(postReports.id)).limit(params.pageSize).offset((params.page - 1) * params.pageSize),
329
+ this.db.select({
330
+ value: sql2`count(*)::int`
331
+ }).from(postReports).where(where)
332
+ ]);
333
+ return {
334
+ rows,
335
+ total: counted?.value ?? 0
336
+ };
337
+ }
338
+ async resolveReport(params) {
339
+ const [row] = await this.db.update(postReports).set({
340
+ resolvedAt: sql2`coalesce(${postReports.resolvedAt}, ${params.now.toISOString()}::timestamptz)`,
341
+ resolvedBy: sql2`coalesce(${postReports.resolvedBy}, ${params.actorUserId})`
342
+ }).where(and(eq(postReports.companyId, params.companyId), eq(postReports.id, params.id))).returning();
343
+ return row;
344
+ }
345
+ async countOpenReports(params) {
346
+ if (params.postIds.length === 0) return /* @__PURE__ */ new Map();
347
+ const rows = await this.db.select({
348
+ postId: postReports.postId,
349
+ value: sql2`count(*)::int`
350
+ }).from(postReports).where(and(eq(postReports.companyId, params.companyId), isNull(postReports.resolvedAt), inArray(postReports.postId, [
351
+ ...params.postIds
352
+ ]))).groupBy(postReports.postId);
353
+ return new Map(rows.map((row) => [
354
+ row.postId,
355
+ row.value
356
+ ]));
357
+ }
358
+ };
359
+
360
+ // src/repositories/PostRepository.ts
361
+ import { and as and3, asc as asc2, desc as desc2, eq as eq3, inArray as inArray3, sql as sql4 } from "drizzle-orm";
362
+ import { COMMUNITY_REVISION_STATE as COMMUNITY_REVISION_STATE2, POST_ORIGIN as POST_ORIGIN3, POST_STATUS as POST_STATUS3 } from "@adatechnology/content-contracts";
124
363
 
125
364
  // src/repositories/conditions.ts
126
- import { and, arrayContains, arrayOverlaps, eq, gt, inArray, lte, ne, or, sql as sql2 } from "drizzle-orm";
127
- import { POST_STATUS } from "@adatechnology/content-contracts";
365
+ import { and as and2, arrayContains, arrayOverlaps, eq as eq2, gt as gt2, inArray as inArray2, lte, ne as ne2, or, sql as sql3 } from "drizzle-orm";
366
+ import { COMMUNITY_REVISION_STATE, POST_ORIGIN as POST_ORIGIN2, POST_STATUS as POST_STATUS2 } from "@adatechnology/content-contracts";
128
367
  function postOwnedByCondition(params) {
129
- return and(eq(posts.companyId, params.companyId), eq(posts.id, params.id));
368
+ return and2(eq2(posts.companyId, params.companyId), eq2(posts.id, params.id));
130
369
  }
131
370
  __name(postOwnedByCondition, "postOwnedByCondition");
132
371
  function postSlugCondition(params) {
133
- return and(eq(posts.companyId, params.companyId), eq(posts.slug, params.slug));
372
+ return and2(eq2(posts.companyId, params.companyId), eq2(posts.slug, params.slug));
134
373
  }
135
374
  __name(postSlugCondition, "postSlugCondition");
375
+ function postOriginCondition(origin) {
376
+ const filter = origin ?? POST_ORIGIN2.STAFF;
377
+ return filter === "all" ? void 0 : eq2(posts.origin, filter);
378
+ }
379
+ __name(postOriginCondition, "postOriginCondition");
136
380
  function postAdminListCondition(params) {
137
381
  const conditions = [
138
- eq(posts.companyId, params.companyId),
382
+ eq2(posts.companyId, params.companyId),
139
383
  templateCondition(params.isTemplate)
140
384
  ];
385
+ const origin = postOriginCondition(params.origin);
386
+ if (origin) conditions.push(origin);
141
387
  if (params.status) conditions.push(statusCondition(params.status, params.now));
142
388
  if (params.tags?.length) conditions.push(arrayOverlaps(posts.tags, [
143
389
  ...params.tags
144
390
  ]));
145
391
  if (params.search) {
146
392
  const pattern = `%${params.search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
147
- conditions.push(sql2`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`);
393
+ conditions.push(sql3`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`);
148
394
  }
149
- return and(...conditions);
395
+ return and2(...conditions);
150
396
  }
151
397
  __name(postAdminListCondition, "postAdminListCondition");
398
+ function revisionStateExpression() {
399
+ return sql3`(case when jsonb_typeof(${posts.pendingRevision}) = 'string' then (${posts.pendingRevision} #>> '{}')::jsonb else ${posts.pendingRevision} end) ->> 'state'`;
400
+ }
401
+ __name(revisionStateExpression, "revisionStateExpression");
402
+ function pendingReviewCondition() {
403
+ return and2(eq2(posts.origin, POST_ORIGIN2.COMMUNITY), or(eq2(posts.status, POST_STATUS2.PENDING_REVIEW), sql3`${revisionStateExpression()} = ${COMMUNITY_REVISION_STATE.PENDING}`));
404
+ }
405
+ __name(pendingReviewCondition, "pendingReviewCondition");
152
406
  function templateCondition(isTemplate) {
153
- if (isTemplate) return and(eq(posts.isTemplate, true), ne(posts.status, POST_STATUS.ARCHIVED));
154
- return eq(posts.isTemplate, false);
407
+ if (isTemplate) return and2(eq2(posts.isTemplate, true), ne2(posts.status, POST_STATUS2.ARCHIVED));
408
+ return eq2(posts.isTemplate, false);
155
409
  }
156
410
  __name(templateCondition, "templateCondition");
157
411
  function statusCondition(status, now) {
158
- if (status === POST_STATUS.PUBLISHED) {
159
- return or(eq(posts.status, POST_STATUS.PUBLISHED), and(eq(posts.status, POST_STATUS.SCHEDULED), lte(posts.publishedAt, now)));
412
+ if (status === POST_STATUS2.PENDING_REVIEW) return pendingReviewCondition();
413
+ if (status === POST_STATUS2.PUBLISHED) {
414
+ return or(eq2(posts.status, POST_STATUS2.PUBLISHED), and2(eq2(posts.status, POST_STATUS2.SCHEDULED), lte(posts.publishedAt, now)));
160
415
  }
161
- if (status === POST_STATUS.SCHEDULED) {
162
- return and(eq(posts.status, POST_STATUS.SCHEDULED), gt(posts.publishedAt, now));
416
+ if (status === POST_STATUS2.SCHEDULED) {
417
+ return and2(eq2(posts.status, POST_STATUS2.SCHEDULED), gt2(posts.publishedAt, now));
163
418
  }
164
- return eq(posts.status, status);
419
+ return eq2(posts.status, status);
165
420
  }
166
421
  __name(statusCondition, "statusCondition");
167
422
  function postPublicCondition(params) {
168
423
  const conditions = [
169
- eq(posts.companyId, params.companyId),
170
- inArray(posts.status, [
171
- POST_STATUS.PUBLISHED,
172
- POST_STATUS.SCHEDULED
424
+ eq2(posts.companyId, params.companyId),
425
+ inArray2(posts.status, [
426
+ POST_STATUS2.PUBLISHED,
427
+ POST_STATUS2.SCHEDULED
173
428
  ]),
174
429
  lte(posts.publishedAt, params.now)
175
430
  ];
176
431
  if (params.tag) conditions.push(arrayContains(posts.tags, [
177
432
  params.tag
178
433
  ]));
179
- return and(...conditions);
434
+ return and2(...conditions);
180
435
  }
181
436
  __name(postPublicCondition, "postPublicCondition");
437
+ function postPublicListCondition(params) {
438
+ return and2(postPublicCondition(params), postOriginCondition(params.origin));
439
+ }
440
+ __name(postPublicListCondition, "postPublicListCondition");
182
441
  function postPublicSlugCondition(params) {
183
- return and(postPublicCondition(params), eq(posts.slug, params.slug));
442
+ return and2(postPublicCondition(params), eq2(posts.slug, params.slug));
184
443
  }
185
444
  __name(postPublicSlugCondition, "postPublicSlugCondition");
186
445
  function postDueCondition(params) {
187
- return and(eq(posts.status, POST_STATUS.SCHEDULED), eq(posts.isTemplate, false), lte(posts.publishedAt, params.now));
446
+ return and2(eq2(posts.status, POST_STATUS2.SCHEDULED), eq2(posts.isTemplate, false), lte(posts.publishedAt, params.now));
188
447
  }
189
448
  __name(postDueCondition, "postDueCondition");
190
449
  function postShortIdCondition(params) {
191
- return and(eq(posts.companyId, params.companyId), eq(posts.shortId, params.shortId));
450
+ return and2(eq2(posts.companyId, params.companyId), eq2(posts.shortId, params.shortId));
192
451
  }
193
452
  __name(postShortIdCondition, "postShortIdCondition");
453
+ function postPublicIdCondition(params) {
454
+ return and2(postPublicCondition(params), eq2(posts.id, params.id));
455
+ }
456
+ __name(postPublicIdCondition, "postPublicIdCondition");
194
457
  function postPublicShortIdCondition(params) {
195
- return and(postPublicCondition(params), eq(posts.shortId, params.shortId));
458
+ return and2(postPublicCondition(params), eq2(posts.shortId, params.shortId));
196
459
  }
197
460
  __name(postPublicShortIdCondition, "postPublicShortIdCondition");
198
461
 
@@ -206,11 +469,11 @@ var SORT_COLUMNS = {
206
469
  };
207
470
  function adminOrder(query) {
208
471
  const column = SORT_COLUMNS[query.sort ?? "updatedAt"];
209
- const direction = (query.order ?? "desc") === "asc" ? asc : desc;
210
- const primary = query.sort === "publishedAt" ? sql3`${column} ${sql3.raw(query.order === "asc" ? "asc" : "desc")} nulls last` : direction(column);
472
+ const direction = (query.order ?? "desc") === "asc" ? asc2 : desc2;
473
+ const primary = query.sort === "publishedAt" ? sql4`${column} ${sql4.raw(query.order === "asc" ? "asc" : "desc")} nulls last` : direction(column);
211
474
  return [
212
475
  primary,
213
- asc(posts.id)
476
+ asc2(posts.id)
214
477
  ];
215
478
  }
216
479
  __name(adminOrder, "adminOrder");
@@ -247,12 +510,16 @@ var PostRepository = class {
247
510
  const [row] = await this.db.select().from(posts).where(postPublicShortIdCondition(params)).limit(1);
248
511
  return row;
249
512
  }
513
+ async findPublicById(params) {
514
+ const [row] = await this.db.select().from(posts).where(postPublicIdCondition(params)).limit(1);
515
+ return row;
516
+ }
250
517
  async findPublicByFormerSlug(params) {
251
518
  const [former] = await this.db.select({
252
519
  postId: postFormerSlugs.postId
253
- }).from(postFormerSlugs).where(and2(eq2(postFormerSlugs.companyId, params.companyId), eq2(postFormerSlugs.slug, params.slug))).limit(1);
520
+ }).from(postFormerSlugs).where(and3(eq3(postFormerSlugs.companyId, params.companyId), eq3(postFormerSlugs.slug, params.slug))).limit(1);
254
521
  if (!former) return void 0;
255
- const [row] = await this.db.select().from(posts).where(and2(postPublicCondition(params), eq2(posts.id, former.postId))).limit(1);
522
+ const [row] = await this.db.select().from(posts).where(and3(postPublicCondition(params), eq3(posts.id, former.postId))).limit(1);
256
523
  return row;
257
524
  }
258
525
  async recordFormerSlug(params) {
@@ -270,7 +537,7 @@ var PostRepository = class {
270
537
  const [rows, [counted]] = await Promise.all([
271
538
  this.db.select().from(posts).where(where).orderBy(...adminOrder(query)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
272
539
  this.db.select({
273
- value: sql3`count(*)::int`
540
+ value: sql4`count(*)::int`
274
541
  }).from(posts).where(where)
275
542
  ]);
276
543
  return {
@@ -279,11 +546,11 @@ var PostRepository = class {
279
546
  };
280
547
  }
281
548
  async listPublic(query) {
282
- const where = postPublicCondition(query);
549
+ const where = postPublicListCondition(query);
283
550
  const [rows, [counted]] = await Promise.all([
284
- this.db.select().from(posts).where(where).orderBy(desc(posts.publishedAt), asc(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
551
+ this.db.select().from(posts).where(where).orderBy(desc2(posts.publishedAt), asc2(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
285
552
  this.db.select({
286
- value: sql3`count(*)::int`
553
+ value: sql4`count(*)::int`
287
554
  }).from(posts).where(where)
288
555
  ]);
289
556
  return {
@@ -292,22 +559,28 @@ var PostRepository = class {
292
559
  };
293
560
  }
294
561
  async countByStatus(params) {
295
- const now = sql3`${params.now.toISOString()}::timestamptz`;
296
- const counted = /* @__PURE__ */ __name((condition) => sql3`count(*) filter (where ${condition})::int`, "counted");
297
- const livePublished = sql3`(${posts.status} = ${POST_STATUS2.PUBLISHED} or (${posts.status} = ${POST_STATUS2.SCHEDULED} and ${posts.publishedAt} <= ${now}))`;
562
+ const now = sql4`${params.now.toISOString()}::timestamptz`;
563
+ const counted = /* @__PURE__ */ __name((condition) => sql4`count(*) filter (where ${condition})::int`, "counted");
564
+ const staff = sql4`${posts.origin} = ${POST_ORIGIN3.STAFF}`;
565
+ const revisionState = revisionStateExpression();
566
+ const livePublished = sql4`(${posts.status} = ${POST_STATUS3.PUBLISHED} or (${posts.status} = ${POST_STATUS3.SCHEDULED} and ${posts.publishedAt} <= ${now}))`;
298
567
  const [row] = await this.db.select({
299
- published: counted(sql3`not ${posts.isTemplate} and ${livePublished}`),
300
- scheduled: counted(sql3`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS2.SCHEDULED} and ${posts.publishedAt} > ${now}`),
301
- draft: counted(sql3`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS2.DRAFT}`),
302
- archived: counted(sql3`not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS2.ARCHIVED}`),
303
- templates: counted(sql3`${posts.isTemplate} and ${posts.status} <> ${POST_STATUS2.ARCHIVED}`)
304
- }).from(posts).where(eq2(posts.companyId, params.companyId));
568
+ published: counted(sql4`${staff} and not ${posts.isTemplate} and ${livePublished}`),
569
+ scheduled: counted(sql4`${staff} and not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS3.SCHEDULED} and ${posts.publishedAt} > ${now}`),
570
+ draft: counted(sql4`${staff} and not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS3.DRAFT}`),
571
+ archived: counted(sql4`${staff} and not ${posts.isTemplate} and ${posts.status} = ${POST_STATUS3.ARCHIVED}`),
572
+ templates: counted(sql4`${posts.isTemplate} and ${posts.status} <> ${POST_STATUS3.ARCHIVED}`),
573
+ pendingReview: counted(sql4`${posts.status} = ${POST_STATUS3.PENDING_REVIEW} or ${revisionState} = ${COMMUNITY_REVISION_STATE2.PENDING}`),
574
+ rejected: counted(sql4`${posts.status} = ${POST_STATUS3.REJECTED}`)
575
+ }).from(posts).where(eq3(posts.companyId, params.companyId));
305
576
  return row ?? {
306
577
  published: 0,
307
578
  scheduled: 0,
308
579
  draft: 0,
309
580
  archived: 0,
310
- templates: 0
581
+ templates: 0,
582
+ pendingReview: 0,
583
+ rejected: 0
311
584
  };
312
585
  }
313
586
  async claimDueScheduled(params) {
@@ -315,12 +588,12 @@ var PostRepository = class {
315
588
  id: posts.id
316
589
  }).from(posts).where(postDueCondition({
317
590
  now: params.now
318
- })).orderBy(asc(posts.publishedAt), asc(posts.id)).limit(params.limit).for("update", {
591
+ })).orderBy(asc2(posts.publishedAt), asc2(posts.id)).limit(params.limit).for("update", {
319
592
  skipLocked: true
320
593
  });
321
594
  return this.db.update(posts).set({
322
- status: POST_STATUS2.PUBLISHED
323
- }).where(inArray2(posts.id, due)).returning();
595
+ status: POST_STATUS3.PUBLISHED
596
+ }).where(inArray3(posts.id, due)).returning();
324
597
  }
325
598
  async listTags(params) {
326
599
  const where = params.publicAt ? postPublicCondition({
@@ -331,20 +604,20 @@ var PostRepository = class {
331
604
  now: /* @__PURE__ */ new Date()
332
605
  });
333
606
  const postTags = this.db.select({
334
- tag: sql3`unnest(${posts.tags})`.as("tag")
607
+ tag: sql4`unnest(${posts.tags})`.as("tag")
335
608
  }).from(posts).where(where).as("post_tags");
336
609
  const rows = await this.db.select({
337
610
  tag: postTags.tag,
338
- count: sql3`count(*)::int`
339
- }).from(postTags).groupBy(postTags.tag).orderBy(sql3`count(*) desc`, asc(postTags.tag)).limit(TAG_LIST_LIMIT);
611
+ count: sql4`count(*)::int`
612
+ }).from(postTags).groupBy(postTags.tag).orderBy(sql4`count(*) desc`, asc2(postTags.tag)).limit(TAG_LIST_LIMIT);
340
613
  return rows;
341
614
  }
342
615
  };
343
616
 
344
617
  // src/repositories/RecurrenceRepository.ts
345
- import { and as and3, asc as asc2, eq as eq3, lte as lte2 } from "drizzle-orm";
618
+ import { and as and4, asc as asc3, eq as eq4, lte as lte2 } from "drizzle-orm";
346
619
  function recurrenceOwnedByCondition(params) {
347
- return and3(eq3(recurrenceRules.companyId, params.companyId), eq3(recurrenceRules.id, params.id));
620
+ return and4(eq4(recurrenceRules.companyId, params.companyId), eq4(recurrenceRules.id, params.id));
348
621
  }
349
622
  __name(recurrenceOwnedByCondition, "recurrenceOwnedByCondition");
350
623
  var RecurrenceRepository = class {
@@ -365,7 +638,7 @@ var RecurrenceRepository = class {
365
638
  return row;
366
639
  }
367
640
  async list(params) {
368
- return this.db.select().from(recurrenceRules).where(eq3(recurrenceRules.companyId, params.companyId)).orderBy(asc2(recurrenceRules.nextRunAt), asc2(recurrenceRules.id));
641
+ return this.db.select().from(recurrenceRules).where(eq4(recurrenceRules.companyId, params.companyId)).orderBy(asc3(recurrenceRules.nextRunAt), asc3(recurrenceRules.id));
369
642
  }
370
643
  async update(params) {
371
644
  const [row] = await this.db.update(recurrenceRules).set(params.values).where(recurrenceOwnedByCondition(params)).returning();
@@ -379,13 +652,13 @@ var RecurrenceRepository = class {
379
652
  }
380
653
  async processDue(params) {
381
654
  return this.db.transaction(async (transaction) => {
382
- const due = await transaction.select().from(recurrenceRules).where(and3(eq3(recurrenceRules.isActive, true), lte2(recurrenceRules.nextRunAt, params.now))).orderBy(asc2(recurrenceRules.nextRunAt), asc2(recurrenceRules.id)).limit(params.limit).for("update", {
655
+ const due = await transaction.select().from(recurrenceRules).where(and4(eq4(recurrenceRules.isActive, true), lte2(recurrenceRules.nextRunAt, params.now))).orderBy(asc3(recurrenceRules.nextRunAt), asc3(recurrenceRules.id)).limit(params.limit).for("update", {
383
656
  skipLocked: true
384
657
  });
385
658
  let processed = 0;
386
659
  for (const rule of due) {
387
660
  const values = await params.handle(rule);
388
- await transaction.update(recurrenceRules).set(values).where(eq3(recurrenceRules.id, rule.id));
661
+ await transaction.update(recurrenceRules).set(values).where(eq4(recurrenceRules.id, rule.id));
389
662
  processed += 1;
390
663
  }
391
664
  return processed;
@@ -393,114 +666,11 @@ var RecurrenceRepository = class {
393
666
  }
394
667
  };
395
668
 
396
- // src/use-cases/Feed.use-cases.ts
397
- import { buildAtomFeed, buildExcerpt, buildPostUrl, buildRssFeed, renderMarkdownToHtml } from "@adatechnology/content-contracts";
398
- var DEFAULT_ITEM_LIMIT = 20;
399
- var SITEMAP_LIMIT = 5e4;
400
- var FEED_FORMAT = {
401
- RSS: "rss",
402
- ATOM: "atom"
403
- };
404
- var BuildFeedUseCase = class {
405
- static {
406
- __name(this, "BuildFeedUseCase");
407
- }
408
- dependencies;
409
- feed;
410
- constructor(dependencies, feed) {
411
- this.dependencies = dependencies;
412
- this.feed = feed;
413
- }
414
- async execute(params) {
415
- const now = this.dependencies.clock.now();
416
- const page = await this.dependencies.posts.listPublic({
417
- companyId: params.companyId,
418
- now,
419
- page: 1,
420
- pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT
421
- });
422
- const channel = {
423
- siteUrl: this.feed.siteUrl,
424
- title: this.feed.title,
425
- ...this.feed.description ? {
426
- description: this.feed.description
427
- } : {},
428
- ...this.feed.language ? {
429
- language: this.feed.language
430
- } : {},
431
- ...params.feedUrl ? {
432
- feedUrl: params.feedUrl
433
- } : {}
434
- };
435
- const items = page.rows.map((row) => this.toItem(row));
436
- return params.format === FEED_FORMAT.ATOM ? buildAtomFeed({
437
- channel,
438
- items,
439
- now
440
- }) : buildRssFeed({
441
- channel,
442
- items
443
- });
444
- }
445
- toItem(row) {
446
- return {
447
- title: row.title,
448
- url: buildPostUrl({
449
- siteUrl: this.feed.siteUrl,
450
- slug: row.slug,
451
- shortId: row.shortId,
452
- postPathTemplate: this.feed.postPathTemplate
453
- }),
454
- publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
455
- updatedAt: row.updatedAt.toISOString(),
456
- summary: row.excerpt ?? buildExcerpt(row.body),
457
- ...this.feed.includeContent ?? true ? {
458
- contentHtml: renderMarkdownToHtml(row.body, {
459
- headingIds: false
460
- })
461
- } : {},
462
- ...row.authorName ? {
463
- authorName: row.authorName
464
- } : {},
465
- categories: row.tags,
466
- ...row.coverImageUrl ? {
467
- imageUrl: row.coverImageUrl
468
- } : {}
469
- };
470
- }
471
- };
472
- var ListSitemapEntriesUseCase = class {
473
- static {
474
- __name(this, "ListSitemapEntriesUseCase");
475
- }
476
- dependencies;
477
- feed;
478
- constructor(dependencies, feed) {
479
- this.dependencies = dependencies;
480
- this.feed = feed;
481
- }
482
- /** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */
483
- async execute(params) {
484
- const page = await this.dependencies.posts.listPublic({
485
- companyId: params.companyId,
486
- now: this.dependencies.clock.now(),
487
- page: 1,
488
- pageSize: SITEMAP_LIMIT
489
- });
490
- return page.rows.map((row) => ({
491
- loc: buildPostUrl({
492
- siteUrl: this.feed.siteUrl,
493
- slug: row.slug,
494
- shortId: row.shortId,
495
- postPathTemplate: this.feed.postPathTemplate
496
- }),
497
- lastmod: row.updatedAt.toISOString()
498
- }));
499
- }
500
- };
669
+ // src/use-cases/community/ContentSettings.use-cases.ts
670
+ import { contentSettingsSchema } from "@adatechnology/content-contracts";
501
671
 
502
672
  // src/use-cases/Post.use-cases.ts
503
- import { buildTagLabels, createPostSchema, DuplicateSlugError, estimateReadingTimeMinutes, listPostsQuerySchema, normalizeTags, POST_EVENT, POST_STATUS as POST_STATUS4, PostNotFoundError, TemplateNotPublishableError, publishPostSchema, buildShortSlug, updatePostSchema, withSlugSuffix } from "@adatechnology/content-contracts";
673
+ import { buildTagLabels, CommunityPostReadOnlyError, createPostSchema, DuplicateSlugError, estimateReadingTimeMinutes, listPostsQuerySchema, normalizeTags, POST_EVENT, POST_ORIGIN as POST_ORIGIN5, POST_STATUS as POST_STATUS5, PostNotFoundError, TemplateNotPublishableError, publishPostSchema, buildShortSlug, updatePostSchema, withSlugSuffix } from "@adatechnology/content-contracts";
504
674
 
505
675
  // src/shared/shortId.ts
506
676
  import { randomInt } from "crypto";
@@ -545,13 +715,19 @@ async function notifyPostChanged(dependencies, type, post) {
545
715
  __name(notifyPostChanged, "notifyPostChanged");
546
716
 
547
717
  // src/shared/toContract.ts
548
- import { POST_STATUS as POST_STATUS3 } from "@adatechnology/content-contracts";
718
+ import { communityRevisionSchema, POST_ORIGIN as POST_ORIGIN4, POST_STATUS as POST_STATUS4 } from "@adatechnology/content-contracts";
549
719
  function effectiveStatus(row, now) {
550
- if (row.status === POST_STATUS3.SCHEDULED && row.publishedAt && row.publishedAt <= now) return POST_STATUS3.PUBLISHED;
720
+ if (row.status === POST_STATUS4.SCHEDULED && row.publishedAt && row.publishedAt <= now) return POST_STATUS4.PUBLISHED;
551
721
  return row.status;
552
722
  }
553
723
  __name(effectiveStatus, "effectiveStatus");
554
- function toPostSummary(row, now) {
724
+ function readPendingRevision(row) {
725
+ if (row.pendingRevision === null || row.pendingRevision === void 0) return null;
726
+ const parsed = communityRevisionSchema.safeParse(row.pendingRevision);
727
+ return parsed.success ? parsed.data : null;
728
+ }
729
+ __name(readPendingRevision, "readPendingRevision");
730
+ function toPostSummary(row, now, openReportCount = 0) {
555
731
  return {
556
732
  id: row.id,
557
733
  companyId: row.companyId,
@@ -572,17 +748,34 @@ function toPostSummary(row, now) {
572
748
  canonicalUrl: row.canonicalUrl,
573
749
  readingTimeMinutes: row.readingTimeMinutes,
574
750
  createdAt: row.createdAt.toISOString(),
575
- updatedAt: row.updatedAt.toISOString()
751
+ updatedAt: row.updatedAt.toISOString(),
752
+ origin: row.origin,
753
+ authorAccountId: row.authorAccountId,
754
+ authorDisplayName: row.authorDisplayName,
755
+ authorReferenceMonth: row.authorReferenceMonth,
756
+ reviewNote: row.reviewNote,
757
+ termsAcceptedAt: row.termsAcceptedAt?.toISOString() ?? null,
758
+ submittedAt: row.submittedAt?.toISOString() ?? null,
759
+ pendingRevision: readPendingRevision(row),
760
+ openReportCount
576
761
  };
577
762
  }
578
763
  __name(toPostSummary, "toPostSummary");
579
- function toPost(row, now) {
764
+ function toPost(row, now, openReportCount = 0) {
580
765
  return {
581
- ...toPostSummary(row, now),
766
+ ...toPostSummary(row, now, openReportCount),
582
767
  body: row.body
583
768
  };
584
769
  }
585
770
  __name(toPost, "toPost");
771
+ function toCommunityAuthor(row) {
772
+ if (row.origin !== POST_ORIGIN4.COMMUNITY) return null;
773
+ return {
774
+ displayName: row.authorDisplayName ?? "",
775
+ referenceMonth: row.authorReferenceMonth
776
+ };
777
+ }
778
+ __name(toCommunityAuthor, "toCommunityAuthor");
586
779
  function toPublicPostSummary(row) {
587
780
  return {
588
781
  id: row.id,
@@ -600,7 +793,9 @@ function toPublicPostSummary(row) {
600
793
  seoTitle: row.seoTitle,
601
794
  seoDescription: row.seoDescription,
602
795
  canonicalUrl: row.canonicalUrl,
603
- readingTimeMinutes: row.readingTimeMinutes
796
+ readingTimeMinutes: row.readingTimeMinutes,
797
+ origin: row.origin,
798
+ communityAuthor: toCommunityAuthor(row)
604
799
  };
605
800
  }
606
801
  __name(toPublicPostSummary, "toPublicPostSummary");
@@ -618,6 +813,36 @@ function toPagination(params) {
618
813
  };
619
814
  }
620
815
  __name(toPagination, "toPagination");
816
+ function toCommunityPost(row) {
817
+ return {
818
+ id: row.id,
819
+ shortId: row.shortId,
820
+ slug: row.slug,
821
+ title: row.title,
822
+ excerpt: row.excerpt,
823
+ body: row.body,
824
+ coverImageUrl: row.coverImageUrl,
825
+ status: row.status,
826
+ displayName: row.authorDisplayName ?? "",
827
+ reviewNote: row.reviewNote,
828
+ pendingRevision: readPendingRevision(row),
829
+ publishedAt: row.publishedAt?.toISOString() ?? null,
830
+ createdAt: row.createdAt.toISOString(),
831
+ updatedAt: row.updatedAt.toISOString()
832
+ };
833
+ }
834
+ __name(toCommunityPost, "toCommunityPost");
835
+ function toPostReport(row) {
836
+ return {
837
+ id: row.id,
838
+ postId: row.postId,
839
+ reason: row.reason,
840
+ createdAt: row.createdAt.toISOString(),
841
+ resolvedAt: row.resolvedAt?.toISOString() ?? null,
842
+ resolvedBy: row.resolvedBy
843
+ };
844
+ }
845
+ __name(toPostReport, "toPostReport");
621
846
 
622
847
  // src/use-cases/Post.use-cases.ts
623
848
  var MAX_SLUG_ATTEMPTS = 50;
@@ -638,6 +863,22 @@ var PostUseCaseBase = class {
638
863
  if (!row) throw new PostNotFoundError(reference2.id);
639
864
  return row;
640
865
  }
866
+ /** Ações de edição da equipe: a equipe modera post da comunidade, não o reescreve (design §4). */
867
+ async findEditableOrFail(reference2) {
868
+ const row = await this.findOrFail(reference2);
869
+ if (row.origin === POST_ORIGIN5.COMMUNITY) throw new CommunityPostReadOnlyError(reference2.id);
870
+ return row;
871
+ }
872
+ /** Denúncias abertas por post numa consulta só; sem o módulo de comunidade, ninguém tem denúncia. */
873
+ async openReportCounts(params) {
874
+ const { community } = this.dependencies;
875
+ const postIds = params.rows.filter((row) => row.origin === POST_ORIGIN5.COMMUNITY).map((row) => row.id);
876
+ if (!community || postIds.length === 0) return /* @__PURE__ */ new Map();
877
+ return community.countOpenReports({
878
+ companyId: params.companyId,
879
+ postIds
880
+ });
881
+ }
641
882
  async save(reference2, values, event) {
642
883
  const row = await this.dependencies.posts.update({
643
884
  ...reference2,
@@ -719,7 +960,7 @@ var CreatePostUseCase = class extends PostUseCaseBase {
719
960
  typed: input.tags ?? [],
720
961
  explicit: input.tagLabels
721
962
  }),
722
- status: POST_STATUS4.DRAFT,
963
+ status: POST_STATUS5.DRAFT,
723
964
  readingTimeMinutes: this.readingTime(input.body),
724
965
  ...optionalFields(input)
725
966
  }).catch((error) => {
@@ -738,7 +979,7 @@ var UpdatePostUseCase = class extends PostUseCaseBase {
738
979
  /** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */
739
980
  async execute(params) {
740
981
  const input = updatePostSchema.parse(params.input);
741
- const existing = await this.findOrFail(params);
982
+ const existing = await this.findEditableOrFail(params);
742
983
  const values = optionalFields(input);
743
984
  if (input.title !== void 0) values.title = input.title;
744
985
  if (input.body !== void 0) {
@@ -773,11 +1014,11 @@ var PublishPostUseCase = class extends PostUseCaseBase {
773
1014
  /** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */
774
1015
  async execute(params) {
775
1016
  const input = publishPostSchema.parse(params.input ?? {});
776
- const existing = await this.findOrFail(params);
1017
+ const existing = await this.findEditableOrFail(params);
777
1018
  if (existing.isTemplate) throw new TemplateNotPublishableError(params.id);
778
1019
  const now = this.now();
779
1020
  const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
780
- const status = publishedAt > now ? POST_STATUS4.SCHEDULED : POST_STATUS4.PUBLISHED;
1021
+ const status = publishedAt > now ? POST_STATUS5.SCHEDULED : POST_STATUS5.PUBLISHED;
781
1022
  return this.save(params, {
782
1023
  status,
783
1024
  publishedAt
@@ -790,9 +1031,9 @@ var UnpublishPostUseCase = class extends PostUseCaseBase {
790
1031
  }
791
1032
  /** Volta a rascunho e tira do ar na hora, inclusive cancelando um agendamento. */
792
1033
  async execute(params) {
793
- await this.findOrFail(params);
1034
+ await this.findEditableOrFail(params);
794
1035
  return this.save(params, {
795
- status: POST_STATUS4.DRAFT,
1036
+ status: POST_STATUS5.DRAFT,
796
1037
  publishedAt: null
797
1038
  }, POST_EVENT.UNPUBLISHED);
798
1039
  }
@@ -805,7 +1046,7 @@ var ArchivePostUseCase = class extends PostUseCaseBase {
805
1046
  async execute(params) {
806
1047
  await this.findOrFail(params);
807
1048
  return this.save(params, {
808
- status: POST_STATUS4.ARCHIVED
1049
+ status: POST_STATUS5.ARCHIVED
809
1050
  }, POST_EVENT.ARCHIVED);
810
1051
  }
811
1052
  };
@@ -814,41 +1055,1024 @@ var GetPostUseCase = class extends PostUseCaseBase {
814
1055
  __name(this, "GetPostUseCase");
815
1056
  }
816
1057
  async execute(params) {
817
- return toPost(await this.findOrFail(params), this.now());
1058
+ const row = await this.findOrFail(params);
1059
+ const counts = await this.openReportCounts({
1060
+ companyId: params.companyId,
1061
+ rows: [
1062
+ row
1063
+ ]
1064
+ });
1065
+ return toPost(row, this.now(), counts.get(row.id) ?? 0);
1066
+ }
1067
+ };
1068
+ var ListPostsUseCase = class extends PostUseCaseBase {
1069
+ static {
1070
+ __name(this, "ListPostsUseCase");
1071
+ }
1072
+ async execute(params) {
1073
+ const { companyId, ...rawQuery } = params;
1074
+ const query = listPostsQuerySchema.parse(rawQuery);
1075
+ const { tag: rawTag, ...rest } = query;
1076
+ const tags = rawTag ? normalizeTags(rawTag.split(",")) : [];
1077
+ const now = this.now();
1078
+ const page = await this.dependencies.posts.listForAdmin({
1079
+ companyId,
1080
+ ...rest,
1081
+ isTemplate: query.isTemplate ?? false,
1082
+ now,
1083
+ ...tags.length > 0 ? {
1084
+ tags
1085
+ } : {}
1086
+ });
1087
+ const counts = await this.openReportCounts({
1088
+ companyId,
1089
+ rows: page.rows
1090
+ });
1091
+ return {
1092
+ data: page.rows.map((row) => toPostSummary(row, now, counts.get(row.id) ?? 0)),
1093
+ pagination: toPagination({
1094
+ total: page.total,
1095
+ page: query.page,
1096
+ pageSize: query.pageSize
1097
+ })
1098
+ };
1099
+ }
1100
+ };
1101
+
1102
+ // src/use-cases/community/ContentSettings.use-cases.ts
1103
+ var ContentSettingsUseCaseBase = class ContentSettingsUseCaseBase2 extends PostUseCaseBase {
1104
+ static {
1105
+ __name(this, "ContentSettingsUseCaseBase");
1106
+ }
1107
+ dependencies;
1108
+ constructor(dependencies) {
1109
+ super(dependencies), this.dependencies = dependencies;
1110
+ }
1111
+ };
1112
+ var GetContentSettingsUseCase = class extends ContentSettingsUseCaseBase {
1113
+ static {
1114
+ __name(this, "GetContentSettingsUseCase");
1115
+ }
1116
+ /** Sem linha da empresa, o padrão do contracts. */
1117
+ execute(params) {
1118
+ return this.dependencies.community.getSettings(params);
1119
+ }
1120
+ };
1121
+ var UpdateContentSettingsUseCase = class extends ContentSettingsUseCaseBase {
1122
+ static {
1123
+ __name(this, "UpdateContentSettingsUseCase");
1124
+ }
1125
+ /** Vale para os próximos envios: o que já está em análise ou no ar não muda de estado. */
1126
+ async execute(params) {
1127
+ const settings = contentSettingsSchema.parse(params.input);
1128
+ return this.dependencies.community.upsertSettings({
1129
+ companyId: params.companyId,
1130
+ settings,
1131
+ now: this.now()
1132
+ });
1133
+ }
1134
+ };
1135
+
1136
+ // src/use-cases/community/CreateCommunityPost.use-case.ts
1137
+ import { CommunityDailyLimitError, createCommunityPostSchema, DuplicateSlugError as DuplicateSlugError2, POST_EVENT as POST_EVENT2, POST_ORIGIN as POST_ORIGIN7, POST_STATUS as POST_STATUS7 } from "@adatechnology/content-contracts";
1138
+
1139
+ // src/use-cases/community/CommunityUseCaseBase.ts
1140
+ import { collectImageSources, CommunityImageNotAllowedError, CommunityTooManyImagesError, parseMarkdown, POST_ORIGIN as POST_ORIGIN6, POST_STATUS as POST_STATUS6, PostNotFoundError as PostNotFoundError2 } from "@adatechnology/content-contracts";
1141
+ var CommunityUseCaseBase = class extends PostUseCaseBase {
1142
+ static {
1143
+ __name(this, "CommunityUseCaseBase");
1144
+ }
1145
+ dependencies;
1146
+ constructor(dependencies) {
1147
+ super(dependencies), this.dependencies = dependencies;
1148
+ }
1149
+ getSettings(companyId) {
1150
+ return this.dependencies.community.getSettings({
1151
+ companyId
1152
+ });
1153
+ }
1154
+ async findOwned(author, id) {
1155
+ const row = await this.dependencies.posts.findById({
1156
+ companyId: author.companyId,
1157
+ id
1158
+ });
1159
+ const isOwned = row?.origin === POST_ORIGIN6.COMMUNITY && row.authorAccountId === author.accountId && row.status !== POST_STATUS6.ARCHIVED;
1160
+ if (!row || !isOwned) throw new PostNotFoundError2(id);
1161
+ return row;
1162
+ }
1163
+ async persist(params) {
1164
+ const { author, id, values, event } = params;
1165
+ const row = await this.dependencies.posts.update({
1166
+ companyId: author.companyId,
1167
+ id,
1168
+ values
1169
+ });
1170
+ if (!row) throw new PostNotFoundError2(id);
1171
+ await notifyPostChanged(this.dependencies, event, toPost(row, this.now()));
1172
+ return row;
1173
+ }
1174
+ /** Só foto enviada por esta conta, nesta empresa, entra no corpo: URL externa seria rastreio sem moderação. */
1175
+ async assertBodyImages(params) {
1176
+ const sources = collectImageSources(parseMarkdown(params.body));
1177
+ if (sources.length > params.settings.maxImagesPerPost) {
1178
+ throw new CommunityTooManyImagesError(params.settings.maxImagesPerPost);
1179
+ }
1180
+ const unique = [
1181
+ ...new Set(sources)
1182
+ ];
1183
+ const owned = await this.dependencies.community.findOwnedImageUrls({
1184
+ companyId: params.author.companyId,
1185
+ accountId: params.author.accountId,
1186
+ urls: unique
1187
+ });
1188
+ if (owned.length !== unique.length) throw new CommunityImageNotAllowedError();
1189
+ return sources;
1190
+ }
1191
+ };
1192
+
1193
+ // src/use-cases/community/CreateCommunityPost.use-case.ts
1194
+ var MIN_RETRY_SECONDS = 1;
1195
+ var CreateCommunityPostUseCase = class extends CommunityUseCaseBase {
1196
+ static {
1197
+ __name(this, "CreateCommunityPostUseCase");
1198
+ }
1199
+ async execute(params) {
1200
+ const { author } = params;
1201
+ const input = createCommunityPostSchema.parse(params.input);
1202
+ const settings = await this.getSettings(author.companyId);
1203
+ const sources = await this.assertBodyImages({
1204
+ author,
1205
+ body: input.body,
1206
+ settings
1207
+ });
1208
+ const slug = await this.generateSlug(author.companyId, input.title);
1209
+ const now = this.now();
1210
+ const outcome = await this.dependencies.community.createWithDailyLimit({
1211
+ accountId: author.accountId,
1212
+ limit: settings.communityDailyLimit,
1213
+ now,
1214
+ values: {
1215
+ companyId: author.companyId,
1216
+ slug,
1217
+ shortId: await this.generateShortId(author.companyId),
1218
+ title: input.title,
1219
+ body: input.body,
1220
+ excerpt: input.excerpt || null,
1221
+ coverImageUrl: sources[0] ?? null,
1222
+ status: POST_STATUS7.DRAFT,
1223
+ origin: POST_ORIGIN7.COMMUNITY,
1224
+ authorAccountId: author.accountId,
1225
+ authorDisplayName: input.displayName ?? author.defaultDisplayName,
1226
+ readingTimeMinutes: this.readingTime(input.body),
1227
+ createdAt: now,
1228
+ updatedAt: now
1229
+ }
1230
+ }).catch((error) => {
1231
+ if (isUniqueViolation(error)) throw new DuplicateSlugError2(slug);
1232
+ throw error;
1233
+ });
1234
+ if (outcome.isLimited) {
1235
+ const seconds = Math.ceil((outcome.freesUpAt.getTime() - now.getTime()) / 1e3);
1236
+ throw new CommunityDailyLimitError(settings.communityDailyLimit, Math.max(MIN_RETRY_SECONDS, seconds));
1237
+ }
1238
+ await notifyPostChanged(this.dependencies, POST_EVENT2.CREATED, toPost(outcome.row, now));
1239
+ return toCommunityPost(outcome.row);
1240
+ }
1241
+ };
1242
+
1243
+ // src/use-cases/community/DeleteOwnCommunityPost.use-case.ts
1244
+ import { POST_EVENT as POST_EVENT3, POST_STATUS as POST_STATUS8 } from "@adatechnology/content-contracts";
1245
+ var ANONYMIZED_VALUES = {
1246
+ status: POST_STATUS8.ARCHIVED,
1247
+ title: ANONYMIZED_TITLE,
1248
+ body: "",
1249
+ excerpt: null,
1250
+ coverImageUrl: null,
1251
+ coverImageAlt: null,
1252
+ authorDisplayName: null,
1253
+ pendingRevision: null,
1254
+ reviewNote: null,
1255
+ readingTimeMinutes: 1
1256
+ };
1257
+ var DeleteOwnCommunityPostUseCase = class extends CommunityUseCaseBase {
1258
+ static {
1259
+ __name(this, "DeleteOwnCommunityPostUseCase");
1260
+ }
1261
+ async execute(params) {
1262
+ await this.findOwned(params.author, params.id);
1263
+ await this.persist({
1264
+ author: params.author,
1265
+ id: params.id,
1266
+ values: ANONYMIZED_VALUES,
1267
+ event: POST_EVENT3.ARCHIVED
1268
+ });
1269
+ }
1270
+ };
1271
+
1272
+ // src/use-cases/community/ReadOwnCommunityPosts.use-cases.ts
1273
+ import { POST_LIMITS } from "@adatechnology/content-contracts";
1274
+ var DEFAULT_PAGE_SIZE = 20;
1275
+ var ListOwnCommunityPostsUseCase = class extends CommunityUseCaseBase {
1276
+ static {
1277
+ __name(this, "ListOwnCommunityPostsUseCase");
1278
+ }
1279
+ async execute(params) {
1280
+ const page = Math.max(1, Math.trunc(params.page ?? 1));
1281
+ const pageSize = Math.min(POST_LIMITS.PUBLIC_PAGE_SIZE, Math.max(1, Math.trunc(params.pageSize ?? DEFAULT_PAGE_SIZE)));
1282
+ const result = await this.dependencies.community.listByAuthor({
1283
+ companyId: params.author.companyId,
1284
+ accountId: params.author.accountId,
1285
+ page,
1286
+ pageSize
1287
+ });
1288
+ return {
1289
+ data: result.rows.map(toCommunityPost),
1290
+ pagination: toPagination({
1291
+ total: result.total,
1292
+ page,
1293
+ pageSize
1294
+ })
1295
+ };
1296
+ }
1297
+ };
1298
+ var GetOwnCommunityPostUseCase = class extends CommunityUseCaseBase {
1299
+ static {
1300
+ __name(this, "GetOwnCommunityPostUseCase");
1301
+ }
1302
+ async execute(params) {
1303
+ return toCommunityPost(await this.findOwned(params.author, params.id));
1304
+ }
1305
+ };
1306
+
1307
+ // src/use-cases/community/ModerateCommunityPost.use-cases.ts
1308
+ import { collectImageSources as collectImageSources2, COMMUNITY_REVISION_STATE as COMMUNITY_REVISION_STATE4, InvalidPostTransitionError, parseMarkdown as parseMarkdown2, POST_EVENT as POST_EVENT4, POST_STATUS as POST_STATUS9, rejectPostSchema, unpublishCommunityPostSchema } from "@adatechnology/content-contracts";
1309
+
1310
+ // src/use-cases/community/CommunityModerationUseCaseBase.ts
1311
+ import { COMMUNITY_REVISION_STATE as COMMUNITY_REVISION_STATE3, POST_ORIGIN as POST_ORIGIN8, PostNotFoundError as PostNotFoundError3 } from "@adatechnology/content-contracts";
1312
+
1313
+ // src/shared/notifyCommunityPostReviewed.ts
1314
+ async function notifyCommunityPostReviewed(dependencies, event) {
1315
+ const hook = dependencies.hooks?.onCommunityPostReviewed;
1316
+ if (!hook) return;
1317
+ try {
1318
+ await hook(event);
1319
+ } catch (error) {
1320
+ dependencies.logger?.error("content-module: hook onCommunityPostReviewed falhou", {
1321
+ postId: event.postId,
1322
+ decision: event.decision,
1323
+ error: error instanceof Error ? error.message : String(error)
1324
+ });
1325
+ }
1326
+ }
1327
+ __name(notifyCommunityPostReviewed, "notifyCommunityPostReviewed");
1328
+
1329
+ // src/use-cases/community/CommunityModerationUseCaseBase.ts
1330
+ var CommunityModerationUseCaseBase = class extends PostUseCaseBase {
1331
+ static {
1332
+ __name(this, "CommunityModerationUseCaseBase");
1333
+ }
1334
+ dependencies;
1335
+ constructor(dependencies) {
1336
+ super(dependencies), this.dependencies = dependencies;
1337
+ }
1338
+ async findCommunityPost(reference2) {
1339
+ const row = await this.dependencies.posts.findById(reference2);
1340
+ if (!row || row.origin !== POST_ORIGIN8.COMMUNITY) throw new PostNotFoundError3(reference2.id);
1341
+ return row;
1342
+ }
1343
+ /** Revisão que ainda espera decisão; uma já recusada não volta para a fila. */
1344
+ openRevision(row) {
1345
+ const revision = readPendingRevision(row);
1346
+ return revision?.state === COMMUNITY_REVISION_STATE3.PENDING ? revision : null;
1347
+ }
1348
+ async decide(params) {
1349
+ const { row, values, event, decision, target, actorUserId } = params;
1350
+ const updated = await this.dependencies.posts.update({
1351
+ companyId: row.companyId,
1352
+ id: row.id,
1353
+ values
1354
+ });
1355
+ if (!updated) throw new PostNotFoundError3(row.id);
1356
+ const post = toPost(updated, this.now());
1357
+ await notifyPostChanged(this.dependencies, event, post);
1358
+ await notifyCommunityPostReviewed(this.dependencies, {
1359
+ companyId: row.companyId,
1360
+ postId: row.id,
1361
+ authorAccountId: row.authorAccountId ?? "",
1362
+ decision,
1363
+ target,
1364
+ actorUserId,
1365
+ statusBefore: row.status,
1366
+ statusAfter: updated.status
1367
+ });
1368
+ return post;
1369
+ }
1370
+ };
1371
+
1372
+ // src/use-cases/community/ModerateCommunityPost.use-cases.ts
1373
+ var ApproveCommunityPostUseCase = class extends CommunityModerationUseCaseBase {
1374
+ static {
1375
+ __name(this, "ApproveCommunityPostUseCase");
1376
+ }
1377
+ async execute(params) {
1378
+ const row = await this.findCommunityPost(params);
1379
+ const { actorUserId } = params;
1380
+ if (row.status === POST_STATUS9.PENDING_REVIEW) {
1381
+ const values = {
1382
+ status: POST_STATUS9.PUBLISHED,
1383
+ publishedAt: this.now(),
1384
+ reviewNote: null,
1385
+ pendingRevision: null
1386
+ };
1387
+ return this.decide({
1388
+ row,
1389
+ values,
1390
+ event: POST_EVENT4.PUBLISHED,
1391
+ decision: "approved",
1392
+ target: "post",
1393
+ actorUserId
1394
+ });
1395
+ }
1396
+ const revision = this.openRevision(row);
1397
+ if (row.status === POST_STATUS9.PUBLISHED && revision) {
1398
+ const values = this.revisionValues(revision);
1399
+ return this.decide({
1400
+ row,
1401
+ values,
1402
+ event: POST_EVENT4.UPDATED,
1403
+ decision: "approved",
1404
+ target: "revision",
1405
+ actorUserId
1406
+ });
1407
+ }
1408
+ throw new InvalidPostTransitionError(row.status, COMMUNITY_ACTION.APPROVE);
1409
+ }
1410
+ revisionValues(revision) {
1411
+ return {
1412
+ title: revision.title,
1413
+ excerpt: revision.excerpt,
1414
+ body: revision.body,
1415
+ readingTimeMinutes: this.readingTime(revision.body),
1416
+ coverImageUrl: collectImageSources2(parseMarkdown2(revision.body))[0] ?? null,
1417
+ pendingRevision: null,
1418
+ reviewNote: null
1419
+ };
1420
+ }
1421
+ };
1422
+ var RejectCommunityPostUseCase = class extends CommunityModerationUseCaseBase {
1423
+ static {
1424
+ __name(this, "RejectCommunityPostUseCase");
1425
+ }
1426
+ async execute(params) {
1427
+ const { note } = rejectPostSchema.parse(params.input);
1428
+ const row = await this.findCommunityPost(params);
1429
+ const { actorUserId } = params;
1430
+ if (row.status === POST_STATUS9.PENDING_REVIEW) {
1431
+ const values = {
1432
+ status: POST_STATUS9.REJECTED,
1433
+ reviewNote: note
1434
+ };
1435
+ return this.decide({
1436
+ row,
1437
+ values,
1438
+ event: POST_EVENT4.UPDATED,
1439
+ decision: "rejected",
1440
+ target: "post",
1441
+ actorUserId
1442
+ });
1443
+ }
1444
+ const revision = this.openRevision(row);
1445
+ if (row.status === POST_STATUS9.PUBLISHED && revision) {
1446
+ const values = {
1447
+ pendingRevision: {
1448
+ ...revision,
1449
+ state: COMMUNITY_REVISION_STATE4.REJECTED
1450
+ },
1451
+ reviewNote: note
1452
+ };
1453
+ return this.decide({
1454
+ row,
1455
+ values,
1456
+ event: POST_EVENT4.UPDATED,
1457
+ decision: "rejected",
1458
+ target: "revision",
1459
+ actorUserId
1460
+ });
1461
+ }
1462
+ throw new InvalidPostTransitionError(row.status, COMMUNITY_ACTION.REJECT);
1463
+ }
1464
+ };
1465
+ var UnpublishCommunityPostUseCase = class extends CommunityModerationUseCaseBase {
1466
+ static {
1467
+ __name(this, "UnpublishCommunityPostUseCase");
1468
+ }
1469
+ /** Tira do ar sem apagar: o autor vê a nota e pode editar e reenviar. A revisão aberta some junto. */
1470
+ async execute(params) {
1471
+ const { note } = unpublishCommunityPostSchema.parse(params.input ?? {});
1472
+ const row = await this.findCommunityPost(params);
1473
+ if (row.status !== POST_STATUS9.PUBLISHED) {
1474
+ throw new InvalidPostTransitionError(row.status, COMMUNITY_ACTION.UNPUBLISH);
1475
+ }
1476
+ const values = {
1477
+ status: POST_STATUS9.REJECTED,
1478
+ reviewNote: note ?? null,
1479
+ pendingRevision: null
1480
+ };
1481
+ return this.decide({
1482
+ row,
1483
+ values,
1484
+ event: POST_EVENT4.UNPUBLISHED,
1485
+ decision: "unpublished",
1486
+ target: "post",
1487
+ actorUserId: params.actorUserId
1488
+ });
1489
+ }
1490
+ };
1491
+ var ArchiveCommunityPostUseCase = class extends CommunityModerationUseCaseBase {
1492
+ static {
1493
+ __name(this, "ArchiveCommunityPostUseCase");
1494
+ }
1495
+ /** Idempotente: já arquivado devolve o post sem gravar nem avisar de novo. */
1496
+ async execute(params) {
1497
+ const row = await this.findCommunityPost(params);
1498
+ if (row.status === POST_STATUS9.ARCHIVED) return toPost(row, this.now());
1499
+ return this.decide({
1500
+ row,
1501
+ values: {
1502
+ status: POST_STATUS9.ARCHIVED,
1503
+ pendingRevision: null
1504
+ },
1505
+ event: POST_EVENT4.ARCHIVED,
1506
+ decision: "archived",
1507
+ target: "post",
1508
+ actorUserId: params.actorUserId
1509
+ });
1510
+ }
1511
+ };
1512
+
1513
+ // src/use-cases/community/ModerateCommunityPostsInBulk.use-case.ts
1514
+ import { bulkModerationSchema, ContentError, rejectPostSchema as rejectPostSchema2 } from "@adatechnology/content-contracts";
1515
+ var ModerateCommunityPostsInBulkUseCase = class extends CommunityModerationUseCaseBase {
1516
+ static {
1517
+ __name(this, "ModerateCommunityPostsInBulkUseCase");
1518
+ }
1519
+ actions;
1520
+ constructor(dependencies) {
1521
+ super(dependencies);
1522
+ const approve = new ApproveCommunityPostUseCase(dependencies);
1523
+ const reject = new RejectCommunityPostUseCase(dependencies);
1524
+ const unpublish = new UnpublishCommunityPostUseCase(dependencies);
1525
+ const archive = new ArchiveCommunityPostUseCase(dependencies);
1526
+ this.actions = {
1527
+ approve: /* @__PURE__ */ __name((item) => approve.execute(item), "approve"),
1528
+ reject: /* @__PURE__ */ __name((item, note) => reject.execute({
1529
+ ...item,
1530
+ input: {
1531
+ note: note ?? ""
1532
+ }
1533
+ }), "reject"),
1534
+ unpublish: /* @__PURE__ */ __name((item, note) => unpublish.execute({
1535
+ ...item,
1536
+ ...note ? {
1537
+ input: {
1538
+ note
1539
+ }
1540
+ } : {}
1541
+ }), "unpublish"),
1542
+ archive: /* @__PURE__ */ __name((item) => archive.execute(item), "archive")
1543
+ };
1544
+ }
1545
+ async execute(params) {
1546
+ const { action, ids, note } = bulkModerationSchema.parse(params.input);
1547
+ if (action === "reject") rejectPostSchema2.parse({
1548
+ note
1549
+ });
1550
+ const uniqueIds = [
1551
+ ...new Set(ids)
1552
+ ];
1553
+ const settled = await Promise.allSettled(uniqueIds.map((id) => this.actions[action]({
1554
+ companyId: params.companyId,
1555
+ id,
1556
+ actorUserId: params.actorUserId
1557
+ }, note)));
1558
+ const succeeded = [];
1559
+ const failed = [];
1560
+ settled.forEach((result, index2) => {
1561
+ const id = uniqueIds[index2] ?? "";
1562
+ if (result.status === "fulfilled") succeeded.push(id);
1563
+ else failed.push({
1564
+ id,
1565
+ ...describeFailure(result.reason)
1566
+ });
1567
+ });
1568
+ return {
1569
+ succeeded,
1570
+ failed
1571
+ };
1572
+ }
1573
+ };
1574
+ function describeFailure(reason) {
1575
+ if (reason instanceof ContentError) return {
1576
+ code: reason.code,
1577
+ message: reason.message
1578
+ };
1579
+ return BULK_UNEXPECTED_FAILURE;
1580
+ }
1581
+ __name(describeFailure, "describeFailure");
1582
+
1583
+ // src/use-cases/community/PostReport.use-cases.ts
1584
+ import { createPostReportSchema, listPostReportsQuerySchema, POST_ORIGIN as POST_ORIGIN9, PostNotFoundError as PostNotFoundError4, ReportNotFoundError } from "@adatechnology/content-contracts";
1585
+
1586
+ // src/shared/notifyPostReported.ts
1587
+ async function notifyPostReported(dependencies, event) {
1588
+ const hook = dependencies.hooks?.onPostReported;
1589
+ if (!hook) return;
1590
+ try {
1591
+ await hook(event);
1592
+ } catch (error) {
1593
+ dependencies.logger?.error("content-module: hook onPostReported falhou", {
1594
+ postId: event.postId,
1595
+ reportId: event.reportId,
1596
+ error: error instanceof Error ? error.message : String(error)
1597
+ });
1598
+ }
1599
+ }
1600
+ __name(notifyPostReported, "notifyPostReported");
1601
+
1602
+ // src/use-cases/community/PostReport.use-cases.ts
1603
+ var PostReportUseCaseBase = class PostReportUseCaseBase2 extends PostUseCaseBase {
1604
+ static {
1605
+ __name(this, "PostReportUseCaseBase");
1606
+ }
1607
+ dependencies;
1608
+ constructor(dependencies) {
1609
+ super(dependencies), this.dependencies = dependencies;
1610
+ }
1611
+ };
1612
+ var CreatePostReportUseCase = class extends PostReportUseCaseBase {
1613
+ static {
1614
+ __name(this, "CreatePostReportUseCase");
1615
+ }
1616
+ /** Só post da comunidade e público: qualquer outro caso é 404, para não revelar rascunho nem post da equipe. */
1617
+ async execute(params) {
1618
+ const { reason } = createPostReportSchema.parse(params.input);
1619
+ const { companyId, postId } = params;
1620
+ const now = this.now();
1621
+ const post = await this.dependencies.posts.findPublicById({
1622
+ companyId,
1623
+ id: postId,
1624
+ now
1625
+ });
1626
+ if (!post || post.origin !== POST_ORIGIN9.COMMUNITY) throw new PostNotFoundError4(postId);
1627
+ const row = await this.dependencies.community.createReport({
1628
+ companyId,
1629
+ postId,
1630
+ reason,
1631
+ now
1632
+ });
1633
+ await notifyPostReported(this.dependencies, {
1634
+ companyId,
1635
+ postId,
1636
+ reportId: row.id
1637
+ });
1638
+ return toPostReport(row);
1639
+ }
1640
+ };
1641
+ var ListPostReportsUseCase = class extends PostReportUseCaseBase {
1642
+ static {
1643
+ __name(this, "ListPostReportsUseCase");
1644
+ }
1645
+ async execute(params) {
1646
+ const { companyId, ...rawQuery } = params;
1647
+ const query = listPostReportsQuerySchema.parse(rawQuery);
1648
+ const page = await this.dependencies.community.listReports({
1649
+ companyId,
1650
+ ...query
1651
+ });
1652
+ return {
1653
+ data: page.rows.map(toPostReport),
1654
+ pagination: toPagination({
1655
+ total: page.total,
1656
+ page: query.page,
1657
+ pageSize: query.pageSize
1658
+ })
1659
+ };
1660
+ }
1661
+ };
1662
+ var ResolvePostReportUseCase = class extends PostReportUseCaseBase {
1663
+ static {
1664
+ __name(this, "ResolvePostReportUseCase");
1665
+ }
1666
+ /** Idempotente: resolver de novo devolve a denúncia como já estava. */
1667
+ async execute(params) {
1668
+ const row = await this.dependencies.community.resolveReport({
1669
+ ...params,
1670
+ now: this.now()
1671
+ });
1672
+ if (!row) throw new ReportNotFoundError(params.id);
1673
+ return toPostReport(row);
1674
+ }
1675
+ };
1676
+
1677
+ // src/use-cases/community/ResolveCommunityAuthor.use-case.ts
1678
+ import { CommunityAuthorNotEligibleError, CommunityUnauthenticatedError } from "@adatechnology/content-contracts";
1679
+ var ResolveCommunityAuthorUseCase = class {
1680
+ static {
1681
+ __name(this, "ResolveCommunityAuthorUseCase");
1682
+ }
1683
+ dependencies;
1684
+ constructor(dependencies) {
1685
+ this.dependencies = dependencies;
1686
+ }
1687
+ async execute(params) {
1688
+ const port = this.dependencies.communityAuthor;
1689
+ const identity = await port.resolveAuthor({
1690
+ headers: params.headers
1691
+ });
1692
+ if (!identity) throw new CommunityUnauthenticatedError();
1693
+ const eligibility = await port.checkEligibility({
1694
+ companyId: identity.companyId,
1695
+ accountId: identity.accountId
1696
+ });
1697
+ if (!eligibility.eligible) throw new CommunityAuthorNotEligibleError();
1698
+ return {
1699
+ companyId: identity.companyId,
1700
+ accountId: identity.accountId,
1701
+ defaultDisplayName: identity.defaultDisplayName,
1702
+ ...eligibility.referenceMonth ? {
1703
+ referenceMonth: eligibility.referenceMonth
1704
+ } : {}
1705
+ };
1706
+ }
1707
+ };
1708
+
1709
+ // src/use-cases/community/SubmitCommunityPost.use-case.ts
1710
+ import { COMMUNITY_MODERATION, CommunityTermsRequiredError, InvalidPostTransitionError as InvalidPostTransitionError2, POST_EVENT as POST_EVENT5, POST_STATUS as POST_STATUS10 } from "@adatechnology/content-contracts";
1711
+
1712
+ // src/shared/notifyCommunityPostSubmitted.ts
1713
+ async function notifyCommunityPostSubmitted(dependencies, event) {
1714
+ const hook = dependencies.hooks?.onCommunityPostSubmitted;
1715
+ if (!hook) return;
1716
+ try {
1717
+ await hook(event);
1718
+ } catch (error) {
1719
+ dependencies.logger?.error("content-module: hook onCommunityPostSubmitted falhou", {
1720
+ postId: event.postId,
1721
+ kind: event.kind,
1722
+ error: error instanceof Error ? error.message : String(error)
1723
+ });
1724
+ }
1725
+ }
1726
+ __name(notifyCommunityPostSubmitted, "notifyCommunityPostSubmitted");
1727
+
1728
+ // src/use-cases/community/SubmitCommunityPost.use-case.ts
1729
+ var SUBMITTABLE_STATUSES = [
1730
+ POST_STATUS10.DRAFT,
1731
+ POST_STATUS10.REJECTED
1732
+ ];
1733
+ var SubmitCommunityPostUseCase = class extends CommunityUseCaseBase {
1734
+ static {
1735
+ __name(this, "SubmitCommunityPostUseCase");
1736
+ }
1737
+ async execute(params) {
1738
+ const { author, id } = params;
1739
+ const row = await this.findOwned(author, id);
1740
+ if (params.termsAccepted !== true) throw new CommunityTermsRequiredError();
1741
+ if (!SUBMITTABLE_STATUSES.includes(row.status)) throw new InvalidPostTransitionError2(row.status, COMMUNITY_ACTION.SUBMIT);
1742
+ const settings = await this.getSettings(author.companyId);
1743
+ const isPublishedNow = settings.communityModeration === COMMUNITY_MODERATION.AFTER && row.status === POST_STATUS10.DRAFT;
1744
+ const now = this.now();
1745
+ const values = {
1746
+ status: isPublishedNow ? POST_STATUS10.PUBLISHED : POST_STATUS10.PENDING_REVIEW,
1747
+ termsAcceptedAt: now,
1748
+ submittedAt: now,
1749
+ reviewNote: null,
1750
+ ...isPublishedNow ? {
1751
+ publishedAt: now
1752
+ } : {},
1753
+ ...row.authorReferenceMonth === null && author.referenceMonth ? {
1754
+ authorReferenceMonth: author.referenceMonth
1755
+ } : {}
1756
+ };
1757
+ const updated = await this.persist({
1758
+ author,
1759
+ id,
1760
+ values,
1761
+ event: isPublishedNow ? POST_EVENT5.PUBLISHED : POST_EVENT5.UPDATED
1762
+ });
1763
+ await this.notifySubmitted(updated, settings.communityModeration);
1764
+ return toCommunityPost(updated);
1765
+ }
1766
+ notifySubmitted(row, moderation) {
1767
+ return notifyCommunityPostSubmitted(this.dependencies, {
1768
+ companyId: row.companyId,
1769
+ postId: row.id,
1770
+ authorAccountId: row.authorAccountId ?? "",
1771
+ kind: "new",
1772
+ moderation
1773
+ });
1774
+ }
1775
+ };
1776
+
1777
+ // src/use-cases/community/UpdateOwnCommunityPost.use-case.ts
1778
+ import { COMMUNITY_MODERATION as COMMUNITY_MODERATION2, COMMUNITY_REVISION_STATE as COMMUNITY_REVISION_STATE5, POST_EVENT as POST_EVENT6, POST_STATUS as POST_STATUS11, updateCommunityPostSchema } from "@adatechnology/content-contracts";
1779
+ var UpdateOwnCommunityPostUseCase = class extends CommunityUseCaseBase {
1780
+ static {
1781
+ __name(this, "UpdateOwnCommunityPostUseCase");
1782
+ }
1783
+ async execute(params) {
1784
+ const { author, id } = params;
1785
+ const input = updateCommunityPostSchema.parse(params.input);
1786
+ const row = await this.findOwned(author, id);
1787
+ const settings = await this.getSettings(author.companyId);
1788
+ const sources = input.body === void 0 ? void 0 : await this.assertBodyImages({
1789
+ author,
1790
+ body: input.body,
1791
+ settings
1792
+ });
1793
+ const isPublished = row.status === POST_STATUS11.PUBLISHED;
1794
+ const isRevision = isPublished && settings.communityModeration === COMMUNITY_MODERATION2.BEFORE;
1795
+ const values = isRevision ? this.revisionValues(row, input) : this.liveValues(row, input, sources);
1796
+ const updated = await this.persist({
1797
+ author,
1798
+ id,
1799
+ values,
1800
+ event: POST_EVENT6.UPDATED
1801
+ });
1802
+ if (isPublished) await this.notifyRevision({
1803
+ row: updated,
1804
+ settings
1805
+ });
1806
+ return toCommunityPost(updated);
1807
+ }
1808
+ liveValues(row, input, sources) {
1809
+ const values = {};
1810
+ if (input.title !== void 0) values.title = input.title;
1811
+ if (input.excerpt !== void 0) values.excerpt = input.excerpt || null;
1812
+ if (input.displayName !== void 0) values.authorDisplayName = input.displayName;
1813
+ if (input.body !== void 0) {
1814
+ values.body = input.body;
1815
+ values.readingTimeMinutes = this.readingTime(input.body);
1816
+ values.coverImageUrl = sources?.[0] ?? null;
1817
+ }
1818
+ return values;
1819
+ }
1820
+ /** O nome exibido não entra na revisão (o contrato dela não o carrega): trocar o nome de um post no ar passa pela equipe numa próxima fase. */
1821
+ revisionValues(row, input) {
1822
+ const open = readPendingRevision(row);
1823
+ const base = open?.state === COMMUNITY_REVISION_STATE5.PENDING ? open : row;
1824
+ const now = this.now();
1825
+ const revision = {
1826
+ title: input.title ?? base.title,
1827
+ excerpt: input.excerpt === void 0 ? base.excerpt : input.excerpt || null,
1828
+ body: input.body ?? base.body,
1829
+ state: COMMUNITY_REVISION_STATE5.PENDING,
1830
+ submittedAt: now.toISOString()
1831
+ };
1832
+ return {
1833
+ pendingRevision: revision,
1834
+ submittedAt: now
1835
+ };
1836
+ }
1837
+ async notifyRevision(params) {
1838
+ await notifyCommunityPostSubmitted(this.dependencies, {
1839
+ companyId: params.row.companyId,
1840
+ postId: params.row.id,
1841
+ authorAccountId: params.row.authorAccountId ?? "",
1842
+ kind: "revision",
1843
+ moderation: params.settings.communityModeration
1844
+ });
1845
+ }
1846
+ };
1847
+
1848
+ // src/use-cases/community/UploadCommunityImage.use-case.ts
1849
+ import { CommunityDailyLimitError as CommunityDailyLimitError2 } from "@adatechnology/content-contracts";
1850
+
1851
+ // src/use-cases/UploadImage.use-case.ts
1852
+ import { ImageStorageDisabledError, InvalidCoverImageError } from "@adatechnology/content-contracts";
1853
+
1854
+ // src/shared/coverImage.constant.ts
1855
+ var CONTENT_IMAGE = {
1856
+ MAX_BYTES: 1024 * 1024,
1857
+ KEY_PREFIX: "content/posts",
1858
+ EXTENSION_BY_MIME: {
1859
+ "image/jpeg": "jpg",
1860
+ "image/png": "png",
1861
+ "image/webp": "webp"
1862
+ }
1863
+ };
1864
+ var COVER_IMAGE = CONTENT_IMAGE;
1865
+
1866
+ // src/use-cases/UploadImage.use-case.ts
1867
+ var UploadImageUseCase = class {
1868
+ static {
1869
+ __name(this, "UploadImageUseCase");
1870
+ }
1871
+ dependencies;
1872
+ constructor(dependencies) {
1873
+ this.dependencies = dependencies;
1874
+ }
1875
+ async execute(params) {
1876
+ const storage = this.dependencies.imageStorage;
1877
+ if (!storage) throw new ImageStorageDisabledError();
1878
+ const mimeType = (params.mimeType.split(";")[0] ?? "").trim().toLowerCase();
1879
+ const extension = CONTENT_IMAGE.EXTENSION_BY_MIME[mimeType];
1880
+ if (!extension) throw new InvalidCoverImageError("unsupported_type");
1881
+ if (params.bytes.byteLength === 0) throw new InvalidCoverImageError("empty");
1882
+ if (params.bytes.byteLength > CONTENT_IMAGE.MAX_BYTES) throw new InvalidCoverImageError("too_large");
1883
+ const key = `${params.keyPrefix ?? CONTENT_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`;
1884
+ return storage.upload({
1885
+ buffer: params.bytes,
1886
+ mimeType,
1887
+ key
1888
+ });
1889
+ }
1890
+ };
1891
+
1892
+ // src/use-cases/community/UploadCommunityImage.use-case.ts
1893
+ var UploadCommunityImageUseCase = class extends CommunityUseCaseBase {
1894
+ static {
1895
+ __name(this, "UploadCommunityImageUseCase");
1896
+ }
1897
+ uploadImage = new UploadImageUseCase(this.dependencies);
1898
+ async execute(params) {
1899
+ const { author } = params;
1900
+ const now = this.now();
1901
+ await this.assertUnderDailyCap({
1902
+ author,
1903
+ now
1904
+ });
1905
+ const uploaded = await this.uploadImage.execute({
1906
+ companyId: author.companyId,
1907
+ bytes: params.bytes,
1908
+ mimeType: params.mimeType,
1909
+ keyPrefix: COMMUNITY_IMAGE_KEY_PREFIX
1910
+ });
1911
+ await this.dependencies.community.recordImage({
1912
+ companyId: author.companyId,
1913
+ accountId: author.accountId,
1914
+ storageKey: uploaded.key,
1915
+ url: uploaded.url,
1916
+ createdAt: now
1917
+ });
1918
+ return uploaded;
1919
+ }
1920
+ async assertUnderDailyCap(params) {
1921
+ const { author, now } = params;
1922
+ const settings = await this.getSettings(author.companyId);
1923
+ const cap = settings.communityDailyLimit * settings.maxImagesPerPost;
1924
+ const recent = await this.dependencies.community.listRecentImageDates({
1925
+ companyId: author.companyId,
1926
+ accountId: author.accountId,
1927
+ since: new Date(now.getTime() - COMMUNITY_WINDOW_MS)
1928
+ });
1929
+ const blocking = recent[recent.length - cap];
1930
+ if (recent.length < cap || !blocking) return;
1931
+ const seconds = Math.ceil((blocking.getTime() + COMMUNITY_WINDOW_MS - now.getTime()) / 1e3);
1932
+ throw new CommunityDailyLimitError2(cap, Math.max(1, seconds));
1933
+ }
1934
+ };
1935
+
1936
+ // src/use-cases/community/buildCommunityUseCases.ts
1937
+ function isCommunityEnabled(dependencies) {
1938
+ return dependencies.communityAuthor !== void 0 && dependencies.community !== void 0;
1939
+ }
1940
+ __name(isCommunityEnabled, "isCommunityEnabled");
1941
+ function buildCommunityUseCases(dependencies) {
1942
+ if (!isCommunityEnabled(dependencies)) return {};
1943
+ return {
1944
+ resolveCommunityAuthor: new ResolveCommunityAuthorUseCase(dependencies),
1945
+ listOwnCommunityPosts: new ListOwnCommunityPostsUseCase(dependencies),
1946
+ getOwnCommunityPost: new GetOwnCommunityPostUseCase(dependencies),
1947
+ createCommunityPost: new CreateCommunityPostUseCase(dependencies),
1948
+ updateOwnCommunityPost: new UpdateOwnCommunityPostUseCase(dependencies),
1949
+ submitCommunityPost: new SubmitCommunityPostUseCase(dependencies),
1950
+ deleteOwnCommunityPost: new DeleteOwnCommunityPostUseCase(dependencies),
1951
+ approveCommunityPost: new ApproveCommunityPostUseCase(dependencies),
1952
+ rejectCommunityPost: new RejectCommunityPostUseCase(dependencies),
1953
+ unpublishCommunityPost: new UnpublishCommunityPostUseCase(dependencies),
1954
+ archiveCommunityPost: new ArchiveCommunityPostUseCase(dependencies),
1955
+ moderateCommunityPostsInBulk: new ModerateCommunityPostsInBulkUseCase(dependencies),
1956
+ getContentSettings: new GetContentSettingsUseCase(dependencies),
1957
+ updateContentSettings: new UpdateContentSettingsUseCase(dependencies),
1958
+ createPostReport: new CreatePostReportUseCase(dependencies),
1959
+ listPostReports: new ListPostReportsUseCase(dependencies),
1960
+ resolvePostReport: new ResolvePostReportUseCase(dependencies),
1961
+ ...dependencies.imageStorage ? {
1962
+ uploadCommunityImage: new UploadCommunityImageUseCase(dependencies)
1963
+ } : {}
1964
+ };
1965
+ }
1966
+ __name(buildCommunityUseCases, "buildCommunityUseCases");
1967
+
1968
+ // src/use-cases/Feed.use-cases.ts
1969
+ import { buildAtomFeed, buildExcerpt, buildPostUrl, buildRssFeed, renderMarkdownToHtml } from "@adatechnology/content-contracts";
1970
+ var DEFAULT_ITEM_LIMIT = 20;
1971
+ var SITEMAP_LIMIT = 5e4;
1972
+ var FEED_FORMAT = {
1973
+ RSS: "rss",
1974
+ ATOM: "atom"
1975
+ };
1976
+ var BuildFeedUseCase = class {
1977
+ static {
1978
+ __name(this, "BuildFeedUseCase");
1979
+ }
1980
+ dependencies;
1981
+ feed;
1982
+ constructor(dependencies, feed) {
1983
+ this.dependencies = dependencies;
1984
+ this.feed = feed;
1985
+ }
1986
+ async execute(params) {
1987
+ const now = this.dependencies.clock.now();
1988
+ const page = await this.dependencies.posts.listPublic({
1989
+ companyId: params.companyId,
1990
+ now,
1991
+ page: 1,
1992
+ pageSize: this.feed.itemLimit ?? DEFAULT_ITEM_LIMIT
1993
+ });
1994
+ const channel = {
1995
+ siteUrl: this.feed.siteUrl,
1996
+ title: this.feed.title,
1997
+ ...this.feed.description ? {
1998
+ description: this.feed.description
1999
+ } : {},
2000
+ ...this.feed.language ? {
2001
+ language: this.feed.language
2002
+ } : {},
2003
+ ...params.feedUrl ? {
2004
+ feedUrl: params.feedUrl
2005
+ } : {}
2006
+ };
2007
+ const items = page.rows.map((row) => this.toItem(row));
2008
+ return params.format === FEED_FORMAT.ATOM ? buildAtomFeed({
2009
+ channel,
2010
+ items,
2011
+ now
2012
+ }) : buildRssFeed({
2013
+ channel,
2014
+ items
2015
+ });
2016
+ }
2017
+ toItem(row) {
2018
+ return {
2019
+ title: row.title,
2020
+ url: buildPostUrl({
2021
+ siteUrl: this.feed.siteUrl,
2022
+ slug: row.slug,
2023
+ shortId: row.shortId,
2024
+ postPathTemplate: this.feed.postPathTemplate
2025
+ }),
2026
+ publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
2027
+ updatedAt: row.updatedAt.toISOString(),
2028
+ summary: row.excerpt ?? buildExcerpt(row.body),
2029
+ ...this.feed.includeContent ?? true ? {
2030
+ contentHtml: renderMarkdownToHtml(row.body, {
2031
+ headingIds: false
2032
+ })
2033
+ } : {},
2034
+ ...row.authorName ? {
2035
+ authorName: row.authorName
2036
+ } : {},
2037
+ categories: row.tags,
2038
+ ...row.coverImageUrl ? {
2039
+ imageUrl: row.coverImageUrl
2040
+ } : {}
2041
+ };
818
2042
  }
819
2043
  };
820
- var ListPostsUseCase = class extends PostUseCaseBase {
2044
+ var ListSitemapEntriesUseCase = class {
821
2045
  static {
822
- __name(this, "ListPostsUseCase");
2046
+ __name(this, "ListSitemapEntriesUseCase");
2047
+ }
2048
+ dependencies;
2049
+ feed;
2050
+ constructor(dependencies, feed) {
2051
+ this.dependencies = dependencies;
2052
+ this.feed = feed;
823
2053
  }
2054
+ /** Entradas para o host juntar ao sitemap dele — o módulo não é dono do sitemap do site. */
824
2055
  async execute(params) {
825
- const { companyId, ...rawQuery } = params;
826
- const query = listPostsQuerySchema.parse(rawQuery);
827
- const { tag: rawTag, ...rest } = query;
828
- const tags = rawTag ? normalizeTags(rawTag.split(",")) : [];
829
- const now = this.now();
830
- const page = await this.dependencies.posts.listForAdmin({
831
- companyId,
832
- ...rest,
833
- isTemplate: query.isTemplate ?? false,
834
- now,
835
- ...tags.length > 0 ? {
836
- tags
837
- } : {}
2056
+ const page = await this.dependencies.posts.listPublic({
2057
+ companyId: params.companyId,
2058
+ now: this.dependencies.clock.now(),
2059
+ page: 1,
2060
+ pageSize: SITEMAP_LIMIT
838
2061
  });
839
- return {
840
- data: page.rows.map((row) => toPostSummary(row, now)),
841
- pagination: toPagination({
842
- total: page.total,
843
- page: query.page,
844
- pageSize: query.pageSize
845
- })
846
- };
2062
+ return page.rows.map((row) => ({
2063
+ loc: buildPostUrl({
2064
+ siteUrl: this.feed.siteUrl,
2065
+ slug: row.slug,
2066
+ shortId: row.shortId,
2067
+ postPathTemplate: this.feed.postPathTemplate
2068
+ }),
2069
+ lastmod: row.updatedAt.toISOString()
2070
+ }));
847
2071
  }
848
2072
  };
849
2073
 
850
2074
  // src/use-cases/PublicPost.use-cases.ts
851
- import { listPublishedPostsQuerySchema, normalizeTag, parsePostRef, PostNotFoundError as PostNotFoundError2 } from "@adatechnology/content-contracts";
2075
+ import { listPublishedPostsQuerySchema, normalizeTag, parsePostRef, PostNotFoundError as PostNotFoundError5 } from "@adatechnology/content-contracts";
852
2076
  var GetPublishedPostBySlugUseCase = class {
853
2077
  static {
854
2078
  __name(this, "GetPublishedPostBySlugUseCase");
@@ -879,7 +2103,7 @@ var GetPublishedPostBySlugUseCase = class {
879
2103
  ...query,
880
2104
  slug: parsed.slug
881
2105
  });
882
- if (!row) throw new PostNotFoundError2(parsed.slug);
2106
+ if (!row) throw new PostNotFoundError5(parsed.slug);
883
2107
  return toPublicPost(row);
884
2108
  }
885
2109
  };
@@ -900,6 +2124,7 @@ var ListPublishedPostsUseCase = class {
900
2124
  now: this.dependencies.clock.now(),
901
2125
  page: query.page,
902
2126
  pageSize: query.pageSize,
2127
+ origin: query.origin,
903
2128
  ...tag ? {
904
2129
  tag
905
2130
  } : {}
@@ -938,7 +2163,7 @@ var ListTagsUseCase = class {
938
2163
  };
939
2164
 
940
2165
  // src/use-cases/Recurrence.use-cases.ts
941
- import { createRecurrenceSchema, NotATemplateError, PostNotFoundError as PostNotFoundError3, RecurrenceNotFoundError, updateRecurrenceSchema } from "@adatechnology/content-contracts";
2166
+ import { createRecurrenceSchema, NotATemplateError, PostNotFoundError as PostNotFoundError6, RecurrenceNotFoundError, updateRecurrenceSchema } from "@adatechnology/content-contracts";
942
2167
  var RecurrenceUseCaseBase = class RecurrenceUseCaseBase2 {
943
2168
  static {
944
2169
  __name(this, "RecurrenceUseCaseBase");
@@ -981,7 +2206,7 @@ var CreateRecurrenceUseCase = class extends RecurrenceUseCaseBase {
981
2206
  companyId: params.companyId,
982
2207
  id: input.templateId
983
2208
  });
984
- if (!template) throw new PostNotFoundError3(input.templateId);
2209
+ if (!template) throw new PostNotFoundError6(input.templateId);
985
2210
  if (!template.isTemplate) throw new NotATemplateError(input.templateId);
986
2211
  const startsAt = new Date(input.startsAt);
987
2212
  const values = {
@@ -1037,7 +2262,7 @@ var RemoveRecurrenceUseCase = class extends RecurrenceUseCaseBase {
1037
2262
  };
1038
2263
 
1039
2264
  // src/use-cases/Scheduling.use-cases.ts
1040
- import { POST_EVENT as POST_EVENT3, POST_STATUS as POST_STATUS6, PostNotPublishedError, republishPostSchema, RepublishDateInFutureError, SLUG_MAX_LENGTH, slugify } from "@adatechnology/content-contracts";
2265
+ import { POST_EVENT as POST_EVENT8, POST_STATUS as POST_STATUS13, PostNotPublishedError, republishPostSchema, RepublishDateInFutureError, SLUG_MAX_LENGTH, slugify } from "@adatechnology/content-contracts";
1041
2266
 
1042
2267
  // src/shared/recurrence.ts
1043
2268
  import { RECURRENCE_FREQUENCY } from "@adatechnology/content-contracts";
@@ -1072,7 +2297,7 @@ function toDateStamp(date) {
1072
2297
  __name(toDateStamp, "toDateStamp");
1073
2298
 
1074
2299
  // src/use-cases/Template.use-cases.ts
1075
- import { createFromTemplateSchema, DuplicateSlugError as DuplicateSlugError2, normalizeTags as normalizeTags2, NotATemplateError as NotATemplateError2, POST_EVENT as POST_EVENT2, POST_STATUS as POST_STATUS5, saveAsTemplateSchema } from "@adatechnology/content-contracts";
2300
+ import { createFromTemplateSchema, DuplicateSlugError as DuplicateSlugError3, normalizeTags as normalizeTags2, NotATemplateError as NotATemplateError2, POST_EVENT as POST_EVENT7, POST_STATUS as POST_STATUS12, saveAsTemplateSchema } from "@adatechnology/content-contracts";
1076
2301
  var TEMPLATE_SLUG_PREFIX = "modelo";
1077
2302
  function copiableFields(row) {
1078
2303
  return {
@@ -1101,16 +2326,16 @@ var TemplateUseCaseBase = class TemplateUseCaseBase2 extends PostUseCaseBase {
1101
2326
  shortId: await this.generateShortId(params.companyId),
1102
2327
  title: params.title,
1103
2328
  isTemplate: params.isTemplate,
1104
- status: params.status ?? POST_STATUS5.DRAFT,
2329
+ status: params.status ?? POST_STATUS12.DRAFT,
1105
2330
  ...params.publishedAt ? {
1106
2331
  publishedAt: params.publishedAt
1107
2332
  } : {}
1108
2333
  }).catch((error) => {
1109
- if (isUniqueViolation(error)) throw new DuplicateSlugError2(params.slug);
2334
+ if (isUniqueViolation(error)) throw new DuplicateSlugError3(params.slug);
1110
2335
  throw error;
1111
2336
  });
1112
2337
  const post = toPost(row, this.now());
1113
- await notifyPostChanged(this.dependencies, POST_EVENT2.CREATED, post);
2338
+ await notifyPostChanged(this.dependencies, POST_EVENT7.CREATED, post);
1114
2339
  return post;
1115
2340
  }
1116
2341
  };
@@ -1121,7 +2346,7 @@ var SaveAsTemplateUseCase = class extends TemplateUseCaseBase {
1121
2346
  /** Copia o post (qualquer status) para um modelo. O original não muda. */
1122
2347
  async execute(params) {
1123
2348
  const input = saveAsTemplateSchema.parse(params.input ?? {});
1124
- const source = await this.findOrFail(params);
2349
+ const source = await this.findEditableOrFail(params);
1125
2350
  const title = input.title ?? source.title;
1126
2351
  const slug = await this.generateSlug(params.companyId, `${TEMPLATE_SLUG_PREFIX} ${title}`);
1127
2352
  return this.insertCopy({
@@ -1140,7 +2365,7 @@ var CreateFromTemplateUseCase = class extends TemplateUseCaseBase {
1140
2365
  /** Cria um RASCUNHO novo com o conteúdo do modelo, pronto para editar e publicar. */
1141
2366
  async execute(params) {
1142
2367
  const input = createFromTemplateSchema.parse(params.input ?? {});
1143
- const template = await this.findOrFail(params);
2368
+ const template = await this.findEditableOrFail(params);
1144
2369
  if (!template.isTemplate) throw new NotATemplateError2(params.id);
1145
2370
  const title = input.title ?? template.title;
1146
2371
  if (input.slug) await this.assertSlugAvailable(params.companyId, input.slug);
@@ -1182,17 +2407,17 @@ var RepublishPostUseCase = class extends PostUseCaseBase {
1182
2407
  */
1183
2408
  async execute(params) {
1184
2409
  const input = republishPostSchema.parse(params.input ?? {});
1185
- const existing = await this.findOrFail(params);
2410
+ const existing = await this.findEditableOrFail(params);
1186
2411
  const now = this.now();
1187
- if (existing.isTemplate || effectiveStatus(existing, now) !== POST_STATUS6.PUBLISHED) {
2412
+ if (existing.isTemplate || effectiveStatus(existing, now) !== POST_STATUS13.PUBLISHED) {
1188
2413
  throw new PostNotPublishedError(params.id);
1189
2414
  }
1190
2415
  const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
1191
2416
  if (publishedAt > now) throw new RepublishDateInFutureError();
1192
2417
  return this.save(params, {
1193
- status: POST_STATUS6.PUBLISHED,
2418
+ status: POST_STATUS13.PUBLISHED,
1194
2419
  publishedAt
1195
- }, POST_EVENT3.REPUBLISHED);
2420
+ }, POST_EVENT8.REPUBLISHED);
1196
2421
  }
1197
2422
  };
1198
2423
  var PublishDueUseCase = class extends PostUseCaseBase {
@@ -1215,7 +2440,7 @@ var PublishDueUseCase = class extends PostUseCaseBase {
1215
2440
  limit
1216
2441
  });
1217
2442
  for (const row of rows) {
1218
- await notifyPostChanged(this.dependencies, POST_EVENT3.PUBLISHED, toPost(row, now));
2443
+ await notifyPostChanged(this.dependencies, POST_EVENT8.PUBLISHED, toPost(row, now));
1219
2444
  }
1220
2445
  if (rows.length > 0 || materialized > 0) {
1221
2446
  this.dependencies.logger?.info("content-module: publishDue", {
@@ -1248,7 +2473,7 @@ var PublishDueUseCase = class extends PostUseCaseBase {
1248
2473
  companyId: rule.companyId,
1249
2474
  id: rule.templateId
1250
2475
  });
1251
- if (!template || !template.isTemplate || template.status === POST_STATUS6.ARCHIVED) {
2476
+ if (!template || !template.isTemplate || template.status === POST_STATUS13.ARCHIVED) {
1252
2477
  this.dependencies.logger?.warn("content-module: modelo da recorr\xEAncia indispon\xEDvel", {
1253
2478
  ruleId: rule.id
1254
2479
  });
@@ -1265,12 +2490,12 @@ var PublishDueUseCase = class extends PostUseCaseBase {
1265
2490
  shortId: await this.generateShortId(rule.companyId),
1266
2491
  title: template.title,
1267
2492
  isTemplate: false,
1268
- status: POST_STATUS6.PUBLISHED,
2493
+ status: POST_STATUS13.PUBLISHED,
1269
2494
  publishedAt: now
1270
2495
  });
1271
2496
  const post = toPost(row, now);
1272
- await notifyPostChanged(this.dependencies, POST_EVENT3.CREATED, post);
1273
- await notifyPostChanged(this.dependencies, POST_EVENT3.PUBLISHED, post);
2497
+ await notifyPostChanged(this.dependencies, POST_EVENT8.CREATED, post);
2498
+ await notifyPostChanged(this.dependencies, POST_EVENT8.PUBLISHED, post);
1274
2499
  return {
1275
2500
  ...advance,
1276
2501
  lastRunAt: now,
@@ -1279,47 +2504,6 @@ var PublishDueUseCase = class extends PostUseCaseBase {
1279
2504
  }
1280
2505
  };
1281
2506
 
1282
- // src/use-cases/UploadImage.use-case.ts
1283
- import { ImageStorageDisabledError, InvalidCoverImageError } from "@adatechnology/content-contracts";
1284
-
1285
- // src/shared/coverImage.constant.ts
1286
- var CONTENT_IMAGE = {
1287
- MAX_BYTES: 1024 * 1024,
1288
- KEY_PREFIX: "content/posts",
1289
- EXTENSION_BY_MIME: {
1290
- "image/jpeg": "jpg",
1291
- "image/png": "png",
1292
- "image/webp": "webp"
1293
- }
1294
- };
1295
- var COVER_IMAGE = CONTENT_IMAGE;
1296
-
1297
- // src/use-cases/UploadImage.use-case.ts
1298
- var UploadImageUseCase = class {
1299
- static {
1300
- __name(this, "UploadImageUseCase");
1301
- }
1302
- dependencies;
1303
- constructor(dependencies) {
1304
- this.dependencies = dependencies;
1305
- }
1306
- async execute(params) {
1307
- const storage = this.dependencies.imageStorage;
1308
- if (!storage) throw new ImageStorageDisabledError();
1309
- const mimeType = (params.mimeType.split(";")[0] ?? "").trim().toLowerCase();
1310
- const extension = CONTENT_IMAGE.EXTENSION_BY_MIME[mimeType];
1311
- if (!extension) throw new InvalidCoverImageError("unsupported_type");
1312
- if (params.bytes.byteLength === 0) throw new InvalidCoverImageError("empty");
1313
- if (params.bytes.byteLength > CONTENT_IMAGE.MAX_BYTES) throw new InvalidCoverImageError("too_large");
1314
- const key = `${CONTENT_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`;
1315
- return storage.upload({
1316
- buffer: params.bytes,
1317
- mimeType,
1318
- key
1319
- });
1320
- }
1321
- };
1322
-
1323
2507
  // src/use-cases/UploadCoverImage.use-case.ts
1324
2508
  var UploadCoverImageUseCase = class extends UploadImageUseCase {
1325
2509
  static {
@@ -1347,6 +2531,7 @@ function createContentModule(params) {
1347
2531
  if (!posts2) throw new ConfigMissingError("db");
1348
2532
  const recurrences = params.providers?.recurrenceStore ?? (params.db ? new RecurrenceRepository(params.db) : void 0);
1349
2533
  if (!recurrences) throw new ConfigMissingError("db");
2534
+ const community = params.providers?.communityStore ?? (params.db ? new CommunityRepository(params.db) : void 0);
1350
2535
  const dependencies = {
1351
2536
  posts: posts2,
1352
2537
  recurrences,
@@ -1360,6 +2545,12 @@ function createContentModule(params) {
1360
2545
  } : {},
1361
2546
  ...params.providers?.logger ? {
1362
2547
  logger: params.providers.logger
2548
+ } : {},
2549
+ ...params.providers?.communityAuthor ? {
2550
+ communityAuthor: params.providers.communityAuthor
2551
+ } : {},
2552
+ ...community ? {
2553
+ community
1363
2554
  } : {}
1364
2555
  };
1365
2556
  return {
@@ -1387,6 +2578,7 @@ function createContentModule(params) {
1387
2578
  uploadCoverImage: new UploadCoverImageUseCase(dependencies),
1388
2579
  uploadImage: new UploadImageUseCase(dependencies)
1389
2580
  } : {},
2581
+ ...buildCommunityUseCases(dependencies),
1390
2582
  ...config.feed ? {
1391
2583
  buildFeed: new BuildFeedUseCase(dependencies, config.feed),
1392
2584
  listSitemapEntries: new ListSitemapEntriesUseCase(dependencies, config.feed)
@@ -1398,17 +2590,192 @@ function createContentModule(params) {
1398
2590
  __name(createContentModule, "createContentModule");
1399
2591
 
1400
2592
  // src/http/adminRoutes.ts
1401
- import { createFromTemplateSchema as createFromTemplateSchema2, createPostSchema as createPostSchema2, createRecurrenceSchema as createRecurrenceSchema2, DEFAULT_ADMIN_SCOPES, listPostsQuerySchema as listPostsQuerySchema2, publishPostSchema as publishPostSchema2, republishPostSchema as republishPostSchema2, saveAsTemplateSchema as saveAsTemplateSchema2, updatePostSchema as updatePostSchema2, updateRecurrenceSchema as updateRecurrenceSchema2 } from "@adatechnology/content-contracts";
2593
+ import { createFromTemplateSchema as createFromTemplateSchema2, createPostSchema as createPostSchema2, createRecurrenceSchema as createRecurrenceSchema2, DEFAULT_ADMIN_SCOPES as DEFAULT_ADMIN_SCOPES2, listPostsQuerySchema as listPostsQuerySchema2, publishPostSchema as publishPostSchema2, republishPostSchema as republishPostSchema2, saveAsTemplateSchema as saveAsTemplateSchema2, updatePostSchema as updatePostSchema2, updateRecurrenceSchema as updateRecurrenceSchema2 } from "@adatechnology/content-contracts";
2594
+
2595
+ // src/http/moderationRoutes.ts
2596
+ import { bulkModerationSchema as bulkModerationSchema2, contentSettingsSchema as contentSettingsSchema2, DEFAULT_ADMIN_SCOPES, listPostReportsQuerySchema as listPostReportsQuerySchema2, rejectPostSchema as rejectPostSchema3, unpublishCommunityPostSchema as unpublishCommunityPostSchema2 } from "@adatechnology/content-contracts";
1402
2597
 
1403
2598
  // src/http/requireCompany.ts
1404
- import { CONTENT_ERROR_CODES, ContentError } from "@adatechnology/content-contracts";
2599
+ import { CONTENT_ERROR_CODES, ContentError as ContentError2 } from "@adatechnology/content-contracts";
1405
2600
  function requireCompany(context) {
1406
2601
  if (!context.auth?.companyId) {
1407
- throw new ContentError("Rota exige contexto autenticado.", 401, CONTENT_ERROR_CODES.CONFIG_MISSING);
2602
+ throw new ContentError2("Rota exige contexto autenticado.", 401, CONTENT_ERROR_CODES.CONFIG_MISSING);
1408
2603
  }
1409
2604
  return context.auth.companyId;
1410
2605
  }
1411
2606
  __name(requireCompany, "requireCompany");
2607
+ function requireActor(context) {
2608
+ if (!context.auth?.userId) {
2609
+ throw new ContentError2("Rota exige um usu\xE1rio da equipe.", 403, CONTENT_ERROR_CODES.CONFIG_MISSING);
2610
+ }
2611
+ return context.auth.userId;
2612
+ }
2613
+ __name(requireActor, "requireActor");
2614
+
2615
+ // src/http/moderationRoutes.ts
2616
+ var json = /* @__PURE__ */ __name((status, data) => ({
2617
+ kind: "json",
2618
+ status,
2619
+ body: {
2620
+ data
2621
+ }
2622
+ }), "json");
2623
+ function staffTarget(context) {
2624
+ return {
2625
+ companyId: requireCompany(context),
2626
+ id: context.params.id ?? "",
2627
+ actorUserId: requireActor(context)
2628
+ };
2629
+ }
2630
+ __name(staffTarget, "staffTarget");
2631
+ function buildModerationRoutes(module) {
2632
+ const { useCases } = module;
2633
+ if (!useCases.approveCommunityPost) return [];
2634
+ const admin = {
2635
+ scope: "admin",
2636
+ requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES
2637
+ };
2638
+ return [
2639
+ {
2640
+ ...admin,
2641
+ method: "POST",
2642
+ path: "/posts/moderation",
2643
+ bodySchema: bulkModerationSchema2,
2644
+ operationId: "moderateCommunityPostsInBulk",
2645
+ summary: "Aprova, recusa, tira do ar ou arquiva v\xE1rios posts da comunidade; devolve o que falhou e por qu\xEA",
2646
+ async handler(context) {
2647
+ const result = await useCases.moderateCommunityPostsInBulk?.execute({
2648
+ companyId: requireCompany(context),
2649
+ actorUserId: requireActor(context),
2650
+ input: context.body
2651
+ });
2652
+ return json(200, result);
2653
+ }
2654
+ },
2655
+ {
2656
+ ...admin,
2657
+ method: "POST",
2658
+ path: "/posts/:id/approve",
2659
+ operationId: "approveCommunityPost",
2660
+ summary: "Aprova o post em an\xE1lise (publica) ou a revis\xE3o pendente de um publicado",
2661
+ async handler(context) {
2662
+ return json(200, await useCases.approveCommunityPost?.execute(staffTarget(context)));
2663
+ }
2664
+ },
2665
+ {
2666
+ ...admin,
2667
+ method: "POST",
2668
+ path: "/posts/:id/reject",
2669
+ bodySchema: rejectPostSchema3,
2670
+ operationId: "rejectCommunityPost",
2671
+ summary: "Recusa o post (ou a revis\xE3o pendente) com uma nota que o autor l\xEA",
2672
+ async handler(context) {
2673
+ const input = context.body;
2674
+ return json(200, await useCases.rejectCommunityPost?.execute({
2675
+ ...staffTarget(context),
2676
+ input
2677
+ }));
2678
+ }
2679
+ },
2680
+ {
2681
+ ...admin,
2682
+ method: "POST",
2683
+ path: "/posts/:id/unpublish-community",
2684
+ bodySchema: unpublishCommunityPostSchema2.optional(),
2685
+ operationId: "unpublishCommunityPost",
2686
+ summary: "Tira do ar um post publicado da comunidade sem apagar; o autor v\xEA a nota e pode reenviar",
2687
+ async handler(context) {
2688
+ const input = context.body;
2689
+ return json(200, await useCases.unpublishCommunityPost?.execute({
2690
+ ...staffTarget(context),
2691
+ ...input ? {
2692
+ input
2693
+ } : {}
2694
+ }));
2695
+ }
2696
+ },
2697
+ ...settingsRoutes(module),
2698
+ ...reportRoutes(module)
2699
+ ];
2700
+ }
2701
+ __name(buildModerationRoutes, "buildModerationRoutes");
2702
+ function settingsRoutes(module) {
2703
+ const { useCases } = module;
2704
+ const admin = {
2705
+ scope: "admin",
2706
+ requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES
2707
+ };
2708
+ return [
2709
+ {
2710
+ ...admin,
2711
+ method: "GET",
2712
+ path: "/settings",
2713
+ operationId: "getContentSettings",
2714
+ summary: "Configura\xE7\xE3o da comunidade da empresa: modera\xE7\xE3o, limite di\xE1rio e fotos por post",
2715
+ async handler(context) {
2716
+ return json(200, await useCases.getContentSettings?.execute({
2717
+ companyId: requireCompany(context)
2718
+ }));
2719
+ }
2720
+ },
2721
+ {
2722
+ ...admin,
2723
+ method: "PUT",
2724
+ path: "/settings",
2725
+ bodySchema: contentSettingsSchema2,
2726
+ operationId: "updateContentSettings",
2727
+ summary: "Substitui a configura\xE7\xE3o da comunidade; vale para os pr\xF3ximos envios",
2728
+ async handler(context) {
2729
+ const input = context.body;
2730
+ return json(200, await useCases.updateContentSettings?.execute({
2731
+ companyId: requireCompany(context),
2732
+ input
2733
+ }));
2734
+ }
2735
+ }
2736
+ ];
2737
+ }
2738
+ __name(settingsRoutes, "settingsRoutes");
2739
+ function reportRoutes(module) {
2740
+ const { useCases } = module;
2741
+ const admin = {
2742
+ scope: "admin",
2743
+ requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES
2744
+ };
2745
+ return [
2746
+ {
2747
+ ...admin,
2748
+ method: "GET",
2749
+ path: "/reports",
2750
+ querySchema: listPostReportsQuerySchema2,
2751
+ operationId: "listPostReports",
2752
+ summary: "Den\xFAncias de posts da comunidade (abertas por padr\xE3o), com pagina\xE7\xE3o",
2753
+ async handler(context) {
2754
+ const query = context.query;
2755
+ const result = await useCases.listPostReports?.execute({
2756
+ companyId: requireCompany(context),
2757
+ ...query
2758
+ });
2759
+ return {
2760
+ kind: "json",
2761
+ status: 200,
2762
+ body: result
2763
+ };
2764
+ }
2765
+ },
2766
+ {
2767
+ ...admin,
2768
+ method: "POST",
2769
+ path: "/reports/:id/resolve",
2770
+ operationId: "resolvePostReport",
2771
+ summary: "Marca a den\xFAncia como resolvida (repetir devolve a den\xFAncia como est\xE1)",
2772
+ async handler(context) {
2773
+ return json(200, await useCases.resolvePostReport?.execute(staffTarget(context)));
2774
+ }
2775
+ }
2776
+ ];
2777
+ }
2778
+ __name(reportRoutes, "reportRoutes");
1412
2779
 
1413
2780
  // src/http/adminRoutes.ts
1414
2781
  function reference(context) {
@@ -1418,7 +2785,7 @@ function reference(context) {
1418
2785
  };
1419
2786
  }
1420
2787
  __name(reference, "reference");
1421
- var json = /* @__PURE__ */ __name((status, data) => ({
2788
+ var json2 = /* @__PURE__ */ __name((status, data) => ({
1422
2789
  kind: "json",
1423
2790
  status,
1424
2791
  body: {
@@ -1427,7 +2794,7 @@ var json = /* @__PURE__ */ __name((status, data) => ({
1427
2794
  }), "json");
1428
2795
  function buildAdminRoutes(module) {
1429
2796
  const { useCases } = module;
1430
- const requiredScopes = module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES;
2797
+ const requiredScopes = module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES2;
1431
2798
  const admin = {
1432
2799
  scope: "admin",
1433
2800
  requiredScopes
@@ -1450,11 +2817,11 @@ function buildAdminRoutes(module) {
1450
2817
  bytes: context.rawBody ?? new Uint8Array(),
1451
2818
  mimeType: context.headers["content-type"] ?? ""
1452
2819
  });
1453
- return json(201, result);
2820
+ return json2(201, result);
1454
2821
  }
1455
2822
  }
1456
2823
  ] : [];
1457
- const imageRoutes = useCases.uploadImage ? [
2824
+ const imageRoutes2 = useCases.uploadImage ? [
1458
2825
  {
1459
2826
  ...admin,
1460
2827
  method: "POST",
@@ -1472,7 +2839,7 @@ function buildAdminRoutes(module) {
1472
2839
  bytes: context.rawBody ?? new Uint8Array(),
1473
2840
  mimeType: context.headers["content-type"] ?? ""
1474
2841
  });
1475
- return json(201, result);
2842
+ return json2(201, result);
1476
2843
  }
1477
2844
  }
1478
2845
  ] : [];
@@ -1508,7 +2875,7 @@ function buildAdminRoutes(module) {
1508
2875
  companyId: requireCompany(context),
1509
2876
  input: context.body
1510
2877
  });
1511
- return json(201, post);
2878
+ return json2(201, post);
1512
2879
  }
1513
2880
  },
1514
2881
  // Antes de `/posts/:id`: `findRoute` para na primeira rota que casa, e `:id` casaria "tags".
@@ -1519,7 +2886,7 @@ function buildAdminRoutes(module) {
1519
2886
  operationId: "listPostTags",
1520
2887
  summary: "Tags usadas em qualquer post da empresa, com contagem",
1521
2888
  async handler(context) {
1522
- return json(200, await useCases.listTags.execute({
2889
+ return json2(200, await useCases.listTags.execute({
1523
2890
  companyId: requireCompany(context),
1524
2891
  scope: TAG_SCOPE.ADMIN
1525
2892
  }));
@@ -1532,14 +2899,15 @@ function buildAdminRoutes(module) {
1532
2899
  operationId: "countPosts",
1533
2900
  summary: "Contagem de posts por aba: publicados, agendados, rascunhos, arquivados e modelos",
1534
2901
  async handler(context) {
1535
- return json(200, await useCases.countPosts.execute({
2902
+ return json2(200, await useCases.countPosts.execute({
1536
2903
  companyId: requireCompany(context)
1537
2904
  }));
1538
2905
  }
1539
2906
  },
1540
2907
  ...recurrenceRoutes(module),
1541
2908
  ...uploadRoutes,
1542
- ...imageRoutes,
2909
+ ...imageRoutes2,
2910
+ ...buildModerationRoutes(module),
1543
2911
  {
1544
2912
  ...admin,
1545
2913
  method: "GET",
@@ -1547,7 +2915,7 @@ function buildAdminRoutes(module) {
1547
2915
  operationId: "getPost",
1548
2916
  summary: "L\xEA um post da empresa (qualquer status)",
1549
2917
  async handler(context) {
1550
- return json(200, await useCases.getPost.execute(reference(context)));
2918
+ return json2(200, await useCases.getPost.execute(reference(context)));
1551
2919
  }
1552
2920
  },
1553
2921
  {
@@ -1558,7 +2926,7 @@ function buildAdminRoutes(module) {
1558
2926
  operationId: "updatePost",
1559
2927
  summary: "Atualiza campos de um post; trocar o t\xEDtulo n\xE3o troca o slug",
1560
2928
  async handler(context) {
1561
- return json(200, await useCases.updatePost.execute({
2929
+ return json2(200, await useCases.updatePost.execute({
1562
2930
  ...reference(context),
1563
2931
  input: context.body
1564
2932
  }));
@@ -1587,7 +2955,7 @@ function buildAdminRoutes(module) {
1587
2955
  operationId: "publishPost",
1588
2956
  summary: "Publica agora, ou agenda quando `publishedAt` \xE9 futuro",
1589
2957
  async handler(context) {
1590
- return json(200, await useCases.publishPost.execute({
2958
+ return json2(200, await useCases.publishPost.execute({
1591
2959
  ...reference(context),
1592
2960
  input: context.body ?? {}
1593
2961
  }));
@@ -1600,7 +2968,7 @@ function buildAdminRoutes(module) {
1600
2968
  operationId: "unpublishPost",
1601
2969
  summary: "Tira do ar (ou cancela o agendamento) e volta a rascunho",
1602
2970
  async handler(context) {
1603
- return json(200, await useCases.unpublishPost.execute(reference(context)));
2971
+ return json2(200, await useCases.unpublishPost.execute(reference(context)));
1604
2972
  }
1605
2973
  },
1606
2974
  {
@@ -1611,7 +2979,7 @@ function buildAdminRoutes(module) {
1611
2979
  operationId: "republishPost",
1612
2980
  summary: "Republica um post no ar com nova data, mantendo o mesmo endere\xE7o (SEO); data futura \xE9 recusada",
1613
2981
  async handler(context) {
1614
- return json(200, await useCases.republishPost.execute({
2982
+ return json2(200, await useCases.republishPost.execute({
1615
2983
  ...reference(context),
1616
2984
  input: context.body ?? {}
1617
2985
  }));
@@ -1625,7 +2993,7 @@ function buildAdminRoutes(module) {
1625
2993
  operationId: "savePostAsTemplate",
1626
2994
  summary: "Copia o post para um modelo (o original n\xE3o muda)",
1627
2995
  async handler(context) {
1628
- return json(201, await useCases.saveAsTemplate.execute({
2996
+ return json2(201, await useCases.saveAsTemplate.execute({
1629
2997
  ...reference(context),
1630
2998
  input: context.body ?? {}
1631
2999
  }));
@@ -1639,7 +3007,7 @@ function buildAdminRoutes(module) {
1639
3007
  operationId: "createPostFromTemplate",
1640
3008
  summary: "Cria um rascunho novo a partir do modelo `:id`",
1641
3009
  async handler(context) {
1642
- return json(201, await useCases.createFromTemplate.execute({
3010
+ return json2(201, await useCases.createFromTemplate.execute({
1643
3011
  ...reference(context),
1644
3012
  input: context.body ?? {}
1645
3013
  }));
@@ -1652,7 +3020,7 @@ function recurrenceRoutes(module) {
1652
3020
  const { useCases } = module;
1653
3021
  const admin = {
1654
3022
  scope: "admin",
1655
- requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES
3023
+ requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES2
1656
3024
  };
1657
3025
  return [
1658
3026
  {
@@ -1662,7 +3030,7 @@ function recurrenceRoutes(module) {
1662
3030
  operationId: "listRecurrences",
1663
3031
  summary: "Regras de recorr\xEAncia da empresa",
1664
3032
  async handler(context) {
1665
- return json(200, await useCases.listRecurrences.execute({
3033
+ return json2(200, await useCases.listRecurrences.execute({
1666
3034
  companyId: requireCompany(context)
1667
3035
  }));
1668
3036
  }
@@ -1675,7 +3043,7 @@ function recurrenceRoutes(module) {
1675
3043
  operationId: "createRecurrence",
1676
3044
  summary: "Cria regra: publica um post novo, copiado do modelo, toda semana ou todo m\xEAs",
1677
3045
  async handler(context) {
1678
- return json(201, await useCases.createRecurrence.execute({
3046
+ return json2(201, await useCases.createRecurrence.execute({
1679
3047
  companyId: requireCompany(context),
1680
3048
  input: context.body
1681
3049
  }));
@@ -1689,7 +3057,7 @@ function recurrenceRoutes(module) {
1689
3057
  operationId: "updateRecurrence",
1690
3058
  summary: "Pausa, retoma ou remarca a pr\xF3xima execu\xE7\xE3o",
1691
3059
  async handler(context) {
1692
- return json(200, await useCases.updateRecurrence.execute({
3060
+ return json2(200, await useCases.updateRecurrence.execute({
1693
3061
  ...reference(context),
1694
3062
  input: context.body
1695
3063
  }));
@@ -1713,8 +3081,158 @@ function recurrenceRoutes(module) {
1713
3081
  }
1714
3082
  __name(recurrenceRoutes, "recurrenceRoutes");
1715
3083
 
3084
+ // src/http/communityRoutes.ts
3085
+ import { createCommunityPostSchema as createCommunityPostSchema2, submitCommunityPostSchema, updateCommunityPostSchema as updateCommunityPostSchema2 } from "@adatechnology/content-contracts";
3086
+ import { z } from "zod";
3087
+ var NO_STORE_HEADERS = {
3088
+ "Cache-Control": "no-store"
3089
+ };
3090
+ var SELF_SERVICE = {
3091
+ scope: "public"
3092
+ };
3093
+ var AUTHOR_NOTE = "exige a sess\xE3o do h\xF3spede (CommunityAuthorPort)";
3094
+ var listOwnQuerySchema = z.object({
3095
+ page: z.coerce.number().int().min(1).max(1e4).optional(),
3096
+ pageSize: z.coerce.number().int().min(1).max(100).optional()
3097
+ });
3098
+ var noStoreJson = /* @__PURE__ */ __name((status, data) => ({
3099
+ kind: "json",
3100
+ status,
3101
+ body: {
3102
+ data
3103
+ },
3104
+ headers: NO_STORE_HEADERS
3105
+ }), "noStoreJson");
3106
+ function buildCommunityRoutes(module) {
3107
+ const { useCases } = module;
3108
+ const { resolveCommunityAuthor } = useCases;
3109
+ if (!resolveCommunityAuthor) return [];
3110
+ const authenticated = /* @__PURE__ */ __name((handle) => async (context) => handle(context, await resolveCommunityAuthor.execute({
3111
+ headers: context.headers
3112
+ })), "authenticated");
3113
+ const routes = [
3114
+ {
3115
+ ...SELF_SERVICE,
3116
+ method: "GET",
3117
+ path: "/community/posts",
3118
+ querySchema: listOwnQuerySchema,
3119
+ operationId: "listOwnCommunityPosts",
3120
+ summary: `Posts do pr\xF3prio h\xF3spede, mais recentes primeiro; ${AUTHOR_NOTE}`,
3121
+ handler: authenticated(async (context, author) => {
3122
+ const { page, pageSize } = context.query;
3123
+ const result = await useCases.listOwnCommunityPosts?.execute({
3124
+ author,
3125
+ ...page ? {
3126
+ page
3127
+ } : {},
3128
+ ...pageSize ? {
3129
+ pageSize
3130
+ } : {}
3131
+ });
3132
+ return {
3133
+ kind: "json",
3134
+ status: 200,
3135
+ body: result,
3136
+ headers: NO_STORE_HEADERS
3137
+ };
3138
+ })
3139
+ },
3140
+ {
3141
+ ...SELF_SERVICE,
3142
+ method: "POST",
3143
+ path: "/community/posts",
3144
+ bodySchema: createCommunityPostSchema2,
3145
+ operationId: "createCommunityPost",
3146
+ summary: `Cria um rascunho do h\xF3spede (respeita o limite di\xE1rio); ${AUTHOR_NOTE}`,
3147
+ handler: authenticated(async (context, author) => noStoreJson(201, await useCases.createCommunityPost?.execute({
3148
+ author,
3149
+ input: context.body
3150
+ })))
3151
+ },
3152
+ // Antes de `/community/posts/:id`: `images` não pode ser lido como id.
3153
+ ...imageRoutes(module, authenticated),
3154
+ {
3155
+ ...SELF_SERVICE,
3156
+ method: "GET",
3157
+ path: "/community/posts/:id",
3158
+ operationId: "getOwnCommunityPost",
3159
+ summary: `L\xEA um post do pr\xF3prio h\xF3spede (post alheio \xE9 404); ${AUTHOR_NOTE}`,
3160
+ handler: authenticated(async (context, author) => noStoreJson(200, await useCases.getOwnCommunityPost?.execute({
3161
+ author,
3162
+ id: context.params.id ?? ""
3163
+ })))
3164
+ },
3165
+ {
3166
+ ...SELF_SERVICE,
3167
+ method: "PATCH",
3168
+ path: "/community/posts/:id",
3169
+ bodySchema: updateCommunityPostSchema2,
3170
+ operationId: "updateOwnCommunityPost",
3171
+ summary: `Edita o pr\xF3prio post; publicado em modera\xE7\xE3o pr\xE9via vira revis\xE3o pendente; ${AUTHOR_NOTE}`,
3172
+ handler: authenticated(async (context, author) => noStoreJson(200, await useCases.updateOwnCommunityPost?.execute({
3173
+ author,
3174
+ id: context.params.id ?? "",
3175
+ input: context.body
3176
+ })))
3177
+ },
3178
+ {
3179
+ ...SELF_SERVICE,
3180
+ method: "DELETE",
3181
+ path: "/community/posts/:id",
3182
+ operationId: "deleteOwnCommunityPost",
3183
+ summary: `Exclui o pr\xF3prio post (anonimiza o publicado); ${AUTHOR_NOTE}`,
3184
+ handler: authenticated(async (context, author) => {
3185
+ await useCases.deleteOwnCommunityPost?.execute({
3186
+ author,
3187
+ id: context.params.id ?? ""
3188
+ });
3189
+ return {
3190
+ kind: "empty",
3191
+ status: 204,
3192
+ headers: NO_STORE_HEADERS
3193
+ };
3194
+ })
3195
+ },
3196
+ {
3197
+ ...SELF_SERVICE,
3198
+ method: "POST",
3199
+ path: "/community/posts/:id/submit",
3200
+ // Corpo ausente chega ao use case como `undefined` e vira 422 de termos, não 400 de formato.
3201
+ bodySchema: submitCommunityPostSchema.partial().optional(),
3202
+ operationId: "submitCommunityPost",
3203
+ summary: `Envia o post para a comunidade, com aceite dos termos; ${AUTHOR_NOTE}`,
3204
+ handler: authenticated(async (context, author) => noStoreJson(200, await useCases.submitCommunityPost?.execute({
3205
+ author,
3206
+ id: context.params.id ?? "",
3207
+ termsAccepted: context.body?.termsAccepted
3208
+ })))
3209
+ }
3210
+ ];
3211
+ return routes;
3212
+ }
3213
+ __name(buildCommunityRoutes, "buildCommunityRoutes");
3214
+ function imageRoutes(module, authenticated) {
3215
+ const upload = module.useCases.uploadCommunityImage;
3216
+ if (!upload) return [];
3217
+ return [
3218
+ {
3219
+ ...SELF_SERVICE,
3220
+ method: "POST",
3221
+ path: "/community/images",
3222
+ operationId: "uploadCommunityImage",
3223
+ summary: `Envia uma foto do h\xF3spede (bytes crus, Content-Type jpeg/png/webp); ${AUTHOR_NOTE}`,
3224
+ handler: authenticated(async (context, author) => noStoreJson(201, await upload.execute({
3225
+ author,
3226
+ bytes: context.rawBody ?? new Uint8Array(),
3227
+ mimeType: context.headers["content-type"] ?? ""
3228
+ })))
3229
+ }
3230
+ ];
3231
+ }
3232
+ __name(imageRoutes, "imageRoutes");
3233
+
1716
3234
  // src/http/publicRoutes.ts
1717
- import { DEFAULT_PUBLIC_CACHE_CONTROL, listPublishedPostsQuerySchema as listPublishedPostsQuerySchema2, PostNotFoundError as PostNotFoundError4 } from "@adatechnology/content-contracts";
3235
+ import { DEFAULT_PUBLIC_CACHE_CONTROL, createPostReportSchema as createPostReportSchema2, listPublishedPostsQuerySchema as listPublishedPostsQuerySchema2, PostNotFoundError as PostNotFoundError7 } from "@adatechnology/content-contracts";
1718
3236
  var PUBLIC = {
1719
3237
  scope: "public"
1720
3238
  };
@@ -1734,10 +3252,40 @@ function buildPublicRoutes(params) {
1734
3252
  headers: context.headers,
1735
3253
  query: context.query
1736
3254
  });
1737
- if (!companyId) throw new PostNotFoundError4("company");
3255
+ if (!companyId) throw new PostNotFoundError7("company");
1738
3256
  return companyId;
1739
3257
  }
1740
3258
  __name(resolveCompany, "resolveCompany");
3259
+ function reportRoutes2() {
3260
+ const { createPostReport } = useCases;
3261
+ if (!createPostReport) return [];
3262
+ return [
3263
+ {
3264
+ ...PUBLIC,
3265
+ method: "POST",
3266
+ path: "/public/posts/:id/reports",
3267
+ bodySchema: createPostReportSchema2,
3268
+ operationId: "createPostReport",
3269
+ summary: "Denuncia um post da comunidade no ar, sem identidade; responde 202 e a equipe analisa",
3270
+ async handler(context) {
3271
+ const report = await createPostReport.execute({
3272
+ companyId: await resolveCompany(context),
3273
+ postId: context.params.id ?? "",
3274
+ input: context.body
3275
+ });
3276
+ return {
3277
+ kind: "json",
3278
+ status: 202,
3279
+ body: {
3280
+ data: report
3281
+ },
3282
+ headers: NO_STORE_HEADERS
3283
+ };
3284
+ }
3285
+ }
3286
+ ];
3287
+ }
3288
+ __name(reportRoutes2, "reportRoutes");
1741
3289
  const routes = [
1742
3290
  {
1743
3291
  ...PUBLIC,
@@ -1785,7 +3333,8 @@ function buildPublicRoutes(params) {
1785
3333
  data: tags
1786
3334
  });
1787
3335
  }
1788
- }
3336
+ },
3337
+ ...reportRoutes2()
1789
3338
  ];
1790
3339
  const { buildFeed, listSitemapEntries } = useCases;
1791
3340
  if (!buildFeed || !listSitemapEntries) return routes;
@@ -1836,17 +3385,32 @@ __name(buildPublicRoutes, "buildPublicRoutes");
1836
3385
  // src/http/routes.ts
1837
3386
  function createContentRoutes(params) {
1838
3387
  const admin = buildAdminRoutes(params.module);
1839
- if (!params.publicCompanyResolver) return admin;
3388
+ const community = buildCommunityRoutes(params.module);
3389
+ if (!params.publicCompanyResolver) return [
3390
+ ...admin,
3391
+ ...community
3392
+ ];
3393
+ const site = buildPublicRoutes({
3394
+ module: params.module,
3395
+ companyResolver: params.publicCompanyResolver
3396
+ });
1840
3397
  return [
1841
3398
  ...admin,
1842
- ...buildPublicRoutes({
1843
- module: params.module,
1844
- companyResolver: params.publicCompanyResolver
1845
- })
3399
+ ...site,
3400
+ ...community
1846
3401
  ];
1847
3402
  }
1848
3403
  __name(createContentRoutes, "createContentRoutes");
1849
3404
 
3405
+ // src/http/rateLimitedOperations.constant.ts
3406
+ var CONTENT_RATE_LIMITED_OPERATIONS = [
3407
+ "createCommunityPost",
3408
+ "updateOwnCommunityPost",
3409
+ "submitCommunityPost",
3410
+ "uploadCommunityImage",
3411
+ "createPostReport"
3412
+ ];
3413
+
1850
3414
  // src/runMigrations.ts
1851
3415
  import { join } from "path";
1852
3416
  var CONTENT_MIGRATIONS_TABLE = "content_migrations";
@@ -1864,12 +3428,19 @@ __name(runContentMigrations, "runContentMigrations");
1864
3428
 
1865
3429
  // src/testing/inMemoryPostStore.ts
1866
3430
  import { randomUUID } from "crypto";
1867
- import { POST_STATUS as POST_STATUS7 } from "@adatechnology/content-contracts";
3431
+ import { COMMUNITY_REVISION_STATE as COMMUNITY_REVISION_STATE6, POST_ORIGIN as POST_ORIGIN10, POST_STATUS as POST_STATUS14 } from "@adatechnology/content-contracts";
1868
3432
  function isPublic(row, now) {
1869
- const live = row.status === POST_STATUS7.PUBLISHED || row.status === POST_STATUS7.SCHEDULED;
3433
+ const live = row.status === POST_STATUS14.PUBLISHED || row.status === POST_STATUS14.SCHEDULED;
1870
3434
  return live && row.publishedAt !== null && row.publishedAt <= now;
1871
3435
  }
1872
3436
  __name(isPublic, "isPublic");
3437
+ var originMatches = /* @__PURE__ */ __name((row, origin) => (origin ?? POST_ORIGIN10.STAFF) === "all" || row.origin === (origin ?? POST_ORIGIN10.STAFF), "originMatches");
3438
+ function matchesStatus(row, query) {
3439
+ if (query.status !== POST_STATUS14.PENDING_REVIEW) return effectiveStatus(row, query.now) === query.status;
3440
+ const isAwaiting = row.status === POST_STATUS14.PENDING_REVIEW || row.pendingRevision?.state === COMMUNITY_REVISION_STATE6.PENDING;
3441
+ return row.origin === POST_ORIGIN10.COMMUNITY && isAwaiting;
3442
+ }
3443
+ __name(matchesStatus, "matchesStatus");
1873
3444
  function adminComparator(query) {
1874
3445
  const sign = query.order === "asc" ? 1 : -1;
1875
3446
  const value = /* @__PURE__ */ __name((row) => {
@@ -1924,6 +3495,12 @@ function createInMemoryPostStore(seed = []) {
1924
3495
  ...row
1925
3496
  } : void 0;
1926
3497
  },
3498
+ async findPublicById({ companyId, id, now }) {
3499
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.id === id && isPublic(candidate, now));
3500
+ return row ? {
3501
+ ...row
3502
+ } : void 0;
3503
+ },
1927
3504
  async findPublicByFormerSlug({ companyId, slug, now }) {
1928
3505
  const former = formerSlugs.find((entry) => entry.companyId === companyId && entry.slug === slug);
1929
3506
  const row = rows.find((candidate) => candidate.id === former?.postId && isPublic(candidate, now));
@@ -1949,7 +3526,7 @@ function createInMemoryPostStore(seed = []) {
1949
3526
  coverImageAlt: null,
1950
3527
  tags: [],
1951
3528
  tagLabels: {},
1952
- status: POST_STATUS7.DRAFT,
3529
+ status: POST_STATUS14.DRAFT,
1953
3530
  isTemplate: false,
1954
3531
  publishedAt: null,
1955
3532
  authorName: null,
@@ -1957,6 +3534,14 @@ function createInMemoryPostStore(seed = []) {
1957
3534
  seoDescription: null,
1958
3535
  canonicalUrl: null,
1959
3536
  readingTimeMinutes: 1,
3537
+ origin: POST_ORIGIN10.STAFF,
3538
+ authorAccountId: null,
3539
+ authorDisplayName: null,
3540
+ authorReferenceMonth: null,
3541
+ reviewNote: null,
3542
+ termsAcceptedAt: null,
3543
+ submittedAt: null,
3544
+ pendingRevision: null,
1960
3545
  createdAt: now,
1961
3546
  updatedAt: now,
1962
3547
  ...values
@@ -1997,7 +3582,7 @@ function createInMemoryPostStore(seed = []) {
1997
3582
  },
1998
3583
  async listForAdmin(query) {
1999
3584
  const search = query.search?.toLowerCase();
2000
- const matched = rows.filter((row) => row.companyId === query.companyId).filter((row) => query.isTemplate ? row.isTemplate && row.status !== POST_STATUS7.ARCHIVED : !row.isTemplate).filter((row) => !query.status || effectiveStatus(row, query.now) === query.status).filter((row) => !query.tags?.length || query.tags.some((tag) => row.tags.includes(tag))).filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search)).sort(adminComparator(query));
3585
+ const matched = rows.filter((row) => row.companyId === query.companyId && originMatches(row, query.origin)).filter((row) => query.isTemplate ? row.isTemplate && row.status !== POST_STATUS14.ARCHIVED : !row.isTemplate).filter((row) => !query.status || matchesStatus(row, query)).filter((row) => !query.tags?.length || query.tags.some((tag) => row.tags.includes(tag))).filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search)).sort(adminComparator(query));
2001
3586
  return paginate(matched, query.page, query.pageSize);
2002
3587
  },
2003
3588
  async countByStatus({ companyId, now }) {
@@ -2006,12 +3591,18 @@ function createInMemoryPostStore(seed = []) {
2006
3591
  scheduled: 0,
2007
3592
  draft: 0,
2008
3593
  archived: 0,
2009
- templates: 0
3594
+ templates: 0,
3595
+ pendingReview: 0,
3596
+ rejected: 0
2010
3597
  };
2011
3598
  for (const row of rows) {
2012
3599
  if (row.companyId !== companyId) continue;
3600
+ if (row.status === POST_STATUS14.PENDING_REVIEW) counts.pendingReview += 1;
3601
+ else if (row.pendingRevision?.state === COMMUNITY_REVISION_STATE6.PENDING) counts.pendingReview += 1;
3602
+ if (row.status === POST_STATUS14.REJECTED) counts.rejected += 1;
3603
+ if (row.origin !== POST_ORIGIN10.STAFF) continue;
2013
3604
  if (row.isTemplate) {
2014
- if (row.status !== POST_STATUS7.ARCHIVED) counts.templates += 1;
3605
+ if (row.status !== POST_STATUS14.ARCHIVED) counts.templates += 1;
2015
3606
  continue;
2016
3607
  }
2017
3608
  counts[effectiveStatus(row, now)] += 1;
@@ -2019,14 +3610,14 @@ function createInMemoryPostStore(seed = []) {
2019
3610
  return counts;
2020
3611
  },
2021
3612
  async claimDueScheduled({ now, limit }) {
2022
- const due = rows.filter((row) => row.status === POST_STATUS7.SCHEDULED && !row.isTemplate && row.publishedAt && row.publishedAt <= now).sort((left, right) => (left.publishedAt?.getTime() ?? 0) - (right.publishedAt?.getTime() ?? 0)).slice(0, limit);
2023
- for (const row of due) row.status = POST_STATUS7.PUBLISHED;
3613
+ const due = rows.filter((row) => row.status === POST_STATUS14.SCHEDULED && !row.isTemplate && row.publishedAt && row.publishedAt <= now).sort((left, right) => (left.publishedAt?.getTime() ?? 0) - (right.publishedAt?.getTime() ?? 0)).slice(0, limit);
3614
+ for (const row of due) row.status = POST_STATUS14.PUBLISHED;
2024
3615
  return due.map((row) => ({
2025
3616
  ...row
2026
3617
  }));
2027
3618
  },
2028
3619
  async listPublic(query) {
2029
- const matched = rows.filter((row) => row.companyId === query.companyId && isPublic(row, query.now)).filter((row) => !query.tag || row.tags.includes(query.tag)).sort((left, right) => (right.publishedAt?.getTime() ?? 0) - (left.publishedAt?.getTime() ?? 0));
3620
+ const matched = rows.filter((row) => row.companyId === query.companyId && isPublic(row, query.now)).filter((row) => originMatches(row, query.origin)).filter((row) => !query.tag || row.tags.includes(query.tag)).sort((left, right) => (right.publishedAt?.getTime() ?? 0) - (left.publishedAt?.getTime() ?? 0));
2030
3621
  return paginate(matched, query.page, query.pageSize);
2031
3622
  },
2032
3623
  async listTags({ companyId, publicAt }) {
@@ -2131,7 +3722,9 @@ export {
2131
3722
  BuildFeedUseCase,
2132
3723
  CONTENT_IMAGE,
2133
3724
  CONTENT_MIGRATIONS_TABLE,
3725
+ CONTENT_RATE_LIMITED_OPERATIONS,
2134
3726
  COVER_IMAGE,
3727
+ CommunityRepository,
2135
3728
  CountPostsUseCase,
2136
3729
  CreateFromTemplateUseCase,
2137
3730
  CreatePostUseCase,