@anthusai/papyrus 5.135.0-next.1 → 5.135.0-next.3

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.
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import json
4
4
  import os
5
+ from datetime import datetime
5
6
  from typing import Any
6
7
 
7
8
  from papyrus_content import request_meter
@@ -39,6 +40,7 @@ from papyrus_content.rebuild_trigger import (
39
40
  trigger_rebuild,
40
41
  trigger_staging_build,
41
42
  )
43
+ from papyrus_content.publication_cadence import cadence_from_environment
42
44
  from papyrus_content.story_reporting import save_story_version
43
45
  from papyrus_content.story_schedule import TASK_NAME as PUBLISH_SCHEDULED_TASK, Caller, ScheduleError, ScheduleService, run_operation as run_schedule_operation, scheduler_from_environment, ZONE_ENV as PUBLICATION_ZONE_ENV
44
46
  from papyrus_content.live_schema import wait_for_live_schema
@@ -47,7 +49,7 @@ from papyrus_content.editorial_checks import GraphQLEditorialStore, ensure_defau
47
49
  from papyrus_content.item_deck_backfill import ensure_item_decks
48
50
  from papyrus_content.item_language_backfill import ensure_item_languages
49
51
  from papyrus_content.reference_intake import IntakeError, intake_email_submission_references, intake_references
50
- from papyrus_content.publish_alerts import PUBLISHED_TASK_KEY, announce_published
52
+ from papyrus_content.publishing import PUBLISHED_TASK_KEY
51
53
  from papyrus_content.localize.dispatch import PUBLISH_TASK as PUBLISH_LOCALIZATION_TASK
