@adatechnology/content-module 0.1.0 → 0.2.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.cjs CHANGED
@@ -25,37 +25,55 @@ __export(index_exports, {
25
25
  BuildFeedUseCase: () => BuildFeedUseCase,
26
26
  CONTENT_MIGRATIONS_TABLE: () => CONTENT_MIGRATIONS_TABLE,
27
27
  COVER_IMAGE: () => COVER_IMAGE,
28
+ CountPostsUseCase: () => CountPostsUseCase,
29
+ CreateFromTemplateUseCase: () => CreateFromTemplateUseCase,
28
30
  CreatePostUseCase: () => CreatePostUseCase,
31
+ CreateRecurrenceUseCase: () => CreateRecurrenceUseCase,
32
+ DEFAULT_SCHEDULER_INTERVAL_MS: () => DEFAULT_SCHEDULER_INTERVAL_MS,
29
33
  FEED_FORMAT: () => FEED_FORMAT,
30
34
  GetPostUseCase: () => GetPostUseCase,
31
35
  GetPublishedPostBySlugUseCase: () => GetPublishedPostBySlugUseCase,
32
36
  ListPostsUseCase: () => ListPostsUseCase,
33
37
  ListPublishedPostsUseCase: () => ListPublishedPostsUseCase,
38
+ ListRecurrencesUseCase: () => ListRecurrencesUseCase,
34
39
  ListSitemapEntriesUseCase: () => ListSitemapEntriesUseCase,
35
40
  ListTagsUseCase: () => ListTagsUseCase,
36
41
  PostRepository: () => PostRepository,
42
+ PublishDueUseCase: () => PublishDueUseCase,
37
43
  PublishPostUseCase: () => PublishPostUseCase,
44
+ RecurrenceRepository: () => RecurrenceRepository,
45
+ RemoveRecurrenceUseCase: () => RemoveRecurrenceUseCase,
46
+ RepublishPostUseCase: () => RepublishPostUseCase,
47
+ SaveAsTemplateUseCase: () => SaveAsTemplateUseCase,
38
48
  TAG_SCOPE: () => TAG_SCOPE,
39
49
  UnpublishPostUseCase: () => UnpublishPostUseCase,
40
50
  UpdatePostUseCase: () => UpdatePostUseCase,
51
+ UpdateRecurrenceUseCase: () => UpdateRecurrenceUseCase,
41
52
  UploadCoverImageUseCase: () => UploadCoverImageUseCase,
42
53
  contentMigrationsFolder: () => contentMigrationsFolder,
43
54
  contentSchema: () => contentSchema,
44
55
  createContentModule: () => createContentModule,
45
56
  createContentRoutes: () => createContentRoutes,
46
57
  createInMemoryPostStore: () => createInMemoryPostStore,
58
+ createInMemoryRecurrenceStore: () => createInMemoryRecurrenceStore,
59
+ nextOccurrence: () => nextOccurrence,
60
+ nextOccurrenceAfter: () => nextOccurrenceAfter,
47
61
  posts: () => posts,
48
- runContentMigrations: () => runContentMigrations
62
+ recurrenceRules: () => recurrenceRules,
63
+ runContentMigrations: () => runContentMigrations,
64
+ startContentScheduler: () => startContentScheduler
49
65
  });
50
66
  module.exports = __toCommonJS(index_exports);
51
67
 
52
68
  // src/ContentModule.ts
53
- var import_content_contracts7 = require("@adatechnology/content-contracts");
69
+ var import_content_contracts13 = require("@adatechnology/content-contracts");
54
70
 
55
71
  // src/repositories/PostRepository.ts
56
- var import_drizzle_orm2 = require("drizzle-orm");
72
+ var import_drizzle_orm3 = require("drizzle-orm");
73
+ var import_content_contracts2 = require("@adatechnology/content-contracts");
57
74
 
58
75
  // src/schema/schema.ts
76
+ var import_drizzle_orm = require("drizzle-orm");
59
77
  var import_pg_core = require("drizzle-orm/pg-core");
60
78
  var contentSchema = (0, import_pg_core.pgSchema)("content");
61
79
  var posts = contentSchema.table("posts", {
@@ -64,6 +82,9 @@ var posts = contentSchema.table("posts", {
64
82
  slug: (0, import_pg_core.varchar)("slug", {
65
83
  length: 120
66
84
  }).notNull(),
85
+ shortId: (0, import_pg_core.varchar)("short_id", {
86
+ length: 6
87
+ }).notNull(),
67
88
  title: (0, import_pg_core.varchar)("title", {
68
89
  length: 200
69
90
  }).notNull(),
@@ -78,9 +99,11 @@ var posts = contentSchema.table("posts", {
78
99
  length: 300
79
100
  }),
80
101
  tags: (0, import_pg_core.text)("tags").array().notNull().default([]),
102
+ tagLabels: (0, import_pg_core.jsonb)("tag_labels").$type().notNull().default({}),
81
103
  status: (0, import_pg_core.varchar)("status", {
82
104
  length: 12
83
105
  }).notNull().default("draft"),
106
+ isTemplate: (0, import_pg_core.boolean)("is_template").notNull().default(false),
84
107
  publishedAt: (0, import_pg_core.timestamp)("published_at", {
85
108
  withTimezone: true
86
109
  }),
@@ -107,69 +130,147 @@ var posts = contentSchema.table("posts", {
107
130
  // Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo
108
131
  // faria um link antigo (já compartilhado) abrir outro post.
109
132
  (0, import_pg_core.uniqueIndex)("idx_posts_company_slug").on(table.companyId, table.slug),
133
+ (0, import_pg_core.uniqueIndex)("idx_posts_company_short_id").on(table.companyId, table.shortId),
110
134
  // Serve a listagem pública: empresa + status + ordem por data.
111
135
  (0, import_pg_core.index)("idx_posts_company_status_published").on(table.companyId, table.status, table.publishedAt),
112
- (0, import_pg_core.index)("idx_posts_tags").using("gin", table.tags)
136
+ (0, import_pg_core.index)("idx_posts_tags").using("gin", table.tags),
137
+ // Serve o `publishDue`: só linha agendada entra, então o índice fica minúsculo.
138
+ (0, import_pg_core.index)("idx_posts_due").on(table.publishedAt).where(import_drizzle_orm.sql`"status" = 'scheduled'`)
139
+ ]);
140
+ var recurrenceRules = contentSchema.table("recurrence_rules", {
141
+ id: (0, import_pg_core.uuid)("id").primaryKey().defaultRandom(),
142
+ companyId: (0, import_pg_core.uuid)("company_id").notNull(),
143
+ templateId: (0, import_pg_core.uuid)("template_id").notNull().references(() => posts.id),
144
+ frequency: (0, import_pg_core.varchar)("frequency", {
145
+ length: 10
146
+ }).notNull(),
147
+ // Dia do mês da primeira execução: mensal em 31 cai no último dia dos meses curtos e volta ao 31.
148
+ anchorDay: (0, import_pg_core.integer)("anchor_day").notNull(),
149
+ isActive: (0, import_pg_core.boolean)("is_active").notNull().default(true),
150
+ nextRunAt: (0, import_pg_core.timestamp)("next_run_at", {
151
+ withTimezone: true
152
+ }).notNull(),
153
+ lastRunAt: (0, import_pg_core.timestamp)("last_run_at", {
154
+ withTimezone: true
155
+ }),
156
+ lastPostId: (0, import_pg_core.uuid)("last_post_id"),
157
+ createdAt: (0, import_pg_core.timestamp)("created_at", {
158
+ withTimezone: true
159
+ }).notNull().defaultNow()
160
+ }, (table) => [
161
+ (0, import_pg_core.index)("idx_recurrence_company").on(table.companyId),
162
+ (0, import_pg_core.index)("idx_recurrence_due").on(table.nextRunAt).where(import_drizzle_orm.sql`"is_active"`)
163
+ ]);
164
+ var postFormerSlugs = contentSchema.table("post_former_slugs", {
165
+ companyId: (0, import_pg_core.uuid)("company_id").notNull(),
166
+ slug: (0, import_pg_core.varchar)("slug", {
167
+ length: 120
168
+ }).notNull(),
169
+ postId: (0, import_pg_core.uuid)("post_id").notNull().references(() => posts.id),
170
+ createdAt: (0, import_pg_core.timestamp)("created_at", {
171
+ withTimezone: true
172
+ }).notNull().defaultNow()
173
+ }, (table) => [
174
+ (0, import_pg_core.primaryKey)({
175
+ columns: [
176
+ table.companyId,
177
+ table.slug
178
+ ]
179
+ })
113
180
  ]);
114
181
 
115
182
  // src/repositories/conditions.ts
116
- var import_drizzle_orm = require("drizzle-orm");
183
+ var import_drizzle_orm2 = require("drizzle-orm");
117
184
  var import_content_contracts = require("@adatechnology/content-contracts");
118
185
  function postOwnedByCondition(params) {
119
- return (0, import_drizzle_orm.and)((0, import_drizzle_orm.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm.eq)(posts.id, params.id));
186
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm2.eq)(posts.id, params.id));
120
187
  }
121
188
  __name(postOwnedByCondition, "postOwnedByCondition");
122
189
  function postSlugCondition(params) {
123
- return (0, import_drizzle_orm.and)((0, import_drizzle_orm.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm.eq)(posts.slug, params.slug));
190
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm2.eq)(posts.slug, params.slug));
124
191
  }
125
192
  __name(postSlugCondition, "postSlugCondition");
