From bb6d2913ef4cff8331133bda5dfc6a5ad2dea7a4 Mon Sep 17 00:00:00 2001 From: Gauthier Eholoum Date: Thu, 3 Dec 2026 10:48:45 +0000 Subject: [PATCH 1/2] feat: report a fact without an account --- astro.config.mjs | 5 +- src/components/contribute/ChoiceCard.astro | 17 ++ src/components/contribute/ChoiceField.astro | 21 ++ src/components/contribute/ConsentField.astro | 17 ++ .../contribute/ContributeIcon.astro | 16 + .../contribute/ContributePage.astro | 45 +++ src/components/contribute/DonePanel.astro | 35 +++ src/components/contribute/FieldError.astro | 12 + src/components/contribute/HowItWorks.astro | 28 ++ src/components/contribute/PickerBox.astro | 20 ++ src/components/contribute/ReportPage.astro | 106 +++++++ src/components/contribute/TextField.astro | 30 ++ src/components/contribute/WizardPage.astro | 84 ++++++ src/components/contribute/YouStep.astro | 25 ++ src/components/provider/EmptySection.astro | 15 +- src/components/provider/ProviderPage.astro | 19 +- src/contribute/build-options.ts | 71 +++++ src/contribute/challenge.ts | 85 ++++++ src/contribute/constants.ts | 32 ++ src/contribute/dom.ts | 43 +++ src/contribute/draft.ts | 41 +++ src/contribute/fee-field.ts | 68 +++++ src/contribute/form-types.ts | 19 ++ src/contribute/icons.ts | 50 ++++ src/contribute/links.ts | 13 + src/contribute/listed.ts | 27 ++ src/contribute/load-turnstile.ts | 25 ++ src/contribute/moment.ts | 23 ++ src/contribute/picker.ts | 154 ++++++++++ src/contribute/report-form.ts | 82 ++++++ src/contribute/send.ts | 16 + src/contribute/service-field.ts | 62 ++++ src/contribute/turnstile-types.ts | 25 ++ src/contribute/types.ts | 94 ++++++ src/contribute/validate.ts | 109 +++++++ src/contribute/web-address.ts | 14 + src/contribute/wizard.ts | 273 ++++++++++++++++++ src/i18n/contribute-en.ts | 168 +++++++++++ src/i18n/contribute-fr.ts | 168 +++++++++++ src/i18n/contribute-types.ts | 159 ++++++++++ src/i18n/translate.ts | 9 + src/i18n/ui-en.ts | 7 +- src/i18n/ui-fr.ts | 11 +- src/lib/form-links.ts | 7 +- src/lib/live-pages.ts | 2 +- src/pages/[locale]/contribute/index.astro | 12 + src/pages/[locale]/contribute/report.astro | 12 + src/styles/contribute.css | 216 ++++++++++++++ tests/contribute-options.test.ts | 66 +++++ tests/contribute-validate.test.ts | 93 ++++++ tests/form-links.test.ts | 12 +- tests/live-pages.test.ts | 3 +- 52 files changed, 2724 insertions(+), 42 deletions(-) create mode 100644 src/components/contribute/ChoiceCard.astro create mode 100644 src/components/contribute/ChoiceField.astro create mode 100644 src/components/contribute/ConsentField.astro create mode 100644 src/components/contribute/ContributeIcon.astro create mode 100644 src/components/contribute/ContributePage.astro create mode 100644 src/components/contribute/DonePanel.astro create mode 100644 src/components/contribute/FieldError.astro create mode 100644 src/components/contribute/HowItWorks.astro create mode 100644 src/components/contribute/PickerBox.astro create mode 100644 src/components/contribute/ReportPage.astro create mode 100644 src/components/contribute/TextField.astro create mode 100644 src/components/contribute/WizardPage.astro create mode 100644 src/components/contribute/YouStep.astro create mode 100644 src/contribute/build-options.ts create mode 100644 src/contribute/challenge.ts create mode 100644 src/contribute/constants.ts create mode 100644 src/contribute/dom.ts create mode 100644 src/contribute/draft.ts create mode 100644 src/contribute/fee-field.ts create mode 100644 src/contribute/form-types.ts create mode 100644 src/contribute/icons.ts create mode 100644 src/contribute/links.ts create mode 100644 src/contribute/listed.ts create mode 100644 src/contribute/load-turnstile.ts create mode 100644 src/contribute/moment.ts create mode 100644 src/contribute/picker.ts create mode 100644 src/contribute/report-form.ts create mode 100644 src/contribute/send.ts create mode 100644 src/contribute/service-field.ts create mode 100644 src/contribute/turnstile-types.ts create mode 100644 src/contribute/types.ts create mode 100644 src/contribute/validate.ts create mode 100644 src/contribute/web-address.ts create mode 100644 src/contribute/wizard.ts create mode 100644 src/i18n/contribute-en.ts create mode 100644 src/i18n/contribute-fr.ts create mode 100644 src/i18n/contribute-types.ts create mode 100644 src/pages/[locale]/contribute/index.astro create mode 100644 src/pages/[locale]/contribute/report.astro create mode 100644 src/styles/contribute.css create mode 100644 tests/contribute-options.test.ts create mode 100644 tests/contribute-validate.test.ts diff --git a/astro.config.mjs b/astro.config.mjs index 4a7c442..a78fa10 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -15,6 +15,9 @@ const site = 'https://paymap.africa'; /** The bare address only picks a language and is not indexed, so it stays out of the sitemap. */ const isLanguagePicker = (page) => page === `${site}/`; +/** The contribution forms are tools, not content: they are not indexed. */ +const isContributionForm = (page) => /\/contribute(\/|$)/.test(new URL(page).pathname); + /** Dates come from the records, never from the build time: a page without a record date has no lastmod. */ const { published, glossary } = loadSite(currentDataRoot()); const lastmods = lastmodByUrl(site, ['en', 'fr'], published, glossary); @@ -31,7 +34,7 @@ export default defineConfig({ }, integrations: [ sitemap({ - filter: (page) => !isLanguagePicker(page), + filter: (page) => !isLanguagePicker(page) && !isContributionForm(page), serialize: (item) => { const lastmod = lastmods.get(item.url); diff --git a/src/components/contribute/ChoiceCard.astro b/src/components/contribute/ChoiceCard.astro new file mode 100644 index 0000000..83dc125 --- /dev/null +++ b/src/components/contribute/ChoiceCard.astro @@ -0,0 +1,17 @@ +--- +/** One answer of a question: its drawing (the slot), its name, what it means. */ +interface Props { + name: string; + value: string; + label: string; + help?: string; +} + +const { name, value, label, help } = Astro.props; +--- + + diff --git a/src/components/contribute/ChoiceField.astro b/src/components/contribute/ChoiceField.astro new file mode 100644 index 0000000..57c94bc --- /dev/null +++ b/src/components/contribute/ChoiceField.astro @@ -0,0 +1,21 @@ +--- +import FieldError from './FieldError.astro'; + +/** A question answered by picking one card. The cards are the slot. */ +interface Props { + name: string; + label: string; + /** Explanations stay visible on phones. */ + explained?: boolean; + /** An odd number of cards: the last one takes the whole row. */ + odd?: boolean; +} + +const { name, label, explained = false, odd = false } = Astro.props; +--- + +
+ {label} +
+ +
diff --git a/src/components/contribute/ConsentField.astro b/src/components/contribute/ConsentField.astro new file mode 100644 index 0000000..e8fcdcf --- /dev/null +++ b/src/components/contribute/ConsentField.astro @@ -0,0 +1,17 @@ +--- +import type { Locale } from '../../i18n/locales'; +import { contributeStrings } from '../../i18n/translate'; +import FieldError from './FieldError.astro'; + +/** The licence the visitor accepts before sending. */ +interface Props { + locale: Locale; +} + +const { locale } = Astro.props; +--- + +
+ + +
diff --git a/src/components/contribute/ContributeIcon.astro b/src/components/contribute/ContributeIcon.astro new file mode 100644 index 0000000..37d01c7 --- /dev/null +++ b/src/components/contribute/ContributeIcon.astro @@ -0,0 +1,16 @@ +--- +import { CONTRIBUTE_ICONS, CONTRIBUTE_TONES, type ContributeIconName, type ContributeTone } from '../../contribute/icons'; + +/** A drawing of the contribution pages, on its coloured disc when a tone is given. Decorative: a name is always next to it. */ +interface Props { + name: ContributeIconName; + tone?: ContributeTone; +} + +const { name, tone } = Astro.props; +const look = tone === undefined ? undefined : CONTRIBUTE_TONES[tone]; +--- + + diff --git a/src/components/contribute/ContributePage.astro b/src/components/contribute/ContributePage.astro new file mode 100644 index 0000000..5eb3e6c --- /dev/null +++ b/src/components/contribute/ContributePage.astro @@ -0,0 +1,45 @@ +--- +import type { Locale } from '../../i18n/locales'; +import { REPORT_PATH } from '../../contribute/links'; +import { catalogueStrings, contributeStrings, localePath } from '../../i18n/translate'; +import { CONTRIBUTING_URL, EXPERIENCE_URL, NEW_PROVIDER_URL } from '../../lib/site-links'; +import Breadcrumb from '../Breadcrumb.astro'; +import Layout from '../Layout.astro'; +import '../../styles/contribute.css'; + +/** The three ways to take part, for people without a GitHub account first. */ +interface Props { + locale: Locale; +} + +const { locale } = Astro.props; +const strings = contributeStrings(locale); +const t = strings.choose; +const trail = catalogueStrings(locale); +const cards = [ + { ...t.suggest, cta: t.reviewCta, href: NEW_PROVIDER_URL, main: true, icon: 'M11 4v14M4 11h14' }, + { ...t.report, cta: t.start, href: localePath(locale, REPORT_PATH), main: false, icon: 'M5 19V4M5 5h11l-2.5 3.5L16 12H5' }, + { ...t.review, cta: t.reviewCta, href: EXPERIENCE_URL, main: false, icon: 'M11 3.5l2.3 4.7 5.2.8-3.8 3.6.9 5.2-4.6-2.5-4.6 2.5.9-5.2L3.5 9l5.2-.8z' }, +]; +--- + + +
+ +
+

{t.heading}

+

{t.intro}

+
+
+ {cards.map((card) => ( + + +

{card.title}

+

{card.text}

+ {card.cta} +
+ ))} +
+ {t.developer} +
+
diff --git a/src/components/contribute/DonePanel.astro b/src/components/contribute/DonePanel.astro new file mode 100644 index 0000000..f0c79e4 --- /dev/null +++ b/src/components/contribute/DonePanel.astro @@ -0,0 +1,35 @@ +--- +import type { Locale } from '../../i18n/locales'; +import { contributeStrings, localePath } from '../../i18n/translate'; +import CheckIcon from '../CheckIcon.astro'; + +/** Shown in place of the form once it is sent. */ +interface Props { + locale: Locale; + heading: string; + again: string; + againHref: string; +} + +const { locale, heading, again, againHref } = Astro.props; +const t = contributeStrings(locale).common; +--- + + diff --git a/src/components/contribute/FieldError.astro b/src/components/contribute/FieldError.astro new file mode 100644 index 0000000..ebc91e7 --- /dev/null +++ b/src/components/contribute/FieldError.astro @@ -0,0 +1,12 @@ +--- +import ContributeIcon from './ContributeIcon.astro'; + +/** Where the message of a refused answer is written. Empty until then. */ +interface Props { + field: string; +} + +const { field } = Astro.props; +--- + + diff --git a/src/components/contribute/HowItWorks.astro b/src/components/contribute/HowItWorks.astro new file mode 100644 index 0000000..c693fdf --- /dev/null +++ b/src/components/contribute/HowItWorks.astro @@ -0,0 +1,28 @@ +--- +import type { Locale } from '../../i18n/locales'; +import { contributeStrings } from '../../i18n/translate'; +import ContributeIcon from './ContributeIcon.astro'; + +/** What happens to a contribution: a panel next to the form, folded under it on phones. */ +interface Props { + locale: Locale; + first: string; + githubUrl: string; +} + +const { locale, first, githubUrl } = Astro.props; +const t = contributeStrings(locale).common; +const rows = [ + { icon: 'pen', title: first, text: t.howSend }, + { icon: 'shield', title: t.howCheck, text: t.howCheckText }, + { icon: 'check', title: t.howPublish, text: t.howPublishText }, +] as const; +--- + +
+ {t.how} +
    + {rows.map(({ icon, title, text }) =>
  1. {title}{text}
  2. )} +
+ {t.developer} +
diff --git a/src/components/contribute/PickerBox.astro b/src/components/contribute/PickerBox.astro new file mode 100644 index 0000000..8515885 --- /dev/null +++ b/src/components/contribute/PickerBox.astro @@ -0,0 +1,20 @@ +--- +/** A search field and the list it filters. The script fills the list. */ +interface Props { + id: string; + label: string; + placeholder: string; + none: string; + describedBy?: string; +} + +const { id, label, placeholder, none, describedBy } = Astro.props; +--- + +
+ + +
diff --git a/src/components/contribute/ReportPage.astro b/src/components/contribute/ReportPage.astro new file mode 100644 index 0000000..9cd3cd5 --- /dev/null +++ b/src/components/contribute/ReportPage.astro @@ -0,0 +1,106 @@ +--- +import { providerOptions } from '../../contribute/build-options'; +import { TOPICS } from '../../contribute/constants'; +import { TOPIC_LOOK } from '../../contribute/icons'; +import type { Locale } from '../../i18n/locales'; +import { catalogueStrings, contributeStrings } from '../../i18n/translate'; +import type { Family } from '../../lib/catalogue-types'; +import { FAMILY_LOOK } from '../../lib/family-look'; +import { currentSite } from '../../lib/site-data'; +import ChoiceCard from './ChoiceCard.astro'; +import ChoiceField from './ChoiceField.astro'; +import ConsentField from './ConsentField.astro'; +import ContributeIcon from './ContributeIcon.astro'; +import FieldError from './FieldError.astro'; +import PickerBox from './PickerBox.astro'; +import TextField from './TextField.astro'; +import WizardPage from './WizardPage.astro'; +import YouStep from './YouStep.astro'; + +/** "Report a fact": which provider, what is wrong, where it is written. */ +interface Props { + locale: Locale; +} + +const { locale } = Astro.props; +const strings = contributeStrings(locale); +const t = strings.report; +const families = Object.fromEntries(Object.entries(catalogueStrings(locale).families).map(([id, { one }]) => [id, { label: one, icon: FAMILY_LOOK[id as Family].icon }])); +const providers = providerOptions(currentSite(), locale); +--- + + + +
+ + + + + +
+ + + {TOPICS.map((topic) => ( + + ))} + + + + + +
+ + + + + + + + + +
+
+ + + +
+
+
{t.before}
+ +
{t.after}
+
+
+
+
+ + +
+
+ + +
+
+ +
+
+ + diff --git a/src/components/contribute/TextField.astro b/src/components/contribute/TextField.astro new file mode 100644 index 0000000..0fef86c --- /dev/null +++ b/src/components/contribute/TextField.astro @@ -0,0 +1,30 @@ +--- +import { MAX_LENGTH } from '../../contribute/constants'; +import type { Locale } from '../../i18n/locales'; +import { contributeStrings } from '../../i18n/translate'; +import FieldError from './FieldError.astro'; + +/** A labelled field of one line, or of several when `lines` is given. */ +interface Props { + locale: Locale; + name: string; + label: string; + type?: 'text' | 'url' | 'email' | 'date'; + placeholder?: string; + help?: string; + optional?: boolean; + lines?: number; + autocomplete?: 'email' | 'nickname' | 'off'; +} + +const { locale, name, label, type = 'text', placeholder, help, optional = false, lines, autocomplete = 'off' } = Astro.props; +const described = [help === undefined ? '' : `${name}-help`, `${name}-error`].filter(Boolean).join(' '); +const shared = { id: name, name, class: 'cf-in', placeholder, autocomplete, maxlength: MAX_LENGTH[name], 'aria-describedby': described }; +--- + +
+ + {lines === undefined ? : `; + + return row(entry, look, control, links.length === 0 ? null : html`${links.map((link, index) => openLink(link, `${look.label} ${index + 1}`))}`); +} + +export function choiceField(entry: Entry, look: Look, choices: 'topic' | 'family'): Html { + const current = first(entry.answers, look.field); + const options = (choices === 'topic' ? TOPIC_CHOICES : FAMILY_CHOICES).map(([value, label]) => html``); + + return row(entry, look, html``, null); +} + +/** Pills that can be taken off or put back, and a list to add a country. */ +export function countriesField(entry: Entry): Html { + const codes = [...new Set([...(entry.answers['countries'] ?? []), ...(entry.received['countries'] ?? [])])]; + const pills = codes.map((code) => pill('countries', code, countryName('fr', code), html``, entry.answers['countries']?.includes(code) === true)); + const options = COUNTRY_CHOICES.map(([code, name]) => html``); + + return group(entry, 'countries', TEXTS.places, html`${pills}`); +} + +export function methodsField(entry: Entry): Html { + const pills = METHODS.map((method) => pill('methods', method, methodName(method), drawing(METHOD_ICON[method]), entry.answers['methods']?.includes(method) === true)); + + return group(entry, 'methods', TEXTS.methods, html`${pills}`); +} + +/** The proposed value, large, in the tile where the change is read. */ +export function valueField(entry: Entry): Html { + const value = first(entry.answers, 'value'); + + return html`
${drawing('edit')}${was(entry, 'value')}
`; +} + +/** The name of a suggested provider, as a title. */ +export function nameField(entry: Entry): Html { + return html`
${drawing('edit')}${was(entry, 'name')}
`; +} + +/** How an answer reads in a sentence. */ +export function shown(answers: Answers, field: string): string { + const value = first(answers, field); + if (field === 'topic') return TOPIC_CHOICES.find(([key]) => key === value)?.[1] ?? value; + if (field === 'family') return FAMILY_CHOICES.find(([key]) => key === value)?.[1] ?? value; + if (field === 'countries') return (answers[field] ?? []).map((code) => countryName('fr', code)).join(', '); + if (field === 'methods') return (answers[field] ?? []).map((method) => METHODS.find((known) => known === method)).flatMap((method) => (method === undefined ? [] : methodName(method))).join(', '); + + return field === 'seen_on' ? shortDay(value) : value; +} + +function row(entry: Entry, { field, label, icon, tone }: Look, control: Html, end: Html | null): Html { + return html`
${disc(icon, tone)}${control}${was(entry, field)}${end}
`; +} + +function group(entry: Entry, field: string, label: string, pills: Html): Html { + return html`
${label}
${pills}
${was(entry, field)}
`; +} + +function pill(field: string, value: string, label: string, mark: Html, on: boolean): Html { + return html``; +} + +/** What was received, shown once the maintainer's version differs. */ +function was(entry: Entry, field: string): Html { + const values = entry.received[field] ?? []; + const same = JSON.stringify(values) === JSON.stringify(entry.answers[field] ?? []); + + return html`${TEXTS.received} ${shown(entry.received, field) || TEXTS.nothing}`; +} + +function openLink(href: string, label: string): Html { + return html`${TEXTS.open} →`; +} + +function methodName(method: MethodChoice): string { + return method === 'other' ? forms.suggest.otherMethod : catalogueStrings('fr').methods[method]; +} diff --git a/service/review/github.ts b/service/review/github.ts new file mode 100644 index 0000000..de3426e --- /dev/null +++ b/service/review/github.ts @@ -0,0 +1,39 @@ +import { z } from 'zod'; + +import type { Issue } from './types'; + +const API = 'https://api.github.com'; + +const INSIDERS: ReadonlySet = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']); + +const created = z.object({ number: z.number().int() }); + +const listed = z.array(z.object({ number: z.number().int(), body: z.string().nullable(), author_association: z.string().optional(), pull_request: z.unknown().optional() })); + +/** + * Number of the issue that carries the marker, created when there is none. An issue whose answer was lost is + * found again instead of being created twice. `null` when GitHub does not answer as expected. + */ +export async function openIssue(issue: Issue, marker: string, repo: string, token: string): Promise { + const call = (path: string, init: RequestInit = {}): Promise => + fetch(`${API}/repos/${repo}/issues${path}`, { + ...init, + headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', 'User-Agent': 'paymap-contributions', 'X-GitHub-Api-Version': '2022-11-28' }, + signal: AbortSignal.timeout(10_000), + }); + + try { + const recent = await call('?state=all&sort=created&direction=desc&per_page=50'); + if (!recent.ok) return null; + + // Anyone can copy a marker into an issue of theirs: only the project's own count. + const known = listed.parse(await recent.json()).find((found) => found.pull_request === undefined && INSIDERS.has(found.author_association ?? '') && found.body?.endsWith(marker) === true); + if (known !== undefined) return known.number; + + const answer = await call('', { method: 'POST', body: JSON.stringify({ ...issue, body: `${issue.body}\n\n${marker}` }) }); + + return answer.status === 201 ? created.parse(await answer.json()).number : null; + } catch { + return null; + } +} diff --git a/service/review/html.ts b/service/review/html.ts new file mode 100644 index 0000000..3a6f017 --- /dev/null +++ b/service/review/html.ts @@ -0,0 +1,24 @@ +/** Markup that is safe to write as it is. */ +export class Html { + constructor(readonly text: string) {} +} + +type Part = Html | string | number | boolean | null | undefined | readonly Part[]; + +/** Builds markup. Every value is escaped unless it is markup itself. */ +export function html(strings: TemplateStringsArray, ...parts: readonly Part[]): Html { + return new Html(strings.reduce((text, string, index) => text + write(parts[index - 1]) + string)); +} + +/** Markup kept in this repository, never a visitor's text. */ +export function trusted(text: string): Html { + return new Html(text); +} + +function write(part: Part): string { + if (part instanceof Html) return part.text; + if (Array.isArray(part)) return part.map(write).join(''); + if (part === null || part === undefined || typeof part === 'boolean') return ''; + + return String(part).replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`); +} diff --git a/service/review/issue-text.ts b/service/review/issue-text.ts new file mode 100644 index 0000000..fb178fa --- /dev/null +++ b/service/review/issue-text.ts @@ -0,0 +1,86 @@ +import { countryName } from '../../src/i18n/country-names'; +import type { Answers } from '../../src/contribute/types'; +import { first } from '../../src/contribute/validate'; +import { catalogueStrings, contributeStrings } from '../../src/i18n/translate'; +import type { Directory, Entry, Issue } from './types'; + +/** The public issue of a contribution. It is written field by field, so that nothing private can slip in. */ +export function issueText(entry: Entry, directory: Directory): Issue { + return entry.kind === 'report' ? reportIssue(entry, directory) : suggestIssue(entry); +} + +/** Hidden in the issue, so that the same contribution is never published twice. */ +export function issueMarker(id: string): string { + return ``; +} + +function reportIssue({ answers }: Entry, directory: Directory): Issue { + const slug = first(answers, 'service'); + const topic = topicName(first(answers, 'topic')); + + return { + title: `Correction: ${oneLine(directory.get(slug) ?? slug)}, ${topic}`, + body: sections([ + ['Service', slug], + ['What it is about', topic], + ['What Paymap shows', first(answers, 'shown')], + ['What it should be', first(answers, 'value')], + ['Official source', first(answers, 'source')], + ['Seen on', first(answers, 'seen_on')], + ...person(answers), + ]), + labels: ['correction', 'needs review'], + }; +} + +function suggestIssue({ answers }: Entry): Issue { + const family = first(answers, 'family'); + const families = catalogueStrings('en').families; + + return { + title: `New provider: ${oneLine(first(answers, 'name'))}`, + body: sections([ + ['Name', first(answers, 'name')], + ['Website', first(answers, 'website')], + ['Type', isFamily(family, families) ? families[family].one : 'Not known'], + ['Countries', (answers['countries'] ?? []).map((code) => countryName('en', code)).join(', ')], + ['Payment methods', (answers['methods'] ?? []).join(', ')], + ['Official links', first(answers, 'links')], + ...person(answers), + ]), + labels: ['new provider', 'needs review'], + }; +} + +function person(answers: Answers): (readonly [string, string])[] { + return [ + ['Works for this service', first(answers, 'linked')], + ['Credit', first(answers, 'credit') === 'yes' ? first(answers, 'credit_name') : 'Anonymous'], + ]; +} + +/** Each answer in a block of plain text: no mention, image or link a visitor wrote comes alive on GitHub. */ +function sections(rows: readonly (readonly [string, string])[]): string { + const filled = rows.filter(([, text]) => text !== '').map(([title, text]) => `### ${title}\n\n${block(text)}`); + + return ['Sent through the guided form of the site, read by a maintainer, not checked yet.', ...filled].join('\n\n'); +} + +function block(text: string): string { + const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map(([run]) => run.length)); + const fence = '`'.repeat(longest + 1); + + return `${fence}text\n${text}\n${fence}`; +} + +function oneLine(text: string): string { + return text.replace(/\s+/g, ' ').replace(/[@#<>`]/g, '').trim().slice(0, 80); +} + +function topicName(topic: string): string { + return Object.entries(contributeStrings('en').report.topics).find(([key]) => key === topic)?.[1] ?? topic; +} + +function isFamily(key: string, families: T): key is Extract { + return Object.hasOwn(families, key); +} diff --git a/service/review/pages.ts b/service/review/pages.ts new file mode 100644 index 0000000..33d7d1a --- /dev/null +++ b/service/review/pages.ts @@ -0,0 +1,128 @@ +import { first } from '../../src/contribute/validate'; +import { STATUSES } from './constants'; +import { moment } from './dates'; +import { areaField, choiceField, countriesField, methodsField, nameField, shown, textField, valueField } from './fields'; +import { html, type Html } from './html'; +import { disc, drawing, logo, nameOf, noticeBox } from './parts'; +import { ASK, TEXTS } from './texts'; +import type { Directory, Entry, Notice, ReviewTools, Status } from './types'; + +type Links = Pick; + +export interface ListView { + readonly status: Status; + readonly entries: readonly Entry[]; + readonly counts: Readonly>; + readonly notice: Notice | null; +} + +/** The lists: to read, being checked, published, refused. */ +export function listPage(view: ListView, directory: Directory, links: Links, now: Date): string { + const { status, entries, counts, notice } = view; + const tabs = STATUSES.map((key) => html`${TEXTS.tabs[key]} ${['pending', 'checking'].includes(key) && html`${counts[key]}`}`); + const items = entries.map((entry) => (status === 'pending' ? pendingItem(entry, directory, links, now) : decidedItem(entry, directory, links, now))); + const [title, text] = TEXTS.empty[status]; + const body = items.length > 0 ? html`
${items}
` : html`
${drawing('check')}

${title}

${text}

`; + + return frame(html`${notice && noticeBox(notice)}

${TEXTS.tabs[status]}

${body}`); +} + +/** One contribution. Every value is corrected where it is read. */ +export function entryPage(entry: Entry, directory: Directory, links: Links, notice: Notice | null): string { + const main = entry.kind === 'report' ? reportParts(entry, directory, links) : suggestParts(entry, directory, links); + + return frame(html`← ${TEXTS.tabs.pending}${notice && noticeBox(notice)}
${main}${personParts(entry, directory)}
${decision()}
`); +} + +export function messagePage(text: string): string { + return frame(html`
${drawing('lock')}

${text}

`); +} + +function frame(body: Html): string { + return html`${TEXTS.title}
Paymap${drawing('lock')}${TEXTS.private}${TEXTS.signOut}
${body}
`.text; +} + +function pendingItem(entry: Entry, directory: Directory, links: Links, now: Date): Html { + return html`${logo(entry, directory, links.siteUrl)}${nameOf(entry, directory)}${about(entry)}${change(entry)}${entry.edited && html`${TEXTS.editedByYou}`}${moment(entry.receivedAt, now)}→`; +} + +function decidedItem(entry: Entry, directory: Directory, links: Links, now: Date): Html { + const when = entry.status === 'published' ? `${TEXTS.publishedAt} · ${moment(entry.publishedAt ?? '', now)}` : `${entry.status === 'refused' ? TEXTS.refusedAt : TEXTS.sentAt} · ${moment(entry.decidedAt ?? '', now)}`; + const reason = entry.reason === null ? '' : ` · ${TEXTS.reasons[entry.reason]}`; + const issue = entry.issue !== null && html`${TEXTS.onGitHub} →`; + const publish = entry.status === 'checking' && html`
`; + + return html`
${logo(entry, directory, links.siteUrl)}${nameOf(entry, directory)}${about(entry)}${change(entry)}${issue}
${track(entry.status)}
${when}${reason}${entry.edited && ` · ${TEXTS.editedByYou}`}${publish}
`; +} + +function track(status: Status): Html { + const { received, checking, published, refused } = TEXTS.steps; + const step = (look: string, icon: 'tick' | 'clock' | 'alert', label: string): Html => html`
  • ${drawing(icon)}${label}
  • `; + if (status === 'refused') return html`
      ${step('past', 'tick', received)}${step('bad', 'alert', refused)}
    `; + + const done = status === 'published'; + + return html`
      ${step('past', 'tick', received)}${step(done ? 'past' : 'on', done ? 'tick' : 'clock', checking)}${step(done ? 'past' : '', done ? 'tick' : 'clock', published)}
    `; +} + +function about(entry: Entry): string { + if (entry.kind === 'suggest') return `${TEXTS.newProvider} · ${familyOf(entry)}`; + + return [shown(entry.answers, 'topic'), place(entry)].filter(Boolean).join(' · '); +} + +function familyOf(entry: Entry): string { + return first(entry.answers, 'family') === 'unknown' ? TEXTS.unknownFamily : shown(entry.answers, 'family'); +} + +function change(entry: Entry): Html { + if (entry.kind === 'suggest') return html`${TEXTS.countries(entry.answers['countries']?.length ?? 0)}`; + + const before = first(entry.answers, 'shown_rate'); + + return html`${before !== '' && html`${before} → `}${first(entry.answers, 'value')}`; +} + +function place(entry: Entry): string { + return first(entry.answers, 'shown').split(' · ').slice(0, 2).join(', '); +} + +function reportParts(entry: Entry, directory: Directory, links: Links): Html { + const slug = first(entry.answers, 'service'); + const before = first(entry.answers, 'shown_rate'); + const sheet = directory.has(slug) && html`${TEXTS.sheet} →`; + + return html`
    ${logo(entry, directory, links.siteUrl)}

    ${nameOf(entry, directory)}

    ${place(entry)}
    ${sheet}
    ${before !== '' && html`
    ${TEXTS.before}${before}
    →`}${valueField(entry)}
    + ${first(entry.received, 'shown') !== '' && textField(entry, { field: 'shown', label: TEXTS.shown, icon: 'percent', tone: 'money' })} + ${textField(entry, { field: 'source', label: TEXTS.source, icon: 'link', tone: 'rules' })} +
    ${choiceField(entry, { field: 'topic', label: TEXTS.topic, icon: 'ask', tone: 'plain' }, 'topic')}${textField(entry, { field: 'seen_on', label: TEXTS.seenOn, icon: 'clock', tone: 'methods' }, 'date')}
    `; +} + +function suggestParts(entry: Entry, directory: Directory, links: Links): Html { + return html`
    ${logo(entry, directory, links.siteUrl)}${nameField(entry)}${TEXTS.newProvider}
    ${countriesField(entry)}${methodsField(entry)}
    +
    ${textField(entry, { field: 'website', label: TEXTS.website, icon: 'globe', tone: 'methods' })}${choiceField(entry, { field: 'family', label: TEXTS.family, icon: 'shop', tone: 'actors' }, 'family')}
    + ${areaField(entry, { field: 'links', label: TEXTS.links, icon: 'link', tone: 'rules' })}`; +} + +function personParts(entry: Entry, directory: Directory): Html { + const named = first(entry.answers, 'credit') === 'yes'; + const tie = first(entry.answers, 'linked') === 'yes' ? TEXTS.linked : TEXTS.notLinked; + const person = named ? textField(entry, { field: 'credit_name', label: `${TEXTS.credit} · ${tie}`, icon: 'user', tone: 'actors' }) : html`
    ${disc('user', 'actors')}${tie}${TEXTS.anonymous}
    `; + const ask = entry.email !== null && html`${TEXTS.ask} →`; + + return html`${person}
    ${disc('mail', 'methods')}${entry.email === null ? TEXTS.noEmail : TEXTS.emailKept}${entry.email !== null && html`${entry.email}`}${ask}
    `; +} + +function mailto(entry: Entry, email: string, directory: Directory): string { + const { subject, body } = ASK[entry.locale]; + const text = body.replace('{name}', () => nameOf(entry, directory)); + + return `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(text)}`; +} + +function decision(): Html { + const reasons = Object.entries(TEXTS.reasons).map(([key, label], index) => html``); + + return html``; +} + diff --git a/service/review/parts.ts b/service/review/parts.ts new file mode 100644 index 0000000..b73a705 --- /dev/null +++ b/service/review/parts.ts @@ -0,0 +1,52 @@ +import logos from '../../data/reference/logos.json'; +import { CONTRIBUTE_ICONS, CONTRIBUTE_TONES, type ContributeIconName, type ContributeTone } from '../../src/contribute/icons'; +import { first } from '../../src/contribute/validate'; +import { normalise } from '../../src/lib/search-match'; +import { html, trusted, type Html } from './html'; +import type { Directory, Entry, Notice } from './types'; + +const DRAWINGS = { + ...CONTRIBUTE_ICONS, + lock: '', + mail: '', + edit: '', + undo: '', + clock: '', + tick: '', +} as const; + +export type DrawingName = keyof typeof DRAWINGS; + +export function drawing(name: DrawingName): Html { + return html``; +} + +export function disc(name: ContributeIconName | DrawingName, tone: ContributeTone): Html { + const [background, colour] = CONTRIBUTE_TONES[tone]; + + return html`${drawing(name)}`; +} + +/** The square logo we hold, drafts included, or the initial of the name. */ +export function logo(entry: Entry, directory: Directory, siteUrl: string): Html { + const name = nameOf(entry, directory); + const key = entry.kind === 'report' ? first(entry.answers, 'service') : nameKey(name); + const mark = logos.find(({ provider, variant }) => variant === 'mark' && (provider === key || nameKey(provider) === key)); + if (mark !== undefined) return html``; + + return html``; +} + +export function nameOf(entry: Entry, directory: Directory): string { + const slug = first(entry.answers, 'service'); + + return entry.kind === 'suggest' ? first(entry.answers, 'name') : (directory.get(slug) ?? slug); +} + +export function noticeBox({ tone, title, text, link }: Notice): Html { + return html`
    ${drawing(tone === 'ok' ? 'check' : 'alert')}${title}${text === '' ? '' : ` ${text}`}${link && html`${link.label} →`}
    `; +} + +function nameKey(name: string): string { + return normalise(name).replace(/[^\p{L}\p{N}]/gu, ''); +} diff --git a/service/review/review-store.ts b/service/review/review-store.ts new file mode 100644 index 0000000..839ec22 --- /dev/null +++ b/service/review/review-store.ts @@ -0,0 +1,99 @@ +import { z } from 'zod'; + +import type { Answers } from '../../src/contribute/types'; +import { before } from '../moments'; +import type { Database } from '../types'; +import { CLAIM_LIFE_MS, LIST_SIZE, REASONS, STATUSES } from './constants'; +import type { Entry, Reason, Status } from './types'; + +const answers = z.string().transform((text) => z.record(z.string(), z.array(z.string())).parse(JSON.parse(text))); + +const row = z.object({ + id: z.string(), + kind: z.enum(['report', 'suggest']), + locale: z.enum(['en', 'fr']), + answers, + edited: answers.nullable(), + email: z.string().nullable(), + status: z.enum(STATUSES), + reason: z.enum(REASONS).nullable(), + issue: z.number().nullable(), + received_at: z.string(), + decided_at: z.string().nullable(), + published_at: z.string().nullable(), +}); + +/** What the maintainer reads and decides. Every change names the status it starts from. */ +export class ReviewStore { + constructor(private readonly db: Database) {} + + async list(status: Status): Promise { + const order = status === 'pending' ? 'received_at ASC' : 'decided_at DESC'; + const { results } = await this.db.prepare(`SELECT * FROM contributions WHERE status = ? ORDER BY ${order} LIMIT ?`).bind(status, LIST_SIZE).all(); + + return results.map(toEntry); + } + + async counts(): Promise>> { + const { results } = await this.db.prepare('SELECT status, COUNT(*) AS total FROM contributions GROUP BY status').all(); + const of = (status: Status): number => Number(results.find((line) => line['status'] === status)?.['total'] ?? 0); + + return { pending: of('pending'), checking: of('checking'), published: of('published'), refused: of('refused') }; + } + + async find(id: string): Promise { + const found = await this.db.prepare('SELECT * FROM contributions WHERE id = ?').bind(id).first(); + + return found === null ? null : toEntry(found); + } + + /** Keeps the maintainer's version. `null` goes back to what was received. */ + async edit(id: string, edited: Answers | null, now: Date): Promise { + return this.changed("UPDATE contributions SET edited = ? WHERE id = ? AND status = 'pending' AND (claimed_at IS NULL OR claimed_at <= ?) RETURNING id", edited === null ? null : JSON.stringify(edited), id, before(now, CLAIM_LIFE_MS)); + } + + /** Keeps the maintainer's version and reserves the contribution while its issue is created. */ + async claim(id: string, edited: Answers | null, now: Date): Promise { + return this.changed("UPDATE contributions SET edited = ?, claimed_at = ? WHERE id = ? AND status = 'pending' AND (claimed_at IS NULL OR claimed_at <= ?) RETURNING id", edited === null ? null : JSON.stringify(edited), now.toISOString(), id, before(now, CLAIM_LIFE_MS)); + } + + async release(id: string): Promise { + await this.changed("UPDATE contributions SET claimed_at = NULL WHERE id = ? AND status = 'pending' RETURNING id", id); + } + + async toChecking(id: string, issue: number, now: Date): Promise { + return this.changed("UPDATE contributions SET status = 'checking', issue = ?, decided_at = ?, claimed_at = NULL WHERE id = ? AND status = 'pending' RETURNING id", issue, now.toISOString(), id); + } + + async refuse(id: string, reason: Reason, now: Date): Promise { + return this.changed("UPDATE contributions SET status = 'refused', reason = ?, decided_at = ? WHERE id = ? AND status = 'pending' AND (claimed_at IS NULL OR claimed_at <= ?) RETURNING id", reason, now.toISOString(), id, before(now, CLAIM_LIFE_MS)); + } + + async publish(id: string, now: Date): Promise { + return this.changed("UPDATE contributions SET status = 'published', published_at = ? WHERE id = ? AND status = 'checking' RETURNING id", now.toISOString(), id); + } + + private async changed(query: string, ...values: (string | number | null)[]): Promise { + return (await this.db.prepare(query).bind(...values).first()) !== null; + } +} + +function toEntry(found: unknown): Entry { + const line = row.parse(found); + + return { + id: line.id, + kind: line.kind, + locale: line.locale, + received: line.answers, + answers: line.edited ?? line.answers, + edited: line.edited !== null, + email: line.email, + status: line.status, + reason: line.reason, + issue: line.issue, + receivedAt: line.received_at, + decidedAt: line.decided_at, + publishedAt: line.published_at, + }; +} diff --git a/service/review/review.ts b/service/review/review.ts new file mode 100644 index 0000000..7fdd3f6 --- /dev/null +++ b/service/review/review.ts @@ -0,0 +1,153 @@ +import type { Answers } from '../../src/contribute/types'; +import { contributeStrings } from '../../src/i18n/translate'; +import { answerErrors, readAnswers } from '../read-submission'; +import type { Database } from '../types'; +import { EDITABLE, REASONS, STATUSES } from './constants'; +import { issueMarker, issueText } from './issue-text'; +import { entryPage, listPage, messagePage } from './pages'; +import { ReviewStore } from './review-store'; +import { TEXTS } from './texts'; +import type { Directory, Entry, Notice, ReviewTools } from './types'; + +const ENTRY_PATH = /^\/c\/([0-9a-f-]{36})$/i; + +const MAX_FORM = 65_536; + +/** The private space of the maintainer: reads, corrects, sends to check, refuses. Nothing is published here. */ +export async function review(request: Request, db: Database, tools: ReviewTools): Promise { + if (!(await tools.admits(request))) return page(messagePage(TEXTS.closed), 403); + + const url = new URL(request.url); + if (request.method === 'GET' && url.pathname.startsWith('/review/')) return tools.asset(request); + + const store = new ReviewStore(db); + const id = ENTRY_PATH.exec(url.pathname)?.[1]; + if (request.method === 'GET' && url.pathname === '/') return showList(url, store, tools); + if (id === undefined) return page(messagePage(TEXTS.missing), 404); + + const entry = await store.find(id); + if (entry === null) return page(messagePage(TEXTS.missing), 404); + if (request.method === 'GET') return showEntry(entry, url, tools); + if (request.method !== 'POST') return page(messagePage(TEXTS.missing), 405); + if (request.headers.get('Origin') !== url.origin) return page(messagePage(TEXTS.closed), 403); + if (Number(request.headers.get('Content-Length') ?? Infinity) > MAX_FORM) return page(messagePage(TEXTS.missing), 413); + + return decide(await request.formData(), entry, store, tools); +} + +async function showList(url: URL, store: ReviewStore, tools: ReviewTools): Promise { + const status = STATUSES.find((known) => known === url.searchParams.get('list')) ?? 'pending'; + const [entries, counts, directory, notice] = await Promise.all([store.list(status), store.counts(), tools.directory(), doneNotice(url, store, tools)]); + + return page(listPage({ status, entries, counts, notice }, directory, tools, tools.now())); +} + +async function doneNotice(url: URL, store: ReviewStore, { repoUrl }: ReviewTools): Promise { + const done = url.searchParams.get('done'); + if (done === 'refused' || done === 'published') return { tone: 'ok', title: TEXTS.done[done], text: '' }; + if (done === 'moved') return failure(TEXTS.moved); + if (done !== 'sent') return null; + + const issue = (await store.find(url.searchParams.get('id') ?? ''))?.issue ?? null; + + return { tone: 'ok', title: TEXTS.done.sent, text: TEXTS.sentText, ...(issue === null ? {} : { link: { href: `${repoUrl}/issues/${issue}`, label: TEXTS.onGitHub } }) }; +} + +async function showEntry(entry: Entry, url: URL, tools: ReviewTools, notice: Notice | null = null, status = 200): Promise { + if (entry.status !== 'pending') return goTo(`/?list=${entry.status}`); + + const saved: Notice | null = url.searchParams.get('done') === 'saved' ? { tone: 'ok', title: TEXTS.done.saved, text: '' } : null; + + return page(entryPage(entry, await tools.directory(), tools, notice ?? saved), status); +} + +async function decide(form: FormData, entry: Entry, store: ReviewStore, tools: ReviewTools): Promise { + const { id } = entry; + const now = tools.now(); + const action = form.get('action'); + + if (action === 'publish') return goTo((await store.publish(id, now)) ? '/?list=checking&done=published' : '/?done=moved'); + if (action === 'refuse') { + const reason = REASONS.find((known) => known === form.get('reason')); + + return goTo(reason !== undefined && (await store.refuse(id, reason, now)) ? '/?done=refused' : '/?done=moved'); + } + if (action !== 'save' && action !== 'send') return page(messagePage(TEXTS.missing), 400); + + const corrected = readAnswers(entry.kind, withEdits(entry, form)); + const errors = corrected === null ? [{ code: 'too_long' } as const] : answerErrors(entry.kind, corrected, now); + if (corrected === null || errors.length > 0) { + const messages = [...new Set(errors.map(({ code }) => contributeStrings('fr').common.errors[code]))].join(' '); + const kept: Entry = { ...entry, answers: corrected ?? entry.answers }; + + return showEntry(kept, new URL('https://review.invalid/'), tools, { tone: 'bad', title: TEXTS.invalid, text: messages }, 422); + } + + const changed = !same(corrected, entry.received); + const edited = changed ? corrected : null; + if (action === 'save') return goTo((await store.edit(id, edited, now)) ? `/c/${id}?done=saved` : '/?done=moved'); + + // Read first: the reservation below is short. + const directory = await tools.directory(); + if (!(await store.claim(id, edited, now))) return goTo('/?done=moved'); + + return sendToCheck({ ...entry, answers: corrected, edited: changed }, directory, store, tools); +} + +async function sendToCheck(entry: Entry, directory: Directory, store: ReviewStore, tools: ReviewTools): Promise { + const issue = await tools.openIssue(issueText(entry, directory), issueMarker(entry.id)); + if (issue === null) { + await store.release(entry.id); + + return showEntry(entry, new URL('https://review.invalid/'), tools, failure(TEXTS.failed), 502); + } + + return goTo((await store.toChecking(entry.id, issue, tools.now())) ? `/?done=sent&id=${entry.id}` : '/?done=moved'); +} + +/** The received answers, with the fields the maintainer may correct taken from the form. */ +function withEdits(entry: Entry, form: FormData): Answers { + const answers: Record = { ...entry.received }; + for (const field of EDITABLE[entry.kind]) { + if (field === 'credit_name' && entry.received['credit']?.[0] !== 'yes') continue; + if (field === 'shown' && entry.received['shown'] === undefined) continue; + + const values = clean(form.getAll(field).filter((value) => typeof value === 'string')); + if (values.length > 0) answers[field] = values; + else delete answers[field]; + } + + return answers; +} + +function same(a: Answers, b: Answers): boolean { + const ordered = (answers: Answers): string => JSON.stringify(Object.entries(answers).map(([field, values]) => [field, clean(values).sort()] as const).filter(([, values]) => values.length > 0).sort(([x], [y]) => x.localeCompare(y))); + + return ordered(a) === ordered(b); +} + +/** Values as they are compared and kept: browsers send other line endings than they show. */ +function clean(values: readonly string[]): string[] { + return values.map((value) => value.trim().replace(/\r\n/g, '\n')).filter(Boolean); +} + +function failure([title, text]: readonly [string, string]): Notice { + return { tone: 'bad', title, text }; +} + +function goTo(path: string): Response { + return new Response(null, { status: 303, headers: { Location: path, 'Cache-Control': 'no-store' } }); +} + +function page(body: string, status = 200): Response { + return new Response(body, { + status, + headers: { + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'no-store', + 'Content-Security-Policy': "default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self'; img-src https://paymap.africa https://cdn.jsdelivr.net; form-action 'self'; base-uri 'none'; frame-ancestors 'none'", + 'Referrer-Policy': 'same-origin', + 'X-Content-Type-Options': 'nosniff', + }, + }); +} diff --git a/service/review/texts.ts b/service/review/texts.ts new file mode 100644 index 0000000..1033733 --- /dev/null +++ b/service/review/texts.ts @@ -0,0 +1,74 @@ +import type { Reason, Status } from './types'; + +/** Texts of the review space, in the language of its one reader. */ +export const TEXTS = { + title: 'Espace privé · Paymap', + private: 'Espace privé', + signOut: 'Se déconnecter', + tabs: { pending: 'À relire', checking: 'En vérification', published: 'Publiées', refused: 'Refusées' } satisfies Record, + empty: { + pending: ['Tout est relu', 'Les nouvelles propositions arriveront ici.'], + checking: ['Rien en vérification', 'Les propositions envoyées sur GitHub apparaîtront ici.'], + published: ['Rien de publié', 'Les propositions publiées apparaîtront ici.'], + refused: ['Rien de refusé', 'Les propositions refusées apparaîtront ici.'], + } satisfies Record, + steps: { received: 'Reçue', checking: 'En vérification', published: 'Publiée', refused: 'Refusée' }, + newProvider: 'Nouvelle solution', + countries: (count: number): string => (count === 0 ? 'Pays non précisés' : count === 1 ? '1 pays' : `${count} pays`), + unknownFamily: 'Type non précisé', + before: 'Sur Paymap', + after: 'Proposé', + sheet: 'Voir la fiche', + open: 'Ouvrir', + edit: 'Modifier', + received: 'Reçu :', + nothing: 'vide', + restore: 'Rétablir', + shown: 'Ce que Paymap affiche, selon la personne', + topic: 'Sujet', + source: 'Lien officiel', + seenOn: 'Vu le', + name: 'Nom', + website: 'Site officiel', + family: 'Type', + places: 'Pays', + addCountry: 'Ajouter un pays', + methods: 'Moyens de paiement', + links: 'Liens officiels, un par ligne', + credit: 'Nom à citer', + anonymous: 'Ne souhaite pas être cité', + linked: 'Travaille pour ce service', + notLinked: 'Sans lien avec le service', + emailKept: 'Privé, effacé 30 jours après la décision', + ask: 'Demander une précision', + noEmail: 'Pas d’e-mail laissé, ou déjà effacé', + decision: 'Votre décision', + sendTask: 'Une tâche publique est créée sur GitHub', + sendSheet: 'La fiche ne change pas encore', + sendPrivate: 'L’e-mail reste privé', + send: 'Envoyer en vérification', + save: 'Enregistrer mes corrections', + refuse: 'Refuser', + why: 'Pourquoi refuser ?', + reasons: { unconfirmed: 'La source ne confirme pas', up_to_date: 'Déjà à jour', duplicate: 'Déjà reçue', spam: 'Indésirable', other: 'Autre raison' } satisfies Record, + confirmRefuse: 'Confirmer le refus', + publish: 'Marquer comme publiée', + onGitHub: 'Voir sur GitHub', + editedByYou: 'Corrigée par vous', + sentAt: 'Envoyée en vérification', + publishedAt: 'Publiée', + refusedAt: 'Refusée', + invalid: 'Réponses à corriger', + done: { sent: 'Envoyée en vérification', saved: 'Corrections enregistrées', refused: 'Proposition refusée', published: 'Marquée comme publiée' }, + sentText: 'La fiche changera quand la source sera confirmée.', + failed: ['La tâche n’a pas été créée', 'GitHub n’a pas répondu. Vos corrections sont gardées, réessayez.'], + moved: ['Rien n’a changé', 'Cette proposition a déjà été traitée, ou l’est en ce moment.'], + missing: 'Cette proposition n’existe pas.', + closed: 'Accès refusé.', +} as const; + +/** Draft of the message asking for a detail, in the language of the person. */ +export const ASK = { + fr: { subject: 'Paymap : une précision sur votre proposition', body: 'Bonjour,\n\nMerci pour votre proposition sur Paymap à propos de {name}.\n\nPouvez-vous préciser : ' }, + en: { subject: 'Paymap: a question about your contribution', body: 'Hello,\n\nThank you for your contribution to Paymap about {name}.\n\nCould you tell us more about: ' }, +} as const; diff --git a/service/review/types.ts b/service/review/types.ts new file mode 100644 index 0000000..b0644ba --- /dev/null +++ b/service/review/types.ts @@ -0,0 +1,55 @@ +import type { Answers, ContributionKind } from '../../src/contribute/types'; +import type { Locale } from '../../src/i18n/locales'; +import type { REASONS, STATUSES } from './constants'; + +export type Status = (typeof STATUSES)[number]; + +export type Reason = (typeof REASONS)[number]; + +/** A contribution as the maintainer sees it. */ +export interface Entry { + readonly id: string; + readonly kind: ContributionKind; + readonly locale: Locale; + readonly received: Answers; + /** The received answers, or the maintainer's version of them. */ + readonly answers: Answers; + readonly edited: boolean; + readonly email: string | null; + readonly status: Status; + readonly reason: Reason | null; + readonly issue: number | null; + readonly receivedAt: string; + readonly decidedAt: string | null; + readonly publishedAt: string | null; +} + +/** Name of each published provider, by slug. */ +export type Directory = ReadonlyMap; + +export interface Issue { + readonly title: string; + readonly body: string; + readonly labels: readonly string[]; +} + +/** What the review space needs from outside, replaced in tests and locally. */ +export interface ReviewTools { + readonly now: () => Date; + /** Whether the request comes from the maintainer. */ + readonly admits: (request: Request) => Promise; + readonly directory: () => Promise; + /** Number of the issue that carries the marker, created when there is none. `null` when GitHub does not answer. */ + readonly openIssue: (issue: Issue, marker: string) => Promise; + readonly asset: (request: Request) => Promise; + readonly siteUrl: string; + readonly repoUrl: string; +} + +/** A message above the page: something was done, or could not be. */ +export interface Notice { + readonly tone: 'ok' | 'bad'; + readonly title: string; + readonly text: string; + readonly link?: { readonly href: string; readonly label: string }; +} diff --git a/service/sender.ts b/service/sender.ts new file mode 100644 index 0000000..4cdb8c2 --- /dev/null +++ b/service/sender.ts @@ -0,0 +1,8 @@ +/** Digest of a visitor's address. Useless without the key, and different once the key changes. */ +export async function senderDigest(address: string, key: string): Promise { + const encoder = new TextEncoder(); + const imported = await crypto.subtle.importKey('raw', encoder.encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); + const signature = await crypto.subtle.sign('HMAC', imported, encoder.encode(address)); + + return [...new Uint8Array(signature)].map((byte) => byte.toString(16).padStart(2, '0')).join(''); +} diff --git a/service/store.ts b/service/store.ts new file mode 100644 index 0000000..77ba615 --- /dev/null +++ b/service/store.ts @@ -0,0 +1,37 @@ +import { ATTEMPT_LIFE_MS, ATTEMPT_WINDOW_MS, EMAIL_LIFE_MS, MAX_ATTEMPTS, UNDECIDED_EMAIL_LIFE_MS } from './constants'; +import { before } from './moments'; +import type { Contribution, Database } from './types'; + +/** The private database. Times are ISO texts in UTC, so that they compare as texts. */ +export class Store { + constructor(private readonly db: Database) {} + + async has(id: string): Promise { + return (await this.db.prepare('SELECT 1 AS found FROM contributions WHERE id = ?').bind(id).first()) !== null; + } + + /** Keeps a contribution. Sent twice, it is kept once. */ + async add({ id, kind, locale, answers, email }: Contribution, now: Date): Promise { + await this.db + .prepare('INSERT INTO contributions (id, kind, locale, answers, email, received_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING') + .bind(id, kind, locale, JSON.stringify(answers), email, now.toISOString()) + .run(); + } + + /** Counts this attempt, unless the sender has made too many. A refused attempt is not counted. */ + async allowAttempt(sender: string, now: Date): Promise { + // One statement, so that requests sent together cannot all pass on the same count. + const counted = await this.db + .prepare('INSERT INTO attempts (sender, made_at) SELECT ?, ? WHERE (SELECT COUNT(*) FROM attempts WHERE sender = ? AND made_at > ?) < ? RETURNING 1 AS counted') + .bind(sender, now.toISOString(), sender, before(now, ATTEMPT_WINDOW_MS), MAX_ATTEMPTS) + .first(); + + return counted !== null; + } + + /** Erases what has been kept long enough. */ + async erase(now: Date): Promise { + await this.db.prepare('UPDATE contributions SET email = NULL WHERE email IS NOT NULL AND (decided_at <= ? OR received_at <= ?)').bind(before(now, EMAIL_LIFE_MS), before(now, UNDECIDED_EMAIL_LIFE_MS)).run(); + await this.db.prepare('DELETE FROM attempts WHERE made_at <= ?').bind(before(now, ATTEMPT_LIFE_MS)).run(); + } +} diff --git a/service/types.ts b/service/types.ts new file mode 100644 index 0000000..8f446e5 --- /dev/null +++ b/service/types.ts @@ -0,0 +1,55 @@ +import type { Submission } from '../src/contribute/types'; + +/** The part of a Cloudflare D1 database the service uses. */ +export interface Database { + prepare(query: string): Statement; +} + +export interface Statement { + bind(...values: (string | number | null)[]): Statement; + run(): Promise; + first(): Promise> | null>; + all(): Promise<{ readonly results: readonly Readonly>[] }>; +} + +/** What the service is given when it is deployed. */ +export interface Environment { + readonly DB: Database; + readonly TURNSTILE_SECRET: string; + /** Key of the sender digests. */ + readonly SENDER_KEY: string; + /** Host a solved challenge must come from. */ + readonly CHALLENGE_HOST: string; +} + +/** Names needed by the private review space only. */ +export interface ReviewEnvironment extends Environment { + readonly ASSETS: { fetch(request: Request): Promise }; + readonly REVIEW_HOST: string; + /** Address of the Access team, such as `https://team.cloudflareaccess.com`. */ + readonly ACCESS_TEAM: string; + readonly ACCESS_AUD: string; + /** The one e-mail let in. A secret: it is personal data. */ + readonly REVIEWER: string; + readonly GITHUB_REPO: string; + readonly GITHUB_TOKEN: string; +} + +/** A contribution as it is kept: the e-mail apart from the answers. */ +export interface Contribution extends Submission { + readonly email: string | null; +} + +/** A challenge answer to check. */ +export interface ChallengeCheck { + readonly secret: string; + readonly host: string; + readonly token: string; + readonly address: string; +} + +/** What a request needs from outside, replaced in tests. */ +export interface Tools { + readonly now: () => Date; + readonly isHuman: (check: ChallengeCheck) => Promise; +} diff --git a/service/worker.local.ts b/service/worker.local.ts new file mode 100644 index 0000000..ce7710a --- /dev/null +++ b/service/worker.local.ts @@ -0,0 +1,37 @@ +import { isHuman } from './challenge'; +import { receive } from './receive'; +import { readDirectory } from './review/directory'; +import { review } from './review/review'; +import type { ReviewEnvironment } from './types'; + +/** Local only, never deployed: the review space opens without Access, and issues are invented. */ +export default { + async fetch(request: Request, env: ReviewEnvironment): Promise { + const url = new URL(request.url); + if (url.hostname === 'review.localhost') { + const site = `http://localhost:${url.port}`; + + const answer = await review(request, env.DB, { + now: () => new Date(), + admits: async () => true, + directory: () => readDirectory((path) => env.ASSETS.fetch(new Request(`${site}${path}`))), + openIssue: async (issue) => { + console.log(issue.title, issue.body); + + return issue.title.includes('GitHub down') ? null : 999; + }, + asset: (incoming) => env.ASSETS.fetch(incoming), + siteUrl: site, + repoUrl: `https://github.com/${env.GITHUB_REPO}`, + }); + const local = new Response(answer.body, answer); + const policy = local.headers.get('Content-Security-Policy'); + if (policy !== null) local.headers.set('Content-Security-Policy', policy.replace('https://paymap.africa', site)); + + return local; + } + if (url.pathname.startsWith('/api/')) return receive(request, env, { now: () => new Date(), isHuman }); + + return env.ASSETS.fetch(request); + }, +}; diff --git a/service/worker.ts b/service/worker.ts new file mode 100644 index 0000000..baf571a --- /dev/null +++ b/service/worker.ts @@ -0,0 +1,40 @@ +import { isHuman } from './challenge'; +import { receive } from './receive'; +import { admits } from './review/access'; +import { readDirectory } from './review/directory'; +import { openIssue } from './review/github'; +import { review } from './review/review'; +import { Store } from './store'; +import type { Environment, ReviewEnvironment } from './types'; + +const SITE_URL = 'https://paymap.africa'; + +/** Entry of the private service: receives contributions, shows them to the maintainer, and erases old personal data once a day. */ +export default { + async fetch(request: Request, env: ReviewEnvironment): Promise { + try { + if (new URL(request.url).hostname === env.REVIEW_HOST) { + return await review(request, env.DB, { + now: () => new Date(), + admits: (incoming) => admits(incoming, env, new Date()), + directory: () => readDirectory((path) => fetch(`${SITE_URL}${path}`, { signal: AbortSignal.timeout(5000) })), + openIssue: (issue, marker) => openIssue(issue, marker, env.GITHUB_REPO, env.GITHUB_TOKEN), + asset: (incoming) => env.ASSETS.fetch(incoming), + siteUrl: SITE_URL, + repoUrl: `https://github.com/${env.GITHUB_REPO}`, + }); + } + + return await receive(request, env, { now: () => new Date(), isHuman }); + } catch (error) { + // The name only: a message could quote an answer. + console.error('Request not answered', error instanceof Error ? error.name : 'unknown'); + + return new Response(null, { status: 500, headers: { 'Cache-Control': 'no-store' } }); + } + }, + + async scheduled(_event: unknown, env: Environment): Promise { + await new Store(env.DB).erase(new Date()); + }, +}; diff --git a/service/wrangler.jsonc b/service/wrangler.jsonc new file mode 100644 index 0000000..5201822 --- /dev/null +++ b/service/wrangler.jsonc @@ -0,0 +1,20 @@ +{ + // Private service of ADR 0003. Deployed apart from the site, which stays static. + "name": "paymap-contributions", + "main": "worker.ts", + "compatibility_date": "2026-11-01", + "workers_dev": false, + "preview_urls": false, + "routes": [ + { "pattern": "paymap.africa/api/contributions", "zone_name": "paymap.africa" }, + // Behind an Access application that lets one e-mail in. + { "pattern": "review.paymap.africa", "custom_domain": true } + ], + // The worker answers first: nothing is served before the visitor is known. + "assets": { "directory": "assets", "binding": "ASSETS", "run_worker_first": true }, + "triggers": { "crons": ["17 3 * * *"] }, + // ACCESS_TEAM and ACCESS_AUD are filled when the Access application is created. Empty, they let nobody in. + "vars": { "CHALLENGE_HOST": "paymap.africa", "REVIEW_HOST": "review.paymap.africa", "GITHUB_REPO": "gausoft/paymap", "ACCESS_TEAM": "", "ACCESS_AUD": "" }, + // The deployed copy, wrangler.production.jsonc, adds the database id and the Access values. It is not versioned. Secrets: TURNSTILE_SECRET, SENDER_KEY, REVIEWER, GITHUB_TOKEN. + "d1_databases": [{ "binding": "DB", "database_name": "paymap-contributions", "migrations_dir": "migrations" }] +} diff --git a/service/wrangler.local.jsonc b/service/wrangler.local.jsonc new file mode 100644 index 0000000..8430ff5 --- /dev/null +++ b/service/wrangler.local.jsonc @@ -0,0 +1,10 @@ +{ + // The built site and the service on one local address. See README.md. + "name": "paymap-local", + "main": "worker.local.ts", + "compatibility_date": "2026-11-01", + "assets": { "directory": "../dist", "binding": "ASSETS", "html_handling": "drop-trailing-slash", "not_found_handling": "404-page", "run_worker_first": true }, + // Public test secret of Turnstile: it always passes, and always answers for example.com. + "vars": { "GITHUB_REPO": "gausoft/paymap", "CHALLENGE_HOST": "example.com", "TURNSTILE_SECRET": "1x0000000000000000000000000000000AA", "SENDER_KEY": "local-only" }, + "d1_databases": [{ "binding": "DB", "database_name": "paymap-local", "database_id": "local", "migrations_dir": "migrations" }] +} diff --git a/src/components/catalogue/CataloguePage.astro b/src/components/catalogue/CataloguePage.astro index 641861f..8f9589c 100644 --- a/src/components/catalogue/CataloguePage.astro +++ b/src/components/catalogue/CataloguePage.astro @@ -9,7 +9,7 @@ import type { CatalogueItem, CatalogueLabels, CatalogueOffers } from '../../lib/ import { heroData } from '../../lib/hero-data'; import { inlineJson } from '../../lib/inline-json'; import { currentSite } from '../../lib/site-data'; -import { NEW_PROVIDER_URL } from '../../lib/site-links'; +import { SUGGEST_PATH } from '../../contribute/links'; import { breadcrumbData, itemListData } from '../../lib/structured-data'; import Breadcrumb from '../Breadcrumb.astro'; import Layout from '../Layout.astro'; @@ -72,7 +72,7 @@ const offers: CatalogueOffers = {

    {t.empty.title}

    {t.empty.text(site.draftCount)}

    - {t.suggest} + {t.suggest}
    ) : ( <> @@ -145,7 +145,7 @@ const offers: CatalogueOffers = {

    {t.noResultHint}

    - {t.suggest} + {t.suggest}
    diff --git a/src/components/contribute/ContributePage.astro b/src/components/contribute/ContributePage.astro index 5eb3e6c..acfcfd6 100644 --- a/src/components/contribute/ContributePage.astro +++ b/src/components/contribute/ContributePage.astro @@ -1,8 +1,8 @@ --- import type { Locale } from '../../i18n/locales'; -import { REPORT_PATH } from '../../contribute/links'; +import { REPORT_PATH, SUGGEST_PATH } from '../../contribute/links'; import { catalogueStrings, contributeStrings, localePath } from '../../i18n/translate'; -import { CONTRIBUTING_URL, EXPERIENCE_URL, NEW_PROVIDER_URL } from '../../lib/site-links'; +import { CONTRIBUTING_URL, EXPERIENCE_URL } from '../../lib/site-links'; import Breadcrumb from '../Breadcrumb.astro'; import Layout from '../Layout.astro'; import '../../styles/contribute.css'; @@ -17,7 +17,7 @@ const strings = contributeStrings(locale); const t = strings.choose; const trail = catalogueStrings(locale); const cards = [ - { ...t.suggest, cta: t.reviewCta, href: NEW_PROVIDER_URL, main: true, icon: 'M11 4v14M4 11h14' }, + { ...t.suggest, cta: t.start, href: localePath(locale, SUGGEST_PATH), main: true, icon: 'M11 4v14M4 11h14' }, { ...t.report, cta: t.start, href: localePath(locale, REPORT_PATH), main: false, icon: 'M5 19V4M5 5h11l-2.5 3.5L16 12H5' }, { ...t.review, cta: t.reviewCta, href: EXPERIENCE_URL, main: false, icon: 'M11 3.5l2.3 4.7 5.2.8-3.8 3.6.9 5.2-4.6-2.5-4.6 2.5.9-5.2L3.5 9l5.2-.8z' }, ]; diff --git a/src/components/contribute/SuggestPage.astro b/src/components/contribute/SuggestPage.astro new file mode 100644 index 0000000..4f3f57c --- /dev/null +++ b/src/components/contribute/SuggestPage.astro @@ -0,0 +1,96 @@ +--- +import { countryOptions, listedProviders, methodLabel } from '../../contribute/build-options'; +import { METHODS } from '../../contribute/constants'; +import { METHOD_ICON } from '../../contribute/icons'; +import { REPORT_PATH } from '../../contribute/links'; +import type { Locale } from '../../i18n/locales'; +import { catalogueStrings, contributeStrings, localePath } from '../../i18n/translate'; +import { FAMILY_ORDER } from '../../lib/catalogue-constants'; +import { familyColours } from '../../lib/family-look'; +import { currentSite } from '../../lib/site-data'; +import FamilyIcon from '../FamilyIcon.astro'; +import ChoiceCard from './ChoiceCard.astro'; +import ChoiceField from './ChoiceField.astro'; +import ConsentField from './ConsentField.astro'; +import ContributeIcon from './ContributeIcon.astro'; +import PickerBox from './PickerBox.astro'; +import TextField from './TextField.astro'; +import WizardPage from './WizardPage.astro'; +import YouStep from './YouStep.astro'; + +/** "Suggest a provider": its name, its site, what the visitor knows about it. */ +interface Props { + locale: Locale; +} + +const { locale } = Astro.props; +const strings = contributeStrings(locale); +const t = strings.suggest; +const families = catalogueStrings(locale).families; +const site = currentSite(); +const recap = [ + { step: 1, rows: ['name', 'website', 'family', 'countries'] }, + { step: 2, rows: ['methods', 'links'] }, + { step: 3, rows: ['linked', 'email', 'credit'] }, +] as const; +--- + + + + + + + + + {FAMILY_ORDER.map((family) => ( + + + + ))} + + + +
    + {t.countries} ({strings.common.optional}) +
    + +
    + +
    +
    + + +
    + {t.methods} ({strings.common.optional}) +
    + {METHODS.map((method) => { + const label = method === 'other' ? t.otherMethod : methodLabel(locale, method); + + return ; + })} +
    +
    + +
    + + + + + {recap.map(({ step, rows }) => ( +
    +

    {t.steps[step - 1]}

    +
    {rows.map((row) => <>
    {t.recap[row]}
    )}
    +
    + ))} + +
    +
    + + diff --git a/src/components/header/SearchDialog.astro b/src/components/header/SearchDialog.astro index f0cf6fe..502832a 100644 --- a/src/components/header/SearchDialog.astro +++ b/src/components/header/SearchDialog.astro @@ -2,9 +2,9 @@ import '../../styles/search.css'; import type { Locale } from '../../i18n/locales'; -import { ui } from '../../i18n/translate'; +import { localePath, ui } from '../../i18n/translate'; import { inlineJson } from '../../lib/inline-json'; -import { NEW_PROVIDER_URL } from '../../lib/site-links'; +import { SUGGEST_PATH } from '../../contribute/links'; /** Search window opened from the header bar, the mobile magnifier or ⌘K. See `src/search/`. */ interface Props { @@ -59,7 +59,7 @@ const t = strings.search;
    - {contribute.suggest} + {contribute.suggest} {contribute.review}
    diff --git a/src/contribute/country-field.ts b/src/contribute/country-field.ts new file mode 100644 index 0000000..c6c5109 --- /dev/null +++ b/src/contribute/country-field.ts @@ -0,0 +1,80 @@ +import { need } from './dom'; +import { Picker } from './picker'; +import type { CountryOption } from './types'; + +/** Countries picked one by one, each a pill that a press removes. */ +export class CountryField { + private readonly pills: HTMLElement; + + private readonly add: HTMLElement; + + private readonly box: HTMLElement; + + private readonly picker: Picker; + + private codes: readonly string[] = []; + + constructor( + form: HTMLFormElement, + private readonly countries: readonly CountryOption[], + private readonly removeLabel: string, + private readonly onChange: () => void, + ) { + this.pills = need(form, '[data-countries]'); + this.add = need(form, '[data-country-add]'); + this.box = need(form, '[data-country-box]'); + this.picker = new Picker(need(this.box, '[data-picker]'), (code) => { + this.set([...this.codes, code]); + this.onChange(); + this.add.focus(); + }); + + this.add.addEventListener('click', () => { + const opening = this.box.hidden; + this.toggle(opening); + if (opening) this.picker.focus(); + }); + } + + set(codes: readonly string[]): void { + this.codes = codes.filter((code) => this.countries.some((country) => country.code === code)); + this.pills.querySelectorAll('[data-country]').forEach((pill) => pill.remove()); + this.add.before(...this.names().map((country) => this.pill(country))); + this.picker.setOptions(this.countries.filter(({ code }) => !this.codes.includes(code)).map(({ code, name, flag }) => ({ id: code, label: name, detail: '', image: flag }))); + this.toggle(false); + } + + names(): CountryOption[] { + return this.codes.flatMap((code) => this.countries.find((country) => country.code === code) ?? []); + } + + private pill(country: CountryOption): HTMLElement { + const pill = document.createElement('button'); + pill.type = 'button'; + pill.className = 'cf-pill sel'; + pill.dataset['country'] = country.code; + pill.setAttribute('aria-label', this.removeLabel.replace('{name}', country.name)); + + const flag = document.createElement('img'); + flag.src = country.flag; + flag.alt = ''; + const value = document.createElement('input'); + value.type = 'hidden'; + value.name = 'countries'; + value.value = country.code; + pill.append(flag, country.name, ' ✕', value); + + pill.addEventListener('click', () => { + this.set(this.codes.filter((code) => code !== country.code)); + this.onChange(); + this.add.focus(); + }); + + return pill; + } + + private toggle(open: boolean): void { + this.box.hidden = !open; + this.add.setAttribute('aria-expanded', String(open)); + } +} diff --git a/src/contribute/suggest-form.ts b/src/contribute/suggest-form.ts new file mode 100644 index 0000000..2746848 --- /dev/null +++ b/src/contribute/suggest-form.ts @@ -0,0 +1,67 @@ +import type { ContributeStrings } from '../i18n/contribute-types'; +import { CountryField } from './country-field'; +import { need, pageData, pickedLabels, writeRecap } from './dom'; +import type { WizardTexts } from './form-types'; +import { listedUnder, shortAddress, siteName } from './listed'; +import type { Answers, CountryOption, ListedProvider } from './types'; +import { first, linkLines } from './validate'; +import { Wizard } from './wizard'; + +interface SuggestOptions { + readonly listed: readonly ListedProvider[]; + readonly countries: readonly CountryOption[]; +} + +type SuggestTexts = WizardTexts & { readonly form: ContributeStrings['suggest'] }; + +/** Opens "Suggest a provider". A provider that is already listed is said so as its name is typed. */ +export function openSuggestForm(): void { + const root = document.querySelector('[data-wizard="suggest"]'); + if (root === null) return; + + const { listed, countries } = pageData(root, '[data-options]'); + const texts = pageData(root, '[data-texts]'); + const form = need(root, '[data-form]'); + const name = need(form, 'input[name="name"]'); + const places = new CountryField(form, countries, texts.common.remove, () => wizard.changed()); + const notice = (): void => writeNotice(form, listedUnder(name.value, listed), texts); + + name.addEventListener('input', notice); + + const wizard = new Wizard(root, 'suggest', texts, { + recap: (answers) => writeSuggestRecap(form, places, answers, texts), + restored: (answers) => { + places.set(answers['countries'] ?? []); + notice(); + }, + extraErrors: (step, answers) => (step === 1 && listedUnder(first(answers, 'name'), listed) !== undefined ? [{ field: 'name', code: 'listed' }] : []), + }); + + wizard.start((draft) => draft); +} + +function writeNotice(form: HTMLFormElement, provider: ListedProvider | undefined, { form: t }: SuggestTexts): void { + const notice = need(form, '[data-listed]'); + notice.hidden = provider === undefined; + if (provider === undefined) return; + + need(notice, '[data-listed-name]').textContent = t.listed.replace('{name}', provider.name); + need(notice, '[data-listed-sheet]').href = provider.href; + const report = need(notice, '[data-listed-report]'); + report.search = new URLSearchParams({ provider: provider.slug }).toString(); +} + +function writeSuggestRecap(form: HTMLFormElement, places: CountryField, answers: Answers, { common }: SuggestTexts): void { + const given = (text: string): string => (text === '' ? common.notGiven : text); + const credit = first(answers, 'credit') === 'yes' ? first(answers, 'credit_name') : ''; + + writeRecap(form, 'name', first(answers, 'name')); + writeRecap(form, 'website', siteName(first(answers, 'website'))); + writeRecap(form, 'family', pickedLabels(form, 'family')[0] ?? ''); + writeRecap(form, 'countries', given(places.names().map((country) => country.name).join(', '))); + writeRecap(form, 'methods', given(pickedLabels(form, 'methods').join(', '))); + writeRecap(form, 'links', linkLines(answers).map(shortAddress).join(', ')); + writeRecap(form, 'linked', first(answers, 'linked') === 'yes' ? common.yes : common.no); + writeRecap(form, 'email', given(first(answers, 'email'))); + writeRecap(form, 'credit', credit === '' ? common.anonymous : credit); +} diff --git a/src/i18n/catalogue-fr.ts b/src/i18n/catalogue-fr.ts index 911f58b..5932fce 100644 --- a/src/i18n/catalogue-fr.ts +++ b/src/i18n/catalogue-fr.ts @@ -61,7 +61,7 @@ export const CATALOGUE_FR: CatalogueStrings = { noResultHint: 'Essayez une autre orthographe, ou une autre famille.', noFilterResult: 'Aucun service ne correspond à ces filtres', reset: 'Afficher tous les services', - suggest: 'Proposer un service', + suggest: 'Référencer une solution', empty: { title: 'Aucun service vérifié pour l’instant', text: (drafts) => diff --git a/src/i18n/home-fr.ts b/src/i18n/home-fr.ts index 942ca9d..aa61157 100644 --- a/src/i18n/home-fr.ts +++ b/src/i18n/home-fr.ts @@ -85,7 +85,7 @@ export const HOME_FR: HomeStrings = { contribute: { title: 'Vous connaissez un service ?', text: 'Proposez-le, ou racontez comment ça s’est passé pour vous.', - suggest: 'Proposer un service', + suggest: 'Référencer une solution', review: 'Donner un avis', }, }; diff --git a/src/i18n/ui-en.ts b/src/i18n/ui-en.ts index 3e1f064..38aef9a 100644 --- a/src/i18n/ui-en.ts +++ b/src/i18n/ui-en.ts @@ -1,5 +1,5 @@ -import { REPORT_PATH } from '../contribute/links'; -import { CONTRIBUTING_URL, EXPERIENCE_URL, NEW_PROVIDER_URL } from '../lib/site-links'; +import { REPORT_PATH, SUGGEST_PATH } from '../contribute/links'; +import { CONTRIBUTING_URL, EXPERIENCE_URL } from '../lib/site-links'; import type { UiStrings } from './ui-types'; export const UI_EN: UiStrings = { @@ -85,7 +85,7 @@ export const UI_EN: UiStrings = { contribute: { title: 'Contribute', links: [ - { label: 'Suggest a provider', href: NEW_PROVIDER_URL }, + { label: 'Suggest a provider', href: SUGGEST_PATH }, { label: 'Report a fact', href: REPORT_PATH }, { label: 'Share a review', href: EXPERIENCE_URL }, { label: 'Contribute on GitHub', href: CONTRIBUTING_URL }, diff --git a/src/i18n/ui-fr.ts b/src/i18n/ui-fr.ts index f961e63..f9db89d 100644 --- a/src/i18n/ui-fr.ts +++ b/src/i18n/ui-fr.ts @@ -1,5 +1,5 @@ -import { REPORT_PATH } from '../contribute/links'; -import { CONTRIBUTING_URL, EXPERIENCE_URL, NEW_PROVIDER_URL } from '../lib/site-links'; +import { REPORT_PATH, SUGGEST_PATH } from '../contribute/links'; +import { CONTRIBUTING_URL, EXPERIENCE_URL } from '../lib/site-links'; import type { UiStrings } from './ui-types'; export const UI_FR: UiStrings = { @@ -85,7 +85,7 @@ export const UI_FR: UiStrings = { contribute: { title: 'Participer', links: [ - { label: 'Référencer une solution', href: NEW_PROVIDER_URL }, + { label: 'Référencer une solution', href: SUGGEST_PATH }, { label: 'Signaler une info', href: REPORT_PATH }, { label: 'Donner un avis', href: EXPERIENCE_URL }, { label: 'Contribuer sur GitHub', href: CONTRIBUTING_URL }, diff --git a/src/lib/live-pages.ts b/src/lib/live-pages.ts index 5ab7b17..2b6f6db 100644 --- a/src/lib/live-pages.ts +++ b/src/lib/live-pages.ts @@ -5,7 +5,7 @@ import { LOCALES } from '../i18n/locales'; * out is shown as "Soon" text instead of a link; adding it here turns every link to * it back on. */ -const LIVE_PATHS: ReadonlySet = new Set(['/', '/providers', '/countries', '/glossary', '/contribute', '/contribute/report']); +const LIVE_PATHS: ReadonlySet = new Set(['/', '/providers', '/countries', '/glossary', '/contribute', '/contribute/report', '/contribute/suggest']); /** Pages built from a pattern, matched on the path without locale: one sheet per provider. */ const LIVE_PATTERNS: readonly RegExp[] = [/^\/providers\/[a-z0-9-]+$/]; diff --git a/src/pages/[locale]/contribute/suggest.astro b/src/pages/[locale]/contribute/suggest.astro new file mode 100644 index 0000000..89d7ea4 --- /dev/null +++ b/src/pages/[locale]/contribute/suggest.astro @@ -0,0 +1,12 @@ +--- +import SuggestPage from '../../../components/contribute/SuggestPage.astro'; +import { LOCALES, type Locale } from '../../../i18n/locales'; + +export function getStaticPaths() { + return LOCALES.map((locale) => ({ params: { locale } })); +} + +const locale = Astro.params.locale as Locale; +--- + + diff --git a/tests/review.test.ts b/tests/review.test.ts new file mode 100644 index 0000000..f165cef --- /dev/null +++ b/tests/review.test.ts @@ -0,0 +1,325 @@ +import { readFileSync } from 'node:fs'; +import { DatabaseSync, type SQLInputValue } from 'node:sqlite'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { admits } from '../service/review/access'; +import { moment } from '../service/review/dates'; +import { openIssue } from '../service/review/github'; +import { html } from '../service/review/html'; +import { review } from '../service/review/review'; +import { ReviewStore } from '../service/review/review-store'; +import type { Issue, ReviewTools } from '../service/review/types'; +import type { Database, Statement } from '../service/types'; + +const NOW = new Date('2026-12-03T09:20:00Z'); +const ID = '6f1d5f0e-5b0a-4c57-9a3e-0f6f0b1c2d3e'; +const URL_BASE = 'https://review.paymap.africa'; +const REPORT = { service: ['some-provider'], topic: ['fees'], shown: ['Card · Togo · 3 %'], shown_rate: ['3 %'], value: ['2 pourcent'], source: ['example.com/pricing'], linked: ['no'], credit: ['yes'], credit_name: ['Awa'], licence: ['yes'] }; +const SUGGESTION = { name: ['Example Pay'], website: ['example.com'], family: ['unknown'], countries: ['SN'], methods: ['card'], links: ['example.com/a'], linked: ['yes'], licence: ['yes'] }; +const FORM = { topic: 'fees', shown: 'Card · Togo · 3 %', value: '2 %', source: 'example.com/pricing', credit_name: 'Awa' }; + +let sqlite: DatabaseSync; +let db: Database; +let issues: Issue[]; + +beforeEach(() => { + sqlite = new DatabaseSync(':memory:'); + sqlite.exec(readFileSync('service/migrations/0001_contributions.sql', 'utf8')); + db = database(sqlite); + issues = []; +}); + +describe('the door', () => { + it('shows nothing to anyone else, files included', async () => { + keep(); + for (const path of ['/', `/c/${ID}`, '/review/review.css']) { + const response = await get(path, { admits: async () => false }); + + expect(response.status).toBe(403); + expect(await response.text()).not.toContain('someone@example.com'); + } + }); + + it('refuses a decision posted by another site', async () => { + keep(); + expect((await post({ ...FORM, action: 'send' }, {}, 'https://elsewhere.example')).status).toBe(403); + expect(line()).toMatchObject({ status: 'pending' }); + }); + + it('lets the maintainer in with a token signed for this application', async () => { + const { sign, jwk } = await signer(); + vi.stubGlobal('fetch', async () => Response.json({ keys: [jwk] })); + const env = { ACCESS_TEAM: 'https://team.example', ACCESS_AUD: 'aud', REVIEWER: 'me@example.com' }; + const good = { iss: env.ACCESS_TEAM, aud: ['aud'], exp: NOW.getTime() / 1000 + 60, email: 'Me@example.com', type: 'app' }; + const enter = async (claims: object, settings = env): Promise => admits(new Request(URL_BASE, { headers: { 'Cf-Access-Jwt-Assertion': await sign(claims) } }), settings, NOW); + + expect(await enter(good)).toBe(true); + expect(await enter({ ...good, email: 'other@example.com' })).toBe(false); + expect(await enter({ ...good, aud: ['other'] })).toBe(false); + expect(await enter({ ...good, iss: 'https://other.example' })).toBe(false); + expect(await enter({ ...good, exp: NOW.getTime() / 1000 - 1 })).toBe(false); + expect(await enter({ ...good, nbf: NOW.getTime() / 1000 + 60 })).toBe(false); + expect(await enter({ ...good, type: 'org' })).toBe(false); + expect(await enter(good, { ...env, REVIEWER: '' })).toBe(false); + expect(await admits(new Request(URL_BASE), env, NOW)).toBe(false); + + const [head, body] = (await sign(good)).split('.'); + const forged = new Request(URL_BASE, { headers: { 'Cf-Access-Jwt-Assertion': `${head}.${body}.${btoa('forged')}` } }); + expect(await admits(forged, env, NOW)).toBe(false); + }); +}); + +describe('reading', () => { + it('lists what waits, with the French time and the known name', async () => { + keep(); + const page = await (await get('/')).text(); + + expect(page).toContain('Some Provider'); + expect(page).toContain('Aujourd’hui à 08h05'); + expect(page).not.toContain('someone@example.com'); + }); + + it('never lets a visitor write markup', async () => { + keep({ ...REPORT, value: [''], credit_name: ['">'] }); + for (const path of ['/', `/c/${ID}`]) { + const page = await (await get(path)).text(); + + expect(page).not.toContain('