@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/README.md +46 -1
- package/dist/index.cjs +1013 -106
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +546 -3
- package/dist/index.d.ts +546 -3
- package/dist/index.js +936 -45
- package/dist/index.js.map +1 -1
- package/dist/migrations/0001_scheduling.sql +32 -0
- package/dist/migrations/meta/0001_snapshot.json +454 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -12,10 +12,12 @@ var __dirname = /* @__PURE__ */ getDirname();
|
|
|
12
12
|
import { ConfigMissingError } from "@adatechnology/content-contracts";
|
|
13
13
|
|
|
14
14
|
// src/repositories/PostRepository.ts
|
|
15
|
-
import { asc, desc, sql as
|
|
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";
|
|
16
17
|
|
|
17
18
|
// src/schema/schema.ts
|
|
18
|
-
import {
|
|
19
|
+
import { sql } from "drizzle-orm";
|
|
20
|
+
import { boolean, index, integer, jsonb, primaryKey, pgSchema, text, timestamp, uniqueIndex, uuid, varchar } from "drizzle-orm/pg-core";
|
|
19
21
|
var contentSchema = pgSchema("content");
|
|
20
22
|
var posts = contentSchema.table("posts", {
|
|
21
23
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
@@ -23,6 +25,9 @@ var posts = contentSchema.table("posts", {
|
|
|
23
25
|
slug: varchar("slug", {
|
|
24
26
|
length: 120
|
|
25
27
|
}).notNull(),
|
|
28
|
+
shortId: varchar("short_id", {
|
|
29
|
+
length: 6
|
|
30
|
+
}).notNull(),
|
|
26
31
|
title: varchar("title", {
|
|
27
32
|
length: 200
|
|
28
33
|
}).notNull(),
|
|
@@ -37,9 +42,11 @@ var posts = contentSchema.table("posts", {
|
|
|
37
42
|
length: 300
|
|
38
43
|
}),
|
|
39
44
|
tags: text("tags").array().notNull().default([]),
|
|
45
|
+
tagLabels: jsonb("tag_labels").$type().notNull().default({}),
|
|
40
46
|
status: varchar("status", {
|
|
41
47
|
length: 12
|
|
42
48
|
}).notNull().default("draft"),
|
|
49
|
+
isTemplate: boolean("is_template").notNull().default(false),
|
|
43
50
|
publishedAt: timestamp("published_at", {
|
|
44
51
|
withTimezone: true
|
|
45
52
|
}),
|
|
@@ -66,13 +73,57 @@ var posts = contentSchema.table("posts", {
|
|
|
66
73
|
// Sem `where deleted_at`: excluir é arquivar, e o slug arquivado continua reservado — reusá-lo
|
|
67
74
|
// faria um link antigo (já compartilhado) abrir outro post.
|
|
68
75
|
uniqueIndex("idx_posts_company_slug").on(table.companyId, table.slug),
|
|
76
|
+
uniqueIndex("idx_posts_company_short_id").on(table.companyId, table.shortId),
|
|
69
77
|
// Serve a listagem pública: empresa + status + ordem por data.
|
|
70
78
|
index("idx_posts_company_status_published").on(table.companyId, table.status, table.publishedAt),
|
|
71
|
-
index("idx_posts_tags").using("gin", table.tags)
|
|
79
|
+
index("idx_posts_tags").using("gin", table.tags),
|
|
80
|
+
// Serve o `publishDue`: só linha agendada entra, então o índice fica minúsculo.
|
|
81
|
+
index("idx_posts_due").on(table.publishedAt).where(sql`"status" = 'scheduled'`)
|
|
82
|
+
]);
|
|
83
|
+
var recurrenceRules = contentSchema.table("recurrence_rules", {
|
|
84
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
85
|
+
companyId: uuid("company_id").notNull(),
|
|
86
|
+
templateId: uuid("template_id").notNull().references(() => posts.id),
|
|
87
|
+
frequency: varchar("frequency", {
|
|
88
|
+
length: 10
|
|
89
|
+
}).notNull(),
|
|
90
|
+
// Dia do mês da primeira execução: mensal em 31 cai no último dia dos meses curtos e volta ao 31.
|
|
91
|
+
anchorDay: integer("anchor_day").notNull(),
|
|
92
|
+
isActive: boolean("is_active").notNull().default(true),
|
|
93
|
+
nextRunAt: timestamp("next_run_at", {
|
|
94
|
+
withTimezone: true
|
|
95
|
+
}).notNull(),
|
|
96
|
+
lastRunAt: timestamp("last_run_at", {
|
|
97
|
+
withTimezone: true
|
|
98
|
+
}),
|
|
99
|
+
lastPostId: uuid("last_post_id"),
|
|
100
|
+
createdAt: timestamp("created_at", {
|
|
101
|
+
withTimezone: true
|
|
102
|
+
}).notNull().defaultNow()
|
|
103
|
+
}, (table) => [
|
|
104
|
+
index("idx_recurrence_company").on(table.companyId),
|
|
105
|
+
index("idx_recurrence_due").on(table.nextRunAt).where(sql`"is_active"`)
|
|
106
|
+
]);
|
|
107
|
+
var postFormerSlugs = contentSchema.table("post_former_slugs", {
|
|
108
|
+
companyId: uuid("company_id").notNull(),
|
|
109
|
+
slug: varchar("slug", {
|
|
110
|
+
length: 120
|
|
111
|
+
}).notNull(),
|
|
112
|
+
postId: uuid("post_id").notNull().references(() => posts.id),
|
|
113
|
+
createdAt: timestamp("created_at", {
|
|
114
|
+
withTimezone: true
|
|
115
|
+
}).notNull().defaultNow()
|
|
116
|
+
}, (table) => [
|
|
117
|
+
primaryKey({
|
|
118
|
+
columns: [
|
|
119
|
+
table.companyId,
|
|
120
|
+
table.slug
|
|
121
|
+
]
|
|
122
|
+
})
|
|
72
123
|
]);
|
|
73
124
|
|
|
74
125
|
// src/repositories/conditions.ts
|
|
75
|
-
import { and, arrayContains, eq, gt, inArray, lte, or, sql } from "drizzle-orm";
|
|
126
|
+
import { and, arrayContains, arrayOverlaps, eq, gt, inArray, lte, ne, or, sql as sql2 } from "drizzle-orm";
|
|
76
127
|
import { POST_STATUS } from "@adatechnology/content-contracts";
|
|
77
128
|
function postOwnedByCondition(params) {
|
|
78
129
|
return and(eq(posts.companyId, params.companyId), eq(posts.id, params.id));
|
|
@@ -84,19 +135,25 @@ function postSlugCondition(params) {
|
|
|
84
135
|
__name(postSlugCondition, "postSlugCondition");
|
|
85
136
|
function postAdminListCondition(params) {
|
|
86
137
|
const conditions = [
|
|
87
|
-
eq(posts.companyId, params.companyId)
|
|
138
|
+
eq(posts.companyId, params.companyId),
|
|
139
|
+
templateCondition(params.isTemplate)
|
|
88
140
|
];
|
|
89
141
|
if (params.status) conditions.push(statusCondition(params.status, params.now));
|
|
90
|
-
if (params.
|
|
91
|
-
params.
|
|
142
|
+
if (params.tags?.length) conditions.push(arrayOverlaps(posts.tags, [
|
|
143
|
+
...params.tags
|
|
92
144
|
]));
|
|
93
145
|
if (params.search) {
|
|
94
146
|
const pattern = `%${params.search.replace(/[\\%_]/g, (character) => `\\${character}`)}%`;
|
|
95
|
-
conditions.push(
|
|
147
|
+
conditions.push(sql2`(${posts.title} ilike ${pattern} or ${posts.slug} ilike ${pattern})`);
|
|
96
148
|
}
|
|
97
149
|
return and(...conditions);
|
|
98
150
|
}
|
|
99
151
|
__name(postAdminListCondition, "postAdminListCondition");
|
|
152
|
+
function templateCondition(isTemplate) {
|
|
153
|
+
if (isTemplate) return and(eq(posts.isTemplate, true), ne(posts.status, POST_STATUS.ARCHIVED));
|
|
154
|
+
return eq(posts.isTemplate, false);
|
|
155
|
+
}
|
|
156
|
+
__name(templateCondition, "templateCondition");
|
|
100
157
|
function statusCondition(status, now) {
|
|
101
158
|
if (status === POST_STATUS.PUBLISHED) {
|
|
102
159
|
return or(eq(posts.status, POST_STATUS.PUBLISHED), and(eq(posts.status, POST_STATUS.SCHEDULED), lte(posts.publishedAt, now)));
|
|
@@ -126,9 +183,37 @@ function postPublicSlugCondition(params) {
|
|
|
126
183
|
return and(postPublicCondition(params), eq(posts.slug, params.slug));
|
|
127
184
|
}
|
|
128
185
|
__name(postPublicSlugCondition, "postPublicSlugCondition");
|
|
186
|
+
function postDueCondition(params) {
|
|
187
|
+
return and(eq(posts.status, POST_STATUS.SCHEDULED), eq(posts.isTemplate, false), lte(posts.publishedAt, params.now));
|
|
188
|
+
}
|
|
189
|
+
__name(postDueCondition, "postDueCondition");
|
|
190
|
+
function postShortIdCondition(params) {
|
|
191
|
+
return and(eq(posts.companyId, params.companyId), eq(posts.shortId, params.shortId));
|
|
192
|
+
}
|
|
193
|
+
__name(postShortIdCondition, "postShortIdCondition");
|
|
194
|
+
function postPublicShortIdCondition(params) {
|
|
195
|
+
return and(postPublicCondition(params), eq(posts.shortId, params.shortId));
|
|
196
|
+
}
|
|
197
|
+
__name(postPublicShortIdCondition, "postPublicShortIdCondition");
|
|
129
198
|
|
|
130
199
|
// src/repositories/PostRepository.ts
|
|
131
200
|
var TAG_LIST_LIMIT = 200;
|
|
201
|
+
var SORT_COLUMNS = {
|
|
202
|
+
title: posts.title,
|
|
203
|
+
status: posts.status,
|
|
204
|
+
publishedAt: posts.publishedAt,
|
|
205
|
+
updatedAt: posts.updatedAt
|
|
206
|
+
};
|
|
207
|
+
function adminOrder(query) {
|
|
208
|
+
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);
|
|
211
|
+
return [
|
|
212
|
+
primary,
|
|
213
|
+
asc(posts.id)
|
|
214
|
+
];
|
|
215
|
+
}
|
|
216
|
+
__name(adminOrder, "adminOrder");
|
|
132
217
|
var PostRepository = class {
|
|
133
218
|
static {
|
|
134
219
|
__name(this, "PostRepository");
|
|
@@ -154,6 +239,25 @@ var PostRepository = class {
|
|
|
154
239
|
const [row] = await this.db.select().from(posts).where(postPublicSlugCondition(params)).limit(1);
|
|
155
240
|
return row;
|
|
156
241
|
}
|
|
242
|
+
async findByShortId(params) {
|
|
243
|
+
const [row] = await this.db.select().from(posts).where(postShortIdCondition(params)).limit(1);
|
|
244
|
+
return row;
|
|
245
|
+
}
|
|
246
|
+
async findPublicByShortId(params) {
|
|
247
|
+
const [row] = await this.db.select().from(posts).where(postPublicShortIdCondition(params)).limit(1);
|
|
248
|
+
return row;
|
|
249
|
+
}
|
|
250
|
+
async findPublicByFormerSlug(params) {
|
|
251
|
+
const [former] = await this.db.select({
|
|
252
|
+
postId: postFormerSlugs.postId
|
|
253
|
+
}).from(postFormerSlugs).where(and2(eq2(postFormerSlugs.companyId, params.companyId), eq2(postFormerSlugs.slug, params.slug))).limit(1);
|
|
254
|
+
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);
|
|
256
|
+
return row;
|
|
257
|
+
}
|
|
258
|
+
async recordFormerSlug(params) {
|
|
259
|
+
await this.db.insert(postFormerSlugs).values(params).onConflictDoNothing();
|
|
260
|
+
}
|
|
157
261
|
async update(params) {
|
|
158
262
|
const [row] = await this.db.update(posts).set({
|
|
159
263
|
...params.values,
|
|
@@ -164,9 +268,9 @@ var PostRepository = class {
|
|
|
164
268
|
async listForAdmin(query) {
|
|
165
269
|
const where = postAdminListCondition(query);
|
|
166
270
|
const [rows, [counted]] = await Promise.all([
|
|
167
|
-
this.db.select().from(posts).where(where).orderBy(
|
|
271
|
+
this.db.select().from(posts).where(where).orderBy(...adminOrder(query)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
|
|
168
272
|
this.db.select({
|
|
169
|
-
value:
|
|
273
|
+
value: sql3`count(*)::int`
|
|
170
274
|
}).from(posts).where(where)
|
|
171
275
|
]);
|
|
172
276
|
return {
|
|
@@ -179,7 +283,7 @@ var PostRepository = class {
|
|
|
179
283
|
const [rows, [counted]] = await Promise.all([
|
|
180
284
|
this.db.select().from(posts).where(where).orderBy(desc(posts.publishedAt), asc(posts.id)).limit(query.pageSize).offset((query.page - 1) * query.pageSize),
|
|
181
285
|
this.db.select({
|
|
182
|
-
value:
|
|
286
|
+
value: sql3`count(*)::int`
|
|
183
287
|
}).from(posts).where(where)
|
|
184
288
|
]);
|
|
185
289
|
return {
|
|
@@ -187,6 +291,37 @@ var PostRepository = class {
|
|
|
187
291
|
total: counted?.value ?? 0
|
|
188
292
|
};
|
|
189
293
|
}
|
|
294
|
+
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}))`;
|
|
298
|
+
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));
|
|
305
|
+
return row ?? {
|
|
306
|
+
published: 0,
|
|
307
|
+
scheduled: 0,
|
|
308
|
+
draft: 0,
|
|
309
|
+
archived: 0,
|
|
310
|
+
templates: 0
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
async claimDueScheduled(params) {
|
|
314
|
+
const due = this.db.select({
|
|
315
|
+
id: posts.id
|
|
316
|
+
}).from(posts).where(postDueCondition({
|
|
317
|
+
now: params.now
|
|
318
|
+
})).orderBy(asc(posts.publishedAt), asc(posts.id)).limit(params.limit).for("update", {
|
|
319
|
+
skipLocked: true
|
|
320
|
+
});
|
|
321
|
+
return this.db.update(posts).set({
|
|
322
|
+
status: POST_STATUS2.PUBLISHED
|
|
323
|
+
}).where(inArray2(posts.id, due)).returning();
|
|
324
|
+
}
|
|
190
325
|
async listTags(params) {
|
|
191
326
|
const where = params.publicAt ? postPublicCondition({
|
|
192
327
|
companyId: params.companyId,
|
|
@@ -196,16 +331,68 @@ var PostRepository = class {
|
|
|
196
331
|
now: /* @__PURE__ */ new Date()
|
|
197
332
|
});
|
|
198
333
|
const postTags = this.db.select({
|
|
199
|
-
tag:
|
|
334
|
+
tag: sql3`unnest(${posts.tags})`.as("tag")
|
|
200
335
|
}).from(posts).where(where).as("post_tags");
|
|
201
336
|
const rows = await this.db.select({
|
|
202
337
|
tag: postTags.tag,
|
|
203
|
-
count:
|
|
204
|
-
}).from(postTags).groupBy(postTags.tag).orderBy(
|
|
338
|
+
count: sql3`count(*)::int`
|
|
339
|
+
}).from(postTags).groupBy(postTags.tag).orderBy(sql3`count(*) desc`, asc(postTags.tag)).limit(TAG_LIST_LIMIT);
|
|
205
340
|
return rows;
|
|
206
341
|
}
|
|
207
342
|
};
|
|
208
343
|
|
|
344
|
+
// src/repositories/RecurrenceRepository.ts
|
|
345
|
+
import { and as and3, asc as asc2, eq as eq3, lte as lte2 } from "drizzle-orm";
|
|
346
|
+
function recurrenceOwnedByCondition(params) {
|
|
347
|
+
return and3(eq3(recurrenceRules.companyId, params.companyId), eq3(recurrenceRules.id, params.id));
|
|
348
|
+
}
|
|
349
|
+
__name(recurrenceOwnedByCondition, "recurrenceOwnedByCondition");
|
|
350
|
+
var RecurrenceRepository = class {
|
|
351
|
+
static {
|
|
352
|
+
__name(this, "RecurrenceRepository");
|
|
353
|
+
}
|
|
354
|
+
db;
|
|
355
|
+
constructor(db) {
|
|
356
|
+
this.db = db;
|
|
357
|
+
}
|
|
358
|
+
async create(values) {
|
|
359
|
+
const [row] = await this.db.insert(recurrenceRules).values(values).returning();
|
|
360
|
+
if (!row) throw new Error("content-module: insert em recurrence_rules n\xE3o retornou linha");
|
|
361
|
+
return row;
|
|
362
|
+
}
|
|
363
|
+
async findById(params) {
|
|
364
|
+
const [row] = await this.db.select().from(recurrenceRules).where(recurrenceOwnedByCondition(params)).limit(1);
|
|
365
|
+
return row;
|
|
366
|
+
}
|
|
367
|
+
async list(params) {
|
|
368
|
+
return this.db.select().from(recurrenceRules).where(eq3(recurrenceRules.companyId, params.companyId)).orderBy(asc2(recurrenceRules.nextRunAt), asc2(recurrenceRules.id));
|
|
369
|
+
}
|
|
370
|
+
async update(params) {
|
|
371
|
+
const [row] = await this.db.update(recurrenceRules).set(params.values).where(recurrenceOwnedByCondition(params)).returning();
|
|
372
|
+
return row;
|
|
373
|
+
}
|
|
374
|
+
async remove(params) {
|
|
375
|
+
const removed = await this.db.delete(recurrenceRules).where(recurrenceOwnedByCondition(params)).returning({
|
|
376
|
+
id: recurrenceRules.id
|
|
377
|
+
});
|
|
378
|
+
return removed.length > 0;
|
|
379
|
+
}
|
|
380
|
+
async processDue(params) {
|
|
381
|
+
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", {
|
|
383
|
+
skipLocked: true
|
|
384
|
+
});
|
|
385
|
+
let processed = 0;
|
|
386
|
+
for (const rule of due) {
|
|
387
|
+
const values = await params.handle(rule);
|
|
388
|
+
await transaction.update(recurrenceRules).set(values).where(eq3(recurrenceRules.id, rule.id));
|
|
389
|
+
processed += 1;
|
|
390
|
+
}
|
|
391
|
+
return processed;
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
|
|
209
396
|
// src/use-cases/Feed.use-cases.ts
|
|
210
397
|
import { buildAtomFeed, buildExcerpt, buildPostUrl, buildRssFeed, renderMarkdownToHtml } from "@adatechnology/content-contracts";
|
|
211
398
|
var DEFAULT_ITEM_LIMIT = 20;
|
|
@@ -261,6 +448,7 @@ var BuildFeedUseCase = class {
|
|
|
261
448
|
url: buildPostUrl({
|
|
262
449
|
siteUrl: this.feed.siteUrl,
|
|
263
450
|
slug: row.slug,
|
|
451
|
+
shortId: row.shortId,
|
|
264
452
|
postPathTemplate: this.feed.postPathTemplate
|
|
265
453
|
}),
|
|
266
454
|
publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
|
|
@@ -303,6 +491,7 @@ var ListSitemapEntriesUseCase = class {
|
|
|
303
491
|
loc: buildPostUrl({
|
|
304
492
|
siteUrl: this.feed.siteUrl,
|
|
305
493
|
slug: row.slug,
|
|
494
|
+
shortId: row.shortId,
|
|
306
495
|
postPathTemplate: this.feed.postPathTemplate
|
|
307
496
|
}),
|
|
308
497
|
lastmod: row.updatedAt.toISOString()
|
|
@@ -311,7 +500,18 @@ var ListSitemapEntriesUseCase = class {
|
|
|
311
500
|
};
|
|
312
501
|
|
|
313
502
|
// src/use-cases/Post.use-cases.ts
|
|
314
|
-
import { createPostSchema, DuplicateSlugError, estimateReadingTimeMinutes, listPostsQuerySchema, normalizeTags, POST_EVENT, POST_STATUS as
|
|
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";
|
|
504
|
+
|
|
505
|
+
// src/shared/shortId.ts
|
|
506
|
+
import { randomInt } from "crypto";
|
|
507
|
+
import { SHORT_ID_LENGTH } from "@adatechnology/content-contracts";
|
|
508
|
+
var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
509
|
+
function generateShortId() {
|
|
510
|
+
let value = "";
|
|
511
|
+
for (let index2 = 0; index2 < SHORT_ID_LENGTH; index2 += 1) value += ALPHABET[randomInt(ALPHABET.length)];
|
|
512
|
+
return value;
|
|
513
|
+
}
|
|
514
|
+
__name(generateShortId, "generateShortId");
|
|
315
515
|
|
|
316
516
|
// src/shared/isUniqueViolation.ts
|
|
317
517
|
var UNIQUE_VIOLATION = "23505";
|
|
@@ -345,9 +545,9 @@ async function notifyPostChanged(dependencies, type, post) {
|
|
|
345
545
|
__name(notifyPostChanged, "notifyPostChanged");
|
|
346
546
|
|
|
347
547
|
// src/shared/toContract.ts
|
|
348
|
-
import { POST_STATUS as
|
|
548
|
+
import { POST_STATUS as POST_STATUS3 } from "@adatechnology/content-contracts";
|
|
349
549
|
function effectiveStatus(row, now) {
|
|
350
|
-
if (row.status ===
|
|
550
|
+
if (row.status === POST_STATUS3.SCHEDULED && row.publishedAt && row.publishedAt <= now) return POST_STATUS3.PUBLISHED;
|
|
351
551
|
return row.status;
|
|
352
552
|
}
|
|
353
553
|
__name(effectiveStatus, "effectiveStatus");
|
|
@@ -356,12 +556,15 @@ function toPostSummary(row, now) {
|
|
|
356
556
|
id: row.id,
|
|
357
557
|
companyId: row.companyId,
|
|
358
558
|
slug: row.slug,
|
|
559
|
+
shortId: row.shortId,
|
|
359
560
|
title: row.title,
|
|
360
561
|
excerpt: row.excerpt,
|
|
361
562
|
coverImageUrl: row.coverImageUrl,
|
|
362
563
|
coverImageAlt: row.coverImageAlt,
|
|
363
564
|
tags: row.tags,
|
|
565
|
+
tagLabels: row.tagLabels,
|
|
364
566
|
status: effectiveStatus(row, now),
|
|
567
|
+
isTemplate: row.isTemplate,
|
|
365
568
|
publishedAt: row.publishedAt?.toISOString() ?? null,
|
|
366
569
|
authorName: row.authorName,
|
|
367
570
|
seoTitle: row.seoTitle,
|
|
@@ -384,11 +587,13 @@ function toPublicPostSummary(row) {
|
|
|
384
587
|
return {
|
|
385
588
|
id: row.id,
|
|
386
589
|
slug: row.slug,
|
|
590
|
+
shortId: row.shortId,
|
|
387
591
|
title: row.title,
|
|
388
592
|
excerpt: row.excerpt,
|
|
389
593
|
coverImageUrl: row.coverImageUrl,
|
|
390
594
|
coverImageAlt: row.coverImageAlt,
|
|
391
595
|
tags: row.tags,
|
|
596
|
+
tagLabels: row.tagLabels,
|
|
392
597
|
publishedAt: (row.publishedAt ?? row.createdAt).toISOString(),
|
|
393
598
|
updatedAt: row.updatedAt.toISOString(),
|
|
394
599
|
authorName: row.authorName,
|
|
@@ -417,7 +622,7 @@ __name(toPagination, "toPagination");
|
|
|
417
622
|
// src/use-cases/Post.use-cases.ts
|
|
418
623
|
var MAX_SLUG_ATTEMPTS = 50;
|
|
419
624
|
var FALLBACK_SLUG = "post";
|
|
420
|
-
var PostUseCaseBase = class
|
|
625
|
+
var PostUseCaseBase = class {
|
|
421
626
|
static {
|
|
422
627
|
__name(this, "PostUseCaseBase");
|
|
423
628
|
}
|
|
@@ -446,6 +651,17 @@ var PostUseCaseBase = class PostUseCaseBase2 {
|
|
|
446
651
|
await notifyPostChanged(this.dependencies, event, post);
|
|
447
652
|
return post;
|
|
448
653
|
}
|
|
654
|
+
/** Id curto livre na empresa; a colisão (~1 em 2 bilhões) só repete o sorteio. */
|
|
655
|
+
async generateShortId(companyId) {
|
|
656
|
+
for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt += 1) {
|
|
657
|
+
const candidate = generateShortId();
|
|
658
|
+
if (!await this.dependencies.posts.findByShortId({
|
|
659
|
+
companyId,
|
|
660
|
+
shortId: candidate
|
|
661
|
+
})) return candidate;
|
|
662
|
+
}
|
|
663
|
+
throw new Error("content-module: sem id curto livre");
|
|
664
|
+
}
|
|
449
665
|
readingTime(body) {
|
|
450
666
|
return estimateReadingTimeMinutes(body, this.dependencies.config.wordsPerMinute);
|
|
451
667
|
}
|
|
@@ -458,7 +674,9 @@ var PostUseCaseBase = class PostUseCaseBase2 {
|
|
|
458
674
|
}
|
|
459
675
|
/** `titulo`, `titulo-2`, `titulo-3`… Sequencial de propósito: cada tentativa depende da anterior. */
|
|
460
676
|
async generateSlug(companyId, title) {
|
|
461
|
-
|
|
677
|
+
return this.uniqueSlug(companyId, buildShortSlug(title, this.dependencies.config.slug) || FALLBACK_SLUG);
|
|
678
|
+
}
|
|
679
|
+
async uniqueSlug(companyId, base) {
|
|
462
680
|
for (let attempt = 1; attempt <= MAX_SLUG_ATTEMPTS; attempt += 1) {
|
|
463
681
|
const candidate = withSlugSuffix(base, attempt);
|
|
464
682
|
if (!await this.dependencies.posts.findBySlug({
|
|
@@ -493,10 +711,15 @@ var CreatePostUseCase = class extends PostUseCaseBase {
|
|
|
493
711
|
const row = await this.dependencies.posts.create({
|
|
494
712
|
companyId,
|
|
495
713
|
slug,
|
|
714
|
+
shortId: await this.generateShortId(companyId),
|
|
496
715
|
title: input.title,
|
|
497
716
|
body: input.body,
|
|
498
717
|
tags: normalizeTags(input.tags ?? []),
|
|
499
|
-
|
|
718
|
+
tagLabels: buildTagLabels({
|
|
719
|
+
typed: input.tags ?? [],
|
|
720
|
+
explicit: input.tagLabels
|
|
721
|
+
}),
|
|
722
|
+
status: POST_STATUS4.DRAFT,
|
|
500
723
|
readingTimeMinutes: this.readingTime(input.body),
|
|
501
724
|
...optionalFields(input)
|
|
502
725
|
}).catch((error) => {
|
|
@@ -522,10 +745,23 @@ var UpdatePostUseCase = class extends PostUseCaseBase {
|
|
|
522
745
|
values.body = input.body;
|
|
523
746
|
values.readingTimeMinutes = this.readingTime(input.body);
|
|
524
747
|
}
|
|
525
|
-
if (input.tags !== void 0
|
|
748
|
+
if (input.tags !== void 0 || input.tagLabels !== void 0) {
|
|
749
|
+
const tags = normalizeTags(input.tags ?? existing.tags);
|
|
750
|
+
values.tags = tags;
|
|
751
|
+
values.tagLabels = buildTagLabels({
|
|
752
|
+
typed: input.tags ?? tags,
|
|
753
|
+
explicit: input.tagLabels,
|
|
754
|
+
previous: existing.tagLabels
|
|
755
|
+
});
|
|
756
|
+
}
|
|
526
757
|
if (input.slug !== void 0 && input.slug !== existing.slug) {
|
|
527
758
|
await this.assertSlugAvailable(params.companyId, input.slug, existing.id);
|
|
528
759
|
values.slug = input.slug;
|
|
760
|
+
await this.dependencies.posts.recordFormerSlug({
|
|
761
|
+
companyId: params.companyId,
|
|
762
|
+
postId: existing.id,
|
|
763
|
+
slug: existing.slug
|
|
764
|
+
});
|
|
529
765
|
}
|
|
530
766
|
return this.save(params, values, POST_EVENT.UPDATED);
|
|
531
767
|
}
|
|
@@ -537,10 +773,11 @@ var PublishPostUseCase = class extends PostUseCaseBase {
|
|
|
537
773
|
/** Sem data: publica agora. Data futura: agenda. Data passada: publica com a data informada. */
|
|
538
774
|
async execute(params) {
|
|
539
775
|
const input = publishPostSchema.parse(params.input ?? {});
|
|
540
|
-
await this.findOrFail(params);
|
|
776
|
+
const existing = await this.findOrFail(params);
|
|
777
|
+
if (existing.isTemplate) throw new TemplateNotPublishableError(params.id);
|
|
541
778
|
const now = this.now();
|
|
542
779
|
const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
|
|
543
|
-
const status = publishedAt > now ?
|
|
780
|
+
const status = publishedAt > now ? POST_STATUS4.SCHEDULED : POST_STATUS4.PUBLISHED;
|
|
544
781
|
return this.save(params, {
|
|
545
782
|
status,
|
|
546
783
|
publishedAt
|
|
@@ -555,7 +792,7 @@ var UnpublishPostUseCase = class extends PostUseCaseBase {
|
|
|
555
792
|
async execute(params) {
|
|
556
793
|
await this.findOrFail(params);
|
|
557
794
|
return this.save(params, {
|
|
558
|
-
status:
|
|
795
|
+
status: POST_STATUS4.DRAFT,
|
|
559
796
|
publishedAt: null
|
|
560
797
|
}, POST_EVENT.UNPUBLISHED);
|
|
561
798
|
}
|
|
@@ -568,7 +805,7 @@ var ArchivePostUseCase = class extends PostUseCaseBase {
|
|
|
568
805
|
async execute(params) {
|
|
569
806
|
await this.findOrFail(params);
|
|
570
807
|
return this.save(params, {
|
|
571
|
-
status:
|
|
808
|
+
status: POST_STATUS4.ARCHIVED
|
|
572
809
|
}, POST_EVENT.ARCHIVED);
|
|
573
810
|
}
|
|
574
811
|
};
|
|
@@ -587,16 +824,16 @@ var ListPostsUseCase = class extends PostUseCaseBase {
|
|
|
587
824
|
async execute(params) {
|
|
588
825
|
const { companyId, ...rawQuery } = params;
|
|
589
826
|
const query = listPostsQuerySchema.parse(rawQuery);
|
|
590
|
-
const tag = query
|
|
591
|
-
|
|
592
|
-
])[0] : void 0;
|
|
827
|
+
const { tag: rawTag, ...rest } = query;
|
|
828
|
+
const tags = rawTag ? normalizeTags(rawTag.split(",")) : [];
|
|
593
829
|
const now = this.now();
|
|
594
830
|
const page = await this.dependencies.posts.listForAdmin({
|
|
595
831
|
companyId,
|
|
596
|
-
...
|
|
832
|
+
...rest,
|
|
833
|
+
isTemplate: query.isTemplate ?? false,
|
|
597
834
|
now,
|
|
598
|
-
...
|
|
599
|
-
|
|
835
|
+
...tags.length > 0 ? {
|
|
836
|
+
tags
|
|
600
837
|
} : {}
|
|
601
838
|
});
|
|
602
839
|
return {
|
|
@@ -611,7 +848,7 @@ var ListPostsUseCase = class extends PostUseCaseBase {
|
|
|
611
848
|
};
|
|
612
849
|
|
|
613
850
|
// src/use-cases/PublicPost.use-cases.ts
|
|
614
|
-
import { listPublishedPostsQuerySchema, normalizeTag, PostNotFoundError as PostNotFoundError2 } from "@adatechnology/content-contracts";
|
|
851
|
+
import { listPublishedPostsQuerySchema, normalizeTag, parsePostRef, PostNotFoundError as PostNotFoundError2 } from "@adatechnology/content-contracts";
|
|
615
852
|
var GetPublishedPostBySlugUseCase = class {
|
|
616
853
|
static {
|
|
617
854
|
__name(this, "GetPublishedPostBySlugUseCase");
|
|
@@ -620,14 +857,29 @@ var GetPublishedPostBySlugUseCase = class {
|
|
|
620
857
|
constructor(dependencies) {
|
|
621
858
|
this.dependencies = dependencies;
|
|
622
859
|
}
|
|
860
|
+
/**
|
|
861
|
+
* `slug` aceita o endereço canônico `<shortId>-<slug>`, o slug atual e slug antigo. O id curto
|
|
862
|
+
* manda: título/slug editado depois não quebra link compartilhado. O host compara `buildPostRef`
|
|
863
|
+
* do resultado com o pedido e redireciona (301) quando forem diferentes.
|
|
864
|
+
*/
|
|
623
865
|
async execute(params) {
|
|
624
|
-
const
|
|
625
|
-
const
|
|
866
|
+
const { posts: posts2, clock } = this.dependencies;
|
|
867
|
+
const parsed = parsePostRef(params.slug);
|
|
868
|
+
const query = {
|
|
626
869
|
companyId: params.companyId,
|
|
627
|
-
|
|
628
|
-
|
|
870
|
+
now: clock.now()
|
|
871
|
+
};
|
|
872
|
+
const row = (parsed.shortId ? await posts2.findPublicByShortId({
|
|
873
|
+
...query,
|
|
874
|
+
shortId: parsed.shortId
|
|
875
|
+
}) : void 0) ?? await posts2.findPublicBySlug({
|
|
876
|
+
...query,
|
|
877
|
+
slug: parsed.slug
|
|
878
|
+
}) ?? await posts2.findPublicByFormerSlug({
|
|
879
|
+
...query,
|
|
880
|
+
slug: parsed.slug
|
|
629
881
|
});
|
|
630
|
-
if (!row) throw new PostNotFoundError2(slug);
|
|
882
|
+
if (!row) throw new PostNotFoundError2(parsed.slug);
|
|
631
883
|
return toPublicPost(row);
|
|
632
884
|
}
|
|
633
885
|
};
|
|
@@ -685,6 +937,348 @@ var ListTagsUseCase = class {
|
|
|
685
937
|
}
|
|
686
938
|
};
|
|
687
939
|
|
|
940
|
+
// src/use-cases/Recurrence.use-cases.ts
|
|
941
|
+
import { createRecurrenceSchema, NotATemplateError, PostNotFoundError as PostNotFoundError3, RecurrenceNotFoundError, updateRecurrenceSchema } from "@adatechnology/content-contracts";
|
|
942
|
+
var RecurrenceUseCaseBase = class RecurrenceUseCaseBase2 {
|
|
943
|
+
static {
|
|
944
|
+
__name(this, "RecurrenceUseCaseBase");
|
|
945
|
+
}
|
|
946
|
+
dependencies;
|
|
947
|
+
constructor(dependencies) {
|
|
948
|
+
this.dependencies = dependencies;
|
|
949
|
+
}
|
|
950
|
+
async toRule(row) {
|
|
951
|
+
const template = await this.dependencies.posts.findById({
|
|
952
|
+
companyId: row.companyId,
|
|
953
|
+
id: row.templateId
|
|
954
|
+
});
|
|
955
|
+
return {
|
|
956
|
+
id: row.id,
|
|
957
|
+
companyId: row.companyId,
|
|
958
|
+
templateId: row.templateId,
|
|
959
|
+
templateTitle: template?.title ?? "",
|
|
960
|
+
frequency: row.frequency,
|
|
961
|
+
isActive: row.isActive,
|
|
962
|
+
nextRunAt: row.nextRunAt.toISOString(),
|
|
963
|
+
lastRunAt: row.lastRunAt?.toISOString() ?? null,
|
|
964
|
+
lastPostId: row.lastPostId,
|
|
965
|
+
createdAt: row.createdAt.toISOString()
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
async findOrFail(params) {
|
|
969
|
+
const row = await this.dependencies.recurrences.findById(params);
|
|
970
|
+
if (!row) throw new RecurrenceNotFoundError(params.id);
|
|
971
|
+
return row;
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
var CreateRecurrenceUseCase = class extends RecurrenceUseCaseBase {
|
|
975
|
+
static {
|
|
976
|
+
__name(this, "CreateRecurrenceUseCase");
|
|
977
|
+
}
|
|
978
|
+
async execute(params) {
|
|
979
|
+
const input = createRecurrenceSchema.parse(params.input);
|
|
980
|
+
const template = await this.dependencies.posts.findById({
|
|
981
|
+
companyId: params.companyId,
|
|
982
|
+
id: input.templateId
|
|
983
|
+
});
|
|
984
|
+
if (!template) throw new PostNotFoundError3(input.templateId);
|
|
985
|
+
if (!template.isTemplate) throw new NotATemplateError(input.templateId);
|
|
986
|
+
const startsAt = new Date(input.startsAt);
|
|
987
|
+
const values = {
|
|
988
|
+
companyId: params.companyId,
|
|
989
|
+
templateId: input.templateId,
|
|
990
|
+
frequency: input.frequency,
|
|
991
|
+
anchorDay: startsAt.getUTCDate(),
|
|
992
|
+
nextRunAt: startsAt
|
|
993
|
+
};
|
|
994
|
+
return this.toRule(await this.dependencies.recurrences.create(values));
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
var ListRecurrencesUseCase = class extends RecurrenceUseCaseBase {
|
|
998
|
+
static {
|
|
999
|
+
__name(this, "ListRecurrencesUseCase");
|
|
1000
|
+
}
|
|
1001
|
+
async execute(params) {
|
|
1002
|
+
const rows = await this.dependencies.recurrences.list(params);
|
|
1003
|
+
return Promise.all(rows.map((row) => this.toRule(row)));
|
|
1004
|
+
}
|
|
1005
|
+
};
|
|
1006
|
+
var UpdateRecurrenceUseCase = class extends RecurrenceUseCaseBase {
|
|
1007
|
+
static {
|
|
1008
|
+
__name(this, "UpdateRecurrenceUseCase");
|
|
1009
|
+
}
|
|
1010
|
+
/** Pausar/retomar e remarcar a próxima execução. */
|
|
1011
|
+
async execute(params) {
|
|
1012
|
+
const input = updateRecurrenceSchema.parse(params.input);
|
|
1013
|
+
await this.findOrFail(params);
|
|
1014
|
+
const values = {};
|
|
1015
|
+
if (input.isActive !== void 0) values.isActive = input.isActive;
|
|
1016
|
+
if (input.nextRunAt !== void 0) {
|
|
1017
|
+
values.nextRunAt = new Date(input.nextRunAt);
|
|
1018
|
+
values.anchorDay = values.nextRunAt.getUTCDate();
|
|
1019
|
+
}
|
|
1020
|
+
const row = await this.dependencies.recurrences.update({
|
|
1021
|
+
companyId: params.companyId,
|
|
1022
|
+
id: params.id,
|
|
1023
|
+
values
|
|
1024
|
+
});
|
|
1025
|
+
if (!row) throw new RecurrenceNotFoundError(params.id);
|
|
1026
|
+
return this.toRule(row);
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
var RemoveRecurrenceUseCase = class extends RecurrenceUseCaseBase {
|
|
1030
|
+
static {
|
|
1031
|
+
__name(this, "RemoveRecurrenceUseCase");
|
|
1032
|
+
}
|
|
1033
|
+
/** Apaga só a regra: os posts que ela já publicou continuam no ar. */
|
|
1034
|
+
async execute(params) {
|
|
1035
|
+
if (!await this.dependencies.recurrences.remove(params)) throw new RecurrenceNotFoundError(params.id);
|
|
1036
|
+
}
|
|
1037
|
+
};
|
|
1038
|
+
|
|
1039
|
+
// 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";
|
|
1041
|
+
|
|
1042
|
+
// src/shared/recurrence.ts
|
|
1043
|
+
import { RECURRENCE_FREQUENCY } from "@adatechnology/content-contracts";
|
|
1044
|
+
var WEEK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
1045
|
+
function daysInMonth(year, monthIndex) {
|
|
1046
|
+
return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();
|
|
1047
|
+
}
|
|
1048
|
+
__name(daysInMonth, "daysInMonth");
|
|
1049
|
+
function addMonths(from, anchorDay, months) {
|
|
1050
|
+
const target = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + months, 1));
|
|
1051
|
+
const day = Math.min(anchorDay, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()));
|
|
1052
|
+
return new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth(), day, from.getUTCHours(), from.getUTCMinutes(), from.getUTCSeconds(), from.getUTCMilliseconds()));
|
|
1053
|
+
}
|
|
1054
|
+
__name(addMonths, "addMonths");
|
|
1055
|
+
function nextOccurrence(params) {
|
|
1056
|
+
if (params.frequency === RECURRENCE_FREQUENCY.WEEKLY) return new Date(params.from.getTime() + WEEK_MS);
|
|
1057
|
+
return addMonths(params.from, params.anchorDay, 1);
|
|
1058
|
+
}
|
|
1059
|
+
__name(nextOccurrence, "nextOccurrence");
|
|
1060
|
+
function nextOccurrenceAfter(params) {
|
|
1061
|
+
let candidate = nextOccurrence(params);
|
|
1062
|
+
while (candidate <= params.now) candidate = nextOccurrence({
|
|
1063
|
+
...params,
|
|
1064
|
+
from: candidate
|
|
1065
|
+
});
|
|
1066
|
+
return candidate;
|
|
1067
|
+
}
|
|
1068
|
+
__name(nextOccurrenceAfter, "nextOccurrenceAfter");
|
|
1069
|
+
function toDateStamp(date) {
|
|
1070
|
+
return date.toISOString().slice(0, 10);
|
|
1071
|
+
}
|
|
1072
|
+
__name(toDateStamp, "toDateStamp");
|
|
1073
|
+
|
|
1074
|
+
// 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";
|
|
1076
|
+
var TEMPLATE_SLUG_PREFIX = "modelo";
|
|
1077
|
+
function copiableFields(row) {
|
|
1078
|
+
return {
|
|
1079
|
+
excerpt: row.excerpt,
|
|
1080
|
+
body: row.body,
|
|
1081
|
+
coverImageUrl: row.coverImageUrl,
|
|
1082
|
+
coverImageAlt: row.coverImageAlt,
|
|
1083
|
+
tags: normalizeTags2(row.tags),
|
|
1084
|
+
tagLabels: row.tagLabels,
|
|
1085
|
+
authorName: row.authorName,
|
|
1086
|
+
seoTitle: row.seoTitle,
|
|
1087
|
+
seoDescription: row.seoDescription,
|
|
1088
|
+
readingTimeMinutes: row.readingTimeMinutes
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
__name(copiableFields, "copiableFields");
|
|
1092
|
+
var TemplateUseCaseBase = class TemplateUseCaseBase2 extends PostUseCaseBase {
|
|
1093
|
+
static {
|
|
1094
|
+
__name(this, "TemplateUseCaseBase");
|
|
1095
|
+
}
|
|
1096
|
+
async insertCopy(params) {
|
|
1097
|
+
const row = await this.dependencies.posts.create({
|
|
1098
|
+
...copiableFields(params.source),
|
|
1099
|
+
companyId: params.companyId,
|
|
1100
|
+
slug: params.slug,
|
|
1101
|
+
shortId: await this.generateShortId(params.companyId),
|
|
1102
|
+
title: params.title,
|
|
1103
|
+
isTemplate: params.isTemplate,
|
|
1104
|
+
status: params.status ?? POST_STATUS5.DRAFT,
|
|
1105
|
+
...params.publishedAt ? {
|
|
1106
|
+
publishedAt: params.publishedAt
|
|
1107
|
+
} : {}
|
|
1108
|
+
}).catch((error) => {
|
|
1109
|
+
if (isUniqueViolation(error)) throw new DuplicateSlugError2(params.slug);
|
|
1110
|
+
throw error;
|
|
1111
|
+
});
|
|
1112
|
+
const post = toPost(row, this.now());
|
|
1113
|
+
await notifyPostChanged(this.dependencies, POST_EVENT2.CREATED, post);
|
|
1114
|
+
return post;
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
var SaveAsTemplateUseCase = class extends TemplateUseCaseBase {
|
|
1118
|
+
static {
|
|
1119
|
+
__name(this, "SaveAsTemplateUseCase");
|
|
1120
|
+
}
|
|
1121
|
+
/** Copia o post (qualquer status) para um modelo. O original não muda. */
|
|
1122
|
+
async execute(params) {
|
|
1123
|
+
const input = saveAsTemplateSchema.parse(params.input ?? {});
|
|
1124
|
+
const source = await this.findOrFail(params);
|
|
1125
|
+
const title = input.title ?? source.title;
|
|
1126
|
+
const slug = await this.generateSlug(params.companyId, `${TEMPLATE_SLUG_PREFIX} ${title}`);
|
|
1127
|
+
return this.insertCopy({
|
|
1128
|
+
companyId: params.companyId,
|
|
1129
|
+
slug,
|
|
1130
|
+
title,
|
|
1131
|
+
source,
|
|
1132
|
+
isTemplate: true
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
var CreateFromTemplateUseCase = class extends TemplateUseCaseBase {
|
|
1137
|
+
static {
|
|
1138
|
+
__name(this, "CreateFromTemplateUseCase");
|
|
1139
|
+
}
|
|
1140
|
+
/** Cria um RASCUNHO novo com o conteúdo do modelo, pronto para editar e publicar. */
|
|
1141
|
+
async execute(params) {
|
|
1142
|
+
const input = createFromTemplateSchema.parse(params.input ?? {});
|
|
1143
|
+
const template = await this.findOrFail(params);
|
|
1144
|
+
if (!template.isTemplate) throw new NotATemplateError2(params.id);
|
|
1145
|
+
const title = input.title ?? template.title;
|
|
1146
|
+
if (input.slug) await this.assertSlugAvailable(params.companyId, input.slug);
|
|
1147
|
+
const slug = input.slug ?? await this.generateSlug(params.companyId, title);
|
|
1148
|
+
return this.insertCopy({
|
|
1149
|
+
companyId: params.companyId,
|
|
1150
|
+
slug,
|
|
1151
|
+
title,
|
|
1152
|
+
source: template,
|
|
1153
|
+
isTemplate: false
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
};
|
|
1157
|
+
var CountPostsUseCase = class extends PostUseCaseBase {
|
|
1158
|
+
static {
|
|
1159
|
+
__name(this, "CountPostsUseCase");
|
|
1160
|
+
}
|
|
1161
|
+
/** Números das abas do painel, numa consulta só. */
|
|
1162
|
+
async execute(params) {
|
|
1163
|
+
return this.dependencies.posts.countByStatus({
|
|
1164
|
+
companyId: params.companyId,
|
|
1165
|
+
now: this.now()
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
};
|
|
1169
|
+
|
|
1170
|
+
// src/use-cases/Scheduling.use-cases.ts
|
|
1171
|
+
var DEFAULT_BATCH_LIMIT = 100;
|
|
1172
|
+
var DATE_SUFFIX_LENGTH = 11;
|
|
1173
|
+
var FALLBACK_SLUG2 = "post";
|
|
1174
|
+
var RepublishPostUseCase = class extends PostUseCaseBase {
|
|
1175
|
+
static {
|
|
1176
|
+
__name(this, "RepublishPostUseCase");
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Muda a data de um post JÁ publicado, mantendo o MESMO endereço. É a opção segura para SEO: o
|
|
1180
|
+
* link antigo (compartilhado, indexado, com backlinks) continua valendo e não nasce conteúdo
|
|
1181
|
+
* duplicado. Data futura é recusada — o post sairia do ar até lá e o leitor veria 404.
|
|
1182
|
+
*/
|
|
1183
|
+
async execute(params) {
|
|
1184
|
+
const input = republishPostSchema.parse(params.input ?? {});
|
|
1185
|
+
const existing = await this.findOrFail(params);
|
|
1186
|
+
const now = this.now();
|
|
1187
|
+
if (existing.isTemplate || effectiveStatus(existing, now) !== POST_STATUS6.PUBLISHED) {
|
|
1188
|
+
throw new PostNotPublishedError(params.id);
|
|
1189
|
+
}
|
|
1190
|
+
const publishedAt = input.publishedAt ? new Date(input.publishedAt) : now;
|
|
1191
|
+
if (publishedAt > now) throw new RepublishDateInFutureError();
|
|
1192
|
+
return this.save(params, {
|
|
1193
|
+
status: POST_STATUS6.PUBLISHED,
|
|
1194
|
+
publishedAt
|
|
1195
|
+
}, POST_EVENT3.REPUBLISHED);
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
var PublishDueUseCase = class extends PostUseCaseBase {
|
|
1199
|
+
static {
|
|
1200
|
+
__name(this, "PublishDueUseCase");
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* Idempotente e seguro com várias instâncias chamando ao mesmo tempo: cada post/regra é reclamado
|
|
1204
|
+
* por uma só execução. Sem trabalho vencido, não faz nada. `now` existe para teste e reprocesso.
|
|
1205
|
+
*/
|
|
1206
|
+
async execute(params = {}) {
|
|
1207
|
+
const now = params.now ?? this.now();
|
|
1208
|
+
const limit = params.limit ?? DEFAULT_BATCH_LIMIT;
|
|
1209
|
+
const materialized = await this.materializeRecurrences({
|
|
1210
|
+
now,
|
|
1211
|
+
limit
|
|
1212
|
+
});
|
|
1213
|
+
const rows = await this.dependencies.posts.claimDueScheduled({
|
|
1214
|
+
now,
|
|
1215
|
+
limit
|
|
1216
|
+
});
|
|
1217
|
+
for (const row of rows) {
|
|
1218
|
+
await notifyPostChanged(this.dependencies, POST_EVENT3.PUBLISHED, toPost(row, now));
|
|
1219
|
+
}
|
|
1220
|
+
if (rows.length > 0 || materialized > 0) {
|
|
1221
|
+
this.dependencies.logger?.info("content-module: publishDue", {
|
|
1222
|
+
published: rows.length,
|
|
1223
|
+
materialized
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
return {
|
|
1227
|
+
published: rows.length,
|
|
1228
|
+
materialized
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
materializeRecurrences(params) {
|
|
1232
|
+
return this.dependencies.recurrences.processDue({
|
|
1233
|
+
...params,
|
|
1234
|
+
handle: /* @__PURE__ */ __name((rule) => this.materialize(rule, params.now), "handle")
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
/** Um post publicado agora a partir do modelo; a regra avança para a próxima data futura. */
|
|
1238
|
+
async materialize(rule, now) {
|
|
1239
|
+
const advance = {
|
|
1240
|
+
nextRunAt: nextOccurrenceAfter({
|
|
1241
|
+
frequency: rule.frequency,
|
|
1242
|
+
from: rule.nextRunAt,
|
|
1243
|
+
anchorDay: rule.anchorDay,
|
|
1244
|
+
now
|
|
1245
|
+
})
|
|
1246
|
+
};
|
|
1247
|
+
const template = await this.dependencies.posts.findById({
|
|
1248
|
+
companyId: rule.companyId,
|
|
1249
|
+
id: rule.templateId
|
|
1250
|
+
});
|
|
1251
|
+
if (!template || !template.isTemplate || template.status === POST_STATUS6.ARCHIVED) {
|
|
1252
|
+
this.dependencies.logger?.warn("content-module: modelo da recorr\xEAncia indispon\xEDvel", {
|
|
1253
|
+
ruleId: rule.id
|
|
1254
|
+
});
|
|
1255
|
+
return {
|
|
1256
|
+
isActive: false
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
const base = (slugify(template.title) || FALLBACK_SLUG2).slice(0, SLUG_MAX_LENGTH - DATE_SUFFIX_LENGTH);
|
|
1260
|
+
const slug = await this.uniqueSlug(rule.companyId, `${base.replace(/-+$/g, "")}-${toDateStamp(now)}`);
|
|
1261
|
+
const row = await this.dependencies.posts.create({
|
|
1262
|
+
...copiableFields(template),
|
|
1263
|
+
companyId: rule.companyId,
|
|
1264
|
+
slug,
|
|
1265
|
+
shortId: await this.generateShortId(rule.companyId),
|
|
1266
|
+
title: template.title,
|
|
1267
|
+
isTemplate: false,
|
|
1268
|
+
status: POST_STATUS6.PUBLISHED,
|
|
1269
|
+
publishedAt: now
|
|
1270
|
+
});
|
|
1271
|
+
const post = toPost(row, now);
|
|
1272
|
+
await notifyPostChanged(this.dependencies, POST_EVENT3.CREATED, post);
|
|
1273
|
+
await notifyPostChanged(this.dependencies, POST_EVENT3.PUBLISHED, post);
|
|
1274
|
+
return {
|
|
1275
|
+
...advance,
|
|
1276
|
+
lastRunAt: now,
|
|
1277
|
+
lastPostId: row.id
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
|
|
688
1282
|
// src/use-cases/UploadCoverImage.use-case.ts
|
|
689
1283
|
import { ImageStorageDisabledError, InvalidCoverImageError } from "@adatechnology/content-contracts";
|
|
690
1284
|
|
|
@@ -743,8 +1337,11 @@ function createContentModule(params) {
|
|
|
743
1337
|
assertValidConfig(config);
|
|
744
1338
|
const posts2 = params.providers?.postStore ?? (params.db ? new PostRepository(params.db) : void 0);
|
|
745
1339
|
if (!posts2) throw new ConfigMissingError("db");
|
|
1340
|
+
const recurrences = params.providers?.recurrenceStore ?? (params.db ? new RecurrenceRepository(params.db) : void 0);
|
|
1341
|
+
if (!recurrences) throw new ConfigMissingError("db");
|
|
746
1342
|
const dependencies = {
|
|
747
1343
|
posts: posts2,
|
|
1344
|
+
recurrences,
|
|
748
1345
|
config,
|
|
749
1346
|
clock: params.providers?.clock ?? SYSTEM_CLOCK,
|
|
750
1347
|
...params.hooks ? {
|
|
@@ -769,6 +1366,15 @@ function createContentModule(params) {
|
|
|
769
1366
|
getPublishedPostBySlug: new GetPublishedPostBySlugUseCase(dependencies),
|
|
770
1367
|
listPublishedPosts: new ListPublishedPostsUseCase(dependencies),
|
|
771
1368
|
listTags: new ListTagsUseCase(dependencies),
|
|
1369
|
+
countPosts: new CountPostsUseCase(dependencies),
|
|
1370
|
+
saveAsTemplate: new SaveAsTemplateUseCase(dependencies),
|
|
1371
|
+
createFromTemplate: new CreateFromTemplateUseCase(dependencies),
|
|
1372
|
+
republishPost: new RepublishPostUseCase(dependencies),
|
|
1373
|
+
createRecurrence: new CreateRecurrenceUseCase(dependencies),
|
|
1374
|
+
listRecurrences: new ListRecurrencesUseCase(dependencies),
|
|
1375
|
+
updateRecurrence: new UpdateRecurrenceUseCase(dependencies),
|
|
1376
|
+
removeRecurrence: new RemoveRecurrenceUseCase(dependencies),
|
|
1377
|
+
publishDue: new PublishDueUseCase(dependencies),
|
|
772
1378
|
...dependencies.imageStorage ? {
|
|
773
1379
|
uploadCoverImage: new UploadCoverImageUseCase(dependencies)
|
|
774
1380
|
} : {},
|
|
@@ -783,7 +1389,7 @@ function createContentModule(params) {
|
|
|
783
1389
|
__name(createContentModule, "createContentModule");
|
|
784
1390
|
|
|
785
1391
|
// src/http/adminRoutes.ts
|
|
786
|
-
import { createPostSchema as createPostSchema2, DEFAULT_ADMIN_SCOPES, listPostsQuerySchema as listPostsQuerySchema2, publishPostSchema as publishPostSchema2, updatePostSchema as updatePostSchema2 } from "@adatechnology/content-contracts";
|
|
1392
|
+
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";
|
|
787
1393
|
|
|
788
1394
|
// src/http/requireCompany.ts
|
|
789
1395
|
import { CONTENT_ERROR_CODES, ContentError } from "@adatechnology/content-contracts";
|
|
@@ -888,6 +1494,19 @@ function buildAdminRoutes(module) {
|
|
|
888
1494
|
}));
|
|
889
1495
|
}
|
|
890
1496
|
},
|
|
1497
|
+
{
|
|
1498
|
+
...admin,
|
|
1499
|
+
method: "GET",
|
|
1500
|
+
path: "/posts/counts",
|
|
1501
|
+
operationId: "countPosts",
|
|
1502
|
+
summary: "Contagem de posts por aba: publicados, agendados, rascunhos, arquivados e modelos",
|
|
1503
|
+
async handler(context) {
|
|
1504
|
+
return json(200, await useCases.countPosts.execute({
|
|
1505
|
+
companyId: requireCompany(context)
|
|
1506
|
+
}));
|
|
1507
|
+
}
|
|
1508
|
+
},
|
|
1509
|
+
...recurrenceRoutes(module),
|
|
891
1510
|
...uploadRoutes,
|
|
892
1511
|
{
|
|
893
1512
|
...admin,
|
|
@@ -951,13 +1570,119 @@ function buildAdminRoutes(module) {
|
|
|
951
1570
|
async handler(context) {
|
|
952
1571
|
return json(200, await useCases.unpublishPost.execute(reference(context)));
|
|
953
1572
|
}
|
|
1573
|
+
},
|
|
1574
|
+
{
|
|
1575
|
+
...admin,
|
|
1576
|
+
method: "POST",
|
|
1577
|
+
path: "/posts/:id/republish",
|
|
1578
|
+
bodySchema: republishPostSchema2.optional(),
|
|
1579
|
+
operationId: "republishPost",
|
|
1580
|
+
summary: "Republica um post no ar com nova data, mantendo o mesmo endere\xE7o (SEO); data futura \xE9 recusada",
|
|
1581
|
+
async handler(context) {
|
|
1582
|
+
return json(200, await useCases.republishPost.execute({
|
|
1583
|
+
...reference(context),
|
|
1584
|
+
input: context.body ?? {}
|
|
1585
|
+
}));
|
|
1586
|
+
}
|
|
1587
|
+
},
|
|
1588
|
+
{
|
|
1589
|
+
...admin,
|
|
1590
|
+
method: "POST",
|
|
1591
|
+
path: "/posts/:id/save-as-template",
|
|
1592
|
+
bodySchema: saveAsTemplateSchema2.optional(),
|
|
1593
|
+
operationId: "savePostAsTemplate",
|
|
1594
|
+
summary: "Copia o post para um modelo (o original n\xE3o muda)",
|
|
1595
|
+
async handler(context) {
|
|
1596
|
+
return json(201, await useCases.saveAsTemplate.execute({
|
|
1597
|
+
...reference(context),
|
|
1598
|
+
input: context.body ?? {}
|
|
1599
|
+
}));
|
|
1600
|
+
}
|
|
1601
|
+
},
|
|
1602
|
+
{
|
|
1603
|
+
...admin,
|
|
1604
|
+
method: "POST",
|
|
1605
|
+
path: "/posts/:id/from-template",
|
|
1606
|
+
bodySchema: createFromTemplateSchema2.optional(),
|
|
1607
|
+
operationId: "createPostFromTemplate",
|
|
1608
|
+
summary: "Cria um rascunho novo a partir do modelo `:id`",
|
|
1609
|
+
async handler(context) {
|
|
1610
|
+
return json(201, await useCases.createFromTemplate.execute({
|
|
1611
|
+
...reference(context),
|
|
1612
|
+
input: context.body ?? {}
|
|
1613
|
+
}));
|
|
1614
|
+
}
|
|
954
1615
|
}
|
|
955
1616
|
];
|
|
956
1617
|
}
|
|
957
1618
|
__name(buildAdminRoutes, "buildAdminRoutes");
|
|
1619
|
+
function recurrenceRoutes(module) {
|
|
1620
|
+
const { useCases } = module;
|
|
1621
|
+
const admin = {
|
|
1622
|
+
scope: "admin",
|
|
1623
|
+
requiredScopes: module.config.adminScopes ?? DEFAULT_ADMIN_SCOPES
|
|
1624
|
+
};
|
|
1625
|
+
return [
|
|
1626
|
+
{
|
|
1627
|
+
...admin,
|
|
1628
|
+
method: "GET",
|
|
1629
|
+
path: "/recurrences",
|
|
1630
|
+
operationId: "listRecurrences",
|
|
1631
|
+
summary: "Regras de recorr\xEAncia da empresa",
|
|
1632
|
+
async handler(context) {
|
|
1633
|
+
return json(200, await useCases.listRecurrences.execute({
|
|
1634
|
+
companyId: requireCompany(context)
|
|
1635
|
+
}));
|
|
1636
|
+
}
|
|
1637
|
+
},
|
|
1638
|
+
{
|
|
1639
|
+
...admin,
|
|
1640
|
+
method: "POST",
|
|
1641
|
+
path: "/recurrences",
|
|
1642
|
+
bodySchema: createRecurrenceSchema2,
|
|
1643
|
+
operationId: "createRecurrence",
|
|
1644
|
+
summary: "Cria regra: publica um post novo, copiado do modelo, toda semana ou todo m\xEAs",
|
|
1645
|
+
async handler(context) {
|
|
1646
|
+
return json(201, await useCases.createRecurrence.execute({
|
|
1647
|
+
companyId: requireCompany(context),
|
|
1648
|
+
input: context.body
|
|
1649
|
+
}));
|
|
1650
|
+
}
|
|
1651
|
+
},
|
|
1652
|
+
{
|
|
1653
|
+
...admin,
|
|
1654
|
+
method: "PATCH",
|
|
1655
|
+
path: "/recurrences/:id",
|
|
1656
|
+
bodySchema: updateRecurrenceSchema2,
|
|
1657
|
+
operationId: "updateRecurrence",
|
|
1658
|
+
summary: "Pausa, retoma ou remarca a pr\xF3xima execu\xE7\xE3o",
|
|
1659
|
+
async handler(context) {
|
|
1660
|
+
return json(200, await useCases.updateRecurrence.execute({
|
|
1661
|
+
...reference(context),
|
|
1662
|
+
input: context.body
|
|
1663
|
+
}));
|
|
1664
|
+
}
|
|
1665
|
+
},
|
|
1666
|
+
{
|
|
1667
|
+
...admin,
|
|
1668
|
+
method: "DELETE",
|
|
1669
|
+
path: "/recurrences/:id",
|
|
1670
|
+
operationId: "removeRecurrence",
|
|
1671
|
+
summary: "Apaga a regra; os posts j\xE1 publicados por ela continuam no ar",
|
|
1672
|
+
async handler(context) {
|
|
1673
|
+
await useCases.removeRecurrence.execute(reference(context));
|
|
1674
|
+
return {
|
|
1675
|
+
kind: "empty",
|
|
1676
|
+
status: 204
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
];
|
|
1681
|
+
}
|
|
1682
|
+
__name(recurrenceRoutes, "recurrenceRoutes");
|
|
958
1683
|
|
|
959
1684
|
// src/http/publicRoutes.ts
|
|
960
|
-
import { DEFAULT_PUBLIC_CACHE_CONTROL, listPublishedPostsQuerySchema as listPublishedPostsQuerySchema2, PostNotFoundError as
|
|
1685
|
+
import { DEFAULT_PUBLIC_CACHE_CONTROL, listPublishedPostsQuerySchema as listPublishedPostsQuerySchema2, PostNotFoundError as PostNotFoundError4 } from "@adatechnology/content-contracts";
|
|
961
1686
|
var PUBLIC = {
|
|
962
1687
|
scope: "public"
|
|
963
1688
|
};
|
|
@@ -977,7 +1702,7 @@ function buildPublicRoutes(params) {
|
|
|
977
1702
|
headers: context.headers,
|
|
978
1703
|
query: context.query
|
|
979
1704
|
});
|
|
980
|
-
if (!companyId) throw new
|
|
1705
|
+
if (!companyId) throw new PostNotFoundError4("company");
|
|
981
1706
|
return companyId;
|
|
982
1707
|
}
|
|
983
1708
|
__name(resolveCompany, "resolveCompany");
|
|
@@ -1107,12 +1832,27 @@ __name(runContentMigrations, "runContentMigrations");
|
|
|
1107
1832
|
|
|
1108
1833
|
// src/testing/inMemoryPostStore.ts
|
|
1109
1834
|
import { randomUUID } from "crypto";
|
|
1110
|
-
import { POST_STATUS as
|
|
1835
|
+
import { POST_STATUS as POST_STATUS7 } from "@adatechnology/content-contracts";
|
|
1111
1836
|
function isPublic(row, now) {
|
|
1112
|
-
const live = row.status ===
|
|
1837
|
+
const live = row.status === POST_STATUS7.PUBLISHED || row.status === POST_STATUS7.SCHEDULED;
|
|
1113
1838
|
return live && row.publishedAt !== null && row.publishedAt <= now;
|
|
1114
1839
|
}
|
|
1115
1840
|
__name(isPublic, "isPublic");
|
|
1841
|
+
function adminComparator(query) {
|
|
1842
|
+
const sign = query.order === "asc" ? 1 : -1;
|
|
1843
|
+
const value = /* @__PURE__ */ __name((row) => {
|
|
1844
|
+
if (query.sort === "title") return row.title.toLowerCase();
|
|
1845
|
+
if (query.sort === "status") return row.status;
|
|
1846
|
+
if (query.sort === "publishedAt") return row.publishedAt?.getTime() ?? sign * Number.POSITIVE_INFINITY;
|
|
1847
|
+
return row.updatedAt.getTime();
|
|
1848
|
+
}, "value");
|
|
1849
|
+
return (left, right) => {
|
|
1850
|
+
const a = value(left);
|
|
1851
|
+
const b = value(right);
|
|
1852
|
+
return (a < b ? -1 : a > b ? 1 : 0) * sign || left.id.localeCompare(right.id);
|
|
1853
|
+
};
|
|
1854
|
+
}
|
|
1855
|
+
__name(adminComparator, "adminComparator");
|
|
1116
1856
|
function paginate(rows, page, pageSize) {
|
|
1117
1857
|
return {
|
|
1118
1858
|
rows: rows.slice((page - 1) * pageSize, page * pageSize).map((row) => ({
|
|
@@ -1132,6 +1872,7 @@ function createInMemoryPostStore(seed = []) {
|
|
|
1132
1872
|
const rows = [
|
|
1133
1873
|
...seed
|
|
1134
1874
|
];
|
|
1875
|
+
const formerSlugs = [];
|
|
1135
1876
|
const assertUniqueSlug = /* @__PURE__ */ __name((companyId, slug, ownId) => {
|
|
1136
1877
|
if (rows.some((row) => row.companyId === companyId && row.slug === slug && row.id !== ownId)) {
|
|
1137
1878
|
throw new UniqueViolation('duplicate key value violates unique constraint "idx_posts_company_slug"');
|
|
@@ -1139,6 +1880,32 @@ function createInMemoryPostStore(seed = []) {
|
|
|
1139
1880
|
}, "assertUniqueSlug");
|
|
1140
1881
|
return {
|
|
1141
1882
|
rows,
|
|
1883
|
+
async findByShortId({ companyId, shortId }) {
|
|
1884
|
+
const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId);
|
|
1885
|
+
return row ? {
|
|
1886
|
+
...row
|
|
1887
|
+
} : void 0;
|
|
1888
|
+
},
|
|
1889
|
+
async findPublicByShortId({ companyId, shortId, now }) {
|
|
1890
|
+
const row = rows.find((candidate) => candidate.companyId === companyId && candidate.shortId === shortId && isPublic(candidate, now));
|
|
1891
|
+
return row ? {
|
|
1892
|
+
...row
|
|
1893
|
+
} : void 0;
|
|
1894
|
+
},
|
|
1895
|
+
async findPublicByFormerSlug({ companyId, slug, now }) {
|
|
1896
|
+
const former = formerSlugs.find((entry) => entry.companyId === companyId && entry.slug === slug);
|
|
1897
|
+
const row = rows.find((candidate) => candidate.id === former?.postId && isPublic(candidate, now));
|
|
1898
|
+
return row ? {
|
|
1899
|
+
...row
|
|
1900
|
+
} : void 0;
|
|
1901
|
+
},
|
|
1902
|
+
async recordFormerSlug(params) {
|
|
1903
|
+
if (!formerSlugs.some((entry) => entry.companyId === params.companyId && entry.slug === params.slug)) {
|
|
1904
|
+
formerSlugs.push({
|
|
1905
|
+
...params
|
|
1906
|
+
});
|
|
1907
|
+
}
|
|
1908
|
+
},
|
|
1142
1909
|
async create(values) {
|
|
1143
1910
|
assertUniqueSlug(values.companyId, values.slug);
|
|
1144
1911
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -1149,7 +1916,9 @@ function createInMemoryPostStore(seed = []) {
|
|
|
1149
1916
|
coverImageUrl: null,
|
|
1150
1917
|
coverImageAlt: null,
|
|
1151
1918
|
tags: [],
|
|
1152
|
-
|
|
1919
|
+
tagLabels: {},
|
|
1920
|
+
status: POST_STATUS7.DRAFT,
|
|
1921
|
+
isTemplate: false,
|
|
1153
1922
|
publishedAt: null,
|
|
1154
1923
|
authorName: null,
|
|
1155
1924
|
seoTitle: null,
|
|
@@ -1196,9 +1965,34 @@ function createInMemoryPostStore(seed = []) {
|
|
|
1196
1965
|
},
|
|
1197
1966
|
async listForAdmin(query) {
|
|
1198
1967
|
const search = query.search?.toLowerCase();
|
|
1199
|
-
const matched = rows.filter((row) => row.companyId === query.companyId).filter((row) => !query.status || effectiveStatus(row, query.now) === query.status).filter((row) => !query.
|
|
1968
|
+
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));
|
|
1200
1969
|
return paginate(matched, query.page, query.pageSize);
|
|
1201
1970
|
},
|
|
1971
|
+
async countByStatus({ companyId, now }) {
|
|
1972
|
+
const counts = {
|
|
1973
|
+
published: 0,
|
|
1974
|
+
scheduled: 0,
|
|
1975
|
+
draft: 0,
|
|
1976
|
+
archived: 0,
|
|
1977
|
+
templates: 0
|
|
1978
|
+
};
|
|
1979
|
+
for (const row of rows) {
|
|
1980
|
+
if (row.companyId !== companyId) continue;
|
|
1981
|
+
if (row.isTemplate) {
|
|
1982
|
+
if (row.status !== POST_STATUS7.ARCHIVED) counts.templates += 1;
|
|
1983
|
+
continue;
|
|
1984
|
+
}
|
|
1985
|
+
counts[effectiveStatus(row, now)] += 1;
|
|
1986
|
+
}
|
|
1987
|
+
return counts;
|
|
1988
|
+
},
|
|
1989
|
+
async claimDueScheduled({ now, limit }) {
|
|
1990
|
+
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);
|
|
1991
|
+
for (const row of due) row.status = POST_STATUS7.PUBLISHED;
|
|
1992
|
+
return due.map((row) => ({
|
|
1993
|
+
...row
|
|
1994
|
+
}));
|
|
1995
|
+
},
|
|
1202
1996
|
async listPublic(query) {
|
|
1203
1997
|
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));
|
|
1204
1998
|
return paginate(matched, query.page, query.pageSize);
|
|
@@ -1219,31 +2013,128 @@ function createInMemoryPostStore(seed = []) {
|
|
|
1219
2013
|
};
|
|
1220
2014
|
}
|
|
1221
2015
|
__name(createInMemoryPostStore, "createInMemoryPostStore");
|
|
2016
|
+
|
|
2017
|
+
// src/scheduler.ts
|
|
2018
|
+
var DEFAULT_SCHEDULER_INTERVAL_MS = 6e4;
|
|
2019
|
+
function startContentScheduler(params) {
|
|
2020
|
+
let isRunning = false;
|
|
2021
|
+
const tick = /* @__PURE__ */ __name(async () => {
|
|
2022
|
+
if (isRunning) return;
|
|
2023
|
+
isRunning = true;
|
|
2024
|
+
try {
|
|
2025
|
+
await params.module.useCases.publishDue.execute();
|
|
2026
|
+
} catch (error) {
|
|
2027
|
+
params.logger?.error("content-module: ciclo do agendador falhou", {
|
|
2028
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2029
|
+
});
|
|
2030
|
+
} finally {
|
|
2031
|
+
isRunning = false;
|
|
2032
|
+
}
|
|
2033
|
+
}, "tick");
|
|
2034
|
+
const timer = setInterval(() => void tick(), params.intervalMs ?? DEFAULT_SCHEDULER_INTERVAL_MS);
|
|
2035
|
+
timer.unref?.();
|
|
2036
|
+
void tick();
|
|
2037
|
+
return () => clearInterval(timer);
|
|
2038
|
+
}
|
|
2039
|
+
__name(startContentScheduler, "startContentScheduler");
|
|
2040
|
+
|
|
2041
|
+
// src/testing/inMemoryRecurrenceStore.ts
|
|
2042
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
2043
|
+
function createInMemoryRecurrenceStore() {
|
|
2044
|
+
const rows = [];
|
|
2045
|
+
const owned = /* @__PURE__ */ __name((companyId, id) => rows.find((row) => row.companyId === companyId && row.id === id), "owned");
|
|
2046
|
+
return {
|
|
2047
|
+
rows,
|
|
2048
|
+
async create(values) {
|
|
2049
|
+
const row = {
|
|
2050
|
+
id: randomUUID2(),
|
|
2051
|
+
isActive: true,
|
|
2052
|
+
lastRunAt: null,
|
|
2053
|
+
lastPostId: null,
|
|
2054
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
2055
|
+
...values
|
|
2056
|
+
};
|
|
2057
|
+
rows.push(row);
|
|
2058
|
+
return {
|
|
2059
|
+
...row
|
|
2060
|
+
};
|
|
2061
|
+
},
|
|
2062
|
+
async findById({ companyId, id }) {
|
|
2063
|
+
const row = owned(companyId, id);
|
|
2064
|
+
return row ? {
|
|
2065
|
+
...row
|
|
2066
|
+
} : void 0;
|
|
2067
|
+
},
|
|
2068
|
+
async list({ companyId }) {
|
|
2069
|
+
return rows.filter((row) => row.companyId === companyId).sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime()).map((row) => ({
|
|
2070
|
+
...row
|
|
2071
|
+
}));
|
|
2072
|
+
},
|
|
2073
|
+
async update({ companyId, id, values }) {
|
|
2074
|
+
const row = owned(companyId, id);
|
|
2075
|
+
if (!row) return void 0;
|
|
2076
|
+
Object.assign(row, values);
|
|
2077
|
+
return {
|
|
2078
|
+
...row
|
|
2079
|
+
};
|
|
2080
|
+
},
|
|
2081
|
+
async remove({ companyId, id }) {
|
|
2082
|
+
const index2 = rows.findIndex((row) => row.companyId === companyId && row.id === id);
|
|
2083
|
+
if (index2 < 0) return false;
|
|
2084
|
+
rows.splice(index2, 1);
|
|
2085
|
+
return true;
|
|
2086
|
+
},
|
|
2087
|
+
async processDue({ now, limit, handle }) {
|
|
2088
|
+
const due = rows.filter((row) => row.isActive && row.nextRunAt <= now).sort((left, right) => left.nextRunAt.getTime() - right.nextRunAt.getTime()).slice(0, limit);
|
|
2089
|
+
for (const row of due) Object.assign(row, await handle({
|
|
2090
|
+
...row
|
|
2091
|
+
}));
|
|
2092
|
+
return due.length;
|
|
2093
|
+
}
|
|
2094
|
+
};
|
|
2095
|
+
}
|
|
2096
|
+
__name(createInMemoryRecurrenceStore, "createInMemoryRecurrenceStore");
|
|
1222
2097
|
export {
|
|
1223
2098
|
ArchivePostUseCase,
|
|
1224
2099
|
BuildFeedUseCase,
|
|
1225
2100
|
CONTENT_MIGRATIONS_TABLE,
|
|
1226
2101
|
COVER_IMAGE,
|
|
2102
|
+
CountPostsUseCase,
|
|
2103
|
+
CreateFromTemplateUseCase,
|
|
1227
2104
|
CreatePostUseCase,
|
|
2105
|
+
CreateRecurrenceUseCase,
|
|
2106
|
+
DEFAULT_SCHEDULER_INTERVAL_MS,
|
|
1228
2107
|
FEED_FORMAT,
|
|
1229
2108
|
GetPostUseCase,
|
|
1230
2109
|
GetPublishedPostBySlugUseCase,
|
|
1231
2110
|
ListPostsUseCase,
|
|
1232
2111
|
ListPublishedPostsUseCase,
|
|
2112
|
+
ListRecurrencesUseCase,
|
|
1233
2113
|
ListSitemapEntriesUseCase,
|
|
1234
2114
|
ListTagsUseCase,
|
|
1235
2115
|
PostRepository,
|
|
2116
|
+
PublishDueUseCase,
|
|
1236
2117
|
PublishPostUseCase,
|
|
2118
|
+
RecurrenceRepository,
|
|
2119
|
+
RemoveRecurrenceUseCase,
|
|
2120
|
+
RepublishPostUseCase,
|
|
2121
|
+
SaveAsTemplateUseCase,
|
|
1237
2122
|
TAG_SCOPE,
|
|
1238
2123
|
UnpublishPostUseCase,
|
|
1239
2124
|
UpdatePostUseCase,
|
|
2125
|
+
UpdateRecurrenceUseCase,
|
|
1240
2126
|
UploadCoverImageUseCase,
|
|
1241
2127
|
contentMigrationsFolder,
|
|
1242
2128
|
contentSchema,
|
|
1243
2129
|
createContentModule,
|
|
1244
2130
|
createContentRoutes,
|
|
1245
2131
|
createInMemoryPostStore,
|
|
2132
|
+
createInMemoryRecurrenceStore,
|
|
2133
|
+
nextOccurrence,
|
|
2134
|
+
nextOccurrenceAfter,
|
|
1246
2135
|
posts,
|
|
1247
|
-
|
|
2136
|
+
recurrenceRules,
|
|
2137
|
+
runContentMigrations,
|
|
2138
|
+
startContentScheduler
|
|
1248
2139
|
};
|
|
1249
2140
|
//# sourceMappingURL=index.js.map
|