|
| 1 | +import "server-only"; |
| 2 | +import atcOfficialLabels from "@/data/ATC 2024 02 15.json"; |
| 3 | + |
| 4 | +async function getGristTableData(tableId: string) { |
| 5 | + const response = await fetch( |
| 6 | + `https://grist.numerique.gouv.fr/api/docs/${process.env.GRIST_DOC_ID}/tables/${tableId}/records`, |
| 7 | + { |
| 8 | + headers: { |
| 9 | + Authorization: `Bearer ${process.env.GRIST_API_KEY}`, |
| 10 | + }, |
| 11 | + }, |
| 12 | + ); |
| 13 | + return await response.json(); |
| 14 | +} |
| 15 | + |
| 16 | +async function getAtcLabel1(code: string): Promise<string> { |
| 17 | + const data = await getGristTableData("Table_Niveau_1"); |
| 18 | + const record = data.records.find( |
| 19 | + (record: any) => record.fields.Lettre_1_ATC_1 === code.slice(0, 1), |
| 20 | + ); |
| 21 | + if (!record) { |
| 22 | + throw new Error(`ATC code not found: ${code.slice(0, 1)}`); |
| 23 | + } |
| 24 | + |
| 25 | + return record.fields.Libelles_niveau_1; |
| 26 | +} |
| 27 | + |
| 28 | +async function getAtcLabel2(code: string): Promise<string> { |
| 29 | + const atcData = await getGristTableData("Table_Niveau_2"); |
| 30 | + const record = atcData.records.find( |
| 31 | + (record: any) => record.fields.Lettre_2_ATC2 === code.slice(0, 3), |
| 32 | + ); |
| 33 | + if (!record) { |
| 34 | + throw new Error(`ATC code not found: ${code.slice(0, 3)}`); |
| 35 | + } |
| 36 | + |
| 37 | + const libeleId = record.fields.Libelles_niveau_2; |
| 38 | + const libeleData = await getGristTableData("Intitules_possibles"); |
| 39 | + const libeleRecord = libeleData.records.find( |
| 40 | + (record: any) => record.id === libeleId, |
| 41 | + ); |
| 42 | + |
| 43 | + if (!libeleRecord) { |
| 44 | + throw new Error(`ATC code not found: ${code.slice(0, 3)}`); |
| 45 | + } |
| 46 | + |
| 47 | + return libeleRecord.fields.Libelles_niveau_2; |
| 48 | +} |
| 49 | + |
| 50 | +async function getAtcOfficialLabel(code: string): Promise<string> { |
| 51 | + if (!(code.slice(0, 7) in atcOfficialLabels)) { |
| 52 | + throw new Error(`ATC code not found: ${code.slice(0, 7)}`); |
| 53 | + } |
| 54 | + |
| 55 | + return (atcOfficialLabels as Record<string, string>)[code.slice(0, 7)]; |
| 56 | +} |
| 57 | + |
| 58 | +export async function getAtcLabels(atc: string): Promise<string[]> { |
| 59 | + return Promise.all( |
| 60 | + [getAtcLabel1, getAtcLabel2, getAtcOfficialLabel].map((f) => f(atc)), |
| 61 | + ); |
| 62 | +} |
0 commit comments