126
193
  function postAdminListCondition(params) {
127
194
  const conditions = [
128
- (0, import_drizzle_orm.eq)(posts.companyId, params.companyId)
195
+ (0, import_drizzle_orm2.eq)(posts.companyId, params.companyId),
196
+ templateCondition(params.isTemplate)
129
197
  ];
130
198
  if (params.status) conditions.push(statusCondition(params.status, params.now));
131
- if (params.tag) conditions.push((0, import_drizzle_orm.arrayContains)(posts.tags, [
132
- params.tag
199
+ if (params.tags?.length) conditions.push((0, import_drizzle_orm2.arrayOverlaps)(posts.tags, [
200
+ ...params.tags
133
201
  ]));
134
202
  if (params.search) {
135
203
  const pattern = `%${params.search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
136
- conditions.push(import_drizzle_orm.sql`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`);
204
+ conditions.push(import_drizzle_orm2.sql`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`);
137
205
  }
138
- return (0, import_drizzle_orm.and)(...conditions);
206
+ return (0, import_drizzle_orm2.and)(...conditions);
139
207
  }
140
208
  __name(postAdminListCondition, "postAdminListCondition");
209
+ function templateCondition(isTemplate) {
210
+ if (isTemplate) return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.isTemplate, true), (0, import_drizzle_orm2.ne)(posts.status, import_content_contracts.POST_STATUS.ARCHIVED));
211
+ return (0, import_drizzle_orm2.eq)(posts.isTemplate, false);
212
+ }
213
+ __name(templateCondition, "templateCondition");
141
214
  function statusCondition(status, now) {
142
215
  if (status === import_content_contracts.POST_STATUS.PUBLISHED) {
143
- return (0, import_drizzle_orm.or)((0, import_drizzle_orm.eq)(posts.status, import_content_contracts.POST_STATUS.PUBLISHED), (0, import_drizzle_orm.and)((0, import_drizzle_orm.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm.lte)(posts.publishedAt, now)));
216
+ return (0, import_drizzle_orm2.or)((0, import_drizzle_orm2.eq)(posts.status, import_content_contracts.POST_STATUS.PUBLISHED), (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm2.lte)(posts.publishedAt, now)));
144
217
  }
145
218
  if (status === import_content_contracts.POST_STATUS.SCHEDULED) {
146
- return (0, import_drizzle_orm.and)((0, import_drizzle_orm.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm.gt)(posts.publishedAt, now));
219
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm2.gt)(posts.publishedAt, now));
147
220
  }
148
- return (0, import_drizzle_orm.eq)(posts.status, status);
221
+ return (0, import_drizzle_orm2.eq)(posts.status, status);
149
222
  }
150
223
  __name(statusCondition, "statusCondition");
151
224
  function postPublicCondition(params) {
152
225
  const conditions = [
153
- (0, import_drizzle_orm.eq)(posts.companyId, params.companyId),
154
- (0, import_drizzle_orm.inArray)(posts.status, [
226
+ (0, import_drizzle_orm2.eq)(posts.companyId, params.companyId),
227
+ (0, import_drizzle_orm2.inArray)(posts.status, [
155
228
  import_content_contracts.POST_STATUS.PUBLISHED,
156
229
  import_content_contracts.POST_STATUS.SCHEDULED
157
230
  ]),
158
- (0, import_drizzle_orm.lte)(posts.publishedAt, params.now)
231
+ (0, import_drizzle_orm2.lte)(posts.publishedAt, params.now)
159
232
  ];
160
- if (params.tag) conditions.push((0, import_drizzle_orm.arrayContains)(posts.tags, [
233
+ if (params.tag) conditions.push((0, import_drizzle_orm2.arrayContains)(posts.tags, [
161
234
  params.tag
162
235
  ]));
163
- return (0, import_drizzle_orm.and)(...conditions);
236
+ return (0, import_drizzle_orm2.and)(...conditions);
164
237
  }
165
238
  __name(postPublicCondition, "postPublicCondition");
166
239
  function postPublicSlugCondition(params) {
167
- return (0, import_drizzle_orm.and)(postPublicCondition(params), (0, import_drizzle_orm.eq)(posts.slug, params.slug));
240
+ return (0, import_drizzle_orm2.and)(postPublicCondition(params), (0, import_drizzle_orm2.eq)(posts.slug, params.slug));
168
241
  }
169
242
  __name(postPublicSlugCondition, "postPublicSlugCondition");
243
+ function postDueCondition(params) {
244
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.status, import_content_contracts.POST_STATUS.SCHEDULED), (0, import_drizzle_orm2.eq)(posts.isTemplate, false), (0, import_drizzle_orm2.lte)(posts.publishedAt, params.now));
245
+ }
246
+ __name(postDueCondition, "postDueCondition");
247
+ function postShortIdCondition(params) {
248
+ return (0, import_drizzle_orm2.and)((0, import_drizzle_orm2.eq)(posts.companyId, params.companyId), (0, import_drizzle_orm2.eq)(posts.shortId, params.shortId));
249
+ }
250
+ __name(postShortIdCondition, "postShortIdCondition");
251
+ function postPublicShortIdCondition(params) {
252
+ return (0, import_drizzle_orm2.and)(postPublicCondition(params), (0, import_drizzle_orm2.eq)(posts.shortId, params.shortId));
253
+ }
254
+ __name(postPublicShortIdCondition, "postPublicShortIdCondition");
170
255
 
171
256
  // src/repositories/PostRepository.ts
172
257
  var TAG_LIST_LIMIT = 200;
258
+ var SORT_COLUMNS = {
259
+ title: posts.title,
260
+ status: posts.status,
261
+ publishedAt: posts.publishedAt,
262
+ updatedAt: posts.updatedAt
263
+ };
264
+ function adminOrder(query) {
265
+ const column = SORT_COLUMNS[query.sort ?? "updatedAt"];
266
+ const direction = (query.order ?? "desc") === "asc" ? import_drizzle_orm3.asc : import_drizzle_orm3.desc;
267
+ const primary = query.sort === "publishedAt" ? import_drizzle_orm3.sql`${column} ${import_drizzle_orm3.sql.raw(query.order === "asc" ? "asc" : "desc")} nulls last` : direction(column);
268
+ return [
269
+ primary,
270
+ (0, import_drizzle_orm3.asc)(posts.id)
271
+ ];
272
+ }
273
+ __name(adminOrder, "adminOrder");
173
274
  var PostRepository = class {
174
275
  static {
175
276
  __name(this, "PostRepository");
@@ -195,6 +296,25 @@ var PostRepository = class {
195
296
  const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1);
196
297
  return row;
197
298
  }
299
+ async findByShortId(params) {
300
+ const [row] = await this.db.select().from(posts).where(postShortIdCondition(params)).limit(1);
301
+ return row;
302
+ }
303
+ async findPublicByShortId(params) {
304
+ const [row] = await this.db.select().from(posts).where(postPublicShortIdCondition(params)).limit(1);
305
+ return row;
306
+ }
307
+ async findPublicByFormerSlug(params) {
308
+ const [former] = await this.db.select({
309
+ postId: postFormerSlugs.postId
310
+ }).from(postFormerSlugs).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(postFormerSlugs.companyId, params.companyId), (0, import_drizzle_orm3.eq)(postFormerSlugs.slug, params.slug))).limit(1);
311
+ if (!former) return void 0;
312
+ const [row] = await this.db.select().from(posts).where((0, import_drizzle_orm3.and)(postPublicCondition(params), (0, import_drizzle_orm3.eq)(posts.id, former.postId))).limit(1);
313
+ return row;
314
+ }
315
+ async recordFormerSlug(params) {
316
+ await this.db.insert(postFormerSlugs).values(params).onConflictDoNothing();
317
+ }
198
318
  async update(params) {
199
319
  const [row] = await this.db.update(posts).set({
200
320
  ...params.values,
@@ -205,9 +325,9 @@ var PostRepository = class {
205
325
  async listForAdmin(query) {
206
326
  const where = postAdminListCondition(query);
207
327
  const [rows, [counted]] = await Promise.all([
208
- this.db.select().from(posts).where(where).orderBy((0, import_drizzle_orm2.desc)(posts.updatedAt), (0, import_drizzle_orm2.asc)(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
328
+ this.db.select().from(posts).where(where).orderBy(...adminOrder(query)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
209
329
  this.db.select({
210
- value: import_drizzle_orm2.sql`count(*)::int`
330
+ value: import_drizzle_orm3.sql`count(*)::int`
211
331
  }).from(posts).where(where)
212
332
  ]);
213
333
  return {
@@ -218,9 +338,9 @@ var PostRepository = class {
218
338
  async listPublic(query) {
219
339
  const where = postPublicCondition(query);
220
340
  const [rows, [counted]] = await Promise.all([
221
- this.db.select().from(posts).where(where).orderBy((0, import_drizzle_orm2.desc)(posts.publishedAt), (0, import_drizzle_orm2.asc)(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
341
+ this.db.select().from(posts).where(where).orderBy((0, import_drizzle_orm3.desc)(posts.publishedAt), (0, import_drizzle_orm3.asc)(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
222
342
  this.db.select({
223
- value: import_drizzle_orm2.sql`count(*)::int`
343
+ value: import_drizzle_orm3.sql`count(*)::int`
224
344
  }).from(posts).where(where)
225
345
  ]);
226
346
  return {
@@ -228,6 +348,37 @@ var PostRepository = class {
228
348
  total: counted?.value ?? 0
229
349
  };
230
350
  }
351
+ async countByStatus(params) {
352
+ const now = import_drizzle_orm3.sql`${params.now.toISOString()}::timestamptz`;
353
+ const counted = /* @__PURE__ */ __name((condition) => import_drizzle_orm3.sql`count(*) filter (where ${condition})::int`, "counted");
354
+ const livePublished = import_drizzle_orm3.sql`(${posts.status} = ${import_content_contracts2.POST_STATUS.PUBLISHED} or (${posts.status} = ${import_content_contracts2.POST_STATUS.SCHEDULED} and ${posts.publishedAt} <= ${now}))`;
355
+ const [row] = await this.db.select({
356
+ published: counted(import_drizzle_orm3.sql`not ${posts.isTemplate} and ${livePublished}`),
357
+ scheduled: counted(import_drizzle_orm3.sql`not ${posts.isTemplate} and ${posts.status} = ${import_content_contracts2.POST_STATUS.SCHEDULED} and ${posts.publishedAt} > ${now}`),
358
+ draft: counted(import_drizzle_orm3.sql`not ${posts.isTemplate} and ${posts.status} = ${import_content_contracts2.POST_STATUS.DRAFT}`),
359
+ archived: counted(import_drizzle_orm3.sql`not ${posts.isTemplate} and ${posts.status} = ${import_content_contracts2.POST_STATUS.ARCHIVED}`),
360
+ templates: counted(import_drizzle_orm3.sql`${posts.isTemplate} and ${posts.status} <> ${import_content_contracts2.POST_STATUS.ARCHIVED}`)
361
+ }).from(posts).where((0, import_drizzle_orm3.eq)(posts.companyId, params.companyId));
362
+ return row ?? {
363
+ published: 0,
364
+ scheduled: 0,
365
+ draft: 0,
366
+ archived: 0,
367
+ templates: 0
368
+ };
369
+ }
370
+ async claimDueScheduled(params) {
371
+ const due = this.db.select({
372
+ id: posts.id
373
+ }).from(posts).where(postDueCondition({
374
+ now: params.now
375
+ })).orderBy((0, import_drizzle_orm3.asc)(posts.publishedAt), (0, import_drizzle_orm3.asc)(posts.id)).limit(params.limit).for("update", {
376
+ skipLocked: true
377
+ });
378
+ return this.db.update(posts).set({
379
+ status: import_content_contracts2.POST_STATUS.PUBLISHED
380
+ }).where((0, import_drizzle_orm3.inArray)(posts.id, due)).returning();
381
+ }
231
382
  async listTags(params) {
232
383
  const where = params.publicAt ? postPublicCondition({
233
384
  companyId: params.companyId,
@@ -237,18 +388,70 @@ var PostRepository = class {
237
388
  now: /* @__PURE__ */ new Date()
238
389
  });
239
390
  const postTags = this.db.select({
240
- tag: import_drizzle_orm2.sql`unnest(${posts.tags})`.as("tag")
391
+ tag: import_drizzle_orm3.sql`unnest(${posts.tags})`.as("tag")
241
392
  }).from(posts).where(where).as("post_tags");
242
393
  const rows = await this.db.select({
243
394
  tag: postTags.tag,
244
- count: import_drizzle_orm2.sql`count(*)::int`
245
- }).from(postTags).groupBy(postTags.tag).orderBy(import_drizzle_orm2.sql`count(*) desc`, (0, import_drizzle_orm2.asc)(postTags.tag)).limit(TAG_LIST_LIMIT);
395
+ count: import_drizzle_orm3.sql`count(*)::int`
396
+ }).from(postTags).groupBy(postTags.tag).orderBy(import_drizzle_orm3.sql`count(*) desc`, (0, import_drizzle_orm3.asc)(postTags.tag)).limit(TAG_LIST_LIMIT);
246
397
  return rows;
247
398
  }
248
399
  };
249
400
 
401
+ // src/repositories/RecurrenceRepository.ts
402
+ var import_drizzle_orm4 = require("drizzle-orm");
403
+ function recurrenceOwnedByCondition(params) {
404
+ return (0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(recurrenceRules.companyId, params.companyId), (0, import_drizzle_orm4.eq)(recurrenceRules.id, params.id));
405
+ }
406
+ __name(recurrenceOwnedByCondition, "recurrenceOwnedByCondition");
407
+ var RecurrenceRepository = class {
408
+ static {
409
+ __name(this, "RecurrenceRepository");
410
+ }
411
+ db;
412
+ constructor(db) {
413
+ this.db = db;
414
+ }
415
+ async create(values) {
416
+ const [row] = await this.db.insert(recurrenceRules).values(values).returning();
417
+ if (!row) throw new Error("content-module: insert em recurrence_rules n\xE3o retornou linha");
418
+ return row;
419
+ }
420
+ async findById(params) {
421
+ const [row] = await this.db.select().from(recurrenceRules).where(recurrenceOwnedByCondition(params)).limit(1);
422
+ return row;
423
+ }
424
+ async list(params) {
425
+ return this.db.select().from(recurrenceRules).where((0, import_drizzle_orm4.eq)(recurrenceRules.companyId, params.companyId)).orderBy((0, import_drizzle_orm4.asc)(recurrenceRules.nextRunAt), (0, import_drizzle_orm4.asc)(recurrenceRules.id));
426
+ }
427
+ async update(params) {
428
+ const [row] = await this.db.update(recurrenceRules).set(params.values).where(recurrenceOwnedByCondition(params)).returning();
429
+ return row;
430
+ }
431
+ async remove(params) {
432
+ const removed = await this.db.delete(recurrenceRules).where(recurrenceOwnedByCondition(params)).returning({
433
+ id: recurrenceRules.id
434
+ });
435
+ return removed.length > 0;
436
+ }
437
+ async processDue(params) {
438
+ return this.db.transaction(async (transaction) => {
439
+ const due = await transaction.select().from(recurrenceRules).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(recurrenceRules.isActive, true), (0, import_drizzle_orm4.lte)(recurrenceRules.nextRunAt, params.now))).orderBy((0, import_drizzle_orm4.asc)(recurrenceRules.nextRunAt), (0, import_drizzle_orm4.asc)(recurrenceRules.id)).limit(params.limit).for("update", {
440
+ skipLocked: true
441
+ });
442
+ let processed = 0;
443
+ for (const rule of due) {
444
+ const values = await params.handle(rule);
445
+ await transaction.update(recurrenceRules).set(values).where((0, import_drizzle_orm4.eq)(recurrenceRules.id, rule.id));
446
+ processed += 1;
447
+ }
448
+ return processed;
449
+ });
450
+ }
451
+ };
452
+
250
453
  // src/use-cases/Feed.use-cases.ts
251
- var import_content_contracts2 = require("@adatechnology/content-contracts");
454
+ var import_content_contracts3 = require("@adatechnology/content-contracts");
252
455
  var DEFAULT_ITEM_LIMIT = 20;
253
456
  var SITEMAP_LIMIT = 5e4;
254
457
  var FEED_FORMAT = {
@@ -287,11 +490,11 @@ var BuildFeedUseCase = class {
287
490
  } : {}
288
491
  };
289
492
  const items = page.rows.map((row) => this.toItem(row));
290
- return params.format === FEED_FORMAT.ATOM ? (0, import_content_contracts2.buildAtomFeed)({
493
+ return params.format === FEED_FORMAT.ATOM ? (0, import_content_contracts3.buildAtomFeed)({
291
494
  channel,
292
495
  items,
293
496
  now
294
- }) : (0, import_content_contracts2.buildRssFeed)({
497
+ }) : (0, import_content_contracts3.buildRssFeed)({
295
498
  channel,
296
499
  items
297
500
  });
@@ -299,16 +502,17 @@ var BuildFeedUseCase = class {
299
502
  toItem(row) {
300
503
  return {
301
504
  title: row.title,
302
- url: (0, import_content_contracts2.buildPostUrl)({
505
+ url: (0, import_content_contracts3.buildPostUrl)({
303
506
  siteUrl: this.feed.siteUrl,
304
507
  slug: row.slug,
508
+ shortId: row.shortId,
305
509
  postPathTemplate: this.feed.postPathTemplate
306
510
  }),
307
511
  publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
308
512
  updatedAt: row.updatedAt.toISOString(),
309
- summary: row.excerpt ?? (0, import_content_contracts2.buildExcerpt)(row.body),
513
+ summary: row.excerpt ?? (0, import_content_contracts3.buildExcerpt)(row.body),
310
514
  ...this.feed.includeContent ?? true ? {
311
- contentHtml: (0, import_content_contracts2.renderMarkdownToHtml)(row.body, {
515
+ contentHtml: (0, import_content_contracts3.renderMarkdownToHtml)(row.body, {
312
516
  headingIds: false
313
517
  })
314
518
  } : {},
@@ -341,9 +545,10 @@ var ListSitemapEntriesUseCase = class {
341
545
  pageSize: SITEMAP_LIMIT
342
546
  });
343
547
  return page.rows.map((row) => ({
344
- loc: (0, import_content_contracts2.buildPostUrl)({
548
+ loc: (0, import_content_contracts3.buildPostUrl)({
345
549
  siteUrl: this.feed.siteUrl,
346
550
  slug: row.slug,
551
+ shortId: row.shortId,
347
552
  postPathTemplate: this.feed.postPathTemplate
348
553
  }),
349
554
  lastmod: row.updatedAt.toISOString()
@@ -352,7 +557,18 @@ var ListSitemapEntriesUseCase = class {
352
557
  };
353
558
 
354
559
  // src/use-cases/Post.use-cases.ts
560
+ var import_content_contracts6 = require("@adatechnology/content-contracts");
561
+
562
+ // src/shared/shortId.ts
563
+ var import_node_crypto = require("crypto");
355
564
  var import_content_contracts4 = require("@adatechnology/content-contracts");
565
+ var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
566
+ function generateShortId() {
567
+ let value = "";
568
+ for (let index2 = 0; index2 < import_content_contracts4.SHORT_ID_LENGTH; index2 += 1) value += ALPHABET[(0, import_node_crypto.randomInt)(ALPHABET.length)];
569
+ return value;
570
+ }
571
+ __name(generateShortId, "generateShortId");
356
572
 
357
573
  // src/shared/isUniqueViolation.ts
358
574
  var UNIQUE_VIOLATION = "23505";
@@ -386,9 +602,9 @@ async function notifyPostChanged(dependencies, type, post) {
386
602
  __name(notifyPostChanged, "notifyPostChanged");
387
603
 
388
604
  // src/shared/toContract.ts
389
- var import_content_contracts3 = require("@adatechnology/content-contracts");
605
+ var import_content_contracts5 = require("@adatechnology/content-contracts");
390
606
  function effectiveStatus(row, now) {
391
- if (row.status === import_content_contracts3.POST_STATUS.SCHEDULED && row.publishedAt && row.publishedAt <= now) return import_content_contracts3.POST_STATUS.PUBLISHED;
607
+ if (row.status === import_content_contracts5.POST_STATUS.SCHEDULED && row.publishedAt && row.publishedAt <= now) return import_content_contracts5.POST_STATUS.PUBLISHED;
392
608
  return row.status;
393
609
  }
394
610
  __name(effectiveStatus, "effectiveStatus");
@@ -397,12 +613,15 @@ function toPostSummary(row, now) {
397
613
  id: row.id,
398
614
  companyId: row.companyId,
399
615
  slug: row.slug,
616
+ shortId: row.shortId,
400
617
  title: row.title,
401
618
  excerpt: row.excerpt,
402
619
  coverImageUrl: row.coverImageUrl,
403
620
  coverImageAlt: row.coverImageAlt,
404
621
  tags: row.tags,
622
+ tagLabels: row.tagLabels,
405
623
  status: effectiveStatus(row, now),
624
+ isTemplate: row.isTemplate,
406
625
  publishedAt: row.publishedAt?.toISOString() ?? null,
407
626
  authorName: row.authorName,
408
627
  seoTitle: row.seoTitle,
@@ -425,11 +644,13 @@ function toPublicPostSummary(row) {
425
644
  return {
426
645
  id: row.id,
427
646
  slug: row.slug,
647
+ shortId: row.shortId,
428
648
  title: row.title,
429
649
  excerpt: row.excerpt,
430
650
  coverImageUrl: row.coverImageUrl,
431
651
  coverImageAlt: row.coverImageAlt,
432
652
  tags: row.tags,
653
+ tagLabels: row.tagLabels,
433
654
  publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
434
655
  updatedAt: row.updatedAt.toISOString(),
435
656
  authorName: row.authorName,
@@ -458,7 +679,7 @@ __name(toPagination, "toPagination");
458
679
  // src/use-cases/Post.use-cases.ts
459
680
  var MAX_SLUG_ATTEMPTS = 50;
460
681
  var FALLBACK_SLUG = "post";
461
- var PostUseCaseBase = class PostUseCaseBase2 {
682
+ var PostUseCaseBase = class {
462
683
  static {
463
684
  __name(this, "PostUseCaseBase");
464
685
  }
@@ -471,7 +692,7 @@ var PostUseCaseBase = class PostUseCaseBase2 {
471
692
  }
472
693
  async findOrFail(reference2) {
473
694
  const row = await this.dependencies.posts.findById(reference2);
474
- if (!row) throw new import_content_contracts4.PostNotFoundError(reference2.id);
695
+ if (!row) throw new import_content_contracts6.PostNotFoundError(reference2.id);
475
696
  return row;
476
697
  }
477
698
  async save(reference2, values, event) {
@@ -479,35 +700,48 @@ var PostUseCaseBase = class PostUseCaseBase2 {
479
700
  ...reference2,
480
701
  values
481
702
  }).catch((error) => {
482
- if (isUniqueViolation(error) && values.slug) throw new import_content_contracts4.DuplicateSlugError(values.slug);
703
+ if (isUniqueViolation(error) && values.slug) throw new import_content_contracts6.DuplicateSlugError(values.slug);
483
704
  throw error;
484
705
  });
485
- if (!row) throw new import_content_contracts4.PostNotFoundError(reference2.id);
706
+ if (!row) throw new import_content_contracts6.PostNotFoundError(reference2.id);
486
707
  const post = toPost(row, this.now());
487
708
  await notifyPostChanged(this.dependencies, event, post);
488
709
  return post;
489
710
  }
711
+ /** Id curto livre na empresa; a colisão (~1 em 2 bilhões) só repete o sorteio. */
712
+ async generateShortId(companyId) {
713
+ for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt += 1) {
714
+ const candidate = generateShortId();
715
+ if (!await this.dependencies.posts.findByShortId({
716
+ companyId,
717
+ shortId: candidate
718
+ })) return candidate;
719
+ }
720
+ throw new Error("content-module: sem id curto livre");
721
+ }
490
722
  readingTime(body) {
491
- return (0, import_content_contracts4.estimateReadingTimeMinutes)(body, this.dependencies.config.wordsPerMinute);
723
+ return (0, import_content_contracts6.estimateReadingTimeMinutes)(body, this.dependencies.config.wordsPerMinute);
492
724
  }
493
725
  async assertSlugAvailable(companyId, slug, ownId) {
494
726
  const existing = await this.dependencies.posts.findBySlug({
495
727
  companyId,
496
728
  slug
497
729
  });
498
- if (existing && existing.id !== ownId) throw new import_content_contracts4.DuplicateSlugError(slug);
730
+ if (existing && existing.id !== ownId) throw new import_content_contracts6.DuplicateSlugError(slug);
499
731
  }
500
732
  /** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */
501
733
  async generateSlug(companyId, title) {
502
- const base = (0, import_content_contracts4.slugify)(title) || FALLBACK_SLUG;
734
+ return this.uniqueSlug(companyId, (0, import_content_contracts6.buildShortSlug)(title, this.dependencies.config.slug) || FALLBACK_SLUG);
735
+ }
736
+ async uniqueSlug(companyId, base) {
503
737
  for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {
504
- const candidate = (0, import_content_contracts4.withSlugSuffix)(base, attempt);
738
+ const candidate = (0, import_content_contracts6.withSlugSuffix)(base, attempt);
505
739
  if (!await this.dependencies.posts.findBySlug({
506
740
  companyId,
507
741
  slug: candidate
508
742
  })) return candidate;
509
743
  }
510
- return (0, import_content_contracts4.withSlugSuffix)(base, Date.now());
744
+ return (0, import_content_contracts6.withSlugSuffix)(base, Date.now());
511
745
  }
512
746
  };
513
747
  function optionalFields(input) {
@@ -527,25 +761,30 @@ var CreatePostUseCase = class extends PostUseCaseBase {
527
761
  __name(this, "CreatePostUseCase");
528
762
  }
529
763
  async execute(params) {
530
- const input = import_content_contracts4.createPostSchema.parse(params.input);
764
+ const input = import_content_contracts6.createPostSchema.parse(params.input);
531
765
  const { companyId } = params;
532
766
  if (input.slug) await this.assertSlugAvailable(companyId, input.slug);
533
767
  const slug = input.slug ?? await this.generateSlug(companyId, input.title);
534
768
  const row = await this.dependencies.posts.create({
535
769
  companyId,
536
770
  slug,
771
+ shortId: await this.generateShortId(companyId),
537
772
  title: input.title,
538
773
  body: input.body,
539
- tags: (0, import_content_contracts4.normalizeTags)(input.tags ?? []),
540
- status: import_content_contracts4.POST_STATUS.DRAFT,
774
+ tags: (0, import_content_contracts6.normalizeTags)(input.tags ?? []),
775
+ tagLabels: (0, import_content_contracts6.buildTagLabels)({
776
+ typed: input.tags ?? [],
777
+ explicit: input.tagLabels
778
+ }),
779
+ status: import_content_contracts6.POST_STATUS.DRAFT,
541
780
  readingTimeMinutes: this.readingTime(input.body),
542
781
  ...optionalFields(input)
543
782
  }).catch((error) => {
544
- if (isUniqueViolation(error)) throw new import_content_contracts4.DuplicateSlugError(slug);
783
+ if (isUniqueViolation(error)) throw new import_content_contracts6.DuplicateSlugError(slug);
545
784
  throw error;
546
785
  });
547
786
  const post = toPost(row, this.now());
548
- await notifyPostChanged(this.dependencies, import_content_contracts4.POST_EVENT.CREATED, post);
787
+ await notifyPostChanged(this.dependencies, import_content_contracts6.POST_EVENT.CREATED, post);
549
788
  return post;
550
789
  }
551
790
  };
@@ -555,7 +794,7 @@ var UpdatePostUseCase = class extends PostUseCaseBase {
555
794
  }
556
795
  /** Trocar o título não muda o slug: o endereço já pode ter sido compartilhado. */
557
796
  async execute(params) {
558
- const input = import_content_contracts4.updatePostSchema.parse(params.input);
797
+ const input = import_content_contracts6.updatePostSchema.parse(params.input);
559
798
  const existing = await this.findOrFail(params);
560
799
  const values = optionalFields(input);
561
800
  if (input.title !== void 0) values.title = input.title;
@@ -563,12 +802,25 @@ var UpdatePostUseCase = class extends PostUseCaseBase {
563
802
  values.body = input.body;
564
803
  values.readingTimeMinutes = this.readingTime(input.body);
565
804
  }
566
- if (input.tags !== void 0) values.tags = (0, import_content_contracts4.normalizeTags)(input.tags);
805
+ if (input.tags !== void 0 || input.tagLabels !== void 0) {
806
+ const tags = (0, import_content_contracts6.normalizeTags)(input.tags ?? existing.tags);
807
+ values.tags = tags;
808
+ values.tagLabels = (0, import_content_contracts6.buildTagLabels)({
809
+ typed: input.tags ?? tags,
810
+ explicit: input.tagLabels,
811
+ previous: existing.tagLabels
812
+ });
813
+ }
567
814
  if (input.slug !== void 0 && input.slug !== existing.slug) {
568
815
  await this.assertSlugAvailable(params.companyId, input.slug, existing.id);
569
816
  values.slug = input.slug;
817
+ await this.dependencies.posts.recordFormerSlug({
818
+ companyId: params.companyId,
819
+ postId: existing.id,
820
+ slug: existing.slug
821
+ });
570
822
  }
571
- return this.save(params, values, import_content_contracts4.POST_EVENT.UPDATED);
823
+ return this.save(params, values, import_content_contracts6.POST_EVENT.UPDATED);
572
824
  }
573
825
  };
574
826
  var PublishPostUseCase = class extends PostUseCaseBase {
@@ -577,15 +829,16 @@ var PublishPostUseCase = class extends PostUseCaseBase {
577
829
  }
578
830
  /** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */
579
831
  async execute(params) {
580
- const input = import_content_contracts4.publishPostSchema.parse(params.input ?? {});
581
- await this.findOrFail(params);
832
+ const input = import_content_contracts6.publishPostSchema.parse(params.input ?? {});
833
+ const existing = await this.findOrFail(params);
834
+ if (existing.isTemplate) throw new import_content_contracts6.TemplateNotPublishableError(params.id);
582
835
  const now = this.now();
583
836
  const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
584
- const status = publishedAt > now ? import_content_contracts4.POST_STATUS.SCHEDULED : import_content_contracts4.POST_STATUS.PUBLISHED;
837
+ const status = publishedAt > now ? import_content_contracts6.POST_STATUS.SCHEDULED : import_content_contracts6.POST_STATUS.PUBLISHED;
585
838
  return this.save(params, {
586
839
  status,
587
840
  publishedAt
588
- }, import_content_contracts4.POST_EVENT.PUBLISHED);
841
+ }, import_content_contracts6.POST_EVENT.PUBLISHED);
589
842
  }
590
843
  };
591
844
  var UnpublishPostUseCase = class extends PostUseCaseBase {
@@ -596,9 +849,9 @@ var UnpublishPostUseCase = class extends PostUseCaseBase {
596
849
  async execute(params) {
597
850
  await this.findOrFail(params);
598
851
  return this.save(params, {
599
- status: import_content_contracts4.POST_STATUS.DRAFT,
852
+ status: import_content_contracts6.POST_STATUS.DRAFT,
600
853
  publishedAt: null
601
- }, import_content_contracts4.POST_EVENT.UNPUBLISHED);
854
+ }, import_content_contracts6.POST_EVENT.UNPUBLISHED);
602
855
  }
603
856
  };
604
857
  var ArchivePostUseCase = class extends PostUseCaseBase {
@@ -609,8 +862,8 @@ var ArchivePostUseCase = class extends PostUseCaseBase {
609
862
  async execute(params) {
610
863
  await this.findOrFail(params);
611
864
  return this.save(params, {
612
- status: import_content_contracts4.POST_STATUS.ARCHIVED
613
- }, import_content_contracts4.POST_EVENT.ARCHIVED);
865
+ status: import_content_contracts6.POST_STATUS.ARCHIVED
866
+ }, import_content_contracts6.POST_EVENT.ARCHIVED);
614
867
  }
615
868
  };
616
869
  var GetPostUseCase = class extends PostUseCaseBase {
@@ -627,17 +880,17 @@ var ListPostsUseCase = class extends PostUseCaseBase {
627
880
  }
628
881
  async execute(params) {
629
882
  const { companyId, ...rawQuery } = params;
630
- const query = import_content_contracts4.listPostsQuerySchema.parse(rawQuery);
631
- const tag = query.tag ? (0, import_content_contracts4.normalizeTags)([
632
- query.tag
633
- ])[0] : void 0;
883
+ const query = import_content_contracts6.listPostsQuerySchema.parse(rawQuery);
884
+ const { tag: rawTag, ...rest } = query;
885
+ const tags = rawTag ? (0, import_content_contracts6.normalizeTags)(rawTag.split(",")) : [];
634
886
  const now = this.now();
635
887
  const page = await this.dependencies.posts.listForAdmin({
636
888
  companyId,
637
- ...query,
889
+ ...rest,
890
+ isTemplate: query.isTemplate ?? false,
638
891
  now,
639
- ...tag ? {
640
- tag
892
+ ...tags.length > 0 ? {
893
+ tags
641
894
  } : {}
642
895
  });
643
896
  return {
@@ -652,7 +905,7 @@ var ListPostsUseCase = class extends PostUseCaseBase {
652
905
  };
653
906
 
654
907
  // src/use-cases/PublicPost.use-cases.ts
655
- var import_content_contracts5 = require("@adatechnology/content-contracts");
908
+ var import_content_contracts7 = require("@adatechnology/content-contracts");
656
909
  var GetPublishedPostBySlugUseCase = class {
657
910
  static {
658
911
  __name(this, "GetPublishedPostBySlugUseCase");
@@ -661,14 +914,29 @@ var GetPublishedPostBySlugUseCase = class {
661
914
  constructor(dependencies) {
662
915
  this.dependencies = dependencies;
663
916
  }
917
+ /**
918
+ * `slug` aceita o endereço canônico `<shortId>-<slug>`, o slug atual e slug antigo. O id curto
919
+ * manda: título/slug editado depois não quebra link compartilhado. O host compara `buildPostRef`
920
+ * do resultado com o pedido e redireciona (301) quando forem diferentes.
921
+ */
664
922
  async execute(params) {
665
- const slug = params.slug.trim().toLowerCase();
666
- const row = await this.dependencies.posts.findPublicBySlug({
923
+ const { posts: posts2, clock } = this.dependencies;
924
+ const parsed = (0, import_content_contracts7.parsePostRef)(params.slug);
925
+ const query = {
667
926
  companyId: params.companyId,
668
- slug,
669
- now: this.dependencies.clock.now()
927
+ now: clock.now()
928
+ };
929
+ const row = (parsed.shortId ? await posts2.findPublicByShortId({
930
+ ...query,
931
+ shortId: parsed.shortId
932
+ }) : void 0) ?? await posts2.findPublicBySlug({
933
+ ...query,
934
+ slug: parsed.slug
935
+ }) ?? await posts2.findPublicByFormerSlug({
936
+ ...query,
937
+ slug: parsed.slug
670
938
  });
671
- if (!row) throw new import_content_contracts5.PostNotFoundError(slug);
939
+ if (!row) throw new import_content_contracts7.PostNotFoundError(parsed.slug);
672
940
  return toPublicPost(row);
673
941
  }
674
942
  };
@@ -682,8 +950,8 @@ var ListPublishedPostsUseCase = class {
682
950
  }
683
951
  async execute(params) {
684
952
  const { companyId, ...rawQuery } = params;
685
- const query = import_content_contracts5.listPublishedPostsQuerySchema.parse(rawQuery);
686
- const tag = query.tag ? (0, import_content_contracts5.normalizeTag)(query.tag) : void 0;
953
+ const query = import_content_contracts7.listPublishedPostsQuerySchema.parse(rawQuery);
954
+ const tag = query.tag ? (0, import_content_contracts7.normalizeTag)(query.tag) : void 0;
687
955
  const page = await this.dependencies.posts.listPublic({
688
956
  companyId,
689
957
  now: this.dependencies.clock.now(),
@@ -726,8 +994,350 @@ var ListTagsUseCase = class {
726
994
  }
727
995
  };
728
996
 
997
+ // src/use-cases/Recurrence.use-cases.ts
998
+ var import_content_contracts8 = require("@adatechnology/content-contracts");
999
+ var RecurrenceUseCaseBase = class RecurrenceUseCaseBase2 {
1000
+ static {
1001
+ __name(this, "RecurrenceUseCaseBase");
1002
+ }
1003
+ dependencies;
1004
+ constructor(dependencies) {
1005
+ this.dependencies = dependencies;
1006
+ }
1007
+ async toRule(row) {
1008
+ const template = await this.dependencies.posts.findById({
1009
+ companyId: row.companyId,
1010
+ id: row.templateId
1011
+ });
1012
+ return {
1013
+ id: row.id,
1014
+ companyId: row.companyId,
1015
+ templateId: row.templateId,
1016
+ templateTitle: template?.title ?? "",
1017
+ frequency: row.frequency,
1018
+ isActive: row.isActive,
1019
+ nextRunAt: row.nextRunAt.toISOString(),
1020
+ lastRunAt: row.lastRunAt?.toISOString() ?? null,
1021
+ lastPostId: row.lastPostId,
1022
+ createdAt: row.createdAt.toISOString()
1023
+ };
1024
+ }
1025
+ async findOrFail(params) {
1026
+ const row = await this.dependencies.recurrences.findById(params);
1027
+ if (!row) throw new import_content_contracts8.RecurrenceNotFoundError(params.id);
1028
+ return row;
1029
+ }
1030
+ };
1031
+ var CreateRecurrenceUseCase = class extends RecurrenceUseCaseBase {
1032
+ static {
1033
+ __name(this, "CreateRecurrenceUseCase");
1034
+ }
1035
+ async execute(params) {
1036
+ const input = import_content_contracts8.createRecurrenceSchema.parse(params.input);
1037
+ const template = await this.dependencies.posts.findById({
1038
+ companyId: params.companyId,
1039
+ id: input.templateId
1040
+ });
1041
+ if (!template) throw new import_content_contracts8.PostNotFoundError(input.templateId);
1042
+ if (!template.isTemplate) throw new import_content_contracts8.NotATemplateError(input.templateId);
1043
+ const startsAt = new Date(input.startsAt);
1044
+ const values = {
1045
+ companyId: params.companyId,
1046
+ templateId: input.templateId,
1047
+ frequency: input.frequency,
1048
+ anchorDay: startsAt.getUTCDate(),
1049
+ nextRunAt: startsAt
1050
+ };
1051
+ return this.toRule(await this.dependencies.recurrences.create(values));
1052
+ }
1053
+ };
1054
+ var ListRecurrencesUseCase = class extends RecurrenceUseCaseBase {
1055
+ static {
1056
+ __name(this, "ListRecurrencesUseCase");
1057
+ }
1058
+ async execute(params) {
1059
+ const rows = await this.dependencies.recurrences.list(params);
1060
+ return Promise.all(rows.map((row) => this.toRule(row)));
1061
+ }
1062
+ };
1063
+ var UpdateRecurrenceUseCase = class extends RecurrenceUseCaseBase {
1064
+ static {
1065
+ __name(this, "UpdateRecurrenceUseCase");
1066
+ }
1067
+ /** Pausar/retomar e remarcar a próxima execução. */
1068
+ async execute(params) {
1069
+ const input = import_content_contracts8.updateRecurrenceSchema.parse(params.input);
1070
+ await this.findOrFail(params);
1071
+ const values = {};
1072
+ if (input.isActive !== void 0) values.isActive = input.isActive;
1073
+ if (input.nextRunAt !== void 0) {
1074
+ values.nextRunAt = new Date(input.nextRunAt);
1075
+ values.anchorDay = values.nextRunAt.getUTCDate();
1076
+ }
1077
+ const row = await this.dependencies.recurrences.update({
1078
+ companyId: params.companyId,
1079
+ id: params.id,
1080
+ values
1081
+ });
1082
+ if (!row) throw new import_content_contracts8.RecurrenceNotFoundError(params.id);
1083
+ return this.toRule(row);
1084
+ }
1085
+ };
1086
+ var RemoveRecurrenceUseCase = class extends RecurrenceUseCaseBase {
1087
+ static {
1088
+ __name(this, "RemoveRecurrenceUseCase");
1089
+ }
1090
+ /** Apaga só a regra: os posts que ela já publicou continuam no ar. */
1091
+ async execute(params) {
1092
+ if (!await this.dependencies.recurrences.remove(params)) throw new import_content_contracts8.RecurrenceNotFoundError(params.id);
1093
+ }
1094
+ };
1095
+
1096
+ // src/use-cases/Scheduling.use-cases.ts
1097
+ var import_content_contracts11 = require("@adatechnology/content-contracts");
1098
+
1099
+ // src/shared/recurrence.ts
1100
+ var import_content_contracts9 = require("@adatechnology/content-contracts");
1101
+ var WEEK_MS = 7 * 24 * 60 * 60 * 1e3;
1102
+ function daysInMonth(year, monthIndex) {
1103
+ return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
1104
+ }
1105
+ __name(daysInMonth, "daysInMonth");
1106
+ function addMonths(from, anchorDay, months) {
1107
+ const target = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + months, 1));
1108
+ const day = Math.min(anchorDay, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()));
1109
+ return new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth(), day, from.getUTCHours(), from.getUTCMinutes(), from.getUTCSeconds(), from.getUTCMilliseconds()));
1110
+ }
1111
+ __name(addMonths, "addMonths");
1112
+ function nextOccurrence(params) {
1113
+ if (params.frequency === import_content_contracts9.RECURRENCE_FREQUENCY.WEEKLY) return new Date(params.from.getTime() + WEEK_MS);
1114
+ return addMonths(params.from, params.anchorDay, 1);
1115
+ }
1116
+ __name(nextOccurrence, "nextOccurrence");
1117
+ function nextOccurrenceAfter(params) {
1118
+ let candidate = nextOccurrence(params);
1119
+ while (candidate <= params.now) candidate = nextOccurrence({
1120
+ ...params,
1121
+ from: candidate
1122
+ });
1123
+ return candidate;
1124
+ }
1125
+ __name(nextOccurrenceAfter, "nextOccurrenceAfter");
1126
+ function toDateStamp(date) {
1127
+ return date.toISOString().slice(0, 10);
1128
+ }
1129
+ __name(toDateStamp, "toDateStamp");
1130
+
1131
+ // src/use-cases/Template.use-cases.ts
1132
+ var import_content_contracts10 = require("@adatechnology/content-contracts");
1133
+ var TEMPLATE_SLUG_PREFIX = "modelo";
1134
+ function copiableFields(row) {
1135
+ return {
1136
+ excerpt: row.excerpt,
1137
+ body: row.body,
1138
+ coverImageUrl: row.coverImageUrl,
1139
+ coverImageAlt: row.coverImageAlt,
1140
+ tags: (0, import_content_contracts10.normalizeTags)(row.tags),
1141
+ tagLabels: row.tagLabels,
1142
+ authorName: row.authorName,
1143
+ seoTitle: row.seoTitle,
1144
+ seoDescription: row.seoDescription,
1145
+ readingTimeMinutes: row.readingTimeMinutes
1146
+ };
1147
+ }
1148
+ __name(copiableFields, "copiableFields");
1149
+ var TemplateUseCaseBase = class TemplateUseCaseBase2 extends PostUseCaseBase {
1150
+ static {
1151
+ __name(this, "TemplateUseCaseBase");
1152
+ }
1153
+ async insertCopy(params) {
1154
+ const row = await this.dependencies.posts.create({
1155
+ ...copiableFields(params.source),
1156
+ companyId: params.companyId,
1157
+ slug: params.slug,
1158
+ shortId: await this.generateShortId(params.companyId),
1159
+ title: params.title,
1160
+ isTemplate: params.isTemplate,
1161
+ status: params.status ?? import_content_contracts10.POST_STATUS.DRAFT,
1162
+ ...params.publishedAt ? {
1163
+ publishedAt: params.publishedAt
1164
+ } : {}
1165
+ }).catch((error) => {
1166
+ if (isUniqueViolation(error)) throw new import_content_contracts10.DuplicateSlugError(params.slug);
1167
+ throw error;
1168
+ });
1169
+ const post = toPost(row, this.now());
1170
+ await notifyPostChanged(this.dependencies, import_content_contracts10.POST_EVENT.CREATED, post);
1171
+ return post;
1172
+ }
1173
+ };
1174
+ var SaveAsTemplateUseCase = class extends TemplateUseCaseBase {
1175
+ static {
1176
+ __name(this, "SaveAsTemplateUseCase");
1177
+ }
1178
+ /** Copia o post (qualquer status) para um modelo. O original não muda. */
1179
+ async execute(params) {
1180
+ const input = import_content_contracts10.saveAsTemplateSchema.parse(params.input ?? {});
1181
+ const source = await this.findOrFail(params);
1182
+ const title = input.title ?? source.title;
1183
+ const slug = await this.generateSlug(params.companyId, `${TEMPLATE_SLUG_PREFIX} ${title}`);
1184
+ return this.insertCopy({
1185
+ companyId: params.companyId,
1186
+ slug,
1187
+ title,
1188
+ source,
1189
+ isTemplate: true
1190
+ });
1191
+ }
1192
+ };
1193
+ var CreateFromTemplateUseCase = class extends TemplateUseCaseBase {
1194
+ static {
1195
+ __name(this, "CreateFromTemplateUseCase");
1196
+ }
1197
+ /** Cria um RASCUNHO novo com o conteúdo do modelo, pronto para editar e publicar. */
1198
+ async execute(params) {
1199
+ const input = import_content_contracts10.createFromTemplateSchema.parse(params.input ?? {});
1200
+ const template = await this.findOrFail(params);
1201
+ if (!template.isTemplate) throw new import_content_contracts10.NotATemplateError(params.id);
1202
+ const title = input.title ?? template.title;
1203
+ if (input.slug) await this.assertSlugAvailable(params.companyId, input.slug);
1204
+ const slug = input.slug ?? await this.generateSlug(params.companyId, title);
1205
+ return this.insertCopy({
1206
+ companyId: params.companyId,
1207
+ slug,
1208
+ title,
1209
+ source: template,
1210
+ isTemplate: false
1211
+ });
1212
+ }
1213
+ };
1214
+ var CountPostsUseCase = class extends PostUseCaseBase {
1215
+ static {
1216
+ __name(this, "CountPostsUseCase");
1217
+ }
1218
+ /** Números das abas do painel, numa consulta só. */
1219
+ async execute(params) {
1220
+ return this.dependencies.posts.countByStatus({
1221
+ companyId: params.companyId,
1222
+ now: this.now()
1223
+ });
1224
+ }
1225
+ };
1226
+
1227
+ // src/use-cases/Scheduling.use-cases.ts
1228
+ var DEFAULT_BATCH_LIMIT = 100;
1229
+ var DATE_SUFFIX_LENGTH = 11;
1230
+ var FALLBACK_SLUG2 = "post";
1231
+ var RepublishPostUseCase = class extends PostUseCaseBase {
1232
+ static {
1233
+ __name(this, "RepublishPostUseCase");
1234
+ }
1235
+ /**
1236
+ * Muda a data de um post JÁ publicado, mantendo o MESMO endereço. É a opção segura para SEO: o
1237
+ * link antigo (compartilhado, indexado, com backlinks) continua valendo e não nasce conteúdo
1238
+ * duplicado. Data futura é recusada — o post sairia do ar até lá e o leitor veria 404.
1239
+ */
1240
+ async execute(params) {
1241
+ const input = import_content_contracts11.republishPostSchema.parse(params.input ?? {});
1242
+ const existing = await this.findOrFail(params);
1243
+ const now = this.now();
1244
+ if (existing.isTemplate || effectiveStatus(existing, now) !== import_content_contracts11.POST_STATUS.PUBLISHED) {
1245
+ throw new import_content_contracts11.PostNotPublishedError(params.id);
1246
+ }
1247
+ const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
1248
+ if (publishedAt > now) throw new import_content_contracts11.RepublishDateInFutureError();
1249
+ return this.save(params, {
1250
+ status: import_content_contracts11.POST_STATUS.PUBLISHED,
1251
+ publishedAt
1252
+ }, import_content_contracts11.POST_EVENT.REPUBLISHED);
1253
+ }
1254
+ };
1255
+ var PublishDueUseCase = class extends PostUseCaseBase {
1256
+ static {
1257
+ __name(this, "PublishDueUseCase");
1258
+ }
1259
+ /**
1260
+ * Idempotente e seguro com várias instâncias chamando ao mesmo tempo: cada post/regra é reclamado
1261
+ * por uma só execução. Sem trabalho vencido, não faz nada. `now` existe para teste e reprocesso.
1262
+ */
1263
+ async execute(params = {}) {
1264
+ const now = params.now ?? this.now();
1265
+ const limit = params.limit ?? DEFAULT_BATCH_LIMIT;
1266
+ const materialized = await this.materializeRecurrences({
1267
+ now,
1268
+ limit
1269
+ });
1270
+ const rows = await this.dependencies.posts.claimDueScheduled({
1271
+ now,
1272
+ limit
1273
+ });
1274
+ for (const row of rows) {
1275
+ await notifyPostChanged(this.dependencies, import_content_contracts11.POST_EVENT.PUBLISHED, toPost(row, now));
1276
+ }
1277
+ if (rows.length > 0 || materialized > 0) {
1278
+ this.dependencies.logger?.info("content-module: publishDue", {
1279
+ published: rows.length,
1280
+ materialized
1281
+ });
1282
+ }
1283
+ return {
1284
+ published: rows.length,
1285
+ materialized
1286
+ };
1287
+ }
1288
+ materializeRecurrences(params) {
1289
+ return this.dependencies.recurrences.processDue({
1290
+ ...params,
1291
+ handle: /* @__PURE__ */ __name((rule) => this.materialize(rule, params.now), "handle")
1292
+ });
1293
+ }
1294
+ /** Um post publicado agora a partir do modelo; a regra avança para a próxima data futura. */
1295
+ async materialize(rule, now) {
1296
+ const advance = {
1297
+ nextRunAt: nextOccurrenceAfter({
1298
+ frequency: rule.frequency,
1299
+ from: rule.nextRunAt,
1300
+ anchorDay: rule.anchorDay,
1301
+ now
1302
+ })
1303
+ };
1304
+ const template = await this.dependencies.posts.findById({
1305
+ companyId: rule.companyId,
1306
+ id: rule.templateId
1307
+ });
1308
+ if (!template || !template.isTemplate || template.status === import_content_contracts11.POST_STATUS.ARCHIVED) {
1309
+ this.dependencies.logger?.warn("content-module: modelo da recorr\xEAncia indispon\xEDvel", {
1310
+ ruleId: rule.id
1311
+ });
1312
+ return {
1313
+ isActive: false
1314
+ };
1315
+ }
1316
+ const base = ((0, import_content_contracts11.slugify)(template.title) || FALLBACK_SLUG2).slice(0, import_content_contracts11.SLUG_MAX_LENGTH - DATE_SUFFIX_LENGTH);
1317
+ const slug = await this.uniqueSlug(rule.companyId, `${base.replace(/-+$/g, "")}-${toDateStamp(now)}`);
1318
+ const row = await this.dependencies.posts.create({
1319
+ ...copiableFields(template),
1320
+ companyId: rule.companyId,
1321
+ slug,
1322
+ shortId: await this.generateShortId(rule.companyId),
1323
+ title: template.title,
1324
+ isTemplate: false,
1325
+ status: import_content_contracts11.POST_STATUS.PUBLISHED,
1326
+ publishedAt: now
1327
+ });
1328
+ const post = toPost(row, now);
1329
+ await notifyPostChanged(this.dependencies, import_content_contracts11.POST_EVENT.CREATED, post);
1330
+ await notifyPostChanged(this.dependencies, import_content_contracts11.POST_EVENT.PUBLISHED, post);
1331
+ return {
1332
+ ...advance,
1333
+ lastRunAt: now,
1334
+ lastPostId: row.id
1335
+ };
1336
+ }
1337
+ };
1338
+
729
1339
  // src/use-cases/UploadCoverImage.use-case.ts
730
- var import_content_contracts6 = require("@adatechnology/content-contracts");
1340
+ var import_content_contracts12 = require("@adatechnology/content-contracts");
731
1341
 
732
1342
  // src/shared/coverImage.constant.ts
733
1343
  var COVER_IMAGE = {
@@ -751,12 +1361,12 @@ var UploadCoverImageUseCase = class {
751
1361
  }
752
1362
  async execute(params) {
753
1363
  const storage = this.dependencies.imageStorage;
754
- if (!storage) throw new import_content_contracts6.ImageStorageDisabledError();
1364
+ if (!storage) throw new import_content_contracts12.ImageStorageDisabledError();
755
1365
  const mimeType = (params.mimeType.split(";")[0] ?? "").trim().toLowerCase();
756
1366
  const extension = COVER_IMAGE.EXTENSION_BY_MIME[mimeType];
757
- if (!extension) throw new import_content_contracts6.InvalidCoverImageError("unsupported_type");
758
- if (params.bytes.byteLength === 0) throw new import_content_contracts6.InvalidCoverImageError("empty");
759
- if (params.bytes.byteLength > COVER_IMAGE.MAX_BYTES) throw new import_content_contracts6.InvalidCoverImageError("too_large");
1367
+ if (!extension) throw new import_content_contracts12.InvalidCoverImageError("unsupported_type");
1368
+ if (params.bytes.byteLength === 0) throw new import_content_contracts12.InvalidCoverImageError("empty");
1369
+ if (params.bytes.byteLength > COVER_IMAGE.MAX_BYTES) throw new import_content_contracts12.InvalidCoverImageError("too_large");
760
1370
  const key = `${COVER_IMAGE.KEY_PREFIX}/${params.companyId}/${crypto.randomUUID()}.${extension}`;
761
1371
  return storage.upload({
762
1372
  buffer: params.bytes,
@@ -771,21 +1381,24 @@ var SYSTEM_CLOCK = {
771
1381
  now: /* @__PURE__ */ __name(() => /* @__PURE__ */ new Date(), "now")
772
1382
  };
773
1383
  function assertValidConfig(config) {
774
- if (config.feed && !/^https?:\/\/[^/]/i.test(config.feed.siteUrl)) throw new import_content_contracts7.ConfigMissingError("feed.siteUrl");
775
- if (config.feed && !config.feed.title.trim()) throw new import_content_contracts7.ConfigMissingError("feed.title");
1384
+ if (config.feed && !/^https?:\/\/[^/]/i.test(config.feed.siteUrl)) throw new import_content_contracts13.ConfigMissingError("feed.siteUrl");
1385
+ if (config.feed && !config.feed.title.trim()) throw new import_content_contracts13.ConfigMissingError("feed.title");
776
1386
  if (config.feed?.postPathTemplate && !config.feed.postPathTemplate.includes("{slug}")) {
777
- throw new import_content_contracts7.ConfigMissingError("feed.postPathTemplate");
1387
+ throw new import_content_contracts13.ConfigMissingError("feed.postPathTemplate");
778
1388
  }
779
- if (config.wordsPerMinute !== void 0 && !(config.wordsPerMinute > 0)) throw new import_content_contracts7.ConfigMissingError("wordsPerMinute");
1389
+ if (config.wordsPerMinute !== void 0 && !(config.wordsPerMinute > 0)) throw new import_content_contracts13.ConfigMissingError("wordsPerMinute");
780
1390
  }
781
1391
  __name(assertValidConfig, "assertValidConfig");
782
1392
  function createContentModule(params) {
783
1393
  const config = params.config ?? {};
784
1394
  assertValidConfig(config);
785
1395
  const posts2 = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : void 0);
786
- if (!posts2) throw new import_content_contracts7.ConfigMissingError("db");
1396
+ if (!posts2) throw new import_content_contracts13.ConfigMissingError("db");
1397
+ const recurrences = params.providers?.recurrenceStore ?? (params.db ? new RecurrenceRepository(params.db) : void 0);
1398
+ if (!recurrences) throw new import_content_contracts13.ConfigMissingError("db");
787
1399
  const dependencies = {
788
1400
  posts: posts2,
1401
+ recurrences,
789
1402
  config,
790
1403
  clock: params.providers?.clock ?? SYSTEM_CLOCK,
791
1404
  ...params.hooks ? {
@@ -810,6 +1423,15 @@ function createContentModule(params) {
810
1423
  getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),
811
1424
  listPublishedPosts: new ListPublishedPostsUseCase(dependencies),
812
1425
  listTags: new ListTagsUseCase(dependencies),
1426
+ countPosts: new CountPostsUseCase(dependencies),
1427
+ saveAsTemplate: new SaveAsTemplateUseCase(dependencies),
1428
+ createFromTemplate: new CreateFromTemplateUseCase(dependencies),
1429
+ republishPost: new RepublishPostUseCase(dependencies),
1430
+ createRecurrence: new CreateRecurrenceUseCase(dependencies),
1431
+ listRecurrences: new ListRecurrencesUseCase(dependencies),
1432
+ updateRecurrence: new UpdateRecurrenceUseCase(dependencies),
1433
+ removeRecurrence: new RemoveRecurrenceUseCase(dependencies),
1434
+ publishDue: new PublishDueUseCase(dependencies),
813
1435
  ...dependencies.imageStorage ? {
814
1436
  uploadCoverImage: new UploadCoverImageUseCase(dependencies)
815
1437
  } : {},
@@ -824,13 +1446,13 @@ function createContentModule(params) {
824
1446
  __name(createContentModule, "createContentModule");
825
1447
 
826
1448
  // src/http/adminRoutes.ts
827
- var import_content_contracts9 = require("@adatechnology/content-contracts");
1449
+ var import_content_contracts15 = require("@adatechnology/content-contracts");
828
1450
 
829
1451
  // src/http/requireCompany.ts
830
- var import_content_contracts8 = require("@adatechnology/content-contracts");
1452
+ var import_content_contracts14 = require("@adatechnology/content-contracts");
831
1453
  function requireCompany(context) {
832
1454
  if (!context.auth?.companyId) {
833
- throw new import_content_contracts8.ContentError("Rota exige contexto autenticado.", 401, import_content_contracts8.CONTENT_ERROR_CODES.CONFIG_MISSING);
1455
+ throw new import_content_contracts14.ContentError("Rota exige contexto autenticado.", 401, import_content_contracts14.CONTENT_ERROR_CODES.CONFIG_MISSING);
834
1456
  }
835
1457
  return context.auth.companyId;
836
1458
  }
@@ -853,7 +1475,7 @@ var json = /* @__PURE__ */ __name((status, data) => ({
853
1475
  }), "json");
854
1476
  function buildAdminRoutes(module2) {
855
1477
  const { useCases } = module2;
856
- const requiredScopes = module2.config.adminScopes ?? import_content_contracts9.DEFAULT_ADMIN_SCOPES;
1478
+ const requiredScopes = module2.config.adminScopes ?? import_content_contracts15.DEFAULT_ADMIN_SCOPES;
857
1479
  const admin = {
858
1480
  scope: "admin",
859
1481
  requiredScopes
@@ -885,7 +1507,7 @@ function buildAdminRoutes(module2) {
885
1507
  ...admin,
886
1508
  method: "GET",
887
1509
  path: "/posts",
888
- querySchema: import_content_contracts9.listPostsQuerySchema,
1510
+ querySchema: import_content_contracts15.listPostsQuerySchema,
889
1511
  operationId: "listPosts",
890
1512
  summary: "Lista posts da empresa (todos os status), com filtro por status, tag e busca",
891
1513
  async handler(context) {
@@ -904,7 +1526,7 @@ function buildAdminRoutes(module2) {
904
1526
  ...admin,
905
1527
  method: "POST",
906
1528
  path: "/posts",
907
- bodySchema: import_content_contracts9.createPostSchema,
1529
+ bodySchema: import_content_contracts15.createPostSchema,
908
1530
  operationId: "createPost",
909
1531
  summary: "Cria um post como rascunho; sem slug, gera a partir do t\xEDtulo",
910
1532
  async handler(context) {
@@ -929,6 +1551,19 @@ function buildAdminRoutes(module2) {
929
1551
  }));
930
1552
  }
931
1553
  },
1554
+ {
1555
+ ...admin,
1556
+ method: "GET",
1557
+ path: "/posts/counts",
1558
+ operationId: "countPosts",
1559
+ summary: "Contagem de posts por aba: publicados, agendados, rascunhos, arquivados e modelos",
1560
+ async handler(context) {
1561
+ return json(200, await useCases.countPosts.execute({
1562
+ companyId: requireCompany(context)
1563
+ }));
1564
+ }
1565
+ },
1566
+ ...recurrenceRoutes(module2),
932
1567
  ...uploadRoutes,
933
1568
  {
934
1569
  ...admin,
@@ -944,7 +1579,7 @@ function buildAdminRoutes(module2) {
944
1579
  ...admin,
945
1580
  method: "PATCH",
946
1581
  path: "/posts/:id",
947
- bodySchema: import_content_contracts9.updatePostSchema,
1582
+ bodySchema: import_content_contracts15.updatePostSchema,
948
1583
  operationId: "updatePost",
949
1584
  summary: "Atualiza campos de um post; trocar o t\xEDtulo n\xE3o troca o slug",
950
1585
  async handler(context) {
@@ -973,7 +1608,7 @@ function buildAdminRoutes(module2) {
973
1608
  method: "POST",
974
1609
  path: "/posts/:id/publish",
975
1610
  // Opcional: `POST /publish` sem corpo publica agora.
976
- bodySchema: import_content_contracts9.publishPostSchema.optional(),
1611
+ bodySchema: import_content_contracts15.publishPostSchema.optional(),
977
1612
  operationId: "publishPost",
978
1613
  summary: "Publica agora, ou agenda quando `publishedAt` \xE9 futuro",
979
1614
  async handler(context) {
@@ -992,19 +1627,125 @@ function buildAdminRoutes(module2) {
992
1627
  async handler(context) {
993
1628
  return json(200, await useCases.unpublishPost.execute(reference(context)));
994
1629
  }
1630
+ },
1631
+ {
1632
+ ...admin,
1633
+ method: "POST",
1634
+ path: "/posts/:id/republish",
1635
+ bodySchema: import_content_contracts15.republishPostSchema.optional(),
1636
+ operationId: "republishPost",
1637
+ summary: "Republica um post no ar com nova data, mantendo o mesmo endere\xE7o (SEO); data futura \xE9 recusada",
1638
+ async handler(context) {
1639
+ return json(200, await useCases.republishPost.execute({
1640
+ ...reference(context),
1641
+ input: context.body ?? {}
1642
+ }));
1643
+ }
1644
+ },
1645
+ {
1646
+ ...admin,
1647
+ method: "POST",
1648
+ path: "/posts/:id/save-as-template",
1649
+ bodySchema: import_content_contracts15.saveAsTemplateSchema.optional(),
1650
+ operationId: "savePostAsTemplate",
1651
+ summary: "Copia o post para um modelo (o original n\xE3o muda)",
1652
+ async handler(context) {
1653
+ return json(201, await useCases.saveAsTemplate.execute({
1654
+ ...reference(context),
1655
+ input: context.body ?? {}
1656
+ }));
1657
+ }
1658
+ },
1659
+ {
1660
+ ...admin,
1661
+ method: "POST",
1662
+ path: "/posts/:id/from-template",
1663
+ bodySchema: import_content_contracts15.createFromTemplateSchema.optional(),
1664
+ operationId: "createPostFromTemplate",
1665
+ summary: "Cria um rascunho novo a partir do modelo `:id`",
1666
+ async handler(context) {
1667
+ return json(201, await useCases.createFromTemplate.execute({
1668
+ ...reference(context),
1669
+ input: context.body ?? {}
1670
+ }));
1671
+ }
995
1672
  }
996
1673
  ];
997
1674
  }
998
1675
  __name(buildAdminRoutes, "buildAdminRoutes");
1676
+ function recurrenceRoutes(module2) {
1677
+ const { useCases } = module2;
1678
+ const admin = {
1679
+ scope: "admin",
1680
+ requiredScopes: module2.config.adminScopes ?? import_content_contracts15.DEFAULT_ADMIN_SCOPES
1681
+ };
1682
+ return [
1683
+ {
1684
+ ...admin,
1685
+ method: "GET",
1686
+ path: "/recurrences",
1687
+ operationId: "listRecurrences",
1688
+ summary: "Regras de recorr\xEAncia da empresa",
1689
+ async handler(context) {
1690
+ return json(200, await useCases.listRecurrences.execute({
1691
+ companyId: requireCompany(context)
1692
+ }));
1693
+ }
1694
+ },
1695
+ {
1696
+ ...admin,
1697
+ method: "POST",
1698
+ path: "/recurrences",
1699
+ bodySchema: import_content_contracts15.createRecurrenceSchema,
1700
+ operationId: "createRecurrence",
1701
+ summary: "Cria regra: publica um post novo, copiado do modelo, toda semana ou todo m\xEAs",
1702
+ async handler(context) {
1703
+ return json(201, await useCases.createRecurrence.execute({
1704
+ companyId: requireCompany(context),
1705
+ input: context.body
1706
+ }));
1707
+ }
1708
+ },
1709
+ {
1710
+ ...admin,
1711
+ method: "PATCH",
1712
+ path: "/recurrences/:id",
1713
+ bodySchema: import_content_contracts15.updateRecurrenceSchema,
1714
+ operationId: "updateRecurrence",
1715
+ summary: "Pausa, retoma ou remarca a pr\xF3xima execu\xE7\xE3o",
1716
+ async handler(context) {
1717
+ return json(200, await useCases.updateRecurrence.execute({
1718
+ ...reference(context),
1719
+ input: context.body
1720
+ }));
1721
+ }
1722
+ },
1723
+ {
1724
+ ...admin,
1725
+ method: "DELETE",
1726
+ path: "/recurrences/:id",
1727
+ operationId: "removeRecurrence",
1728
+ summary: "Apaga a regra; os posts j\xE1 publicados por ela continuam no ar",
1729
+ async handler(context) {
1730
+ await useCases.removeRecurrence.execute(reference(context));
1731
+ return {
1732
+ kind: "empty",
1733
+ status: 204
1734
+ };
1735
+ }
1736
+ }
1737
+ ];
1738
+ }
1739
+ __name(recurrenceRoutes, "recurrenceRoutes");
999
1740
 
1000
1741
  // src/http/publicRoutes.ts
1001
- var import_content_contracts10 = require("@adatechnology/content-contracts");
1742
+ var import_content_contracts16 = require("@adatechnology/content-contracts");
1002
1743
  var PUBLIC = {
1003
1744
  scope: "public"
1004
1745
  };
1005
1746
  function buildPublicRoutes(params) {
1006
1747
  const { useCases } = params.module;
1007
- const cacheControl = params.module.config.publicCacheControl ?? import_content_contracts10.DEFAULT_PUBLIC_CACHE_CONTROL;
1748
+ const cacheControl = params.module.config.publicCacheControl ?? import_content_contracts16.DEFAULT_PUBLIC_CACHE_CONTROL;
1008
1749
  const cached = /* @__PURE__ */ __name((data) => ({
1009
1750
  kind: "json",
1010
1751
  status: 200,
@@ -1018,7 +1759,7 @@ function buildPublicRoutes(params) {
1018
1759
  headers: context.headers,
1019
1760
  query: context.query
1020
1761
  });
1021
- if (!companyId) throw new import_content_contracts10.PostNotFoundError("company");
1762
+ if (!companyId) throw new import_content_contracts16.PostNotFoundError("company");
1022
1763
  return companyId;
1023
1764
  }
1024
1765
  __name(resolveCompany, "resolveCompany");
@@ -1027,7 +1768,7 @@ function buildPublicRoutes(params) {
1027
1768
  ...PUBLIC,
1028
1769
  method: "GET",
1029
1770
  path: "/public/posts",
1030
- querySchema: import_content_contracts10.listPublishedPostsQuerySchema,
1771
+ querySchema: import_content_contracts16.listPublishedPostsQuerySchema,
1031
1772
  operationId: "listPublishedPosts",
1032
1773
  summary: "Posts publicados, mais recentes primeiro, com filtro por tag",
1033
1774
  async handler(context) {
@@ -1147,13 +1888,28 @@ async function runContentMigrations(params) {
1147
1888
  __name(runContentMigrations, "runContentMigrations");
1148
1889
 
1149
1890
  // src/testing/inMemoryPostStore.ts
1150
- var import_node_crypto = require("crypto");
1151
- var import_content_contracts11 = require("@adatechnology/content-contracts");
1891
+ var import_node_crypto2 = require("crypto");
1892
+ var import_content_contracts17 = require("@adatechnology/content-contracts");
1152
1893
  function isPublic(row, now) {
1153
- const live = row.status === import_content_contracts11.POST_STATUS.PUBLISHED || row.status === import_content_contracts11.POST_STATUS.SCHEDULED;
1894
+ const live = row.status === import_content_contracts17.POST_STATUS.PUBLISHED || row.status === import_content_contracts17.POST_STATUS.SCHEDULED;
1154
1895
  return live && row.publishedAt !== null && row.publishedAt <= now;
1155
1896
  }
1156
1897
  __name(isPublic, "isPublic");
1898
+ function adminComparator(query) {
1899
+ const sign = query.order === "asc" ? 1 : -1;
1900
+ const value = /* @__PURE__ */ __name((row) => {
1901
+ if (query.sort === "title") return row.title.toLowerCase();
1902
+ if (query.sort === "status") return row.status;
1903
+ if (query.sort === "publishedAt") return row.publishedAt?.getTime() ?? sign * Number.POSITIVE_INFINITY;
1904
+ return row.updatedAt.getTime();
1905
+ }, "value");
1906
+ return (left, right) => {
1907
+ const a = value(left);
1908
+ const b = value(right);
1909
+ return (a < b ? -1 : a > b ? 1 : 0) * sign || left.id.localeCompare(right.id);
1910
+ };
1911
+ }
1912
+ __name(adminComparator, "adminComparator");
1157
1913
  function paginate(rows, page, pageSize) {
1158
1914
  return {
1159
1915
  rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({
@@ -1173,6 +1929,7 @@ function createInMemoryPostStore(seed = []) {
1173
1929
  const rows = [
1174
1930
  ...seed
1175
1931
  ];
1932
+ const formerSlugs = [];
1176
1933
  const assertUniqueSlug = /* @__PURE__ */ __name((companyId, slug, ownId) => {
1177
1934
  if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {
1178
1935
  throw new UniqueViolation('duplicate key value violates unique constraint "idx_posts_company_slug"');
@@ -1180,17 +1937,45 @@ function createInMemoryPostStore(seed = []) {
1180
1937
  }, "assertUniqueSlug");
1181
1938
  return {
1182
1939
  rows,
1940
+ async findByShortId({ companyId, shortId }) {
1941
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId);
1942
+ return row ? {
1943
+ ...row
1944
+ } : void 0;
1945
+ },
1946
+ async findPublicByShortId({ companyId, shortId, now }) {
1947
+ const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId && isPublic(candidate, now));
1948
+ return row ? {
1949
+ ...row
1950
+ } : void 0;
1951
+ },
1952
+ async findPublicByFormerSlug({ companyId, slug, now }) {
1953
+ const former = formerSlugs.find((entry) => entry.companyId === companyId && entry.slug === slug);
1954
+ const row = rows.find((candidate) => candidate.id === former?.postId && isPublic(candidate, now));
1955
+ return row ? {
1956
+ ...row
1957
+ } : void 0;
1958
+ },
1959
+ async recordFormerSlug(params) {
1960
+ if (!formerSlugs.some((entry) => entry.companyId === params.companyId && entry.slug === params.slug)) {
1961
+ formerSlugs.push({
1962
+ ...params
1963
+ });
1964
+ }
1965
+ },
1183
1966
  async create(values) {
1184
1967
  assertUniqueSlug(values.companyId, values.slug);
1185
1968
  const now = /* @__PURE__ */ new Date();
1186
1969
  const row = {
1187
- id: (0, import_node_crypto.randomUUID)(),
1970
+ id: (0, import_node_crypto2.randomUUID)(),
1188
1971
  excerpt: null,
1189
1972
  body: "",
1190
1973
  coverImageUrl: null,
1191
1974
  coverImageAlt: null,
1192
1975
  tags: [],
1193
- status: import_content_contracts11.POST_STATUS.DRAFT,
1976
+ tagLabels: {},
1977
+ status: import_content_contracts17.POST_STATUS.DRAFT,
1978
+ isTemplate: false,
1194
1979
  publishedAt: null,
1195
1980
  authorName: null,
1196
1981
  seoTitle: null,
@@ -1237,9 +2022,34 @@ function createInMemoryPostStore(seed = []) {
1237
2022
  },
1238
2023
  async listForAdmin(query) {
1239
2024
  const search = query.search?.toLowerCase();
1240
- const matched = rows.filter((row) => row.companyId === query.companyId).filter((row) => !query.status || effectiveStatus(row, query.now) === query.status).filter((row) => !query.tag || row.tags.includes(query.tag)).filter((row) => !search || row.title.toLowerCase().includes(search) || row.slug.includes(search)).sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime());
2025
+ const matched = rows.filter((row) => row.companyId === query.companyId).filter((row) => query.isTemplate ? row.isTemplate && row.status !== import_content_contracts17.POST_STATUS.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));
1241
2026
  return paginate(matched, query.page, query.pageSize);
1242
2027
  },
2028
+ async countByStatus({ companyId, now }) {
2029
+ const counts = {
2030
+ published: 0,
2031
+ scheduled: 0,
2032
+ draft: 0,
2033
+ archived: 0,
2034
+ templates: 0
2035
+ };
2036
+ for (const row of rows) {
2037
+ if (row.companyId !== companyId) continue;
2038
+ if (row.isTemplate) {
2039
+ if (row.status !== import_content_contracts17.POST_STATUS.ARCHIVED) counts.templates += 1;
2040
+ continue;
2041
+ }
2042
+ counts[effectiveStatus(row, now)] += 1;
2043
+ }
2044
+ return counts;
2045
+ },
2046
+ async claimDueScheduled({ now, limit }) {
2047
+ const due = rows.filter((row) => row.status === import_content_contracts17.POST_STATUS.SCHEDULED && !row.isTemplate && row.publishedAt && row.publishedAt <= now).sort((left, right) => (left.publishedAt?.getTime() ?? 0) - (right.publishedAt?.getTime() ?? 0)).slice(0, limit);
2048
+ for (const row of due) row.status = import_content_contracts17.POST_STATUS.PUBLISHED;
2049
+ return due.map((row) => ({
2050
+ ...row
2051
+ }));
2052
+ },
1243
2053
  async listPublic(query) {
1244
2054
  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));
1245
2055
  return paginate(matched, query.page, query.pageSize);
@@ -1260,32 +2070,129 @@ function createInMemoryPostStore(seed = []) {
1260
2070
  };
1261
2071
  }
1262
2072
  __name(createInMemoryPostStore, "createInMemoryPostStore");
2073
+
2074
+ // src/scheduler.ts
2075
+ var DEFAULT_SCHEDULER_INTERVAL_MS = 6e4;
2076
+ function startContentScheduler(params) {
2077
+ let isRunning = false;
2078
+ const tick = /* @__PURE__ */ __name(async () => {
2079
+ if (isRunning) return;
2080
+ isRunning = true;
2081
+ try {
2082
+ await params.module.useCases.publishDue.execute();
2083
+ } catch (error) {
2084
+ params.logger?.error("content-module: ciclo do agendador falhou", {
2085
+ error: error instanceof Error ? error.message : String(error)
2086
+ });
2087
+ } finally {
2088
+ isRunning = false;
2089
+ }
2090
+ }, "tick");
2091
+ const timer = setInterval(() => void tick(), params.intervalMs ?? DEFAULT_SCHEDULER_INTERVAL_MS);
2092
+ timer.unref?.();
2093
+ void tick();
2094
+ return () => clearInterval(timer);
2095
+ }
2096
+ __name(startContentScheduler, "startContentScheduler");
2097
+
2098
+ // src/testing/inMemoryRecurrenceStore.ts
2099
+ var import_node_crypto3 = require("crypto");
2100
+ function createInMemoryRecurrenceStore() {
2101
+ const rows = [];
2102
+ const owned = /* @__PURE__ */ __name((companyId, id) => rows.find((row) => row.companyId === companyId && row.id === id), "owned");
2103
+ return {
2104
+ rows,
2105
+ async create(values) {
2106
+ const row = {
2107
+ id: (0, import_node_crypto3.randomUUID)(),
2108
+ isActive: true,
2109
+ lastRunAt: null,
2110
+ lastPostId: null,
2111
+ createdAt: /* @__PURE__ */ new Date(),
2112
+ ...values
2113
+ };
2114
+ rows.push(row);
2115
+ return {
2116
+ ...row
2117
+ };
2118
+ },
2119
+ async findById({ companyId, id }) {
2120
+ const row = owned(companyId, id);
2121
+ return row ? {
2122
+ ...row
2123
+ } : void 0;
2124
+ },
2125
+ async list({ companyId }) {
2126
+ return rows.filter((row) => row.companyId === companyId).sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime()).map((row) => ({
2127
+ ...row
2128
+ }));
2129
+ },
2130
+ async update({ companyId, id, values }) {
2131
+ const row = owned(companyId, id);
2132
+ if (!row) return void 0;
2133
+ Object.assign(row, values);
2134
+ return {
2135
+ ...row
2136
+ };
2137
+ },
2138
+ async remove({ companyId, id }) {
2139
+ const index2 = rows.findIndex((row) => row.companyId === companyId && row.id === id);
2140
+ if (index2 < 0) return false;
2141
+ rows.splice(index2, 1);
2142
+ return true;
2143
+ },
2144
+ async processDue({ now, limit, handle }) {
2145
+ const due = rows.filter((row) => row.isActive && row.nextRunAt <= now).sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime()).slice(0, limit);
2146
+ for (const row of due) Object.assign(row, await handle({
2147
+ ...row
2148
+ }));
2149
+ return due.length;
2150
+ }
2151
+ };
2152
+ }
2153
+ __name(createInMemoryRecurrenceStore, "createInMemoryRecurrenceStore");
1263
2154
  // Annotate the CommonJS export names for ESM import in node:
1264
2155
  0 && (module.exports = {
1265
2156
  ArchivePostUseCase,
1266
2157
  BuildFeedUseCase,
1267
2158
  CONTENT_MIGRATIONS_TABLE,
1268
2159
  COVER_IMAGE,
2160
+ CountPostsUseCase,
2161
+ CreateFromTemplateUseCase,
1269
2162
  CreatePostUseCase,
2163
+ CreateRecurrenceUseCase,
2164
+ DEFAULT_SCHEDULER_INTERVAL_MS,
1270
2165
  FEED_FORMAT,
1271
2166
  GetPostUseCase,
1272
2167
  GetPublishedPostBySlugUseCase,
1273
2168
  ListPostsUseCase,
1274
2169
  ListPublishedPostsUseCase,
2170
+ ListRecurrencesUseCase,
1275
2171
  ListSitemapEntriesUseCase,
1276
2172
  ListTagsUseCase,
1277
2173
  PostRepository,
2174
+ PublishDueUseCase,
1278
2175
  PublishPostUseCase,
2176
+ RecurrenceRepository,
2177
+ RemoveRecurrenceUseCase,
2178
+ RepublishPostUseCase,
2179
+ SaveAsTemplateUseCase,
1279
2180
  TAG_SCOPE,
1280
2181
  UnpublishPostUseCase,
1281
2182
  UpdatePostUseCase,
2183
+ UpdateRecurrenceUseCase,
1282
2184
  UploadCoverImageUseCase,
1283
2185
  contentMigrationsFolder,
1284
2186
  contentSchema,
1285
2187
  createContentModule,
1286
2188
  createContentRoutes,
1287
2189
  createInMemoryPostStore,
2190
+ createInMemoryRecurrenceStore,
2191
+ nextOccurrence,
2192
+ nextOccurrenceAfter,
1288
2193
  posts,
1289
- runContentMigrations
2194
+ recurrenceRules,
2195
+ runContentMigrations,
2196
+ startContentScheduler
1290
2197
  });
1291
2198
  //# sourceMappingURL=index.cjs.map