-
Notifications
You must be signed in to change notification settings - Fork 0
/
ds-to-grist.js
188 lines (171 loc) · 5 KB
/
ds-to-grist.js
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
import ky from "ky";
import _ from "lodash-es";
const {
DS_API_TOKEN,
GRIST_DOC_ID,
GRIST_TABLE_ID,
GRIST_ACCESS_TOKEN,
DS_DEMARCHE_ID,
} = process.env;
const gristApi = ky.extend({
prefixUrl: `https://docs.getgrist.com/api/docs/${GRIST_DOC_ID}/tables/${GRIST_TABLE_ID}`,
headers: { Authorization: `Bearer ${GRIST_ACCESS_TOKEN}` },
});
const dsApi = ky.extend({
prefixUrl: "https://www.demarches-simplifiees.fr/api/v2/graphql",
headers: {
Authorization: `Bearer ${DS_API_TOKEN}`,
},
});
async function main() {
// Fetch DS data
const query = `
query GetEntries {
demarche(number: ${DS_DEMARCHE_ID}) {
dossiers {
pageInfo {
hasNextPage
endCursor
}
nodes {
id
state
champs {
id
label
stringValue
__typename
... on PieceJustificativeChamp {
files {
filename
url
}
}
}
demandeur {
__typename
... on PersonneMorale {
siret
entreprise {
raisonSociale
}
association {
titre
}
}
... on PersonneMoraleIncomplete {
siret
}
... on PersonnePhysique {
nom
prenom
civilite
}
}
dateDepot
dateDerniereModification
dateExpiration
datePassageEnConstruction
datePassageEnInstruction
dateSuppressionParAdministration
dateSuppressionParUsager
dateTraitement
pdf {
url
}
}
}
}
}
`;
console.log("Fetching data from demarche-simplifiee...");
const dsData = await dsApi
.post("", { json: { query, variables: {} } })
.json();
const uploadedDataColumns = new Map([
["ds_id", "DS ID"],
["statut", "Statut"],
["pdf", "PDF"],
["demandeur", "Demandeur"],
["demandeur_siret", "Demandeur (Siret)"],
]);
// Build records data
const uploadDataPayload = {
records: dsData.data.demarche.dossiers.nodes.map((dossier) => {
let demandeur;
let demandeurSiret;
if (dossier.demandeur.__typename === "PersonneMorale") {
demandeur =
dossier.demandeur.entreprise?.raisonSociale ||
dossier.demandeur.association?.titre;
demandeurSiret = dossier.demandeur.siret;
} else if (dossier.demandeur.__typename === "PersonnePhysique") {
demander = `${dossier.demandeur.civilite} ${dossier.demandeur.prenom} ${dossier.demandeur.nom}`;
} else if (dossier.demandeur.__typename === "PersonneMoraleIncomplete") {
demandeurSiret = dossier.demandeur.siret;
}
return {
require: {
ds_id: dossier.id,
},
fields: {
ds_id: dossier.id,
statut: dossier.state,
pdf: dossier.pdf.url,
demandeur: demandeur,
demandeur_siret: demandeurSiret,
...Object.fromEntries(
dossier.champs.map((c) => {
let value = c.stringValue;
// File field
if (c.__typename === "PieceJustificativeChamp") {
if (c.files.length) {
value = c.files[0].url;
}
}
uploadedDataColumns.set(dsIdToGristId(c.id), c.label);
return [dsIdToGristId(c.id), value];
})
),
},
};
}),
};
// Compare existing columns with records data columns
// - fetch existings columns
console.log("Fetching existing columns from Grist");
const { columns } = await gristApi.get("columns").json();
const columnIds = columns.map((col) => col.id);
// - list columns to be uploaded
const uploadedDataColumnIds = Array.from(uploadedDataColumns.keys());
// If needed create new columns on Grist
const columnDifference = _.difference(uploadedDataColumnIds, columnIds);
if (columnDifference.length > 0) {
console.log(
`${columnDifference.length} missing columns. Creating new columns...`
);
const newColumnsPayload = {
columns: columnDifference.map((colId) => ({
id: colId,
fields: { label: uploadedDataColumns.get(colId) },
})),
};
await gristApi.post("columns", { json: newColumnsPayload });
console.log("✅ New columns created on Grist");
} else {
console.log("No column update needed.");
}
// Send new records to grist
console.log("Uploading form data to Grist...");
await gristApi.put("records", { json: uploadDataPayload });
console.log("✅ Successfully uploaded data to Grist");
}
main();
/**
*
* @param {string} dsId
* @returns string
*/
export function dsIdToGristId(dsId) {
return atob(dsId).toLowerCase().replace("-", "_");
}