a tool for shared writing and social publishing
1import { GetLeafletDataReturnType } from "app/api/rpc/[command]/get_leaflet_data";
2import { Json } from "supabase/database.types";
3
4export function getPublicationMetadataFromLeafletData(
5 data?: GetLeafletDataReturnType["result"]["data"],
6) {
7 if (!data) return null;
8
9 let pubData:
10 | {
11 description: string;
12 title: string;
13 leaflet: string;
14 doc: string | null;
15 publications: {
16 identity_did: string;
17 name: string;
18 indexed_at: string;
19 record: Json | null;
20 uri: string;
21 } | null;
22 documents: {
23 data: Json;
24 indexed_at: string;
25 uri: string;
26 } | null;
27 }
28 | undefined
29 | null =
30 data?.leaflets_in_publications?.[0] ||
31 data?.permission_token_rights[0].entity_sets?.permission_tokens?.find(
32 (p) => p.leaflets_in_publications?.length,
33 )?.leaflets_in_publications?.[0];
34
35 // If not found, check for standalone documents (looseleafs)
36 let standaloneDoc = data?.leaflets_to_documents;
37
38 // Only use standaloneDoc if it exists and has meaningful data
39 // (either published with a document, or saved as draft with a title)
40 if (
41 !pubData &&
42 standaloneDoc &&
43 (standaloneDoc.document || standaloneDoc.title)
44 ) {
45 // Transform standalone document data to match the expected format
46 pubData = {
47 ...standaloneDoc,
48 publications: null, // No publication for standalone docs
49 doc: standaloneDoc.document,
50 leaflet: data.id,
51 };
52 }
53
54 // Also check nested permission tokens for looseleafs
55 if (!pubData) {
56 let nestedStandaloneDoc =
57 data?.permission_token_rights[0].entity_sets?.permission_tokens?.find(
58 (p) =>
59 p.leaflets_to_documents &&
60 (p.leaflets_to_documents.document || p.leaflets_to_documents.title),
61 )?.leaflets_to_documents;
62
63 if (nestedStandaloneDoc) {
64 pubData = {
65 ...nestedStandaloneDoc,
66 publications: null,
67 doc: nestedStandaloneDoc.document,
68 leaflet: data.id,
69 };
70 }
71 }
72
73 return pubData;
74}