52
54
  from papyrus_content.publishing import (
53
55
  ItemFields,
@@ -133,7 +135,28 @@ INVOKED_FUNCTION_ARN: str | None = None # this function's own ARN, from the in
133
135
 
134
136
  def schedule_service(client) -> ScheduleService:
135
137
  """The site's scheduled-publishing service: the publication's time zone and its Scheduler come from the environment the deploy set."""
136
- return ScheduleService(client, zone_name=os.environ.get(PUBLICATION_ZONE_ENV), scheduler=scheduler_from_environment(invoked_function_arn=INVOKED_FUNCTION_ARN))
138
+ zone_name = os.environ.get(PUBLICATION_ZONE_ENV)
139
+ return ScheduleService(client, zone_name=zone_name, scheduler=scheduler_from_environment(invoked_function_arn=INVOKED_FUNCTION_ARN), cadence=cadence_from_environment(zone_name))
140
+
141
+
142
+ def count_first_publication(client, item: dict, item_id: str) -> dict:
143
+ """A Story went live for the first time: add it to the publication's rhythm (the hours of the week it publishes in), which "Suggest a time" learns from. The publish
144
+ has already happened, so a failure is reported in the answer and never undoes it; a site with no time zone or no lock table keeps no rhythm. A new version of a Story
145
+ that is already out, a translation and anything that is not a Story are not first publications."""
146
+ from papyrus_content.content_item_lifecycle import is_story_item_type
147
+ from papyrus_content.localization_publish import original_of
148
+
149
+ if item.get("publishedAt") or not is_story_item_type(item.get("type")) or original_of(None, item) is not None:
150
+ return {}
151
+ try:
152
+ store = cadence_from_environment(os.environ.get(PUBLICATION_ZONE_ENV))
153
+ if store is None:
154
+ return {}
155
+ published = client.get_record("Item", item_id) or {} # the first publication time the publish just wrote
156
+ store.record_first_publication(datetime.fromisoformat(str(published["publishedAt"]).replace("Z", "+00:00")))
157
+ except Exception as error: # noqa: BLE001 - reported to the caller in the answer
158
+ return {"cadence": {"error": f"{type(error).__name__}: {error}"}}
159
+ return {}
137
160
 
138
161
 
139
162
  class ProjectionTaskFailed(Exception):
@@ -202,7 +225,7 @@ def project_item_action(client, item_id: str, *, unpublished: bool, published_it
202
225
  is live, here when the projection succeeds, or by the scheduled retry (which carries the same marker) when it did not."""
203
226
  if not projection_configured():
204
227
  if published_item_id:
205
- announce_published_story(client, item_id, published_item_id)
228
+ story_is_live(client, item_id, published_item_id)
206
229
  return {}
207
230
  liveness = {} if unpublished else {"live": False}
208
231
  task = {"task": "item", "itemId": item_id, "unpublished": unpublished}
@@ -239,7 +262,7 @@ def project_item_action(client, item_id: str, *, unpublished: bool, published_it
239
262
  if report.follow_up_item_pages:
240
263
  schedule_item_pages(item_id)
241
264
  if report.ok and published_item_id:
242
- announce_published_story(client, item_id, published_item_id)
265
+ story_is_live(client, item_id, published_item_id)
243
266
  return response
244
267
 
245
268
 
@@ -478,7 +501,7 @@ def build_item_job(client, context, jobs, item_id: str, job_id: str | None, *, u
478
501
  jobs.finish(item_id, job_id, ok=report.ok, outcome=outcome)
479
502
  if report.ok and not unpublished and isinstance(published, dict):
480
503
  # A real publish (the CLI marks it, as does the newsroom's retry): the page is live, so tell the newsletter.
481
- announce_published_story(client, item_id, published.get("publishedItemId"))
504
+ story_is_live(client, item_id, published.get("publishedItemId"))
482
505
  return report
483
506
 
484
507
 
@@ -874,6 +897,7 @@ def publish_item_action(arguments: dict, actor: str, approved_by: str | None = N
874
897
  "publishedId": result.published_item_id,
875
898
  "versionNumber": result.version_number,
876
899
  **remove_schedules(client, candidate, int(candidate["versionNumber"]) if candidate.get("versionNumber") else None), # publishing now ends the schedule
900
+ **(count_first_publication(client, candidate, arguments["id"]) if result.changed else {}),
877
901
  }
878
902
  if result.changed and live is not None and live.get("type") and live.get("type") != candidate.get("type"):
879
903
  # The type decides the address (urls.types), so the live page moves; the projection leaves a redirect from the old address.
@@ -938,11 +962,11 @@ def schedule_item_action(arguments: dict, event: dict) -> dict:
938
962
  return run_schedule_operation(str(arguments.get("operation") or ""), arguments.get("arguments") or {}, service, caller_from_event(event))
939
963
 
940
964
 
941
- def announce_published_story(client, item_id: str, published_item_id: str | None) -> None:
942
- """A Story is live: tell the newsletter and the notifications function, and ask for its translations when the site translates on publish
943
- (``languages.auto``; docs/story-translation-procedure.md). Neither can fail the publish, which is already done. A translation request that could
944
- not be written is logged and left for ``papyrus stories localize --all``, which finds every Story with no up-to-date translation."""
945
- announce_published(item_id, published_item_id)
965
+ def story_is_live(client, item_id: str, published_item_id: str | None) -> None:
966
+ """A Story's page is live: ask for its translations when the site translates on publish (``languages.auto``; docs/story-translation-procedure.md). It cannot fail
967
+ the publish, which is already done. A translation request that could not be written is logged and left for ``papyrus stories localize --all``, which finds every
968
+ Story with no up-to-date translation. Nothing here tells the newsletter, the notifications function or any announcement: the Story's own record entering the
969
+ published stage reaches the announce agent through the Item change feed (docs/announcement-records.md), so a publish writes only its own records."""
946
970
  try:
947
971
  from papyrus_content.localize.auto import request_translations
948
972
 
@@ -15,11 +15,9 @@ import { pythonLambdaCode } from "../../functions/shared/python-bundle.js";
15
15
  import { resolveNewsletterConfig } from "./config.js";
16
16
  import { newsletterOps } from "./ops/resource.js";
17
17
  import { NEWSLETTER_MUTATIONS, NEWSLETTER_QUERIES, newsletterSchemaDefinitions } from "./schema.js";
18
- import { functionArn, newsletterFunctionName, wireSending } from "./sending.js";
18
+ import { newsletterFunctionName, wireSending } from "./sending.js";
19
19
  export { resolveNewsletterConfig };
20
20
  export const NEWSLETTER_OUTPUT_KEY = "newsletter";
21
- /** Set on the site's content-actions function: it invokes this function (`item-published`) after a real publish. Unset: no alerts. */
22
- export const NEWSLETTER_FUNCTION_ENV = "PAPYRUS_NEWSLETTER_FUNCTION";
23
21
  export const NEWSLETTER_HANDLER = "papyrus_content.newsletter.handler.handler";
24
22
  /** `boto3` is bundled because the runtime's copy may predate SESv2 `Simple.Headers` (List-Unsubscribe). */
25
23
  export const NEWSLETTER_REQUIREMENTS = ["PyYAML>=6.0.2,<7", "citeproc-py>=0.8.2,<1", "anthus-markus==0.7.0", "Pillow>=11.3,<12", "boto3>=1.35.8,<2"];
@@ -237,15 +235,6 @@ export const newsletterPlugin = {
237
235
  });
238
236
  alarm.addAlarmAction(new SnsAction(alarmTopic));
239
237
  }
240
- // The publish path tells this function about a real publish. The ARN is spelled out (not referenced) so the content-actions
241
- // stack does not depend on this one, and the grant is for this one function only.
242
- const contentActions = context.contentActionsLambda;
243
- contentActions.addEnvironment(NEWSLETTER_FUNCTION_ENV, newsletterFunctionName(config.siteId));
244
- contentActions.addToRolePolicy(new PolicyStatement({
245
- effect: Effect.ALLOW,
246
- actions: ["lambda:InvokeFunction"],
247
- resources: [functionArn(Stack.of(contentActions), newsletterFunctionName(config.siteId))],
248
- }));
249
238
  lambda.addPermission("InvokeFromCmsCompute", {
250
239
  principal: new ArnPrincipal(config.computeRoleArn),
251
240
  action: "lambda:InvokeFunction",
@@ -16,14 +16,12 @@ import type { PapyrusPlugin, PluginManifest, PluginWiringContext } from "../type
16
16
  import { resolveNewsletterConfig, type NewsletterConfig } from "./config";
17
17
  import { newsletterOps } from "./ops/resource";
18
18
  import { NEWSLETTER_MUTATIONS, NEWSLETTER_QUERIES, newsletterSchemaDefinitions } from "./schema";
19
- import { functionArn, newsletterFunctionName, wireSending } from "./sending";
19
+ import { newsletterFunctionName, wireSending } from "./sending";
20
20
 
21
21
  export { resolveNewsletterConfig };
22
22
  export type { NewsletterConfig };
23
23
 
24
24
  export const NEWSLETTER_OUTPUT_KEY = "newsletter";
25
- /** Set on the site's content-actions function: it invokes this function (`item-published`) after a real publish. Unset: no alerts. */
26
- export const NEWSLETTER_FUNCTION_ENV = "PAPYRUS_NEWSLETTER_FUNCTION";
27
25
  export const NEWSLETTER_HANDLER = "papyrus_content.newsletter.handler.handler";
28
26
  /** `boto3` is bundled because the runtime's copy may predate SESv2 `Simple.Headers` (List-Unsubscribe). */
29
27
  export const NEWSLETTER_REQUIREMENTS = ["PyYAML>=6.0.2,<7", "citeproc-py>=0.8.2,<1", "anthus-markus==0.7.0", "Pillow>=11.3,<12", "boto3>=1.35.8,<2"];
@@ -276,18 +274,6 @@ export const newsletterPlugin: PapyrusPlugin<NewsletterConfig, { newsletterOps:
276
274
  alarm.addAlarmAction(new SnsAction(alarmTopic));
277
275
  }
278
276
 
279
- // The publish path tells this function about a real publish. The ARN is spelled out (not referenced) so the content-actions
280
- // stack does not depend on this one, and the grant is for this one function only.
281
- const contentActions = context.contentActionsLambda;
282
- contentActions.addEnvironment(NEWSLETTER_FUNCTION_ENV, newsletterFunctionName(config.siteId));
283
- contentActions.addToRolePolicy(
284
- new PolicyStatement({
285
- effect: Effect.ALLOW,
286
- actions: ["lambda:InvokeFunction"],
287
- resources: [functionArn(Stack.of(contentActions), newsletterFunctionName(config.siteId))],
288
- }),
289
- );
290
-
291
277
  lambda.addPermission("InvokeFromCmsCompute", {
292
278
  principal: new ArnPrincipal(config.computeRoleArn),
293
279
  action: "lambda:InvokeFunction",
@@ -14,13 +14,11 @@ import { fileURLToPath } from "node:url";
14
14
  import { pythonLambdaCode } from "../../functions/shared/python-bundle.js";
15
15
  import { SecureStringParameter } from "../newsletter/secure-string-parameter.js";
16
16
  import { ALARM_MINIMUM_SENDS, BOUNCE_RATE_THRESHOLD, COMPLAINT_RATE_THRESHOLD } from "../newsletter/papyrus.plugin.js";
17
- import { functionArn, postalAddressParameterArns } from "../newsletter/sending.js";
17
+ import { postalAddressParameterArns } from "../newsletter/sending.js";
18
18
  import { resolveNotificationsConfig } from "./config.js";
19
19
  import { siteApiEnvironment } from "../../site-api-access.js";
20
20
  export { resolveNotificationsConfig };
21
21
  export const NOTIFICATIONS_OUTPUT_KEY = "notifications";
22
- /** Set on the site's content-actions function: it invokes the router function (`story-published`) after a real publish. Unset: no notices. */
23
- export const NOTIFICATIONS_FUNCTION_ENV = "PAPYRUS_NOTIFICATIONS_FUNCTION";
24
22
  export const HANDLERS = {
25
23
  router: "papyrus_content.notifications.handler.router",
26
24
  email: "papyrus_content.notifications.handler.email",
@@ -352,16 +350,7 @@ export const notificationsPlugin = {
352
350
  treatMissingData: TreatMissingData.NOT_BREACHING,
353
351
  });
354
352
  }
355
- // The publish path tells the router about a real publish. The ARN is spelled out (not referenced) so the content-actions
356
- // stack does not depend on this one, and the grant is for this one function only.
357
- const contentActions = context.contentActionsLambda;
358
- contentActions.addEnvironment(NOTIFICATIONS_FUNCTION_ENV, notificationsFunctionName(config.siteId));
359
- contentActions.addToRolePolicy(new PolicyStatement({
360
- effect: Effect.ALLOW,
361
- actions: ["lambda:InvokeFunction"],
362
- resources: [functionArn(Stack.of(contentActions), notificationsFunctionName(config.siteId))],
363
- }));
364
- // The CMS routes are the only other caller.
353
+ // The CMS routes are the only caller: a publish tells this function nothing (the announce agent is woken by the Item change feed).
365
354
  router.addPermission("InvokeFromCmsCompute", { principal: new ArnPrincipal(config.computeRoleArn), action: "lambda:InvokeFunction" });
366
355
  backend.addOutput({ custom: { [NOTIFICATIONS_OUTPUT_KEY]: { actionsFunction: router.functionName } } });
367
356
  },
@@ -14,7 +14,7 @@ import { fileURLToPath } from "node:url";
14
14
  import { pythonLambdaCode } from "../../functions/shared/python-bundle";
15
15
  import { SecureStringParameter } from "../newsletter/secure-string-parameter";
16
16
  import { ALARM_MINIMUM_SENDS, BOUNCE_RATE_THRESHOLD, COMPLAINT_RATE_THRESHOLD } from "../newsletter/papyrus.plugin";
17
- import { functionArn, postalAddressParameterArns } from "../newsletter/sending";
17
+ import { postalAddressParameterArns } from "../newsletter/sending";
18
18
  import type { PapyrusPlugin, PluginManifest, PluginWiringContext } from "../types";
19
19
  import { resolveNotificationsConfig, type NotificationsConfig } from "./config";
20
20
  import { siteApiEnvironment } from "../../site-api-access";
@@ -23,8 +23,6 @@ export { resolveNotificationsConfig };
23
23
  export type { NotificationsConfig };
24
24
 
25
25
  export const NOTIFICATIONS_OUTPUT_KEY = "notifications";
26
- /** Set on the site's content-actions function: it invokes the router function (`story-published`) after a real publish. Unset: no notices. */
27
- export const NOTIFICATIONS_FUNCTION_ENV = "PAPYRUS_NOTIFICATIONS_FUNCTION";
28
26
  export const HANDLERS = {
29
27
  router: "papyrus_content.notifications.handler.router",
30
28
  email: "papyrus_content.notifications.handler.email",
@@ -383,18 +381,7 @@ export const notificationsPlugin: PapyrusPlugin<NotificationsConfig, Record<stri
383
381
  });
384
382
  }
385
383
 
386
- // The publish path tells the router about a real publish. The ARN is spelled out (not referenced) so the content-actions
387
- // stack does not depend on this one, and the grant is for this one function only.
388
- const contentActions = context.contentActionsLambda;
389
- contentActions.addEnvironment(NOTIFICATIONS_FUNCTION_ENV, notificationsFunctionName(config.siteId));
390
- contentActions.addToRolePolicy(
391
- new PolicyStatement({
392
- effect: Effect.ALLOW,
393
- actions: ["lambda:InvokeFunction"],
394
- resources: [functionArn(Stack.of(contentActions), notificationsFunctionName(config.siteId))],
395
- }),
396
- );
397
- // The CMS routes are the only other caller.
384
+ // The CMS routes are the only caller: a publish tells this function nothing (the announce agent is woken by the Item change feed).
398
385
  router.addPermission("InvokeFromCmsCompute", { principal: new ArnPrincipal(config.computeRoleArn), action: "lambda:InvokeFunction" });
399
386
 
400
387
  backend.addOutput({ custom: { [NOTIFICATIONS_OUTPUT_KEY]: { actionsFunction: router.functionName } } });
@@ -10,7 +10,7 @@ import { hasEditorRights } from "../lib/staff-groups";
10
10
  import { isEditorialWorkAssignment } from "../lib/newsroom-assignments";
11
11
  import { isLocalPreviewEnabled } from "../lib/local-preview";
12
12
  import { AUTO_ACCEPTED_PAGE_SIZE, autoAcceptedFromRecords, autoAcceptedServerFilter, collectAutoAcceptedPage, type AutoAcceptedPage } from "../lib/auto-accepted-references";
13
- import { createLocalPreviewAssignments, createLocalPreviewContentItemVersions, createLocalPreviewReferences, createLocalPreviewScheduledVersions } from "../lib/local-preview-seed";
13
+ import { createLocalPreviewAssignments, createLocalPreviewContentItemVersions, createLocalPreviewPublishedStories, createLocalPreviewReferences, createLocalPreviewScheduledVersions } from "../lib/local-preview-seed";
14
14
  import { generateClient } from "aws-amplify/data";
15
15
  import { testEditorOverrideAllowed } from "../lib/test-editor-override";
16
16
  import { downloadData, getUrl } from "aws-amplify/storage";
@@ -69,7 +69,8 @@ import {
69
69
  } from "../lib/conversation";
70
70
  import { LINK_MESSAGE_HASHTAGS_MUTATION, messageHasHashtag, postMessageArguments, postMessageMutation } from "../lib/post-message";
71
71
  import { isStoryItemType, legacyStageKeysToLoad, type ContentItemVersionRecord } from "../lib/content-item-lifecycle";
72
- import { readScheduledRange, SCHEDULE_PAGE_STATES, type ScheduleQueryFetch } from "../lib/story-schedule-query";
72
+ import { readPublishedRange, readScheduledRange, SCHEDULE_PAGE_STATES, type PublishedQueryFetch, type PublishedStoryRow, type ScheduleQueryFetch } from "../lib/story-schedule-query";
73
+ import { ALWAYS_PROJECTED, siteStoryTypes } from "../lib/site-story-types";
73
74
  import { readStoryStageChangesSince, readStoryStagePage, STORY_STAGE_PAGE_LIMIT, type StageQueryFetch } from "../lib/story-stage-query";
74
75
  import { readWithStoryStageIndex } from "../lib/story-stage-mode";
75
76
  import { getContentItemStageDefinitions } from "../lib/site-brand";
@@ -2560,6 +2561,12 @@ export async function loadNewsroomScheduledStories(from: string, to: string): Pr
2560
2561
  return readScheduledRange(contentItemStageFetch() as ScheduleQueryFetch, from, to);
2561
2562
  }
2562
2563
 
2564
+ /** Every Story first published between two UTC instants, read from the PublishedItem `typeStatus` + `publishedAt` index (lib/story-schedule-query.ts). */
2565
+ export async function loadNewsroomPublishedStories(from: string, to: string): Promise<PublishedStoryRow[]> {
2566
+ if (isLocalPreviewEnabled()) return createLocalPreviewPublishedStories(from, to);
2567
+ return readPublishedRange(contentItemStageFetch() as unknown as PublishedQueryFetch, [...siteStoryTypes().types, ...ALWAYS_PROJECTED], from, to);
2568
+ }
2569
+
2563
2570
  export async function loadModelPayloadsForOwner(
2564
2571
  ownerKind: string,
2565
2572
  ownerId: string,
@@ -218,6 +218,7 @@ export function NewsroomArticleEditor({ articleId, demo, embedded = false, stars
218
218
  };
219
219
  }, [activeArticleId, backend, blocked, isNew, reloadToken]);
220
220
 
221
+ const loadedVersionNumber = editor?.versionNumber ?? null; // a version saved from this drawer changes what "newer than the scheduled one" means, so the schedule is read again
221
222
  useEffect(() => {
222
223
  setScheduleKnown(false);
223
224
  if (!scheduleZone || !lineageId) { setSchedule(undefined); return; }
@@ -227,7 +228,7 @@ export function NewsroomArticleEditor({ articleId, demo, embedded = false, stars
227
228
  .then((result) => { if (!cancelled) { setSchedule(scheduleFromEntries(result.schedules)); setScheduleKnown(true); } })
228
229
  .catch((error: unknown) => { if (!cancelled) setNotice({ tone: "error", text: `The schedule could not be read. ${failureMessage(error)}` }); });
229
230
  return () => { cancelled = true; };
230
- }, [backend, lineageId, scheduleZone, reloadToken]);
231
+ }, [backend, lineageId, scheduleZone, reloadToken, loadedVersionNumber]);
231
232
 
232
233
  const savedItemId = editor?.id ?? null;
233
234
  useEffect(() => {
@@ -768,6 +769,7 @@ export function NewsroomArticleEditor({ articleId, demo, embedded = false, stars
768
769
  zone={scheduleZone}
769
770
  schedule={schedule}
770
771
  blockedReason={editor.dirty ? "Save your changes first: a schedule publishes the saved version." : isOlderVersion ? "This is an older version of the Story." : null}
772
+ suggest={() => backend.actions.scheduleSuggest({ storyLineageId: lineageId })}
771
773
  save={async (scheduledPublishAt) => {
772
774
  const saved = scheduleFromResult(await backend.actions.scheduleStory({ itemId: editor.id!, lineageId, scheduledPublishAt }));
773
775
  setSchedule(saved);
@@ -4,7 +4,7 @@ import dynamic from "next/dynamic";
4
4
  import Link from "next/link";
5
5
  import { useRouter } from "next/navigation";
6
6
  import { useCallback, useEffect, useRef, useState } from "react";
7
- import { CalendarClock } from "lucide-react";
7
+ import { CalendarClock, TriangleAlert, Undo2 } from "lucide-react";
8
8
  import "./newsroom-theme";
9
9
  import { canReadNewsroomBoard, contentItemBoardPathSegment } from "../lib/newsroom-board";
10
10
  import { displayNewsroomSectionShortTitle } from "../lib/newsroom-sections";
@@ -13,14 +13,16 @@ import { newsroomHref } from "../lib/newsroom-base-path";
13
13
  import { SITE_BRAND } from "../lib/site-brand";
14
14
  import { useScheduleZone } from "../lib/schedule-zone";
15
15
  import { formatScheduleTime, scheduleFromFields, scheduleWording, zoneCity } from "../lib/story-schedule";
16
+ import { isLocalPreviewEnabled } from "../lib/local-preview";
17
+ import { resolveArticlesBackend } from "../lib/newsroom-articles";
18
+ import type { PublishedStoryRow } from "../lib/story-schedule-query";
16
19
  import type { ContentItemVersionRecord } from "../lib/content-item-lifecycle";
17
20
  import type { NewsroomSectionRecord } from "../lib/category-repository";
18
- import { loadNewsroomScheduledStories } from "./news-desk-taxonomy-client";
21
+ import { loadNewsroomPublishedStories, loadNewsroomScheduledStories } from "./news-desk-taxonomy-client";
19
22
  import { NewsDeskAccessGate } from "./newsroom-access-gate";
20
23
  import { useOptionalNewsDeskClient } from "./news-desk-client-provider";
21
24
  import { NewsroomOpsShell, NewsroomOpsStatusBanner } from "./newsroom-ops-shell";
22
- import { SCHEDULE_ICONS } from "./story-schedule-badge";
23
- import type { ScheduleCalendarItem, ScheduleView } from "./schedule-calendar";
25
+ import { SCHEDULE_ITEM_ICONS, canDrag, type RescheduleOutcome, type ScheduleCalendarItem, type ScheduleView } from "./schedule-calendar";
24
26
 
25
27
  /** FullCalendar is about 80 kB; it loads here and nowhere else. */
26
28
  const ScheduleCalendar = dynamic(() => import("./schedule-calendar"), {
@@ -29,6 +31,9 @@ const ScheduleCalendar = dynamic(() => import("./schedule-calendar"), {
29
31
  });
30
32
 
31
33
  const STATE_WORD = { scheduled: "Scheduled", overdue: "Overdue", superseded: "Superseded" } as const;
34
+ /** The backend's own words for a time that has passed; the drop is refused here first, so nothing is sent. */
35
+ const PAST_DROP_MESSAGE = "That time has passed.";
36
+ type Notice = { tone: "done" | "problem"; text: string; undo?: () => void };
32
37
  const EMPTY_TEXT: Record<ScheduleView, string> = { day: "Nothing is scheduled today.", week: "Nothing is scheduled this week.", month: "Nothing is scheduled this month." };
33
38
 
34
39
  /** A phone shows the lists: the seven-day grid does not fit 375 pixels. */
@@ -45,8 +50,9 @@ function usePhone(): boolean | null {
45
50
  }
46
51
 
47
52
  /**
48
- * The Schedule page: the Stories that are scheduled, overdue or superseded, by day, week or month in the publication's time zone, with a
49
- * plain list of the same items under the calendar for keyboard and screen-reader use. It reads one time range of the schedule index at a time.
53
+ * The Schedule page: the Stories that are scheduled, overdue or superseded, and the ones published in the same range, by day, week or month in the publication's
54
+ * time zone, with a plain list of the same items under the calendar for keyboard and screen-reader use. It reads one time range of the schedule index and of the
55
+ * published index at a time. Dragging a scheduled Story to a new time reschedules it through the same operation as the drawer and offers Undo.
50
56
  */
51
57
  export function NewsroomSchedulePage() {
52
58
  const session = useOptionalNewsDeskClient();
@@ -57,20 +63,55 @@ export function NewsroomSchedulePage() {
57
63
  const [range, setRange] = useState<{ from: string; to: string; view: ScheduleView } | null>(null);
58
64
  const [rows, setRows] = useState<ReturnType<typeof scheduleRows> | null>(null);
59
65
  const [error, setError] = useState<string | null>(null);
66
+ const [notice, setNotice] = useState<Notice | null>(null);
60
67
  const request = useRef(0);
68
+ const shown = useRef<ReturnType<typeof scheduleRows> | null>(null);
69
+ shown.current = rows;
61
70
 
62
71
  useEffect(() => {
63
72
  if (!allowed || !zone || !range) return;
64
- const current = ++request.current;
73
+ const mine = ++request.current;
65
74
  setError(null);
66
- loadNewsroomScheduledStories(range.from, range.to).then(versions => {
67
- if (request.current === current) setRows(scheduleRows(versions, zone));
75
+ setNotice(null);
76
+ Promise.all([loadNewsroomScheduledStories(range.from, range.to), loadNewsroomPublishedStories(range.from, range.to)]).then(([versions, published]) => {
77
+ if (request.current === mine) setRows(scheduleRows(versions, published, zone));
68
78
  }, reason => {
69
- if (request.current === current) setError(reason instanceof Error ? reason.message : "The schedule could not be loaded.");
79
+ if (request.current === mine) setError(reason instanceof Error ? reason.message : "The schedule could not be loaded.");
70
80
  });
71
81
  }, [allowed, zone, range]);
72
82
 
73
83
  const onRange = useCallback((next: { from: string; to: string; view: ScheduleView }) => setRange(previous => previous && previous.from === next.from && previous.to === next.to && previous.view === next.view ? previous : next), []);
84
+ /** Moves one scheduled Story to a UTC instant and shows the result in the calendar and the list; a refusal changes nothing. */
85
+ const move = useCallback(async (id: string, at: string): Promise<{ ok: true; from: string } | { ok: false; message: string }> => {
86
+ const item = shown.current?.items.find(candidate => candidate.id === id);
87
+ if (!item || !canDrag(item)) return { ok: false, message: "That Story cannot be moved here." };
88
+ if (Date.parse(at) <= Date.now()) return { ok: false, message: PAST_DROP_MESSAGE };
89
+ try {
90
+ await resolveArticlesBackend(isLocalPreviewEnabled()).actions.scheduleStory({ itemId: id, lineageId: item.lineageId, scheduledPublishAt: at });
91
+ } catch (reason) {
92
+ return { ok: false, message: reason instanceof Error ? reason.message : "The schedule could not be saved." };
93
+ }
94
+ setRows(previous => previous && zone ? { items: moveItem(previous.items, id, at, zone) } : previous);
95
+ return { ok: true, from: item.at };
96
+ }, [zone]);
97
+
98
+ const reschedule = useCallback(async (id: string, at: string): Promise<RescheduleOutcome> => {
99
+ const item = shown.current?.items.find(candidate => candidate.id === id);
100
+ const outcome = await move(id, at);
101
+ if (!zone || !item) return { ok: false, message: "That Story cannot be moved here." };
102
+ if (!outcome.ok) {
103
+ setNotice({ tone: "problem", text: `${outcome.message} “${item.title}” stays at ${formatScheduleTime(item.at, zone)}.` });
104
+ return outcome;
105
+ }
106
+ setNotice({
107
+ tone: "done", text: `Rescheduled “${item.title}” for ${formatScheduleTime(at, zone)}.`,
108
+ undo: () => { void move(id, outcome.from).then(back => setNotice(back.ok
109
+ ? { tone: "done", text: `“${item.title}” is back at ${formatScheduleTime(outcome.from, zone)}.` }
110
+ : { tone: "problem", text: `${back.message} “${item.title}” stays at ${formatScheduleTime(at, zone)}.` })); },
111
+ });
112
+ return { ok: true };
113
+ }, [move, zone]);
114
+
74
115
  const storyHref = (itemId: string) => getNewsroomNavHref(`/newsroom/articles/${encodeURIComponent(itemId)}`);
75
116
 
76
117
  if (!allowed) return <NewsDeskAccessGate shell={session?.shell ?? null} />;
@@ -82,8 +123,13 @@ export function NewsroomSchedulePage() {
82
123
  : <>
83
124
  <p className="schedule-zone-note" data-schedule-zone>All times are {zoneCity(zone)} time.</p>
84
125
  {error ? <NewsroomOpsStatusBanner tone="error">{error}</NewsroomOpsStatusBanner> : null}
85
- {phone === null ? null : <ScheduleCalendar items={rows?.items ?? []} zone={zone} phone={phone} onRange={onRange} onOpen={id => { const row = rows?.items.find(item => item.id === id); if (row) router.push(storyHref(id)); }} />}
86
- {rows && rows.items.length === 0 && range ? <p className="schedule-empty" data-schedule-empty role="status">
126
+ {phone === null ? null : <ScheduleCalendar items={rows?.items ?? []} zone={zone} phone={phone} onRange={onRange} onOpen={id => { const row = rows?.items.find(item => item.id === id); if (row) router.push(storyHref(id)); }} onReschedule={reschedule} />}
127
+ {notice ? <p className="schedule-notice" data-schedule-notice data-schedule-notice-tone={notice.tone} role={notice.tone === "problem" ? "alert" : "status"}>
128
+ {notice.tone === "problem" ? <TriangleAlert aria-hidden size={14} /> : <CalendarClock aria-hidden size={14} />}
129
+ <span>{notice.text}</span>
130
+ {notice.undo ? <button type="button" data-schedule-undo onClick={notice.undo}><Undo2 aria-hidden size={14} />Undo</button> : null}
131
+ </p> : null}
132
+ {rows && rows.items.every(item => item.kind === "published") && range ? <p className="schedule-empty" data-schedule-empty role="status">
87
133
  {EMPTY_TEXT[range.view]}
88
134
  <Link href={newsroomHref(contentItemBoardPathSegment())}><CalendarClock aria-hidden size={14} />Schedule a Story</Link>
89
135
  </p> : null}
@@ -91,7 +137,7 @@ export function NewsroomSchedulePage() {
91
137
  <h2 id="schedule-list-heading">Everything in this view, as a list</h2>
92
138
  <ol className="schedule-list">
93
139
  {rows.items.map(item => {
94
- const Icon = SCHEDULE_ICONS[item.kind];
140
+ const Icon = SCHEDULE_ITEM_ICONS[item.kind];
95
141
  return <li className="schedule-list-item" key={item.id} data-schedule-item={item.id} data-schedule-kind={item.kind}>
96
142
  <Link href={storyHref(item.id)}>{item.title}</Link>
97
143
  <small><Icon aria-hidden size={12} /><span>{item.state}: {formatScheduleTime(item.at, zone, true)}{item.section ? ` · ${item.section}` : ""}</span></small>
@@ -104,7 +150,10 @@ export function NewsroomSchedulePage() {
104
150
  </NewsroomOpsShell>;
105
151
  }
106
152
 
107
- function scheduleRows(versions: readonly ContentItemVersionRecord[], zone: string): { items: ScheduleCalendarItem[] } {
153
+ const sectionTitle = (section: string | null | undefined) => section ? displayNewsroomSectionShortTitle({ id: section } as NewsroomSectionRecord) : null;
154
+
155
+ /** Scheduled, overdue and superseded Stories from the schedule index, with the Stories published in the same range, earliest first. */
156
+ function scheduleRows(versions: readonly ContentItemVersionRecord[], published: readonly PublishedStoryRow[], zone: string): { items: ScheduleCalendarItem[] } {
108
157
  const now = new Date();
109
158
  const items: ScheduleCalendarItem[] = [];
110
159
  for (const version of versions) {
@@ -112,11 +161,24 @@ function scheduleRows(versions: readonly ContentItemVersionRecord[], zone: strin
112
161
  if (!schedule) continue;
113
162
  const wording = scheduleWording(schedule, zone, now);
114
163
  items.push({
115
- id: version.id,
164
+ id: version.id, lineageId: version.lineageId ?? version.id,
116
165
  title: version.headline || version.title || version.slug,
117
- section: version.section ? displayNewsroomSectionShortTitle({ id: version.section } as NewsroomSectionRecord) : null,
166
+ section: sectionTitle(version.section),
118
167
  at: schedule.at, kind: wording.kind, state: STATE_WORD[wording.kind], label: wording.label,
119
168
  });
120
169
  }
121
- return { items };
170
+ for (const story of published) {
171
+ items.push({
172
+ id: story.id, lineageId: story.lineageId, title: story.title, section: sectionTitle(story.section),
173
+ at: story.publishedAt, kind: "published", state: "Published", label: `Published ${formatScheduleTime(story.publishedAt, zone)}`,
174
+ });
175
+ }
176
+ return { items: items.sort((left, right) => left.at.localeCompare(right.at) || left.id.localeCompare(right.id)) };
177
+ }
178
+
179
+ /** The same items with one scheduled Story at its new time, worded again for it. */
180
+ function moveItem(items: readonly ScheduleCalendarItem[], id: string, at: string, zone: string): ScheduleCalendarItem[] {
181
+ const wording = scheduleWording({ at, state: "scheduled", by: null, scheduledAt: null }, zone, new Date());
182
+ return items.map(item => item.id !== id ? item : { ...item, at, kind: wording.kind, state: STATE_WORD[wording.kind], label: wording.label })
183
+ .sort((left, right) => left.at.localeCompare(right.at) || left.id.localeCompare(right.id));
122
184
  }
@@ -28,3 +28,4 @@
28
28
  .schedule-calendar .schedule-event[data-schedule-kind=overdue]{background:color-mix(in oklab,var(--org-ink) 22%,var(--org-paper))}
29
29
  .schedule-calendar .schedule-event[data-schedule-kind=scheduled]{background:color-mix(in oklab,var(--org-accent) 22%,var(--org-paper))}
30
30
  .schedule-calendar :focus-visible{outline:2px solid var(--org-ink);outline-offset:1px}
31
+ .schedule-calendar .schedule-event[data-schedule-kind=published]{background:color-mix(in oklab,var(--org-ink) 7%,var(--org-paper))}
@@ -5,19 +5,26 @@ import classicTheme from "@fullcalendar/react/themes/classic";
5
5
  import dayGrid from "@fullcalendar/react/daygrid";
6
6
  import timeGrid from "@fullcalendar/react/timegrid";
7
7
  import list from "@fullcalendar/react/list";
8
+ import interaction from "@fullcalendar/react/interaction";
8
9
  import "@fullcalendar/react/skeleton.css";
9
10
  import "@fullcalendar/react/themes/classic/theme.css";
10
11
  import "./schedule-calendar.css";
12
+ import { CircleCheck, type LucideIcon } from "lucide-react";
11
13
  import { SCHEDULE_ICONS } from "./story-schedule-badge";
12
14
  import type { ScheduleKind } from "../lib/story-schedule";
13
15
 
16
+ /** What an item on the page is: a schedule state, or a Story that already went out. */
17
+ export type ScheduleItemKind = ScheduleKind | "published";
18
+ export const SCHEDULE_ITEM_ICONS: Record<ScheduleItemKind, LucideIcon> = { ...SCHEDULE_ICONS, published: CircleCheck };
19
+
14
20
  export type ScheduleCalendarItem = {
15
21
  id: string;
16
22
  title: string;
17
23
  section: string | null;
18
- /** The UTC instant. */
24
+ lineageId: string;
25
+ /** The UTC instant: when it goes live, or when it went live. */
19
26
  at: string;
20
- kind: ScheduleKind;
27
+ kind: ScheduleItemKind;
21
28
  /** The state in one or two words: Scheduled, Overdue, Superseded, Published. */
22
29
  state: string;
23
30
  /** Every fact, for a screen reader. */
@@ -25,6 +32,9 @@ export type ScheduleCalendarItem = {
25
32
  };
26
33
 
27
34
  export type ScheduleView = "day" | "week" | "month";
35
+ export type RescheduleOutcome = { ok: true } | { ok: false; message: string };
36
+ /** Only a Story that is still waiting for its time moves by dragging; an overdue, superseded or published one is changed in its drawer or not at all. */
37
+ export const canDrag = (item: Pick<ScheduleCalendarItem, "kind">): boolean => item.kind === "scheduled";
28
38
  const VIEWS = {
29
39
  wide: { initial: "timeGridWeek", right: "timeGridDay,timeGridWeek,dayGridMonth", of: { timeGridDay: "day", timeGridWeek: "week", dayGridMonth: "month" } },
30
40
  phone: { initial: "listWeek", right: "listDay,listWeek,listMonth", of: { listDay: "day", listWeek: "week", listMonth: "month" } },
@@ -35,26 +45,31 @@ const clockTime = (iso: string, zone: string) => new Intl.DateTimeFormat("en-US"
35
45
  /**
36
46
  * FullCalendar 7 in the publication's named time zone, loaded only on the Schedule page. Week is the default; Day and Month switch; a phone gets the lists of
37
47
  * the same three spans because the seven-day grid does not fit 375 pixels. Events are focusable (`eventInteractive`) and open the Story. The page owns the data:
38
- * the calendar reports the range on screen and shows the items it is given.
48
+ * the calendar reports the range on screen and shows the items it is given. A scheduled Story can be dragged in the week, day and month grids: the drop asks the
49
+ * page to reschedule it (which revalidates the time with the backend) and the calendar puts it back when the page says no.
39
50
  */
40
- export default function ScheduleCalendar({ items, zone, phone, onRange, onOpen }: {
51
+ export default function ScheduleCalendar({ items, zone, phone, onRange, onOpen, onReschedule }: {
41
52
  items: readonly ScheduleCalendarItem[];
42
53
  zone: string;
43
54
  phone: boolean;
44
55
  onRange: (range: { from: string; to: string; view: ScheduleView }) => void;
45
56
  onOpen: (id: string) => void;
57
+ /** Asks to move a Story to a UTC instant; the calendar reverts the drop on a refusal. */
58
+ onReschedule: (id: string, at: string) => Promise<RescheduleOutcome>;
46
59
  }) {
47
60
  const views = phone ? VIEWS.phone : VIEWS.wide;
48
61
  return <div className="schedule-calendar" data-schedule-calendar data-schedule-layout={phone ? "list" : "grid"}>
49
62
  <FullCalendar
50
63
  key={phone ? "phone" : "wide"}
51
- plugins={[classicTheme, dayGrid, timeGrid, list]}
64
+ plugins={[classicTheme, dayGrid, timeGrid, list, interaction]}
52
65
  timeZone={zone}
53
66
  initialView={views.initial}
54
67
  headerToolbar={{ left: "prev,next today", center: "title", right: views.right }}
55
68
  buttons={{ today: { text: "Today" }, ...Object.fromEntries(Object.entries(views.of).map(([view, span]) => [view, { text: span[0].toUpperCase() + span.slice(1) }])) }}
56
- events={items.map(item => ({ id: item.id, title: item.title, start: item.at, extendedProps: item }))}
69
+ events={items.map(item => ({ id: item.id, title: item.title, start: item.at, startEditable: canDrag(item), extendedProps: item }))}
57
70
  eventInteractive
71
+ eventDurationEditable={false}
72
+ eventDrop={arg => { void onReschedule(arg.event.id, new Date(arg.event.startStr).toISOString()).then(outcome => { if (!outcome.ok) arg.revert(); }); }}
58
73
  eventDisplay="block"
59
74
  defaultTimedEventDuration="02:00"
60
75
  height="auto"
@@ -62,7 +77,7 @@ export default function ScheduleCalendar({ items, zone, phone, onRange, onOpen }
62
77
  eventClick={arg => { arg.jsEvent.preventDefault(); onOpen(arg.event.id); }}
63
78
  eventContent={arg => {
64
79
  const item = arg.event.extendedProps as ScheduleCalendarItem;
65
- const Icon = SCHEDULE_ICONS[item.kind];
80
+ const Icon = SCHEDULE_ITEM_ICONS[item.kind];
66
81
  return <span className="schedule-event" data-schedule-kind={item.kind} title={item.label}>
67
82
  <Icon aria-hidden size={13} />
68
83
  <span className="schedule-event-text">
@@ -1,9 +1,12 @@
1
1
  "use client";
2
2
 
3
3
  import { useEffect, useId, useState } from "react";
4
- import { CalendarClock, CalendarX2, Pencil } from "lucide-react";
4
+ import { CalendarClock, CalendarSearch, CalendarX2, Pencil } from "lucide-react";
5
+ import type { ScheduleSuggestResult } from "../lib/content-actions-client";
5
6
  import {
7
+ NEWER_VERSION_NOTE,
6
8
  PAST_TIME_MESSAGE,
9
+ SUGGESTION_BASIS,
7
10
  ownZoneTime,
8
11
  resolveWallTime,
9
12
  scheduleSentence,
@@ -25,7 +28,7 @@ function failureText(reason: unknown): string {
25
28
  * refuses it; what the editor typed stays in the form so nothing has to be typed again. A wall-clock time that does not exist (the spring-forward gap) is refused
26
29
  * here with a plain message; one that happens twice (fall back) asks which one. Publish now is the editor's own button and is not touched.
27
30
  */
28
- export function StorySchedulePanel({ zone, schedule, blockedReason, save, onChanged }: {
31
+ export function StorySchedulePanel({ zone, schedule, blockedReason, save, suggest, onChanged }: {
29
32
  zone: string;
30
33
  /** What was last saved. */
31
34
  schedule: StorySchedule | undefined;
@@ -33,6 +36,8 @@ export function StorySchedulePanel({ zone, schedule, blockedReason, save, onChan
33
36
  blockedReason: string | null;
34
37
  /** Saves a UTC instant, or clears with null, and returns the schedule the backend recorded. */
35
38
  save: (scheduledPublishAt: string | null) => Promise<StorySchedule | undefined>;
39
+ /** Asks for the time the publication's own rhythm suggests (the backend's `schedule_suggest`), or why there is none. */
40
+ suggest: () => Promise<ScheduleSuggestResult>;
36
41
  onChanged?: (schedule: StorySchedule | undefined) => void;
37
42
  }) {
38
43
  const ids = useId();
@@ -44,6 +49,9 @@ export function StorySchedulePanel({ zone, schedule, blockedReason, save, onChan
44
49
  const [chosen, setChosen] = useState<string | null>(null);
45
50
  const [problem, setProblem] = useState<string | null>(null);
46
51
  const [saving, setSaving] = useState(false);
52
+ /** What the picker says about the suggested time: its basis, or why there is none. Cleared as soon as the editor types a time of their own. */
53
+ const [suggestionNote, setSuggestionNote] = useState<string | null>(null);
54
+ const [asking, setAsking] = useState(false);
47
55
  const shown = optimistic ? optimistic.schedule : schedule;
48
56
  const now = new Date();
49
57
  const kind = shown ? scheduleKind(shown, now) : null;
@@ -52,7 +60,28 @@ export function StorySchedulePanel({ zone, schedule, blockedReason, save, onChan
52
60
 
53
61
  const open = () => {
54
62
  const start = shown ? wallTimeOf(shown.at, zone) : wallTimeOf(new Date(Date.now() + 24 * 3_600_000).toISOString(), zone);
55
- setDate(start.date); setTime(shown ? start.time : "09:00"); setChoices(null); setChosen(null); setProblem(null); setEditing(true);
63
+ setDate(start.date); setTime(shown ? start.time : "09:00"); setChoices(null); setChosen(null); setProblem(null); setSuggestionNote(null); setEditing(true);
64
+ };
65
+
66
+ /** Opens the picker on the suggested time, or on the time it already had with the reason there is no suggestion. The editor may pick any other time. */
67
+ const askForSuggestion = async () => {
68
+ setProblem(null); setAsking(true);
69
+ try {
70
+ const answer = await suggest();
71
+ if (!editing) open();
72
+ setChoices(null); setChosen(null);
73
+ if (answer.suggestion) {
74
+ const picked = wallTimeOf(answer.suggestion.at, zone);
75
+ setDate(picked.date); setTime(picked.time);
76
+ setSuggestionNote(SUGGESTION_BASIS);
77
+ } else {
78
+ setSuggestionNote(answer.reason ?? "No suggestion yet: this publication has no publishing history.");
79
+ }
80
+ } catch (reason) {
81
+ setProblem(failureText(reason));
82
+ } finally {
83
+ setAsking(false);
84
+ }
56
85
  };
57
86
 
58
87
  const apply = async (scheduledPublishAt: string | null) => {
@@ -89,7 +118,7 @@ export function StorySchedulePanel({ zone, schedule, blockedReason, save, onChan
89
118
  };
90
119
 
91
120
  const own = shown ? ownZoneTime(shown.at, zone) : null;
92
- const controlsOff = blockedReason !== null || saving;
121
+ const controlsOff = blockedReason !== null || saving || asking;
93
122
 
94
123
  return <section className="story-schedule" data-story-schedule-panel aria-labelledby={`${ids}-heading`}>
95
124
  <h3 className="story-schedule-heading" id={`${ids}-heading`}><CalendarClock aria-hidden size={15} />Schedule</h3>
@@ -100,16 +129,19 @@ export function StorySchedulePanel({ zone, schedule, blockedReason, save, onChan
100
129
  </p>
101
130
  {own ? <p className="story-schedule-own" data-story-schedule-own>{own}</p> : null}
102
131
  {kind === "superseded" ? <p className="story-schedule-note">A newer version was saved after this was scheduled. Schedule it again.</p> : null}
132
+ {shown.newerVersion && kind !== "superseded" ? <p className="story-schedule-note" data-story-schedule-newer-version>{NEWER_VERSION_NOTE}</p> : null}
133
+ {shown.notes?.map(note => <p className="story-schedule-note" key={note} data-story-schedule-rating-note>{note}</p>)}
103
134
  {kind === "overdue" ? <p className="story-schedule-note">It was not published at its time. Publish it now, or pick a new time.</p> : null}
104
135
  </div> : <p className="story-schedule-note" data-story-schedule-none>Not scheduled. Use Publish to publish now, or pick a time. Times are in {zoneCity(zone)} time.</p>}
105
136
  {problem && !editing ? <p className="story-schedule-problem" role="alert" data-story-schedule-problem>{problem}</p> : null}
106
137
  {editing ? <form className="story-schedule-form" data-story-schedule-form onSubmit={event => { event.preventDefault(); submit(); }}>
107
138
  <div className="story-schedule-fields">
108
139
  <label htmlFor={`${ids}-date`}>Date</label>
109
- <input id={`${ids}-date`} type="date" value={date} onChange={event => { setDate(event.target.value); setChoices(null); setChosen(null); }} data-story-schedule-date />
140
+ <input id={`${ids}-date`} type="date" value={date} onChange={event => { setDate(event.target.value); setChoices(null); setChosen(null); setSuggestionNote(null); }} data-story-schedule-date />
110
141
  <label htmlFor={`${ids}-time`}>Time ({zoneCity(zone)})</label>
111
- <input id={`${ids}-time`} type="time" value={time} onChange={event => { setTime(event.target.value); setChoices(null); setChosen(null); }} data-story-schedule-time />
142
+ <input id={`${ids}-time`} type="time" value={time} onChange={event => { setTime(event.target.value); setChoices(null); setChosen(null); setSuggestionNote(null); }} data-story-schedule-time />
112
143
  </div>
144
+ {suggestionNote ? <p className="story-schedule-note" data-story-schedule-suggestion><CalendarSearch aria-hidden size={14} />{suggestionNote}</p> : null}
113
145
  {choices ? <fieldset className="story-schedule-choices" data-story-schedule-choices>
114
146
  <legend>Which one?</legend>
115
147
  {choices.map(option => <label key={option.utc}>
@@ -120,12 +152,16 @@ export function StorySchedulePanel({ zone, schedule, blockedReason, save, onChan
120
152
  {problem ? <p className="story-schedule-problem" role="alert" data-story-schedule-problem>{problem}</p> : null}
121
153
  <div className="story-schedule-buttons">
122
154
  <button type="submit" className="story-schedule-button" disabled={saving} data-story-schedule-save><CalendarClock aria-hidden size={14} />Save schedule</button>
123
- <button type="button" className="story-schedule-button" onClick={() => { setEditing(false); setProblem(null); }} data-story-schedule-cancel>Cancel</button>
155
+ <button type="button" className="story-schedule-button" disabled={asking} onClick={() => void askForSuggestion()} data-story-schedule-suggest><CalendarSearch aria-hidden size={14} />Suggest a time</button>
156
+ <button type="button" className="story-schedule-button" onClick={() => { setEditing(false); setProblem(null); setSuggestionNote(null); }} data-story-schedule-cancel>Cancel</button>
124
157
  </div>
125
158
  </form> : <div className="story-schedule-buttons">
126
159
  <button type="button" className="story-schedule-button" disabled={controlsOff} onClick={open} data-story-schedule-open>
127
160
  {shown ? <Pencil aria-hidden size={14} /> : <CalendarClock aria-hidden size={14} />}{shown ? "Change time" : "Schedule…"}
128
161
  </button>
162
+ <button type="button" className="story-schedule-button" disabled={controlsOff} onClick={() => void askForSuggestion()} data-story-schedule-suggest>
163
+ <CalendarSearch aria-hidden size={14} />Suggest a time
164
+ </button>
129
165
  {shown ? <button type="button" className="story-schedule-button" disabled={controlsOff} onClick={() => void apply(null)} data-story-schedule-clear>
130
166
  <CalendarX2 aria-hidden size={14} />Unschedule
131
167
  </button> : null}
@@ -23,6 +23,7 @@
23
23
  .story-schedule-sentence{margin:0;font-size:13px}
24
24
  .story-schedule-own{margin:0;font-size:11px;color:var(--org-muted)}
25
25
  .story-schedule-note{margin:0;font-size:12px;color:var(--org-muted)}
26
+ .story-schedule-note svg{display:inline-block;vertical-align:-2px;margin-right:6px}
26
27
  .story-schedule-problem{margin:0;padding:8px 10px;border-radius:8px;background:color-mix(in oklab,var(--org-ink) 14%,var(--org-paper));font-size:12px;font-weight:600}
27
28
  .story-schedule-form{display:grid;gap:8px}
28
29
  .story-schedule-fields{display:grid;grid-template-columns:auto minmax(0,1fr);gap:6px 10px;align-items:center}
@@ -35,3 +36,7 @@
35
36
  .story-schedule-button{display:inline-flex;align-items:center;gap:6px;min-height:36px;padding:2px 12px;border:0;border-radius:8px;background:var(--card,var(--org-paper));color:var(--org-ink);font:600 12px var(--kb-theme-ui-font);cursor:pointer}
36
37
  .story-schedule-button:disabled{opacity:.6;cursor:default}
37
38
  .newsroom-organizer .story-schedule-button,.newsroom-organizer .story-schedule-fields input,.newsroom-organizer .story-schedule-badge{border-radius:8px !important}
39
+ .schedule-page .schedule-notice{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:0;padding:10px 14px;border-radius:12px;background:color-mix(in oklab,var(--org-accent) 18%,var(--org-paper));font-size:14px}
40
+ .schedule-page .schedule-notice[data-schedule-notice-tone=problem]{background:color-mix(in oklab,var(--org-ink) 12%,var(--org-paper))}
41
+ .schedule-page .schedule-notice svg{flex:none}
42
+ .schedule-page .schedule-notice button{display:inline-flex;align-items:center;gap:6px;min-height:36px;padding:6px 12px;border:0;border-radius:8px;background:var(--org-ink);color:var(--org-paper);font:600 14px/1 var(--kb-theme-ui-font);cursor:pointer}
@@ -48,7 +48,11 @@ export type MoveStoryStageResult = { ok: true; changed: boolean; stage: string }
48
48
  * instant is UTC: the console turns the publication-zone time an editor picked into it (lib/story-schedule.ts), so the backend never has to read a wall-clock time.
49
49
  */
50
50
  export type ScheduleStoryInput = { itemId: string; lineageId: string; scheduledPublishAt: string | null };
51
- export type ScheduleStoryResult = { ok: true; scheduledPublishAt: string | null; scheduledBy: string | null };
51
+ export type ScheduleStoryResult = {
52
+ ok: true; scheduledPublishAt: string | null; scheduledBy: string | null;
53
+ /** What scheduling will and will not do for this Story (the backend's own words, for example for an unrated Story). */
54
+ notes: string[];
55
+ };
52
56
 
53
57
  /**
54
58
  * One scheduled version in the `schedule_list` answer (`story_schedule.ScheduleService.entry`). `state` is the effective state (overdue when the time passed and it
@@ -59,10 +63,19 @@ export type ScheduleEntry = {
59
63
  state: "scheduled" | "publishing" | "blocked" | "overdue"; storedState: "scheduled" | "publishing" | "blocked";
60
64
  scheduledPublishAt: string; scheduledBy: string | null; scheduledAt: string | null;
61
65
  headItemId?: string; headVersionNumber?: number | null; newerVersionExists?: boolean;
66
+ /** One-Story reads only: what scheduling will and will not do for the Story's rating, in the backend's words. */
67
+ notes?: string[];
62
68
  };
63
69
  /** The `schedule_list` operation of `scheduleItem`: the schedules of one Story (`storyLineageId`), soonest first. */
64
70
  export type ScheduleListResult = { ok: true; timeZone: string | null; schedules: ScheduleEntry[] };
65
71
 
72
+ /**
73
+ * The `schedule_suggest` operation of `scheduleItem`: the next time to schedule a Story, learned from the publication's own history of first publications
74
+ * (`publication_cadence.py`), or `suggestion: null` with the reason when the publication has no history yet. `storyLineageId` leaves that Story's own schedule out.
75
+ */
76
+ export type ScheduleSuggestion = { at: string; local: string; label: string; zone: string; publications: number; meanGapHours: number; latestScheduledAt: string | null };
77
+ export type ScheduleSuggestResult = { ok: true; suggestion: ScheduleSuggestion | null; reason: string | null; timeZone: string | null };
78
+
66
79
  /** The `schedule_settings` operation of `scheduleItem`: whether scheduling is on and the publication's time zone, which the backend owns (docs/scheduled-publishing.md). */
67
80
  export type ScheduleZoneResult = { ok: true; enabled: boolean; timeZone: string | null };
68
81
 
@@ -175,13 +188,17 @@ export function createContentActionsClient(transport: ContentActionsTransport) {
175
188
  const operation = input.scheduledPublishAt === null
176
189
  ? { operation: "schedule", arguments: { storyLineageId: input.lineageId, clear: true } }
177
190
  : { operation: "schedule", arguments: { itemId: input.itemId, at: input.scheduledPublishAt } };
178
- const result = parseActionResponse<{ scheduledPublishAt?: string; scheduledBy?: string }>(await transport.mutations.scheduleItem({ input: JSON.stringify(operation) }, USER_POOL));
179
- return { ok: true, scheduledPublishAt: result.scheduledPublishAt ?? null, scheduledBy: result.scheduledBy ?? null };
191
+ const result = parseActionResponse<{ scheduledPublishAt?: string; scheduledBy?: string; notes?: string[] }>(await transport.mutations.scheduleItem({ input: JSON.stringify(operation) }, USER_POOL));
192
+ return { ok: true, scheduledPublishAt: result.scheduledPublishAt ?? null, scheduledBy: result.scheduledBy ?? null, notes: result.notes ?? [] };
180
193
  },
181
194
  async scheduleList(input: { storyLineageId: string }): Promise<ScheduleListResult> {
182
195
  const result = parseActionResponse<{ timeZone?: string | null; schedules?: ScheduleEntry[] }>(await transport.mutations.scheduleItem({ input: JSON.stringify({ operation: "schedule_list", arguments: { storyLineageId: input.storyLineageId } }) }, USER_POOL));
183
196
  return { ok: true, timeZone: result.timeZone ?? null, schedules: result.schedules ?? [] };
184
197
  },
198
+ async scheduleSuggest(input: { storyLineageId?: string }): Promise<ScheduleSuggestResult> {
199
+ const result = parseActionResponse<{ suggestion?: ScheduleSuggestion | null; reason?: string | null; timeZone?: string | null }>(await transport.mutations.scheduleItem({ input: JSON.stringify({ operation: "schedule_suggest", arguments: input.storyLineageId ? { storyLineageId: input.storyLineageId } : {} }) }, USER_POOL));
200
+ return { ok: true, suggestion: result.suggestion ?? null, reason: result.reason ?? null, timeZone: result.timeZone ?? null };
201
+ },
185
202
  async scheduleZone(): Promise<ScheduleZoneResult> {
186
203
  const result = parseActionResponse<{ enabled: boolean; timeZone?: string | null }>(await transport.mutations.scheduleItem({ input: JSON.stringify({ operation: "schedule_settings", arguments: {} }) }, USER_POOL));
187
204
  return { ok: true, enabled: result.enabled, timeZone: result.timeZone ?? null };
@@ -215,6 +232,7 @@ export const createStoryFromReference = (input: CreateStoryFromReferenceInput) =
215
232
  export const moveStoryStage = (input: MoveStoryStageInput) => contentActionsClient().moveStoryStage(input);
216
233
  export const scheduleStory = (input: ScheduleStoryInput) => contentActionsClient().scheduleStory(input);
217
234
  export const scheduleList = (input: { storyLineageId: string }) => contentActionsClient().scheduleList(input);
235
+ export const scheduleSuggest = (input: { storyLineageId?: string }) => contentActionsClient().scheduleSuggest(input);
218
236
  export const scheduleZone = () => contentActionsClient().scheduleZone();
219
237
  export const setStoryStep = (input: SetStoryStepInput) => contentActionsClient().setStoryStep(input);
220
238
  export const unpublishItem = (id: string) => contentActionsClient().unpublishItem(id);
@@ -13,6 +13,7 @@ import type {
13
13
  ScheduleStoryInput,
14
14
  ScheduleListResult,
15
15
  ScheduleStoryResult,
16
+ ScheduleSuggestResult,
16
17
  CreateStoryFromReferenceInput,
17
18
  CreateStoryFromReferenceResult,
18
19
  } from "./content-actions-client";
@@ -22,9 +23,9 @@ import {
22
23
  demoContentHash,
23
24
  type DemoArticleRecord,
24
25
  } from "./newsroom-demo-articles";
25
- import { createLocalPreviewEditableArticle, lineageForPreviewVersion, localPreviewScheduleFields, recordLocalPreviewDesk, recordLocalPreviewVersion, setLocalPreviewSchedule } from "./local-preview-seed";
26
+ import { createLocalPreviewEditableArticle, lineageForPreviewVersion, localPreviewScheduleFields, localPreviewSuggestedTime, recordLocalPreviewDesk, recordLocalPreviewVersion, setLocalPreviewSchedule } from "./local-preview-seed";
26
27
  import { createDemoAnnouncementsDoor } from "./announcements-demo";
27
- import { scheduleFromFields } from "./story-schedule";
28
+ import { UNRATED_NOTE, scheduleFromFields } from "./story-schedule";
28
29
  import { LOCAL_PREVIEW_TIME_ZONE } from "./schedule-zone";
29
30
  import { sourceLineOffset, type ArticlesBackend, type EditableArticle, type NewsroomArticleRow } from "./newsroom-articles";
30
31
 
@@ -112,6 +113,13 @@ export function createDemoArticlesBackend(): ArticlesBackend {
112
113
  return record;
113
114
  };
114
115
 
116
+ /** What scheduling will and will not do for a Story with no rating, as the backend words it: the preview reads the sample Story's rating. */
117
+ const unratedNotes = (itemId: string): string[] => {
118
+ loadPreviewRecord(itemId);
119
+ const record = records.get(itemId);
120
+ return record && !record.starRating ? [UNRATED_NOTE] : [];
121
+ };
122
+
115
123
  return {
116
124
  actions: {
117
125
  async deriveMarkus(input: DeriveMarkusInput): Promise<DeriveMarkusResult> {
@@ -235,7 +243,7 @@ export function createDemoArticlesBackend(): ArticlesBackend {
235
243
  async scheduleStory(input: ScheduleStoryInput): Promise<ScheduleStoryResult> {
236
244
  try {
237
245
  const fields = setLocalPreviewSchedule(input.lineageId, input.scheduledPublishAt);
238
- return { ok: true, scheduledPublishAt: fields.scheduledPublishAt ?? null, scheduledBy: fields.scheduledBy ?? null };
246
+ return { ok: true, scheduledPublishAt: fields.scheduledPublishAt ?? null, scheduledBy: fields.scheduledBy ?? null, notes: fields.scheduledPublishAt ? unratedNotes(input.itemId) : [] };
239
247
  } catch (error) {
240
248
  throw new ContentActionFailure([{ code: "schedule-refused", message: error instanceof Error ? error.message : String(error), line: null }]);
241
249
  }
@@ -247,10 +255,15 @@ export function createDemoArticlesBackend(): ArticlesBackend {
247
255
  ok: true, timeZone: LOCAL_PREVIEW_TIME_ZONE,
248
256
  schedules: schedule ? [{
249
257
  itemId: input.storyLineageId, lineageId: input.storyLineageId, versionNumber: null, title: "", state: schedule.state, storedState: schedule.state,
250
- scheduledPublishAt: schedule.at, scheduledBy: schedule.by, scheduledAt: schedule.scheduledAt,
258
+ scheduledPublishAt: schedule.at, scheduledBy: schedule.by, scheduledAt: schedule.scheduledAt, notes: unratedNotes(input.storyLineageId.replace("-lineage-", "-version-")),
251
259
  }] : [],
252
260
  };
253
261
  },
262
+ async scheduleSuggest(input: { storyLineageId?: string }): Promise<ScheduleSuggestResult> {
263
+ // The preview has no publishing history to learn from: it stands in for a publication that publishes on weekday mornings.
264
+ const picked = localPreviewSuggestedTime(LOCAL_PREVIEW_TIME_ZONE, input.storyLineageId);
265
+ return { ok: true, suggestion: { at: picked, local: picked, label: picked, zone: LOCAL_PREVIEW_TIME_ZONE, publications: 0, meanGapHours: 0, latestScheduledAt: null }, reason: null, timeZone: LOCAL_PREVIEW_TIME_ZONE };
266
+ },
254
267
  async moveStoryStage(input: MoveStoryStageInput): Promise<MoveStoryStageResult> {
255
268
  return { ok: true, changed: true, stage: input.stage };
256
269
  },
@@ -9,7 +9,8 @@ import { contentItemHeadStageKey, contentItemStageKeys, type ContentItemVersionR
9
9
  import { getContentItemStageDefinitions } from "./site-brand";
10
10
  import { noteProblem, stepChangeProblem, summarizeStoryChecklist, type StoryStepNote, type StoryStepRecord } from "./story-checklist";
11
11
  import { LOCAL_PREVIEW_TENANTS, getLocalPreviewTenantId } from "./local-preview-tenant";
12
- import type { ScheduleFields } from "./story-schedule";
12
+ import { resolveWallTime, wallTimeOf, type ScheduleFields } from "./story-schedule";
13
+ import type { PublishedStoryRow } from "./story-schedule-query";
13
14
 
14
15
  const SEED_TIMESTAMP_BASE = Date.parse("2026-10-01T12:00:00.000Z");
15
16
  const ONE_HOUR_IN_MILLISECONDS = 60 * 60 * 1000;
@@ -205,11 +206,50 @@ export function setLocalPreviewSchedule(lineageId: string, scheduledPublishAt: s
205
206
  return fields ?? {};
206
207
  }
207
208
 
209
+ /**
210
+ * What the preview says when an editor asks for a suggested time. The preview has no history to learn from, so it stands in for a publication that publishes on weekday
211
+ * mornings: 9:00 in the publication's zone on the first weekday after now and after the latest scheduled sample Story plus a day. (The real backend learns the hours
212
+ * and the gap from the publication's own first publications: src/papyrus_content/publication_cadence.py.)
213
+ */
214
+ export function localPreviewSuggestedTime(zone: string, ownLineageId: string | undefined, now: Date = new Date()): string {
215
+ const latest = createLocalPreviewContentItemVersions()
216
+ .filter(version => version.lineageId !== ownLineageId && version.scheduledPublishAt && (version.scheduleState === "scheduled" || version.scheduleState === "publishing"))
217
+ .map(version => Date.parse(version.scheduledPublishAt!))
218
+ .reduce((most, at) => Math.max(most, at), 0);
219
+ const after = Math.max(now.getTime(), latest ? latest + DAY : 0);
220
+ for (let offset = 0; offset < 14; offset += 1) {
221
+ const day = wallTimeOf(new Date(now.getTime() + offset * DAY).toISOString(), zone).date;
222
+ const weekday = new Date(`${day}T12:00:00Z`).getUTCDay();
223
+ if (weekday === 0 || weekday === 6) continue;
224
+ const resolved = resolveWallTime(day, "09:00", zone);
225
+ if (resolved.kind === "ok" && Date.parse(resolved.utc) > after) return resolved.utc;
226
+ }
227
+ throw new Error("The preview found no weekday morning in the next two weeks.");
228
+ }
229
+
208
230
  export function resetLocalPreviewSchedules(): void {
209
231
  previewScheduleChanges.clear();
210
232
  previewScheduleTouchedAt.clear();
211
233
  }
212
234
 
235
+ /**
236
+ * Fake first-publication times for the sample published Stories, placed relative to the start of today (UTC) like the schedules: two went out three days ago,
237
+ * so the Schedule page shows what went out beside what is coming.
238
+ */
239
+ function seededPublishedAt(now: Date = new Date()): Record<string, string> {
240
+ const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
241
+ const at = (days: number, hours: number) => new Date(today + days * DAY + hours * HOUR).toISOString();
242
+ return { "preview-item-lineage-published-0": at(-3, 14), "preview-item-lineage-published-1": at(-3, 18) };
243
+ }
244
+
245
+ /** Every sample published Story first published in [from, to), for the Schedule page. */
246
+ export function createLocalPreviewPublishedStories(from: string, to: string): PublishedStoryRow[] {
247
+ const publishedAt = seededPublishedAt();
248
+ return createLocalPreviewContentItemVersions()
249
+ .filter(version => version.lineageId && publishedAt[version.lineageId] && publishedAt[version.lineageId] >= from && publishedAt[version.lineageId] < to)
250
+ .map(version => ({ id: version.id, lineageId: version.lineageId!, title: version.headline || version.title || version.slug, section: version.section ?? null, publishedAt: publishedAt[version.lineageId!] }));
251
+ }
252
+
213
253
  /** Every sample Story that has a schedule, for the Schedule page: the rows whose scheduled time falls in [from, to) and whose state is one of `states`. */
214
254
  export function createLocalPreviewScheduledVersions(from: string, to: string, states: readonly string[]): ContentItemVersionRecord[] {
215
255
  return createLocalPreviewContentItemVersions().filter(version => {
@@ -8,6 +8,7 @@ import {
8
8
  moveStoryStage,
9
9
  scheduleStory,
10
10
  scheduleList,
11
+ scheduleSuggest,
11
12
  createStoryFromReference,
12
13
  type ContentActionError,
13
14
  } from "./content-actions-client";
@@ -107,6 +108,8 @@ export type ArticlesBackend = {
107
108
  scheduleStory: typeof scheduleStory;
108
109
  /** The Story's schedules (the `schedule_list` operation): the drawer shows what the backend says, not what the loaded row happens to hold. */
109
110
  scheduleList: typeof scheduleList;
111
+ /** The next time the publication's own rhythm suggests for a Story (the `schedule_suggest` operation), or why there is none. */
112
+ scheduleSuggest: typeof scheduleSuggest;
110
113
  createStoryFromReference: typeof createStoryFromReference;
111
114
  /** Saves an editor's rating of a Story (any version id of it; null clears it). A plain update: no new version, nothing republished. */
112
115
  setItemStars: (itemId: string, stars: number | null) => Promise<void>;
@@ -351,7 +354,7 @@ export function createLiveArticlesBackend(): ArticlesBackend {
351
354
  return client;
352
355
  };
353
356
  return {
354
- actions: { deriveMarkus, saveItemDraft, publishItem, unpublishItem, moveStoryStage, scheduleStory, scheduleList, createStoryFromReference, setItemStars },
357
+ actions: { deriveMarkus, saveItemDraft, publishItem, unpublishItem, moveStoryStage, scheduleStory, scheduleList, scheduleSuggest, createStoryFromReference, setItemStars },
355
358
  listRows: () => loadArticleRows(dataClient()),
356
359
  loadArticle: (id) => loadEditableArticle(dataClient(), id),
357
360
  announcementsDoor,
@@ -4,7 +4,7 @@
4
4
  * only versions that are or were scheduled, and nothing reads a table to show a few items. Pure, with the GraphQL call passed in, so the paging is tested against
5
5
  * synthetic rows (scripts/test-story-schedule.ts).
6
6
  */
7
- import { storyItemTypeFilter, type ContentItemVersionRecord } from "./content-item-lifecycle";
7
+ import { isStoryItemType, storyItemTypeFilter, type ContentItemVersionRecord } from "./content-item-lifecycle";
8
8
  import { SCHEDULE_ROW_FIELDS } from "./story-schedule";
9
9
 
10
10
  /** The stored states, each one partition of the sparse index. Overdue is a scheduled or publishing row whose time has passed, so it is read with them. */
@@ -39,3 +39,51 @@ export async function readScheduledRange(fetch: ScheduleQueryFetch, from: string
39
39
  }));
40
40
  return perState.flat().sort((left, right) => String(left.scheduledPublishAt).localeCompare(String(right.scheduledPublishAt)) || left.id.localeCompare(right.id));
41
41
  }
42
+
43
+ /** One published Story as the Schedule page shows it: the live version of a Story, with the moment it first went live. */
44
+ export type PublishedStoryRow = {
45
+ /** The Item version that is live; it opens the Story in the editor. */
46
+ id: string;
47
+ lineageId: string;
48
+ title: string;
49
+ section: string | null;
50
+ /** The UTC instant the Story was first published (`publishedAt` carries the first publication forward, so a republish does not move it). */
51
+ publishedAt: string;
52
+ };
53
+
54
+ type PublishedItemRecord = { sourceItemId?: string | null; itemLineageId?: string | null; title?: string | null; headline?: string | null; slug?: string | null; section?: string | null; publishedAt?: string | null };
55
+ export type PublishedQueryFetch = (request: { query: string; field: string; variables: Record<string, unknown> }) => Promise<{ items: PublishedItemRecord[]; nextToken: string | null }>;
56
+
57
+ const PUBLISHED_FIELD = "listPublishedItemsByTypeStatusAndPublishedAt";
58
+ const PUBLISHED_QUERY = `
59
+ query ListPublishedItemsByTypeStatusAndPublishedAt($typeStatus: String!, $publishedAt: ModelStringKeyConditionInput, $limit: Int, $nextToken: String) {
60
+ ${PUBLISHED_FIELD}(typeStatus: $typeStatus, publishedAt: $publishedAt, sortDirection: ASC, limit: $limit, nextToken: $nextToken) {
61
+ items { sourceItemId itemLineageId title headline slug section publishedAt }
62
+ nextToken
63
+ }
64
+ }
65
+ `;
66
+
67
+ /**
68
+ * Every Story first published in [from, to] (UTC instants), from the existing `typeStatus` + `publishedAt` index of PublishedItem: one key-conditioned query per
69
+ * Story type of the site (`<type>#published`), so only the range on screen is read. Pages and the other system types are not Stories and are left out.
70
+ */
71
+ export async function readPublishedRange(fetch: PublishedQueryFetch, types: readonly string[], from: string, to: string): Promise<PublishedStoryRow[]> {
72
+ const perType = await Promise.all([...new Set(types)].filter(isStoryItemType).map(async type => {
73
+ const rows: PublishedStoryRow[] = [];
74
+ let nextToken: string | null = null;
75
+ do {
76
+ const page: { items: PublishedItemRecord[]; nextToken: string | null } = await fetch({
77
+ query: PUBLISHED_QUERY, field: PUBLISHED_FIELD,
78
+ variables: { typeStatus: `${type}#published`, publishedAt: { between: [from, to] }, limit: 100, nextToken },
79
+ });
80
+ for (const item of page.items) {
81
+ if (!item.sourceItemId || !item.publishedAt) continue;
82
+ rows.push({ id: item.sourceItemId, lineageId: item.itemLineageId ?? item.sourceItemId, title: item.headline || item.title || item.slug || "Untitled", section: item.section ?? null, publishedAt: item.publishedAt });
83
+ }
84
+ nextToken = page.nextToken;
85
+ } while (nextToken);
86
+ return rows;
87
+ }));
88
+ return perType.flat().sort((left, right) => left.publishedAt.localeCompare(right.publishedAt) || left.id.localeCompare(right.id));
89
+ }
@@ -27,6 +27,10 @@ export type StorySchedule = {
27
27
  state: ScheduleState;
28
28
  by: string | null;
29
29
  scheduledAt: string | null;
30
+ /** What scheduling will and will not do for the Story's rating, in the backend's words (an unrated Story is not listed or announced until it is rated). */
31
+ notes?: string[];
32
+ /** A newer version of the Story exists than the one that is scheduled: the schedule will not publish, and the editor is told as soon as the version is saved. */
33
+ newerVersion?: boolean;
30
34
  };
31
35
 
32
36
  export function scheduleFromFields(fields: ScheduleFields): StorySchedule | undefined {
@@ -40,16 +44,25 @@ export function scheduleFromFields(fields: ScheduleFields): StorySchedule | unde
40
44
  * The schedule the drawer shows for a Story, from its `schedule_list` answer: the newest scheduled version, since a schedule that sits on an earlier version
41
45
  * is the one a newer save superseded. The state is the stored one; Overdue is derived from the time (`scheduleKind`), as the backend derives it.
42
46
  */
43
- export function scheduleFromEntries(entries: readonly { versionNumber: number | null; storedState: string; scheduledPublishAt: string; scheduledBy: string | null; scheduledAt: string | null }[]): StorySchedule | undefined {
47
+ export function scheduleFromEntries(entries: readonly { versionNumber: number | null; storedState: string; scheduledPublishAt: string; scheduledBy: string | null; scheduledAt: string | null; newerVersionExists?: boolean; notes?: string[] }[]): StorySchedule | undefined {
44
48
  const newest = [...entries].sort((left, right) => (right.versionNumber ?? 0) - (left.versionNumber ?? 0))[0];
45
- return newest ? scheduleFromFields({ scheduledPublishAt: newest.scheduledPublishAt, scheduleState: newest.storedState, scheduledBy: newest.scheduledBy, scheduledAt: newest.scheduledAt }) : undefined;
49
+ const found = newest ? scheduleFromFields({ scheduledPublishAt: newest.scheduledPublishAt, scheduleState: newest.storedState, scheduledBy: newest.scheduledBy, scheduledAt: newest.scheduledAt }) : undefined;
50
+ return found ? { ...found, notes: newest.notes ?? [], newerVersion: newest.newerVersionExists === true } : undefined;
46
51
  }
47
52
 
48
53
  /** The schedule a successful `schedule` call recorded: none after a clear, else scheduled for the instant that was sent. */
49
- export function scheduleFromResult(result: { scheduledPublishAt: string | null; scheduledBy: string | null }, at: Date = new Date()): StorySchedule | undefined {
50
- return result.scheduledPublishAt ? { at: result.scheduledPublishAt, state: "scheduled", by: result.scheduledBy, scheduledAt: at.toISOString() } : undefined;
54
+ export function scheduleFromResult(result: { scheduledPublishAt: string | null; scheduledBy: string | null; notes?: string[] }, at: Date = new Date()): StorySchedule | undefined {
55
+ return result.scheduledPublishAt ? { at: result.scheduledPublishAt, state: "scheduled", by: result.scheduledBy, scheduledAt: at.toISOString(), notes: result.notes ?? [], newerVersion: false } : undefined;
51
56
  }
52
57
 
58
+ /** What scheduling does for a Story with no rating: the backend's sentence (`story_schedule.UNRATED_NOTE`), which the local preview repeats for its sample Stories. */
59
+ export const UNRATED_NOTE = "Unrated: it will publish but will not be listed or announced until it is rated.";
60
+
61
+ /** Said under the schedule when a newer version of the Story exists than the one that is scheduled. */
62
+ export const NEWER_VERSION_NOTE = "A newer version exists than the one scheduled";
63
+ /** Said in the form beside a suggested time. A publication with no history to suggest from is told why in the backend's own sentence (`publication_cadence.NO_HISTORY`). */
64
+ export const SUGGESTION_BASIS = "Suggested from this publication's usual publishing times. Pick any other time if you prefer.";
65
+
53
66
  /**
54
67
  * What a reader sees. A time that has passed while the version is still scheduled or being published is Overdue (derived, as the backend derives it); a blocked
55
68
  * schedule is Superseded: a newer version was saved after it was scheduled.
package/package.json CHANGED
@@ -650,7 +650,7 @@
650
650
  "optional": true
651
651
  }
652
652
  },
653
- "version": "5.135.0-next.1",
653
+ "version": "5.135.0-next.3",
654
654
  "dependencies": {
655
655
  "@aws-amplify/adapter-nextjs": "^1.7.3",
656
656
  "@aws-crypto/sha256-js": "5.2.0",
@@ -677,7 +677,7 @@
677
677
  "@fontsource-variable/source-serif-4": "5.3.1",
678
678
  "@fontsource/ibm-plex-mono": "5.3.0",
679
679
  "@fontsource/ibm-plex-sans": "5.3.0",
680
- "@fullcalendar/react": "^7.1.5",
680
+ "@fullcalendar/react": "7.1.4",
681
681
  "@kanbus/ui": "https://github.com/AnthusAI/Kanbus/releases/download/ui-v0.5.1/kanbus-ui-0.5.1.tgz",
682
682
  "@lezer/highlight": "^1.2.5",
683
683
  "@radix-ui/colors": "3.0.0",
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "5.135.0-next.1",
2
+ "version": "5.135.0-next.3",
3
3
  "routes": [
4
4
  {
5
5
  "file": "app/%5F_preview/[[...path]]/route.ts",