app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

editor-workflow.ts (10673B)


      1 import {
      2   exactLocalFields,
      3   type PublicDraftForm
      4 } from '../contracts/local-records.ts';
      5 import {
      6   buildFoodTemplate,
      7   type FoodDraftErrorCode
      8 } from '../contracts/food-availability-v1/write.ts';
      9 import type { InboxSetupView } from '../messaging/inbox-setup-view.ts';
     10 import {
     11   reviewListingEditor,
     12   listingEditorReviewCurrent,
     13   editListingEditor,
     14   listingEditorSnapshot,
     15   type ListingEditor
     16 } from './listing-editor.ts';
     17 import {
     18   listingReviewSnapshot,
     19   listingReviewOwnership,
     20   reserveNewListing,
     21   type ListingReview,
     22   type ListingPreview
     23 } from './prepare-listing.ts';
     24 import {
     25   beginListingSigning,
     26   runListingSigning,
     27   stopListingSigning,
     28   type ListingSigning
     29 } from './sign-listing.ts';
     30 import {
     31   deliverListing,
     32   type ListingDeliveryResult
     33 } from './deliver-listing.ts';
     34 import { getPublicPool } from '../nostr/public-pool.ts';
     35 import {
     36   readListingOperationView,
     37   closeListingOperationView,
     38   type ListingOperationView
     39 } from './listing-operation-view.ts';
     40 
     41 export type EditorFormError = Readonly<{
     42   field: keyof PublicDraftForm;
     43   message: string;
     44 }>;
     45 const fields = [
     46   'title',
     47   'description',
     48   'location',
     49   'amount',
     50   'currency',
     51   'unit',
     52   'quantity',
     53   'contactType',
     54   'contactValue'
     55 ] as const;
     56 export function validateEditorForm(
     57   input: PublicDraftForm
     58 ): readonly EditorFormError[] {
     59   try {
     60     if (
     61       !exactLocalFields(input, fields) ||
     62       fields.some((field) => typeof input[field] !== 'string')
     63     )
     64       return [{ field: 'title', message: 'Keep all listing fields as text.' }];
     65     if (input.contactType === '' && input.contactValue !== '')
     66       return [
     67         {
     68           field: 'contactValue',
     69           message: 'Choose a public contact type or remove the contact details.'
     70         }
     71       ];
     72     const built = buildFoodTemplate({
     73       identifier: '00000000-0000-4000-8000-000000000001',
     74       created_at: 1,
     75       published_at: 1,
     76       status: 'active',
     77       title: input.title,
     78       description: input.description,
     79       location: input.location,
     80       amount: input.amount,
     81       currency: input.currency,
     82       unit: input.unit,
     83       ...(input.quantity === '' ? {} : { quantity: input.quantity }),
     84       ...(input.contactType === ''
     85         ? {}
     86         : {
     87             contact: {
     88               type: input.contactType,
     89               value: input.contactValue,
     90               public: true as const
     91             }
     92           })
     93     });
     94     if (built.ok) return [];
     95     const messages: Partial<Record<FoodDraftErrorCode, EditorFormError>> = {
     96       title_invalid: {
     97         field: 'title',
     98         message: 'Use a product name within the public text limit.'
     99       },
    100       location_invalid: {
    101         field: 'location',
    102         message: 'Use a public area within the text limit.'
    103       },
    104       description_invalid: {
    105         field: 'description',
    106         message: 'Add a complete description within the public text limit.'
    107       },
    108       summary_invalid: {
    109         field: 'description',
    110         message: 'Use supported public text in the description.'
    111       },
    112       price_invalid: {
    113         field: 'amount',
    114         message: 'Use a supported price, currency and price unit.'
    115       },
    116       quantity_invalid: {
    117         field: 'quantity',
    118         message: 'Use a supported advertised quantity in the selected unit.'
    119       },
    120       contact_invalid: {
    121         field: 'contactValue',
    122         message: 'Use supported public contact details for the selected type.'
    123       }
    124     };
    125     return [
    126       messages[built.error.code] ?? {
    127         field: 'description',
    128         message: 'The public listing exceeds its supported limits.'
    129       }
    130     ];
    131   } catch {
    132     return [
    133       {
    134         field: 'title',
    135         message:
    136           'The listing fields could not be read. Keep your current input.'
    137       }
    138     ];
    139   }
    140 }
    141 declare const reviewBrand: unique symbol;
    142 export type EditorReview = Readonly<{ [reviewBrand]: true }>;
    143 type Owned = Readonly<{
    144   editor: ListingEditor;
    145   original: ListingReview;
    146   active(): boolean;
    147   close(): void;
    148   signing(): ListingSigning | undefined;
    149   setSigning(value: ListingSigning): void;
    150   operation(): ListingOperationView | undefined;
    151   setOperation(value: ListingOperationView): void;
    152 }>;
    153 function createReviewOwner(
    154   editor: ListingEditor,
    155   original: ListingReview
    156 ): Owned {
    157   let active = true;
    158   let signing: ListingSigning | undefined;
    159   let operation: ListingOperationView | undefined;
    160   return {
    161     editor,
    162     original,
    163     active: () => active,
    164     signing: () => signing,
    165     setSigning(value) {
    166       signing = value;
    167     },
    168     operation: () => operation,
    169     setOperation(value) {
    170       if (operation) closeListingOperationView(operation);
    171       operation = value;
    172     },
    173     close() {
    174       active = false;
    175       if (signing) stopListingSigning(signing);
    176       if (operation) closeListingOperationView(operation);
    177     }
    178   };
    179 }
    180 const reviews = new WeakMap<EditorReview, Owned>();
    181 const publishing = new WeakMap<EditorReview, Promise<ListingDeliveryResult>>();
    182 export type EditorReviewSnapshot = ListingPreview &
    183   Readonly<{ content: string; tags: readonly (readonly string[])[] }>;
    184 export async function openEditorReview(
    185   editor: ListingEditor,
    186   setup: InboxSetupView | undefined,
    187   form: PublicDraftForm,
    188   status: 'active' | 'sold' | 'withdrawal' = 'active'
    189 ): Promise<
    190   | Readonly<{ status: 'review'; review: EditorReview }>
    191   | Readonly<{
    192       status: 'blocked';
    193       errors: readonly EditorFormError[];
    194       message: string;
    195     }>
    196 > {
    197   const errors = status === 'withdrawal' ? [] : validateEditorForm(form);
    198   if (errors.length)
    199     return {
    200       status: 'blocked',
    201       errors,
    202       message: 'Check the linked fields. Your input remains here.'
    203     };
    204   if (
    205     listingEditorSnapshot(editor)?.mode === 'edit' &&
    206     !(await editListingEditor(editor, form))
    207   )
    208     return {
    209       status: 'blocked',
    210       errors: [],
    211       message:
    212         'Keep your proposed changes. The current listing could not be safely prepared.'
    213     };
    214   const result = await reviewListingEditor(editor, setup, form, status);
    215   if (
    216     result.status !== 'review' ||
    217     !listingEditorReviewCurrent(editor, result.review)
    218   )
    219     return {
    220       status: 'blocked',
    221       errors: [],
    222       message:
    223         result.status === 'blocked' && result.reason === 'unavailable'
    224           ? 'Enable messages before reviewing this listing. Your draft remains in this browser.'
    225           : 'The saved listing or account changed. Keep your input and review the current values again.'
    226     };
    227   const review = Object.freeze({}) as EditorReview;
    228   reviews.set(review, createReviewOwner(editor, result.review));
    229   return { status: 'review', review };
    230 }
    231 export function editorReviewSnapshot(
    232   review: EditorReview
    233 ): EditorReviewSnapshot | undefined {
    234   const owned = reviews.get(review);
    235   if (!owned || !listingEditorReviewCurrent(owned.editor, owned.original))
    236     return;
    237   const preview = listingReviewSnapshot(owned.original);
    238   if (!preview) return;
    239   const wire = JSON.parse(preview.templateWire) as {
    240     content: string;
    241     tags: string[][];
    242   };
    243   return { ...preview, content: wire.content, tags: wire.tags };
    244 }
    245 export function closeEditorReview(review: EditorReview): void {
    246   const owned = reviews.get(review);
    247   owned?.close();
    248   reviews.delete(review);
    249 }
    250 export function editorPublicationOperation(
    251   review: EditorReview
    252 ): ListingOperationView | undefined {
    253   const owned = reviews.get(review);
    254   return owned?.active() ? owned.operation() : undefined;
    255 }
    256 // Revokes future effects of this original action; stored/sent evidence remains.
    257 export function stopEditorAction(review: EditorReview): void {
    258   const owned = reviews.get(review);
    259   const signing = owned?.active() ? owned.signing() : undefined;
    260   if (signing) stopListingSigning(signing);
    261 }
    262 // Existing publication pipeline only. One original review deduplicates clicks;
    263 // explicit consent does not bypass original editor/source/draft/current-head.
    264 export function publishEditorRevision(
    265   review: EditorReview,
    266   consent: unknown
    267 ): Promise<ListingDeliveryResult> {
    268   const owned = reviews.get(review);
    269   const preview = owned && listingReviewSnapshot(owned.original);
    270   if (
    271     !owned?.active() ||
    272     (!preview?.revision && !preview?.withdrawal) ||
    273     consent !==
    274       (preview?.withdrawal
    275         ? 'publish_reviewed_withdrawal'
    276         : 'publish_reviewed_revision')
    277   )
    278     return Promise.resolve({ status: 'invalid' });
    279   const pending = publishing.get(review);
    280   if (pending) return pending;
    281   const job = (async (): Promise<ListingDeliveryResult> => {
    282     const original = listingReviewOwnership(owned.original);
    283     if (!original || !listingEditorReviewCurrent(owned.editor, owned.original))
    284       return { status: 'unavailable' };
    285     const current = () =>
    286       owned.active() &&
    287       reviews.get(review) === owned &&
    288       listingEditorReviewCurrent(owned.editor, owned.original);
    289     try {
    290       const reserved = await reserveNewListing(
    291         owned.original,
    292         'publish_reviewed_listing'
    293       );
    294       if (!current()) return { status: 'stopped' };
    295       if (reserved.status !== 'saved' && reserved.status !== 'existing')
    296         return {
    297           status: reserved.status === 'busy' ? 'busy' : 'storage_failed'
    298         };
    299       const signing = beginListingSigning(
    300         owned.original,
    301         'sign_reviewed_listing'
    302       );
    303       if (!signing) return { status: 'unavailable' };
    304       owned.setSigning(signing);
    305       const signed = await runListingSigning(signing, 'sign_reviewed_listing');
    306       if (!current()) return { status: 'stopped' };
    307       if (signed.status !== 'prepared')
    308         return {
    309           status:
    310             signed.status === 'busy'
    311               ? 'busy'
    312               : signed.status === 'stopped'
    313                 ? 'stopped'
    314                 : 'needs_action'
    315         };
    316       const pool = getPublicPool(original.readiness.policy);
    317       if (!pool || !current()) return { status: 'unavailable' };
    318       return await deliverListing(
    319         signed.publication,
    320         pool,
    321         original.readiness.policy,
    322         'publish_stored_listing'
    323       );
    324     } catch {
    325       return { status: 'needs_action' };
    326     } finally {
    327       const read = await readListingOperationView(
    328         original.repository,
    329         original.readiness.identity,
    330         original.command,
    331         owned.signing()
    332       );
    333       if (read.status === 'found') {
    334         if (owned.active() && reviews.get(review) === owned) {
    335           owned.setOperation(read.view);
    336         } else closeListingOperationView(read.view);
    337       }
    338     }
    339   })().finally(() => {
    340     if (publishing.get(review) === job) publishing.delete(review);
    341   });
    342   publishing.set(review, job);
    343   return job;
    344 }