Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | 3x 3x 187x 3x 49x 49x 49x 49x 49x 245x 245x 49x 245x 131x 44x 36x 36x 34x 34x 38x 33x 33x 93x 89x 33x 38x 33x 39x 38x 36x 36x 38x 38x 36x 23x 39x 7x 7x 7x 25x 25x 25x 11x 11x 14x 13x 3x 10x 2x 8x 7x 35x 35x 7x 7x 2x 2x | /**
* Publish readiness — THE definition of the bar, server-side, in one place.
*
* THE BAR
* -------
* profile complete + at least one published project with >= 3 photos
*
* Before this module the bar existed only as client-side theatre: the portal's
* `PublishChecklist` listed one required item and four "recommended" ones, and
* offered a "Publish Anyway" button that bypassed all four. The server
* validated nothing, and a pro could not publish their own studio at all.
*
* THREE SURFACES, ONE ANSWER
* --------------------------
* Everything that needs to know whether a studio has cleared the bar goes
* through this module:
* 1. `GET /api/pro/:proId/publish-readiness` — the first-run phase rail on
* the portal dashboard renders the server's answer verbatim.
* 2. `POST /api/pro/:proId/projects/:projectId/publish` — rejects a publish
* that fails the blocking requirement, returning the same item list.
* 3. `maybeAutoPublishPro()` — the draft -> published studio transition.
*
* Do not add a second definition of "complete" anywhere. If a new surface
* needs the bar, call `gatherPublishReadiness()`; if the bar itself should
* change, change `REQUIREMENTS` below and nothing else.
*
* ONE REQUIREMENT BLOCKS, FOUR ADVISE
* -----------------------------------
* `project_photo_minimum` blocks: a publish that fails it is refused. The
* other four are advisory — they are what the studio still needs before it
* goes live, but they never refuse a request. That asymmetry is deliberate:
* making an advertised gate true is the minimum honest implementation, not a
* licence to invent new hard gates the UI never promised.
*/
import type { Pro } from "../db/schema/pros";
import { CACHE_KEYS, createDualCache } from "./cache";
import { invalidateEntity } from "./cache-invalidation";
import { NotFoundError } from "./errors";
import { logger } from "./logger";
import { isAutoPublishEnabled, type RuntimeConfigEnv } from "./runtime-config";
/**
* Photos a project needs before it may be published, and therefore before the
* studio behind it can go live. Exposed on the wire so no client hardcodes 3.
*/
export const PROJECT_PHOTO_MINIMUM = 3;
/** Stable ids. The portal keys copy, icons and deep links off these. */
export const PUBLISH_REQUIREMENT_IDS = [
"profile_basics",
"profile_services",
"profile_location",
"project_published",
"project_photo_minimum",
] as const;
export type PublishRequirementId = (typeof PUBLISH_REQUIREMENT_IDS)[number];
/** Which half of the bar a requirement belongs to. */
export type PublishRequirementGroup = "profile" | "portfolio";
/** A studio status, as stored in `pros.status`. */
export type StudioStatus = Pro["status"];
/** One requirement, evaluated. This is the wire shape the portal renders. */
export interface PublishRequirement {
id: PublishRequirementId;
group: PublishRequirementGroup;
/** Human label. Server-owned so every surface says the same thing. */
label: string;
passes: boolean;
/** True for the one requirement that refuses a publish when it fails. */
blocks: boolean;
}
/** The facts the bar is evaluated against. Pure data — no DB, no Hono. */
export interface PublishReadinessInput {
profile: {
businessName: string | null;
tagline: string | null;
about: string | null;
serviceCategoryIds: string[];
cityId: string | null;
};
/** How many of the studio's projects are currently published. */
publishedProjectCount: number;
/**
* Photos on the project in question: the project being published, or —
* when assessing the studio as a whole — the best-stocked *published*
* project. Videos do not count; three videos are not three photos.
*/
photoCount: number;
}
/** The evaluated bar. Returned as-is by the readiness endpoint. */
export interface PublishReadiness {
/** Every requirement passes — the studio has cleared the bar. */
ready: boolean;
/** The profile half of the bar passes. The one definition of "complete". */
profileComplete: boolean;
/** A blocking requirement fails — a publish request must be refused. */
blocked: boolean;
/** `PROJECT_PHOTO_MINIMUM`, so clients never hardcode it. */
photoMinimum: number;
requirements: PublishRequirement[];
/** The subset of `requirements` that does not pass, in the same order. */
failing: PublishRequirement[];
}
function isFilled(value: string | null | undefined): boolean {
return typeof value === "string" && value.trim().length > 0;
}
/**
* The bar, as one table. Order is the order the portal renders.
*
* Changing this table changes every surface at once — that is the point.
*/
const REQUIREMENTS: ReadonlyArray<{
id: PublishRequirementId;
group: PublishRequirementGroup;
label: string;
blocks: boolean;
passes: (input: PublishReadinessInput) => boolean;
}> = [
{
id: "profile_basics",
group: "profile",
label: "Studio name, tagline and about",
blocks: false,
passes: (input) =>
isFilled(input.profile.businessName) &&
isFilled(input.profile.tagline) &&
isFilled(input.profile.about),
},
{
id: "profile_services",
group: "profile",
label: "Services you offer",
blocks: false,
passes: (input) => input.profile.serviceCategoryIds.length > 0,
},
{
id: "profile_location",
group: "profile",
label: "Your city",
blocks: false,
passes: (input) => isFilled(input.profile.cityId),
},
{
id: "project_published",
group: "portfolio",
label: "One published project",
blocks: false,
passes: (input) => input.publishedProjectCount > 0,
},
{
id: "project_photo_minimum",
group: "portfolio",
label: `At least ${PROJECT_PHOTO_MINIMUM} photos on the project`,
blocks: true,
passes: (input) => input.photoCount >= PROJECT_PHOTO_MINIMUM,
},
];
/** Evaluate the bar. Pure: same input, same answer, no I/O. */
export function evaluatePublishReadiness(
input: PublishReadinessInput,
): PublishReadiness {
const requirements: PublishRequirement[] = REQUIREMENTS.map((spec) => ({
id: spec.id,
group: spec.group,
label: spec.label,
blocks: spec.blocks,
passes: spec.passes(input),
}));
const failing = requirements.filter((r) => !r.passes);
return {
ready: failing.length === 0,
profileComplete: requirements
.filter((r) => r.group === "profile")
.every((r) => r.passes),
blocked: failing.some((r) => r.blocks),
photoMinimum: PROJECT_PHOTO_MINIMUM,
requirements,
failing,
};
}
// ── Gathering the facts from the database ────────────────────────────────────
/** The pro columns the bar reads. `Pro` from the DAL satisfies this. */
export type ReadinessProRow = PublishReadinessInput["profile"] & {
status: StudioStatus;
};
/** Structural subsets of the DAL, so tests can pass a minimal fake. */
export type PublishReadinessDal = {
pros: { findById(id: string): Promise<ReadinessProRow | undefined> };
projects: {
findByProId(proId: string): Promise<Array<{ id: string; status: string }>>;
};
rooms: {
findByProjectIds(
projectIds: string[],
): Promise<Array<{ id: number; projectId: string }>>;
};
media: {
findByRoomIds(
roomIds: number[],
): Promise<Array<{ roomId: number; mediaType: string }>>;
};
};
/**
* Photo count per project id. Two queries total (rooms, then media) regardless
* of project count; both DAL methods already chunk under D1's 100-bind limit.
* Projects with no photos are simply absent from the map — read with `?? 0`.
*/
async function countPhotosByProject(
dal: PublishReadinessDal,
projectIds: string[],
): Promise<Map<string, number>> {
const counts = new Map<string, number>();
if (projectIds.length === 0) return counts;
const rooms = await dal.rooms.findByProjectIds(projectIds);
if (rooms.length === 0) return counts;
const media = await dal.media.findByRoomIds(rooms.map((r) => r.id));
const photosByRoom = new Map<number, number>();
for (const item of media) {
// Only images are photos. A room full of videos does not clear the bar.
if (item.mediaType !== "image") continue;
photosByRoom.set(item.roomId, (photosByRoom.get(item.roomId) ?? 0) + 1);
}
for (const room of rooms) {
counts.set(
room.projectId,
(counts.get(room.projectId) ?? 0) + (photosByRoom.get(room.id) ?? 0),
);
}
return counts;
}
export interface GatheredReadiness {
pro: ReadinessProRow;
readiness: PublishReadiness;
}
/**
* Read the facts for a studio and evaluate the bar.
*
* @param opts.projectId When set, `project_photo_minimum` is evaluated against
* that project — the one being published, which is still a draft. When unset,
* it is evaluated against the best-stocked already-published project, which is
* what "at least one published project with >= 3 photos" means for the studio.
*/
export async function gatherPublishReadiness(
dal: PublishReadinessDal,
proId: string,
opts: { projectId?: string } = {},
): Promise<GatheredReadiness> {
const pro = await dal.pros.findById(proId);
if (!pro) throw new NotFoundError("Pro", proId);
const projects = await dal.projects.findByProId(proId);
const photoCounts = await countPhotosByProject(
dal,
projects.map((p) => p.id),
);
const publishedProjects = projects.filter((p) => p.status === "published");
const photoCount =
opts.projectId === undefined
? publishedProjects.reduce(
(best, p) => Math.max(best, photoCounts.get(p.id) ?? 0),
0,
)
: (photoCounts.get(opts.projectId) ?? 0);
return {
pro,
readiness: evaluatePublishReadiness({
profile: {
businessName: pro.businessName,
tagline: pro.tagline,
about: pro.about,
serviceCategoryIds: pro.serviceCategoryIds,
cityId: pro.cityId,
},
publishedProjectCount: publishedProjects.length,
photoCount,
}),
};
}
// ── The draft -> published studio transition ─────────────────────────────────
/** What made us look. Recorded on the transition log line. */
export type AutoPublishTrigger = "project_publish" | "profile_update";
export type AutoPublishReason =
| "published"
| "disabled"
| "not_draft"
| "not_ready"
| "error";
/**
* Drop the caches that would otherwise keep a freshly published studio off the
* marketplace: its own proFull/proCard entries, the pros list generation, and
* the two consolidated marketplace payloads that embed pro data.
*
* Never throws — the transition has already been committed and logged by the
* time this runs, so a KV hiccup must not be reported as a failed publish.
*/
async function invalidatePublishedProCaches(
env: RuntimeConfigEnv,
proId: string,
): Promise<void> {
/* v8 ignore start -- unreachable: auto-publish is disabled outright when
KV_CACHE is absent (runtime-config.ts fails closed), so this is only ever
reached with the binding present. Kept to satisfy the optional type. */
if (!env.KV_CACHE) return;
/* v8 ignore stop */
try {
const cache = createDualCache(env.KV_CACHE);
await Promise.all([
invalidateEntity(cache, "pro", { id: proId }),
cache.delete(CACHE_KEYS.MARKETPLACE_HOMEPAGE),
cache.delete(CACHE_KEYS.MARKETPLACE_ROOM_CATEGORIES),
]);
/* v8 ignore start -- defensive: the dual cache already swallows KV
failures internally (lib/cache.ts), so this only fires if
createDualCache itself throws. Kept so a cache fault can never be
reported back as a failed publish. */
} catch (err) {
logger.error("pro_auto_publish_cache_invalidation_failed", {
event: "pro_auto_publish_cache_invalidation_failed",
proId,
error: err instanceof Error ? err.message : String(err),
});
}
/* v8 ignore stop */
}
export interface AutoPublishOutcome<TPro> {
transitioned: boolean;
reason: AutoPublishReason;
/** The freshly published studio — present only when `transitioned`. */
pro?: TPro;
/** Absent when the config toggle short-circuited, or on error. */
readiness?: PublishReadiness;
}
/**
* Move a studio from `draft` to `published` if — and only if — it has cleared
* the bar, and log the transition.
*
* SHARP EDGE: this is irreversible in reputation terms. A bad listing on a
* public marketplace is harder to undo than a slow queue. There are exactly
* two brakes, and both are load-bearing:
* 1. the no-deploy config toggle, read fresh from KV on every attempt
* (`runtime-config.ts`) — checked first, so an off switch costs zero
* database work and stops every subsequent transition immediately;
* 2. the existing admin unpublish (`POST /api/admin/pros/:id/disable`),
* which sets `archived`. The `status !== "draft"` guard below is what
* makes that stick: an archived studio is never auto-republished.
*
* Never throws. Auto-publish is a side effect of someone else's request, and a
* failure here must not fail that request.
*
* Idempotent: once the status is `published` the guard returns `not_draft`, so
* crossing the bar fires exactly once. Two genuinely concurrent crossings can
* both see `draft` and both write `published` — same final state, two log
* lines. D1 has no transactions (see `apps/api/CLAUDE.md`), and a duplicate
* idempotent write is the right cost to pay for that.
*/
export async function maybeAutoPublishPro<TPro>(args: {
dal: PublishReadinessDal;
services: { pro: { publish(id: string, userId: string): Promise<TPro> } };
env: RuntimeConfigEnv;
proId: string;
trigger: AutoPublishTrigger;
/** The user whose request crossed the bar. The actor is the system. */
userId: string;
}): Promise<AutoPublishOutcome<TPro>> {
const { dal, services, env, proId, trigger, userId } = args;
try {
if (!(await isAutoPublishEnabled(env))) {
logger.info("pro_auto_publish_suppressed", {
event: "pro_auto_publish_suppressed",
proId,
trigger,
reason: "config_toggle_off",
});
return { transitioned: false, reason: "disabled" };
}
const { pro, readiness } = await gatherPublishReadiness(dal, proId);
if (pro.status !== "draft") {
return { transitioned: false, reason: "not_draft", readiness };
}
if (!readiness.ready) {
return { transitioned: false, reason: "not_ready", readiness };
}
const published = await services.pro.publish(proId, userId);
// Part of the deliverable, not decoration: who/what triggered the
// transition and which requirements were true at that moment.
logger.info("pro_auto_published", {
event: "pro_auto_published",
proId,
previousStatus: "draft",
newStatus: "published",
actor: "system:auto-publish",
trigger,
triggeredByUserId: userId,
requirementsPassed: readiness.requirements
.filter((r) => r.passes)
.map((r) => r.id),
at: new Date().toISOString(),
});
// Without this the studio is `published` in D1 but absent from the
// marketplace until the 24h pro-cache TTL expires — an auto-publish
// nobody can see is not an auto-publish. Mirrors what the admin enable
// route invalidates. Separate try/catch: a cache miss must not turn a
// transition that already happened into a reported failure.
await invalidatePublishedProCaches(env, proId);
return {
transitioned: true,
reason: "published",
pro: published,
readiness,
};
} catch (err) {
logger.error("pro_auto_publish_failed", {
event: "pro_auto_publish_failed",
proId,
trigger,
error: err instanceof Error ? err.message : String(err),
});
return { transitioned: false, reason: "error" };
}
}
|