34 Commits

Author SHA1 Message Date
Maxco10
343363d54f Added Italian language (#233)
* Update i18n.ts

* Update de-DE.json

* Update en-US.json

* Update es.json

* Update fi.json

* Update fr-FR.json

* Update ru-RU.json

* Update zh-CN.json

* Create it-IT.json

* Update it-IT.json

* Update it-IT.json

* Update it-IT.json

* Update it-IT.json

* Update it-IT.json

* Prettier

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-10-05 10:30:45 -04:00
Mert Demir
8742bd59da Fix format for integer amounts (#231)
* support both fractions and integer values

* test fractions

* prettier
2024-09-29 09:24:10 -04:00
Kostas Vrouvas
8eea062218 Fix form columns not working properly (#224) 2024-09-28 18:41:19 -04:00
Mert Demir
9a5674e239 Fix amount preview for scanned receipts (#227)
* no division of amount

* use gpt-4-turbo

* testing setup and naive test

* test multiple variants

* document

* correct locale names

* test large amounts

* test wth strings

* prettier
2024-09-28 18:39:01 -04:00
Tobias Genannt
50b3a2e431 Fix: Correctly display loaded expense (#210)
* Fix #209: Correctly display loaded expense

- Don't load default split options after displaying an existing expense
- Re-validate form after changing the "paidFor" selection.
  This fixes the error message "The expense must be paid for at least one
  participant." after clicking "Select None" and the selecting one participant.

* Fix Paid For Field reset in Edit Expense Page for split Mode 'Unevenly - By amount'

---------

Co-authored-by: partho.kunda <partho.kunda@chaldal.net>
2024-09-28 18:28:27 -04:00
Nikita Utkin
e8d46cd4f3 Add russian localization (#216) 2024-09-28 18:23:17 -04:00
Zack_Z
8f896f7412 Add Chinese translation (#215)
* Added Chinese translation

* Add home page translation

* Fix translations

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-09-28 18:18:27 -04:00
chrisschuller
504631454a feat: add German language support (#207)
* feat: add German language support

* fix: translate other locale names to German

* chore: integrate recommendations from the PR review

* i18n: add translation recommendations from the PR

* Fix translations

---------

Co-authored-by: Christian Schuller <christianschuller.biz@gmail.com>
Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-09-28 18:11:30 -04:00
Pau Sansa
345f3716c9 feature: add Spanish language support (#214)
* create ES i18n json

* add ES locale to i18n and existing locales

* capitalize words at es.json

* Add missing translation

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-09-28 18:06:15 -04:00
Sebastien Castiel
5fff8da08d Fix translation 2024-09-28 17:58:04 -04:00
Strekol
07e24f7fcb Add French translation (#196)
* Added french version and title/description from json messages

* Revert back default language to en-US

* Code reviewed with prettier :)

* Updated json to add information field

* Updated json to add information block (missed on previous)

* Reviewed code language

* correction traduction "groupes étoilés" en "groupes favoris"

---------

Co-authored-by: Andy Trouvé <andy@strekol.eu>
2024-09-28 17:56:55 -04:00
Sebastien Castiel
5dfe03b3f1 Make header buttons smaller (#191) 2024-08-02 12:22:39 -04:00
Sebastien Castiel
26bed11116 Update Next.js + Npm audit fix (#190)
* Audit fix

* Upade Next
2024-08-02 12:18:49 -04:00
Chris Johnston
972bb9dadb add group information field to group settings and Information tab (#164)
* add group information field to group and Information tab to display

* add breaks to info page

* Improve UX

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-08-02 12:03:36 -04:00
Tuomas Jaakola
4f5e124ff0 Internationalization + Finnish language (#181)
* I18n with next-intl

* package-lock

* Finnish translations

* Development fix

* Use locale for positioning currency symbol

* Translations: Expenses.ActiveUserModal

* Translations: group 404

* Better translation for ExpenseCard

* Apply translations in CategorySelect search

* Fix for Finnish translation

* Translations for ExpenseDocumentsInput

* Translations for CreateFromReceipt

* Fix for Finnish translation

* Translations for schema errors

* Fix for Finnish translation

* Fixes for Finnish translations

* Prettier

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-08-02 11:26:23 -04:00
Miska Pajukangas
c392c06b39 feat: add auto-balancing for the amount edit (#173)
* feat: add auto-balancing for the amount edit

this implementation allocates the rest of the total
to participants, whose rows have yet not been edited.

* fix: reset already edited on total amount change
2024-08-02 11:04:21 -04:00
Laszlo Makk
002e867bc4 Make recalculation stable across repayments in suggested reimbursements (#179)
* suggested reimbursements: make recalculation stable across repayments

Previously, after a group participant executed a suggested reimbursement, rerunning getSuggestedReimbursements() could return a completely new list of suggestions.

With this change, getSuggestedReimbursements() should now be stable:
if it returns a graph with n edges, and then a repayment is made according to one of those edges, when called again, it should now return the same graph but with that one edge removed.

The trick is that the main logic in getSuggestedReimbursements() does not rely on balancesArray being sorted based on .total values, only that the array gets partitioned into participants with credit first and then participants with debt last. After a repayment is made, re-sorting based on .total values would result in a new order hence new suggestions, but sorting based on usernames/participantIds should be unaffected.

fixes https://github.com/spliit-app/spliit/issues/178

* Prettier

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-08-02 10:58:46 -04:00
Tuomas Jaakola
9b8f716a6a Use unique name for postgres container (#171) 2024-08-02 10:58:33 -04:00
Tuomas Jaakola
853f1791d2 recent-groups-page.tsx removed (#182) 2024-08-02 10:57:39 -04:00
Sergio Behrends
7145cb6f30 Increase fuzzines of search results (#187)
* Introduce normalizeString fn

* Prettier

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-08-02 10:57:18 -04:00
Sebastien Castiel
e990e00a75 Upgrade Next.js & React to latest versions (#159) 2024-05-29 22:25:52 -04:00
Stefan Hynst
0c05499107 Add support for group income (= negative expenses) (#158)
* Allow negative amount for expenses to be entered

- an expense becomes an income
- this does not affect calculations, i.e. an income can be split just like an expense

* Incomes should not be reimbursements

when entering a negative number
- deselect 'isReimbursement'
- hide reimbursement checkbox

* Change captions when entering a negative number

- "expense" becomes "income"
- "paid" becomes "received"

* Format incomes on expense list

- replace "paid by" with "received by"

* Format incomes on "Stats" tab

- a group's or participants balance might be negative
- in this case "spendings" will be "earnings" (display accordingly)
- always display positive numbers
- for active user: highlight spendings/earnings in red/green

* Fix typo

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-05-29 22:20:04 -04:00
Oliver Wong
3887efd9ee Use placeholder for new participant input (#153)
* use placeholder for new participant

* Fix formatting

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-05-29 22:11:24 -04:00
dcbr
e619c1a5b4 Add basic activity log (#141)
* Add basic activity log

* Add database migration

* Fix layout

* Fix types

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-05-29 22:06:45 -04:00
Lauri Vuorela
10e13d1f6b copy the next.config.js in order to get custom domains working again (#147) 2024-05-29 21:46:16 -04:00
Lauri Vuorela
f9d915378b change onClick to onFocus, with a slight delay for safari (#144)
* change onClick to onFocus, with a slight delay for safari

* typo

* fix variable name

* Fix style

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-05-29 21:45:46 -04:00
Antonin RAFFIN
74465c0565 Fix relative path docker db script (#154)
Without this, docker complained:
```
docker: Error response from daemon: create ./postgres-data: "./postgres-data" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intended to pass a host directory, use absolute path.
```

Followed recommendation from https://stackoverflow.com/questions/46526165/docker-invalid-characters-for-volume-when-using-relative-paths
2024-05-29 21:38:37 -04:00
Stefan Hynst
d3fd8027a5 Implement "infinite scroll" for expenses (#95)
* Extract ExpenseCard vom ExpenseList

* Implement simple pagination of expenses (see #30)

- display only this year's entries by default
- a "Show more" button reveals all expenses

* Turn getPrisma() into constant "prisma"

- getPrisma() is not async and doesn't need to be awaited
- turn getPrisma() into exported constant "prisma"

* Select fields to be returned by getGroupExpenses()

- make JSON more concise and less redundant
- some properties were removed (i.e.instead of "expense.paidById" use "expense.paidBy.id")

* Remove "participants" from ExpenseCard

- no need to search for participant by id to get it's name
- name property is already present in expense

* Add option to fetch a slice of group expenses

- specify offset and length to get expenses for [offset, offset+length[
- add function to get total number of group expenses

* Add api route for client to fetch group expenses

* Remove "Show more" button from expense list

* Implement infinite scroll

- in server component Page
  - only load first 200 expenses max
  - pass preloaded expenses and total count

- in client component ExpenseList, if there are more expenses to show
  - test if there are more expenses
  - append preloading "skeletons" to end of list
  - fetch more expenses when last item in list comes into view
  - after each fetch increase fetch-length by factor 1.5
    - rationale: db fetch usually is not the issue here, the longer the list gets, the longer react needs to redraw

* Use server action instead of api endpoint

* Fixes

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-05-29 21:36:07 -04:00
Stefan Hynst
833237b613 Add "x" button to cancel search in search bar (#107) 2024-05-29 21:26:04 -04:00
dcbr
1cd2b273f9 Show the impact of an expense on the active user's balance (#139)
* Add devcontainer configuration for codespace support

* Show the impact of an expense on the active user's balance

* Run prettier

* Put the balance on a different line

---------

Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-04-13 13:07:18 -04:00
dcbr
1ad470309b Add devcontainer configuration for codespace support (#138) 2024-04-13 12:57:47 -04:00
Deep Golani
2fd38aadd9 Add notes in expense (#126)
* Feature: Added notes in expense

* Add missing notes in form values

* Prettier

---------

Co-authored-by: deep.golani <deep.golani@bfhl.in>
Co-authored-by: Sebastien Castiel <sebastien@castiel.me>
2024-04-05 08:38:38 -04:00
magomzr
b61d1836ea Add titles for a better user experience (#137)
Co-authored-by: Mario Gómez <60667991+mgomezarr@users.noreply.github.com>
2024-04-05 08:29:08 -04:00
Sahil Mehra
c3903849ec Bug: Fixed wrong paid by Name in Reimbursement (#134) 2024-04-02 08:20:56 -04:00
72 changed files with 14574 additions and 1358 deletions

View File

@@ -0,0 +1,42 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node-postgres
{
"name": "spliit",
"dockerComposeFile": "docker-compose.yml",
"service": "app",
// Features to add to the dev container. More info: https://containers.dev/features.
// "features": {
// "ghcr.io/frntn/devcontainers-features/prism:1": {}
// },
// Use 'postCreateCommand' to run commands after the container is created.
"postCreateCommand": "cp container.env.example .env && npm install",
"postAttachCommand": {
"npm": "npm run dev"
},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// This can be used to network with other containers or with the host.
"forwardPorts": [3000, 5432],
"portsAttributes": {
"3000": {
"label": "App"
},
"5432": {
"label": "PostgreSQL"
}
},
// Configure tool-specific properties.
"customizations": {
"codespaces": {
"openFiles": [
"README.md"
]
}
}
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}

View File

@@ -0,0 +1,33 @@
version: '3.8'
services:
app:
image: mcr.microsoft.com/devcontainers/typescript-node:latest
volumes:
- ../..:/workspaces:cached
# Overrides default command so things don't shut down after the process ends.
command: sleep infinity
# Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function.
network_mode: service:db
# Use "forwardPorts" in **devcontainer.json** to forward an app port locally.
# (Adding the "ports" property to this file will not forward from a Codespace.)
db:
image: postgres:latest
restart: unless-stopped
volumes:
- postgres-data:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: 1234
POSTGRES_USER: postgres
POSTGRES_DB: postgres
# Add "forwardPorts": ["5432"] to **devcontainer.json** to forward PostgreSQL locally.
# (Adding the "ports" property to this file will not forward from a Codespace.)
volumes:
postgres-data:

View File

@@ -27,7 +27,7 @@ RUN rm -r .next/cache
FROM node:21-alpine as runtime-deps FROM node:21-alpine as runtime-deps
WORKDIR /usr/app WORKDIR /usr/app
COPY --from=base /usr/app/package.json /usr/app/package-lock.json ./ COPY --from=base /usr/app/package.json /usr/app/package-lock.json /usr/app/next.config.js ./
COPY --from=base /usr/app/prisma ./prisma COPY --from=base /usr/app/prisma ./prisma
RUN npm ci --omit=dev --omit=optional --ignore-scripts && \ RUN npm ci --omit=dev --omit=optional --ignore-scripts && \
@@ -38,7 +38,7 @@ FROM node:21-alpine as runner
EXPOSE 3000/tcp EXPOSE 3000/tcp
WORKDIR /usr/app WORKDIR /usr/app
COPY --from=base /usr/app/package.json /usr/app/package-lock.json ./ COPY --from=base /usr/app/package.json /usr/app/package-lock.json /usr/app/next.config.js ./
COPY --from=runtime-deps /usr/app/node_modules ./node_modules COPY --from=runtime-deps /usr/app/node_modules ./node_modules
COPY ./public ./public COPY ./public ./public
COPY ./scripts ./scripts COPY ./scripts ./scripts

18
jest.config.ts Normal file
View File

@@ -0,0 +1,18 @@
import type { Config } from 'jest'
import nextJest from 'next/jest.js'
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
})
// Add any custom config to be passed to Jest
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)

397
messages/de-DE.json Normal file
View File

@@ -0,0 +1,397 @@
{
"Homepage": {
"title": "Teile <strong>Ausgaben</strong> mit <strong>Freunden & Familie</strong>",
"description": "Willkommen zu deiner neuen <strong>Spliit</strong>-Instanz!",
"button": {
"groups": "Zu den Gruppen",
"github": "GitHub"
}
},
"Header": {
"groups": "Gruppen"
},
"Footer": {
"madeIn": "Entwickelt in Montréal, Québec 🇨🇦",
"builtBy": "Erstellt von <author>Sebastien Castiel</author> und <source>Mitwirkenden</source>"
},
"Expenses": {
"title": "Ausgaben",
"description": "Hier sind die Ausgaben, die du für deine Gruppe erstellt hast.",
"create": "Ausgabe hinzufügen",
"createFirst": "Erstelle die Erste",
"noExpenses": "Deine Gruppe hat noch keine Ausgaben.",
"exportJson": "Als JSON exportieren",
"searchPlaceholder": "Suche nach einer Ausgabe…",
"ActiveUserModal": {
"title": "Wer bist du?",
"description": "Sag uns, welcher Teilnehmer du bist, um die angezeigten Informationen auf dich anzupassen.",
"nobody": "Ich will niemanden auswählen",
"save": "Änderungen speichern",
"footer": "Diese Einstellung kann später in den Gruppeneinstellungen geändert werden."
},
"Groups": {
"upcoming": "Bevorstehend",
"thisWeek": "Diese Woche",
"earlierThisMonth": "Diesen Monat",
"lastMonth": "Letzten Monat",
"earlierThisYear": "Dieses Jahr",
"lastYera": "Letztes Jahr",
"older": "Älter"
}
},
"ExpenseCard": {
"paidBy": "Gezahlt von <strong>{paidBy}</strong> für <paidFor></paidFor>",
"receivedBy": "Empfangen von <strong>{paidBy}</strong> für <paidFor></paidFor>",
"yourBalance": "Deine Bilanz:"
},
"Groups": {
"myGroups": "Meine Gruppen",
"create": "Erstellen",
"loadingRecent": "Lade letzte Gruppen…",
"NoRecent": {
"description": "Du hast in der letzten Zeit keine Gruppe besucht.",
"create": "Erstelle eine",
"orAsk": "oder bitte einen Freund, dir einen Link zu einer Existierenden zu schicken."
},
"recent": "Letzte Gruppen",
"starred": "Favorisierte Gruppen",
"archived": "Archivierte Gruppen",
"archive": "Gruppe archivieren",
"unarchive": "Gruppe wiederherstellen",
"removeRecent": "Aus letzten Gruppen entfernen",
"RecentRemovedToast": {
"title": "Gruppe wurde entfernt",
"description": "Die Gruppe wurde von deiner Liste der letzten Gruppen entfernt.",
"undoAlt": "Gruppe entfernen rückgängig machen",
"undo": "Rückgängig machen"
},
"AddByURL": {
"button": "Mit URL hinzufügen",
"title": "Gruppe mit URL hinzufügen",
"description": "Wenn eine Gruppe mit dir geteilt wurde, kannst du ihre URL hier einfügen, um sie zu deiner Liste hinzuzufügen.",
"error": "Ups, wir können die Gruppe mit der angegebenen URL nicht finden…"
},
"NotFound": {
"text": "Diese Gruppe existiert nicht.",
"link": "Gehe zu zuletzt besuchten Gruppen"
}
},
"GroupForm": {
"title": "Gruppeninformationen",
"NameField": {
"label": "Gruppenname",
"placeholder": "Sommerurlaub",
"description": "Gib deiner Gruppe einen Namen."
},
"InformationField": {
"label": "Gruppeninformationen",
"placeholder": "Welche Informationen sind relevant für Gruppenmitglieder?"
},
"CurrencyField": {
"label": "Währungssymbol",
"placeholder": "€, $, £…",
"description": "Wir benutzen es, um Beträge anzuzeigen."
},
"Participants": {
"title": "Mitglieder",
"description": "Füge einen Namen für jedes Gruppenmitglied hinzu.",
"protectedParticipant": "Dieses Mitglied ist Teil der Ausgaben und kann nicht entfernt werden.",
"new": "Neu",
"add": "Mitglied hinzufügen",
"John": "Johannes",
"Jane": "Janina",
"Jack": "Jakob"
},
"Settings": {
"title": "Lokale Einstellungen",
"description": "Dies sind Einstellungen pro Gerät, die verwendet werden, um deine Benutzererfahrung zu verbessern.",
"ActiveUserField": {
"label": "Aktiver Nutzer",
"placeholder": "Wähle ein Mitglied",
"none": "Keiner",
"description": "Standardnutzer, der die Ausgaben übernimmt."
},
"save": "Speichern",
"saving": "Speichert…",
"create": "Erstellen",
"creating": "Erstellt…",
"cancel": "Abbrechen"
}
},
"ExpenseForm": {
"Income": {
"create": "Einnahme erstellen",
"edit": "Einnahme bearbeiten",
"TitleField": {
"label": "Titel der Einnahme",
"placeholder": "Montagabend Restaurant",
"description": "Füge eine Beschreibung für die Einnahme hinzu."
},
"DateField": {
"label": "Datum der Einnahme",
"description": "Füge ein Datum hinzu für wann die Einnahme erhalten wurde."
},
"categoryFieldDescription": "Wähle die Kategorie der Einnahme.",
"paidByField": {
"label": "Empfangen von",
"description": "Wähle das Mitglied, das die Einnahme erhalten hat."
},
"paidFor": {
"title": "Empfangen für",
"description": "Wähle für wen die Einnahme empfangen wurde."
},
"splitModeDescription": "Wähle, wie die Einnahme aufgeteilt werden soll.",
"attachDescription": "Füge der Einnahme einen Beleg hinzu."
},
"Expense": {
"create": "Augabe erstellen",
"edit": "Ausgabe bearbeiten",
"TitleField": {
"label": "Titel der Ausgabe",
"placeholder": "Montagabend Restaurant",
"description": "Füge eine Beschreibung für die Ausgabe hinzu."
},
"DateField": {
"label": "Datum der Ausgabe",
"description": "Füge das Datum ein, zu dem die Ausgabe getätigt wurde."
},
"categoryFieldDescription": "Wähle eine Kategorie für die Ausgabe.",
"paidByField": {
"label": "Gezahlt von",
"description": "Wähle das Mitglied, das die Ausgabe bezahlt hat."
},
"paidFor": {
"title": "Gezahlt für",
"description": "Wähle für wen die Ausgabe gezahlt wurde."
},
"splitModeDescription": "Wähle, wie die Ausgabe aufgeteilt werden soll.",
"attachDescription": "Füge der Ausgabe einen Beleg hinzu."
},
"amountField": {
"label": "Betrag"
},
"isReimbursementField": {
"label": "Das ist eine Rückzahlung"
},
"categoryField": {
"label": "Kategorie"
},
"notesField": {
"label": "Notizen"
},
"selectNone": "Keine auswählen",
"selectAll": "Alle auswählen",
"shares": "Anteil(e)",
"advancedOptions": "Fortgeschrittene Aufteilungsoptionen…",
"SplitModeField": {
"label": "Aufteilungsart",
"evenly": "Gleich verteilt",
"byShares": "Ungleich Nach Anteilen",
"byPercentage": "Ungleich Prozentual",
"byAmount": "Ungleich Nach Betrag",
"saveAsDefault": "Als Standardoptionen zur Aufteilung speichern"
},
"DeletePopup": {
"label": "Löschen",
"title": "Diese Ausgabe löschen?",
"description": "Willst du diese Ausgabe wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.",
"yes": "Ja",
"cancel": "Abbrechen"
},
"attachDocuments": "Dokument hinzufügen",
"create": "Erstellen",
"creating": "Erstellt…",
"save": "Speichern",
"saving": "Speichert…",
"cancel": "Abbrechen"
},
"ExpenseDocumentsInput": {
"TooBigToast": {
"title": "Die Datei ist zu groß",
"description": "Die maximale Dateigröße ist {maxSize}. Deine ist ${size}."
},
"ErrorToast": {
"title": "Fehler beim Hochladen der Datei",
"description": "Beim Hochladen der Datei ist etwas schiefgelaufen. Versuche es später nochmal oder wähle eine andere Datei.",
"retry": "Wiederholen"
}
},
"CreateFromReceipt": {
"Dialog": {
"triggerTitle": "Ausgabe von Rechnungsbeleg erstellen",
"title": "Von Rechnungsbeleg erstellen",
"description": "Ausgabeninformationen von einem Foto einer Rechnung lesen.",
"body": "Lade ein Foto der Rechnung hoch und wir versuchen die Ausgabeinformationen zu extrahieren",
"selectImage": "Bild wählen…",
"titleLabel": "Titel:",
"categoryLabel": "Kategorie:",
"amountLabel": "Betrag:",
"dateLabel": "Datum:",
"editNext": "Als nächstes kannst du die Informationen zur Ausgabe editieren.",
"continue": "Weiter"
},
"unknown": "Unbekannt",
"TooBigToast": {
"title": "Die Datei ist zu groß",
"description": "Die maximale Dateigröße ist {maxSize}. Deine ist ${size}."
},
"ErrorToast": {
"title": "Fehler beim Hochladen der Datei",
"description": "Beim Hochladen der Datei ist etwas schiefgelaufen. Versuche es später nochmal oder wähle eine andere Datei.",
"retry": "Wiederholen"
}
},
"Balances": {
"title": "Bilanz",
"description": "Das sind die Beträge, die jedes Mitglied bezahlt oder empfangen hat.",
"Reimbursements": {
"title": "Vorgeschlagene Rückzahlungen",
"description": "Hier sind Vorschläge für optimierte Rückzahlungen zwischen Mitgliedern.",
"noImbursements": "Es sieht aus, als seien in der Gruppe keine Rückzahlungen nötig 😁",
"owes": "<strong>{from}</strong> schuldet <strong>{to}</strong>",
"markAsPaid": "Als gezahlt markieren"
}
},
"Stats": {
"title": "Statistiken",
"Totals": {
"title": "Gesamtausgaben",
"description": "Zusammenfassung der Ausgaben der gesamten Gruppe.",
"groupSpendings": "Gesamte Ausgaben der Gruppe",
"groupEarnings": "Gesamte Einnahmen der Gruppe",
"yourSpendings": "Deine gesamten Ausgaben",
"yourEarnings": "Deine gesamten Einnahmen",
"yourShare": "Dein gesamter Anteil"
}
},
"Activity": {
"title": "Aktivitäten",
"description": "Zusammenfassung aller Aktivitäten in dieser Gruppe.",
"noActivity": "Es gab noch keine Aktivität in dieser Gruppe.",
"someone": "Jemand",
"settingsModified": "Die Gruppeneinstellungen wurden von <strong>{participant}</strong> verändert.",
"expenseCreated": "Augabe <em>{expense}</em> wurde von <strong>{participant}</strong> erstellt.",
"expenseUpdated": "Ausgabe <em>{expense}</em> wurde von <strong>{participant}</strong> aktualisiert.",
"expenseDeleted": "Ausgabe <em>{expense}</em> wurde von <strong>{participant}</strong> gelöscht.",
"Groups": {
"today": "Heute",
"yesterday": "Gestern",
"earlierThisWeek": "Diese Woche",
"lastWeek": "Letze Woche",
"earlierThisMonth": "Diesen Monat",
"lastMonth": "Letzen Monat",
"earlierThisYear": "Dieses Jahr",
"lastYear": "Letztes Jahr",
"older": "Älter"
}
},
"Information": {
"title": "Informationen",
"description": "Nutze diesen Ort, um Informationen hinzuzufügen, die für die Gruppenmitglieder wichtig sein könnten.",
"empty": "Noch keine Gruppeninformationen vorhanden."
},
"Settings": {
"title": "Einstellungen"
},
"Locale": {
"en-US": "English",
"fi": "Suomi",
"fr-FR": "Français",
"es": "Español",
"de-DE": "Deutsch",
"zh-CN": "Chinese (Simplified)",
"ru-RU": "Русский",
"it-IT": "Italiano"
},
"Share": {
"title": "Teilen",
"description": "Teile die URL, damit andere Mitglieder die Gruppe sehen und Ausgaben hinzufügen können.",
"warning": "Achtung!",
"warningHelp": "Jede person mit der Gruppen-URL kann Ausgaben sehen und editieren. Teile den Link mit Bedacht!"
},
"SchemaErrors": {
"min1": "Gib mindestens ein Zeichen ein.",
"min2": "Gib mindestens zwei Zeichen ein.",
"max5": "Gib maximal fünf Zeichen ein.",
"max50": "Gib maximal 50 Zeichen ein.",
"duplicateParticipantName": "Der Name ist bereits an ein anderes Gruppenmitglied vergeben.",
"titleRequired": "Bitte gib einen Titel an.",
"invalidNumber": "Zahl nicht valide.",
"amountRequired": "Du musst einen Betrag angeben.",
"amountNotZero": "Der Betrag darf nicht 0 sein.",
"amountTenMillion": "Der Betrag muss kleiner als 10.000.000 sein",
"paidByRequired": "Du musst ein Mitglied auswählen.",
"paidForMin1": "Die Ausgabe muss mindestens für ein Mitglied bezahlt werden.",
"noZeroShares": "Alle Anteile müssen größer als 0 sein.",
"amountSum": "Die Summe der Beträge muss dem Betrag der Ausgabe entsprechen.",
"percentageSum": "Die Summe der prozentualen Anteile muss 100 ergeben."
},
"Categories": {
"search": "Nach Kategorie suchen...",
"noCategory": "Keine Kategorie gefunden.",
"Uncategorized": {
"heading": "Nicht kategorisiert",
"General": "Allgemein",
"Payment": "Zahlung"
},
"Entertainment": {
"heading": "Vergnügen",
"Entertainment": "Vergnügen",
"Games": "Spiele",
"Movies": "Filme",
"Music": "Musik",
"Sports": "Sport"
},
"Food and Drink": {
"heading": "Essen und Trinken",
"Food and Drink": "Essen und Trinken",
"Dining Out": "Essen gehen",
"Groceries": "Lebensmittel",
"Liquor": "Alkohol"
},
"Home": {
"heading": "Zuhause",
"Home": "Zuhause",
"Electronics": "Elektronik",
"Furniture": "Möbel",
"Household Supplies": "Haushaltsgegenstände",
"Maintenance": "Wartung",
"Mortgage": "Hypothek",
"Pets": "Haustiere",
"Rent": "Miete",
"Services": "Dienstleistungen"
},
"Life": {
"heading": "Leben",
"Childcare": "Kinderversorgung",
"Clothing": "Kleidung",
"Education": "Bildung",
"Gifts": "Geschenke",
"Insurance": "Versicherung",
"Medical Expenses": "Medizinische Ausgaben",
"Taxes": "Steuern"
},
"Transportation": {
"heading": "Transport",
"Transportation": "Transport",
"Bicycle": "Fahrrad",
"Bus/Train": "Bus/Bahn",
"Car": "Auto",
"Gas/Fuel": "Tanken",
"Hotel": "Hotel",
"Parking": "Parken",
"Plane": "Flugzeug",
"Taxi": "Taxi"
},
"Utilities": {
"heading": "Versorgung",
"Utilities": "Versorgung",
"Cleaning": "Reinigung/Putzen",
"Electricity": "Strom",
"Heat/Gas": "Heizung",
"Trash": "Müll",
"TV/Phone/Internet": "TV/Internet/Telefonie",
"Water": "Wasser"
}
}
}

397
messages/en-US.json Normal file
View File

@@ -0,0 +1,397 @@
{
"Homepage": {
"title": "Share <strong>Expenses</strong> with <strong>Friends & Family</strong>",
"description": "Welcome to your new <strong>Spliit</strong> instance !",
"button": {
"groups": "Go to groups",
"github": "GitHub"
}
},
"Header": {
"groups": "Groups"
},
"Footer": {
"madeIn": "Made in Montréal, Québec 🇨🇦",
"builtBy": "Built by <author>Sebastien Castiel</author> and <source>contributors</source>"
},
"Expenses": {
"title": "Expenses",
"description": "Here are the expenses that you created for your group.",
"create": "Create expense",
"createFirst": "Create the first one",
"noExpenses": "Your group doesnt contain any expense yet.",
"exportJson": "Export to JSON",
"searchPlaceholder": "Search for an expense…",
"ActiveUserModal": {
"title": "Who are you?",
"description": "Tell us which participant you are to let us customize how the information is displayed.",
"nobody": "I dont want to select anyone",
"save": "Save changes",
"footer": "This setting can be changed later in the group settings."
},
"Groups": {
"upcoming": "Upcoming",
"thisWeek": "This week",
"earlierThisMonth": "Earlier this month",
"lastMonth": "Last month",
"earlierThisYear": "Earlier this year",
"lastYera": "Last year",
"older": "Older"
}
},
"ExpenseCard": {
"paidBy": "Paid by <strong>{paidBy}</strong> for <paidFor></paidFor>",
"receivedBy": "Received by <strong>{paidBy}</strong> for <paidFor></paidFor>",
"yourBalance": "Your balance:"
},
"Groups": {
"myGroups": "My groups",
"create": "Create",
"loadingRecent": "Loading recent groups…",
"NoRecent": {
"description": "You have not visited any group recently.",
"create": "Create one",
"orAsk": "or ask a friend to send you the link to an existing one."
},
"recent": "Recent groups",
"starred": "Starred groups",
"archived": "Archived groups",
"archive": "Archive group",
"unarchive": "Unarchive group",
"removeRecent": "Remove from recent groups",
"RecentRemovedToast": {
"title": "Group has been removed",
"description": "The group was removed from your recent groups list.",
"undoAlt": "Undo group removal",
"undo": "Undo"
},
"AddByURL": {
"button": "Add by URL",
"title": "Add a group by URL",
"description": "If a group was shared with you, you can paste its URL here to add it to your list.",
"error": "Oops, we are not able to find the group from the URL you provided…"
},
"NotFound": {
"text": "This group does not exist.",
"link": "Go to recently visited groups"
}
},
"GroupForm": {
"title": "Group information",
"NameField": {
"label": "Group name",
"placeholder": "Summer vacations",
"description": "Enter a name for your group."
},
"InformationField": {
"label": "Group information",
"placeholder": "What information is relevant to group participants?"
},
"CurrencyField": {
"label": "Currency symbol",
"placeholder": "$, €, £…",
"description": "Well use it to display amounts."
},
"Participants": {
"title": "Participants",
"description": "Enter the name for each participant.",
"protectedParticipant": "This participant is part of expenses, and can not be removed.",
"new": "New",
"add": "Add participant",
"John": "John",
"Jane": "Jane",
"Jack": "Jack"
},
"Settings": {
"title": "Local settings",
"description": "These settings are set per-device, and are used to customize your experience.",
"ActiveUserField": {
"label": "Active user",
"placeholder": "Select a participant",
"none": "None",
"description": "User used as default for paying expenses."
},
"save": "Save",
"saving": "Saving…",
"create": "Create",
"creating": "Creating…",
"cancel": "Cancel"
}
},
"ExpenseForm": {
"Income": {
"create": "Create income",
"edit": "Edit income",
"TitleField": {
"label": "Income title",
"placeholder": "Monday evening restaurant",
"description": "Enter a description for the income."
},
"DateField": {
"label": "Income date",
"description": "Enter the date the income was received."
},
"categoryFieldDescription": "Select the income category.",
"paidByField": {
"label": "Received by",
"description": "Select the participant who received the income."
},
"paidFor": {
"title": "Received for",
"description": "Select who the income was received for."
},
"splitModeDescription": "Select how to split the income.",
"attachDescription": "See and attach receipts to the income."
},
"Expense": {
"create": "Create expense",
"edit": "Edit expense",
"TitleField": {
"label": "Expense title",
"placeholder": "Monday evening restaurant",
"description": "Enter a description for the expense."
},
"DateField": {
"label": "Expense date",
"description": "Enter the date the expense was paid."
},
"categoryFieldDescription": "Select the expense category.",
"paidByField": {
"label": "Paid by",
"description": "Select the participant who paid the expense."
},
"paidFor": {
"title": "Paid for",
"description": "Select who the expense was paid for."
},
"splitModeDescription": "Select how to split the expense.",
"attachDescription": "See and attach receipts to the expense."
},
"amountField": {
"label": "Amount"
},
"isReimbursementField": {
"label": "This is a reimbursement"
},
"categoryField": {
"label": "Category"
},
"notesField": {
"label": "Notes"
},
"selectNone": "Select none",
"selectAll": "Select all",
"shares": "share(s)",
"advancedOptions": "Advanced splitting options…",
"SplitModeField": {
"label": "Split mode",
"evenly": "Evenly",
"byShares": "Unevenly By shares",
"byPercentage": "Unevenly By percentage",
"byAmount": "Unevenly By amount",
"saveAsDefault": "Save as default splitting options"
},
"DeletePopup": {
"label": "Delete",
"title": "Delete this expense?",
"description": "Do you really want to delete this expense? This action is irreversible.",
"yes": "Yes",
"cancel": "Cancel"
},
"attachDocuments": "Attach documents",
"create": "Create",
"creating": "Creating…",
"save": "Save",
"saving": "Saving…",
"cancel": "Cancel"
},
"ExpenseDocumentsInput": {
"TooBigToast": {
"title": "The file is too big",
"description": "The maximum file size you can upload is {maxSize}. Yours is ${size}."
},
"ErrorToast": {
"title": "Error while uploading document",
"description": "Something wrong happened when uploading the document. Please retry later or select a different file.",
"retry": "Retry"
}
},
"CreateFromReceipt": {
"Dialog": {
"triggerTitle": "Create expense from receipt",
"title": "Create from receipt",
"description": "Extract the expense information from a receipt photo.",
"body": "Upload the photo of a receipt, and well scan it to extract the expense information if we can.",
"selectImage": "Select image…",
"titleLabel": "Title:",
"categoryLabel": "Category:",
"amountLabel": "Amount:",
"dateLabel": "Date:",
"editNext": "Youll be able to edit the expense information next.",
"continue": "Continue"
},
"unknown": "Unknown",
"TooBigToast": {
"title": "The file is too big",
"description": "The maximum file size you can upload is {maxSize}. Yours is ${size}."
},
"ErrorToast": {
"title": "Error while uploading document",
"description": "Something wrong happened when uploading the document. Please retry later or select a different file.",
"retry": "Retry"
}
},
"Balances": {
"title": "Balances",
"description": "This is the amount that each participant paid or was paid for.",
"Reimbursements": {
"title": "Suggested reimbursements",
"description": "Here are suggestions for optimized reimbursements between participants.",
"noImbursements": "It looks like your group doesnt need any reimbursement 😁",
"owes": "<strong>{from}</strong> owes <strong>{to}</strong>",
"markAsPaid": "Mark as paid"
}
},
"Stats": {
"title": "Stats",
"Totals": {
"title": "Totals",
"description": "Spending summary of the entire group.",
"groupSpendings": "Total group spendings",
"groupEarnings": "Total group earnings",
"yourSpendings": "Your total spendings",
"yourEarnings": "Your total earnings",
"yourShare": "Your total share"
}
},
"Activity": {
"title": "Activity",
"description": "Overview of all activity in this group.",
"noActivity": "There is not yet any activity in your group.",
"someone": "Someone",
"settingsModified": "Group settings were modified by <strong>{participant}</strong>.",
"expenseCreated": "Expense <em>{expense}</em> created by <strong>{participant}</strong>.",
"expenseUpdated": "Expense <em>{expense}</em> updated by <strong>{participant}</strong>.",
"expenseDeleted": "Expense <em>{expense}</em> deleted by <strong>{participant}</strong>.",
"Groups": {
"today": "Today",
"yesterday": "Yesterday",
"earlierThisWeek": "Earlier this week",
"lastWeek": "Last week",
"earlierThisMonth": "Earlier this month",
"lastMonth": "Last month",
"earlierThisYear": "Earlier this year",
"lastYear": "Last year",
"older": "Older"
}
},
"Information": {
"title": "Information",
"description": "Use this place to add any information that can be relevant to the group participants.",
"empty": "No group information yet."
},
"Settings": {
"title": "Settings"
},
"Locale": {
"en-US": "English",
"fi": "Suomi",
"fr-FR": "Français",
"es": "Español",
"de-DE": "Deutsch",
"zh-CN": "Chinese (Simplified)",
"ru-RU": "Русский",
"it-IT": "Italiano"
},
"Share": {
"title": "Share",
"description": "For other participants to see the group and add expenses, share its URL with them.",
"warning": "Warning!",
"warningHelp": "Every person with the group URL will be able to see and edit expenses. Share with caution!"
},
"SchemaErrors": {
"min1": "Enter at least one character.",
"min2": "Enter at least two characters.",
"max5": "Enter at most five characters.",
"max50": "Enter at most 50 characters.",
"duplicateParticipantName": "Another participant already has this name.",
"titleRequired": "Please enter a title.",
"invalidNumber": "Invalid number.",
"amountRequired": "You must enter an amount.",
"amountNotZero": "The amount must not be zero.",
"amountTenMillion": "The amount must be lower than 10,000,000.",
"paidByRequired": "You must select a participant.",
"paidForMin1": "The expense must be paid for at least one participant.",
"noZeroShares": "All shares must be higher than 0.",
"amountSum": "Sum of amounts must equal the expense amount.",
"percentageSum": "Sum of percentages must equal 100."
},
"Categories": {
"search": "Search category...",
"noCategory": "No category found.",
"Uncategorized": {
"heading": "Uncategorized",
"General": "General",
"Payment": "Payment"
},
"Entertainment": {
"heading": "Entertainment",
"Entertainment": "Entertainment",
"Games": "Games",
"Movies": "Movies",
"Music": "Music",
"Sports": "Sports"
},
"Food and Drink": {
"heading": "Food and Drink",
"Food and Drink": "Food and Drink",
"Dining Out": "Dining Out",
"Groceries": "Groceries",
"Liquor": "Liquor"
},
"Home": {
"heading": "Home",
"Home": "Home",
"Electronics": "Electronics",
"Furniture": "Furniture",
"Household Supplies": "Household Supplies",
"Maintenance": "Maintenance",
"Mortgage": "Mortgage",
"Pets": "Pets",
"Rent": "Rent",
"Services": "Services"
},
"Life": {
"heading": "Life",
"Childcare": "Childcare",
"Clothing": "Clothing",
"Education": "Education",
"Gifts": "Gifts",
"Insurance": "Insurance",
"Medical Expenses": "Medical Expenses",
"Taxes": "Taxes"
},
"Transportation": {
"heading": "Transportation",
"Transportation": "Transportation",
"Bicycle": "Bicycle",
"Bus/Train": "Bus/Train",
"Car": "Car",
"Gas/Fuel": "Gas/Fuel",
"Hotel": "Hotel",
"Parking": "Parking",
"Plane": "Plane",
"Taxi": "Taxi"
},
"Utilities": {
"heading": "Utilities",
"Utilities": "Utilities",
"Cleaning": "Cleaning",
"Electricity": "Electricity",
"Heat/Gas": "Heat/Gas",
"Trash": "Trash",
"TV/Phone/Internet": "TV/Phone/Internet",
"Water": "Water"
}
}
}

397
messages/es.json Normal file
View File

@@ -0,0 +1,397 @@
{
"Homepage": {
"title": "Comparte <strong>Gastos</strong> con <strong>Amigos y Familia</strong>",
"description": "¡Bienvenido a tu nueva instancia de <strong>Spliit</strong>!",
"button": {
"groups": "Ir a grupos",
"github": "GitHub"
}
},
"Header": {
"groups": "Grupos"
},
"Footer": {
"madeIn": "Hecho en Montréal, Québec 🇨🇦",
"builtBy": "Construido por <author>Sebastien Castiel</author> y <source>colaboradores</source>"
},
"Expenses": {
"title": "Gastos",
"description": "Aqui encontraras los gastos que has creado para tu grupo.",
"create": "Crear gasto",
"createFirst": "Crea el primero",
"noExpenses": "Tu grupo aun no tiene gastos.",
"exportJson": "Exportar a JSON",
"searchPlaceholder": "Busca un gasto…",
"ActiveUserModal": {
"title": "¿Quién es usted?",
"description": "Dinos qué participante eres para que podamos personalizar cómo se muestra la información.",
"nobody": "No quiero seleccionar a nadie",
"save": "Guardar cambios",
"footer": "Esta configuración puede modificarse posteriormente en los ajustes del grupo."
},
"Groups": {
"upcoming": "Próximamente",
"thisWeek": "Esta semana",
"earlierThisMonth": "A principios de este mes",
"lastMonth": "El mes pasado",
"earlierThisYear": "A principios de este año",
"lastYera": "El año pasado",
"older": "Más antiguos"
}
},
"ExpenseCard": {
"paidBy": "Pagado por <strong>{paidBy}</strong> para <paidFor></paidFor>",
"receivedBy": "Recibido por <strong>{paidBy}</strong> para <paidFor></paidFor>",
"yourBalance": "Tu balance:"
},
"Groups": {
"myGroups": "Mis grupos",
"create": "Crear",
"loadingRecent": "Cargando grupos recientes…",
"NoRecent": {
"description": "No has visitado ningun grupo recientemente.",
"create": "Crea uno",
"orAsk": "o pídele a un amigo que te envíe el enlace a uno ya existente.."
},
"recent": "Grupos recientes",
"starred": "Grupos favoritos",
"archived": "Grupos archivados",
"archive": "Archivar grupo",
"unarchive": "Desarchivar groupo",
"removeRecent": "Remove from recent groups",
"RecentRemovedToast": {
"title": "El grupo fue eliminado",
"description": "El grupo ha sido eliminado de tu lista de grupos recientes.",
"undoAlt": "Deshacer la eliminación del grupo",
"undo": "Deshacer"
},
"AddByURL": {
"button": "Añadir mediante url",
"title": "Añadir grupo mediante url",
"description": "Si te han compartido un grupo, puedes pegar aquí su URL para añadirlo a tu lista.",
"error": "Oops, no somos capaces de encontrar el grupo desde la URL que has proporcionado..."
},
"NotFound": {
"text": "Este grupo no existe.",
"link": "Ir a los últimos grupos visitados"
}
},
"GroupForm": {
"title": "Información del grupo",
"NameField": {
"label": "Nombre del grupo",
"placeholder": "Vacaciones en Barcelona",
"description": "Inserta un nombre para tu nuevo grupo."
},
"InformationField": {
"label": "Información del grupo",
"placeholder": "Qué información es relevante para los participantes del grupo?"
},
"CurrencyField": {
"label": "Símbolo de divisa",
"placeholder": "$, €, £…",
"description": "Lo usaremos para mostrar balances."
},
"Participants": {
"title": "Participantes",
"description": "Ingresa el nombre de cada participante.",
"protectedParticipant": "Estos participantes forman parte de gastos y no pueden ser eliminados.",
"new": "Nuevo",
"add": "Añadir participante",
"John": "Juan",
"Jane": "Maria",
"Jack": "Sergio"
},
"Settings": {
"title": "Ajustes locales",
"description": "Estos ajustes se establecen por dispositivo y se utilizan para personalizar su experiencia.",
"ActiveUserField": {
"label": "Usuario activo",
"placeholder": "Selecciona un participante...",
"none": "Ninguno",
"description": "Usuario que paga los gastos por defecto."
},
"save": "Guardar",
"saving": "Guardando",
"create": "Crear",
"creating": "Creando",
"cancel": "Cancelar"
}
},
"ExpenseForm": {
"Income": {
"create": "Crear ingreso",
"edit": "Editar ingreso",
"TitleField": {
"label": "Título del ingreso",
"placeholder": "Comida Hamburgeseria",
"description": "Introduce una descripción para este ingreso."
},
"DateField": {
"label": "Fecha del ingreso",
"description": "Ingresa la fecha en que se recibio el ingreso."
},
"categoryFieldDescription": "Seleccione la categoría de ingresos.",
"paidByField": {
"label": "Recibido por",
"description": "Seleccione el participante que recibió los ingresos."
},
"paidFor": {
"title": "Recibido para for",
"description": "Seleccione para quién se recibió el ingreso."
},
"splitModeDescription": "Seleccione como quieres dividir el ingreso.",
"attachDescription": "Ver y adjuntar tickets para el ingreso."
},
"Expense": {
"create": "Crear gasto",
"edit": "Editar gasto",
"TitleField": {
"label": "Título del gasto",
"placeholder": "Monday evening restaurant",
"description": "Enter a description for the expense."
},
"DateField": {
"label": "Fecha del gasto",
"description": "Ingresa la fecha en que se recibio el gasto."
},
"categoryFieldDescription": "Select the expense category.",
"paidByField": {
"label": "Pagado por",
"description": "Seleccione el participante que pagó el gasto."
},
"paidFor": {
"title": "Pagado para",
"description": "Seleccione para quién se pagó el gasto."
},
"splitModeDescription": "Seleccione como quieres dividir el gasto.",
"attachDescription": "Ver y adjuntar tickets para el gasto."
},
"amountField": {
"label": "Cantidad"
},
"isReimbursementField": {
"label": "Esto es un reembolso"
},
"categoryField": {
"label": "Categoria"
},
"notesField": {
"label": "Notas"
},
"selectNone": "Seleccionar ninguno",
"selectAll": "Seleccionar todos",
"shares": "partes",
"advancedOptions": "Opciones avanzadas",
"SplitModeField": {
"label": "Modo de división",
"evenly": "Uniformemente",
"byShares": "Desigualmente Por partes",
"byPercentage": "Desigualmente por porcentaje",
"byAmount": "Desigualmente por cantidad",
"saveAsDefault": "Guardar como modo preferido"
},
"DeletePopup": {
"label": "Borrar",
"title": "Borrar gasto?",
"description": "Seguro que quieres borrar este gasto? Esta acción es irreversible.",
"yes": "Si",
"cancel": "Cancelar"
},
"attachDocuments": "Adjuntar documentos",
"create": "Crear",
"creating": "Creando",
"save": "Guardar",
"saving": "Guardando",
"cancel": "Cancelar"
},
"ExpenseDocumentsInput": {
"TooBigToast": {
"title": "El archivo es demasiado grande",
"description": "El tamaño máximo de archivo que puede cargar es {maxSize}. El tuyo pesa ${size}."
},
"ErrorToast": {
"title": "Error al cargar el documento",
"description": "Ha ocurrido un error al cargar el documento. Vuelva a intentarlo más tarde o seleccione otro archivo.",
"retry": "Reintentar"
}
},
"CreateFromReceipt": {
"Dialog": {
"triggerTitle": "Crear gasto desde ticket",
"title": "Crear desde ticket",
"description": "Extraer la información de gastos de una foto de recibo.",
"body": "Sube la foto de un recibo y lo escanearemos para extraer la información del gasto si podemos.",
"selectImage": "Seleccionar imagen…",
"titleLabel": "Titulo:",
"categoryLabel": "Categoria:",
"amountLabel": "Cantidad:",
"dateLabel": "Fecha:",
"editNext": "A continuación podrá editar la información de los gastos.",
"continue": "Continuar"
},
"unknown": "Desconocido",
"TooBigToast": {
"title": "El archivo es demasiado grande",
"description": "El tamaño máximo de archivo que puede cargar es {maxSize}. El tuyo pesa ${size}."
},
"ErrorToast": {
"title": "Error al cargar el documento",
"description": "Ha ocurrido un error al cargar el documento. Vuelva a intentarlo más tarde o seleccione otro archivo.",
"retry": "Reintentar"
}
},
"Balances": {
"title": "Balances",
"description": "Se trata del importe que ha pagado o ha recibido cada participante.",
"Reimbursements": {
"title": "Reembolsos propuestos",
"description": "He aquí algunas sugerencias para optimizar los reembolsos entre los participantes.",
"noImbursements": "Parece que tu grupo no necesita ningún reembolso 😁",
"owes": "<strong>{from}</strong> debe <strong>{to}</strong>",
"markAsPaid": "Marcar como pagado"
}
},
"Stats": {
"title": "Estadísticas",
"Totals": {
"title": "Totales",
"description": "Resumen de gastos de todo el grupo.",
"groupSpendings": "Gastos de todo el grupo",
"groupEarnings": "Ingresos de todo el grupo",
"yourSpendings": "Tus gastos totales",
"yourEarnings": "Tus ingresos totales",
"yourShare": "Tu parte final"
}
},
"Activity": {
"title": "Actividad",
"description": "Aquí encontrarás todas las actividades recientes en tu grupo.",
"noActivity": "No hay actividad reciente en este grupo.",
"someone": "Alguien",
"settingsModified": "Los ajustes del grupo fueron modificados por <strong>{participant}</strong>.",
"expenseCreated": "Gasto <em>{expense}</em> creado por <strong>{participant}</strong>.",
"expenseUpdated": "Gasto <em>{expense}</em> actualizado por <strong>{participant}</strong>.",
"expenseDeleted": "Gasto <em>{expense}</em> borrado por <strong>{participant}</strong>.",
"Groups": {
"today": "Hoy",
"yesterday": "Ayer",
"earlierThisWeek": "A principios de esta semana",
"lastWeek": "La semana pasada",
"earlierThisMonth": "A principios de este mes",
"lastMonth": "El mes pasado",
"earlierThisYear": "A principios de este año",
"lastYear": "El ultimo año",
"older": "Más antiguos"
}
},
"Information": {
"title": "Información",
"description": "Utilice este lugar para añadir cualquier información que pueda ser relevante para los participantes del grupo.",
"empty": "Aún no hay información sobre el grupo."
},
"Settings": {
"title": "Ajustes"
},
"Locale": {
"en-US": "English",
"fi": "Suomi",
"fr-FR": "Français",
"es": "Español",
"de-DE": "Deutsch",
"zh-CN": "Chinese (Simplified)",
"ru-RU": "Русский",
"it-IT": "Italiano"
},
"Share": {
"title": "Compartir",
"description": "Para que otros participantes puedan ver el grupo y añadir gastos, compárteles su URL.",
"warning": "Cuidado!",
"warningHelp": "Todas las personas que tengan la URL del grupo podrán ver y editar los gastos. ¡Comparte con precaución!"
},
"SchemaErrors": {
"min1": "Introduzca al menos un carácter.",
"min2": "Introduzca al menos dos carácter.",
"max5": "Introduzca al menos cinco carácter.",
"max50": "Introduzca al menos treinta carácter.",
"duplicateParticipantName": "Otro participante ya tiene este nombre",
"titleRequired": "Por favor, introduzca un título",
"invalidNumber": "Número inválido",
"amountRequired": "Debe introducir un importe",
"amountNotZero": "El importe no debe ser cero.",
"amountTenMillion": "El importe debe ser inferior a 10.000.000.",
"paidByRequired": "Debe seleccionar un participante",
"paidForMin1": "El gasto debe ser pagado por al menos un participante",
"noZeroShares": "Todas las participaciones deben ser superiores a 0",
"amountSum": "La suma de los importes debe ser igual al importe del gasto",
"percentageSum": "Suma de porcentajes debe ser igual a 100"
},
"Categories": {
"search": "Buscar categoría...",
"noCategory": "Categoría no encontrada!",
"Uncategorized": {
"heading": "Sin categoría",
"General": "General",
"Payment": "Pago"
},
"Entertainment": {
"heading": "Ocio",
"Entertainment": "Ocio",
"Games": "Juegos",
"Movies": "Películas",
"Music": "Musica",
"Sports": "Deportes"
},
"Food and Drink": {
"heading": "Comida y bebida",
"Food and Drink": "Comida y bebida",
"Dining Out": "Comer fuera",
"Groceries": "Comestibles",
"Liquor": "Licores"
},
"Home": {
"heading": "Hogar",
"Home": "Hogar",
"Electronics": "Electrónica",
"Furniture": "Muebles",
"Household Supplies": "Suministros del hogar",
"Maintenance": "Mantenimiento",
"Mortgage": "Hipoteca",
"Pets": "Mascotas",
"Rent": "Alquiler",
"Services": "Servicios"
},
"Life": {
"heading": "Vida",
"Childcare": "Cuidado de niños",
"Clothing": "Ropa",
"Education": "Educación",
"Gifts": "Regalos",
"Insurance": "Seguro",
"Medical Expenses": "Gastos médicos",
"Taxes": "Impuestos"
},
"Transportation": {
"heading": "Transporte",
"Transportation": "Transporte",
"Bicycle": "Bicicleta",
"Bus/Train": "Autobús/Tren",
"Car": "Coche",
"Gas/Fuel": "Gasolina/Combustible",
"Hotel": "Hotel",
"Parking": "Parking",
"Plane": "Avión",
"Taxi": "Taxi"
},
"Utilities": {
"heading": "Utilidades",
"Utilities": "Utilidades",
"Cleaning": "Limpieza",
"Electricity": "Electricidad",
"Heat/Gas": "Calefacción/Gas",
"Trash": "Basura",
"TV/Phone/Internet": "TV/Teléfono/Internet",
"Water": "Agua"
}
}
}

397
messages/fi.json Normal file
View File

@@ -0,0 +1,397 @@
{
"Homepage": {
"title": "Jaa kulut ystävien ja perheen kanssa",
"description": "Tervetuloa uuteen Spliit-instanssiisi!",
"button": {
"groups": "Siirry ryhmiin",
"github": "GitHub"
}
},
"Header": {
"groups": "Ryhmät"
},
"Footer": {
"madeIn": "Made in Montréal, Québec 🇨🇦",
"builtBy": "Tekijät: <author>Sebastien Castiel</author> ja <source>muut osallistujat</source>"
},
"Expenses": {
"title": "Kulut",
"description": "Tässä ovat ryhmässä luodut kulut.",
"create": "Lisää kulu",
"createFirst": "Lisää ensimmäinen kulu",
"noExpenses": "Ryhmälläsi ei ole vielä yhtään kulua.",
"exportJson": "Vie JSON-tiedostoon",
"searchPlaceholder": "Etsi kulua…",
"ActiveUserModal": {
"title": "Kuka olet?",
"description": "Valitse kuka osallistujista olet, jotta tiedot näkyvät oikein.",
"nobody": "En halua valita ketään",
"save": "Tallenna muutokset",
"footer": "Tämän asetuksen voi vaihtaa myöhemmin ryhmän asetuksista."
},
"Groups": {
"upcoming": "Tulevat",
"thisWeek": "Tällä viikolla",
"earlierThisMonth": "Aikaisemmin tässä kuussa",
"lastMonth": "Viime kuussa",
"earlierThisYear": "Aikaisemmin tänä vuonna",
"lastYear": "Viime vuonna",
"older": "Vanhemmat"
}
},
"ExpenseCard": {
"paidBy": "<strong>{paidBy}</strong> maksoi {forCount, plural, =1 {henkilön} other {henkilöiden}} <paidFor></paidFor> puolesta",
"receivedBy": "<strong>{paidBy}</strong> sai rahaa {forCount, plural, =1 {henkilön} other {henkilöiden}} <paidFor></paidFor> puolesta",
"yourBalance": "Saldosi:"
},
"Groups": {
"myGroups": "Omat ryhmät",
"create": "Luo ryhmä",
"loadingRecent": "Ladataan äskettäisiä ryhmiä…",
"NoRecent": {
"description": "Et ole ollut missään ryhmässä äskettäin.",
"create": "Luo uusi ryhmä",
"orAsk": "tai pyydä ystävää lähettämään linkki olemassaolevaan ryhmään."
},
"recent": "Äskettäiset",
"starred": "Suosikit",
"archived": "Arkistoidut",
"archive": "Arkistoi ryhmä",
"unarchive": "Palauta ryhmä arkistosta",
"removeRecent": "Poista äskettäisistä",
"RecentRemovedToast": {
"title": "Ryhmä poistettu",
"description": "Ryhmä poistettu äskettäisten listaltasi.",
"undoAlt": "Peruuta ryhmän poisto",
"undo": "Peruuta"
},
"AddByURL": {
"button": "Lisää URLilla",
"title": "Lisää ryhmä URL-osoitteella",
"description": "Jos ryhmä on jaettu sinulle, voit lisätä sen listaasi liittämällä URL-osoitteen tähän.",
"error": "Hups, emme löytäneet ryhmää antamastasi URL-osoitteesta…"
},
"NotFound": {
"text": "Tätä ryhmää ei löydy.",
"link": "Siirry äskettäisiin ryhmiin"
}
},
"GroupForm": {
"title": "Ryhmän tiedot",
"NameField": {
"label": "Ryhmän nimi",
"placeholder": "Kesälomareissu",
"description": "Syötä ryhmäsi nimi."
},
"InformationField": {
"label": "Ryhmän tiedot",
"placeholder": "Mitkä tiedot ovat merkityksellisiä ryhmän osallistujille?"
},
"CurrencyField": {
"label": "Valuuttamerkki",
"placeholder": "$, €, £…",
"description": "Näytetään rahasummien yhteydessä."
},
"Participants": {
"title": "Osallistujat",
"description": "Syötä jokaisen osallistujan nimi.",
"protectedParticipant": "Tätä osallistujaa ei voida poistaa, koska hän osallistuu kuluihin.",
"add": "Lisää osallistuja",
"new": "Uusi",
"John": "Antti",
"Jane": "Laura",
"Jack": "Jussi"
},
"Settings": {
"title": "Paikalliset asetukset",
"description": "Nämä asetukset ovat laitekohtaisia. Voit muokata niillä käytettävyyttä.",
"ActiveUserField": {
"label": "Aktiivinen käyttäjä",
"placeholder": "Valitse osallistuja",
"none": "Ei kukaan",
"description": "Käytetään kulujen oletusmaksajana."
},
"save": "Tallenna",
"saving": "Tallennetaan…",
"create": "Luo ryhmä",
"creating": "Luodaan…",
"cancel": "Peruuta"
}
},
"ExpenseForm": {
"Income": {
"create": "Lisää tulo",
"edit": "Muokkaa tuloa",
"TitleField": {
"label": "Otsikko",
"placeholder": "Maanantain ravintola",
"description": "Anna lyhyt kuvaus tulolle."
},
"DateField": {
"label": "Päivä",
"description": "Valitse päivä jolloin tulo saatiin."
},
"categoryFieldDescription": "Valitse tulokategoria.",
"paidByField": {
"label": "Vastaanottaja",
"description": "Valitse kuka vastaanotti tulon."
},
"paidFor": {
"title": "Tulon jakaminen",
"description": "Valitse kenelle tulo jaetaan."
},
"splitModeDescription": "Valitse miten tulo jaetaan osallistujien kesken.",
"attachDescription": "Katso ja liitä tuloon liittyviä kuitteja."
},
"Expense": {
"create": "Lisää kulu",
"edit": "Muokkaa kulua",
"TitleField": {
"label": "Otsikko",
"placeholder": "Maanantain ravintola",
"description": "Anna lyhyt kuvaus kululle."
},
"DateField": {
"label": "Päivä",
"description": "Valitse päivä jolloin kulu maksettiin."
},
"categoryFieldDescription": "Valitse kulukategoria.",
"paidByField": {
"label": "Maksaja",
"description": "Valitse kuka maksoi kulun."
},
"paidFor": {
"title": "Kulun jakaminen",
"description": "Valitse ketkä osallistuvat kuluun."
},
"splitModeDescription": "Valitse miten kulu jaetaan osallistujien kesken.",
"attachDescription": "Katso ja liitä kuluun liittyviä kuitteja."
},
"amountField": {
"label": "Summa"
},
"isReimbursementField": {
"label": "Tämä on velanmaksu"
},
"categoryField": {
"label": "Kategoria"
},
"notesField": {
"label": "Muistiinpanot"
},
"selectNone": "Tyhjennä valinnat",
"selectAll": "Valitse kaikki",
"shares": "osuutta",
"advancedOptions": "Lisäasetuksia jakamiseen…",
"SplitModeField": {
"label": "Jakamistapa",
"evenly": "Tasan",
"byShares": "Epätasan osuuksien mukaan",
"byPercentage": "Epätasan prosenttien mukaan",
"byAmount": "Epätasan summan mukaan",
"saveAsDefault": "Tallenna oletustavaksi"
},
"DeletePopup": {
"label": "Poista",
"title": "Poistetaanko tämä kulu?",
"description": "Haluatko varmasti poistaa tämän kulun? Poistoa ei voi peruuttaa.",
"yes": "Kyllä",
"cancel": "Peruuta"
},
"attachDocuments": "Liitä dokumenttejä",
"create": "Lisää kulu",
"creating": "Luodaan kulua…",
"save": "Tallenna",
"saving": "Tallennetaan…",
"cancel": "Peruuta"
},
"ExpenseDocumentsInput": {
"TooBigToast": {
"title": "Tiedosto on liian suuri",
"description": "Maksimikoko ladattavalle tiedostolle on {maxSize}. Tiedostosi on ${size}."
},
"ErrorToast": {
"title": "Virhe tiedostoa ladattaessa",
"description": "Jokin meni vikaan dokumentin lataamisessa. Yritä myöhemmin uudelleen tai valitse toinen tiedosto.",
"retry": "Yritä uudelleen"
}
},
"CreateFromReceipt": {
"Dialog": {
"triggerTitle": "Luo kulu kuitista",
"title": "Luo kuitista",
"description": "Lue kuitin valokuvasta kulun tiedot.",
"body": "Lataa kuitista valokuva. Siitä skannataan tiedot kulua varten.",
"selectImage": "Valitse kuva…",
"titleLabel": "Otsikko:",
"categoryLabel": "Kategoria:",
"amountLabel": "Summa:",
"dateLabel": "Päivä:",
"editNext": "Voit muokata kulun tietoja seuraavaksi.",
"continue": "Jatka"
},
"unknown": "Unknown",
"TooBigToast": {
"title": "The file is too big",
"description": "The maximum file size you can upload is {maxSize}. Yours is ${size}."
},
"ErrorToast": {
"title": "Error while uploading document",
"description": "Something wrong happened when uploading the document. Please retry later or select a different file.",
"retry": "Retry"
}
},
"Balances": {
"title": "Saldo",
"description": "Osallistujien saatavat tai velat.",
"Reimbursements": {
"title": "Maksuehdotus",
"description": "Optimoitu ehdotus kuka maksaa kenellekin.",
"noImbursements": "Näyttää siltä, että kaikki ovat sujut 😁",
"owes": "<strong>{from}</strong> maksaa henkilölle <strong>{to}</strong>",
"markAsPaid": "Merkitse maksetuksi"
}
},
"Stats": {
"title": "Tilastot",
"Totals": {
"title": "Yhteenveto",
"description": "Koko ryhmän kulut.",
"groupSpendings": "Koko ryhmän kulutus",
"groupEarnings": "Koko ryhmän saatavat",
"yourSpendings": "Kulutuksesi",
"yourEarnings": "Saatavasi",
"yourShare": "Osuutesi"
}
},
"Activity": {
"title": "Tapahtumat",
"description": "Yleisnäkymä ryhmän kaikista tapahtumista.",
"noActivity": "Ryhmässäsi ei ole vielä tapahtumia.",
"someone": "Tuntematon",
"settingsModified": "<strong>{participant}</strong> muokkasi ryhmän asetuksia.",
"expenseCreated": "<strong>{participant}</strong> lisäsi kulun <em>{expense}</em>.",
"expenseUpdated": "<strong>{participant}</strong> muokkasi kulua <em>{expense}</em>.",
"expenseDeleted": "<strong>{participant}</strong> poisti kulun <em>{expense}</em>.",
"Groups": {
"today": "Tänään",
"yesterday": "Eilen",
"earlierThisWeek": "Tällä viikolla",
"lastWeek": "Viime viikolla",
"earlierThisMonth": "Tässä kuussa",
"lastMonth": "Viime kuussa",
"earlierThisYear": "Tänä vuonna",
"lastYear": "Viime vuonna",
"older": "Vanhemmat"
}
},
"Information": {
"title": "Tiedot",
"description": "Käytä tätä paikkaa lisätäksesi kaikki tiedot, joilla voi olla merkitystä ryhmän osallistujille.",
"empty": "Ryhmätietoja ei vielä ole."
},
"Settings": {
"title": "Asetukset"
},
"Locale": {
"en-US": "English",
"fi": "Suomi",
"fr-FR": "Français",
"es": "Español",
"de-DE": "Deutsch",
"zh-CN": "Chinese (Simplified)",
"ru-RU": "Русский",
"it-IT": "Italiano"
},
"Share": {
"title": "Jaa",
"description": "Jaa ryhmän URL muille jäsenille, jotta he voivat nähdä sen ja lisätä kuluja.",
"warning": "Varoitus!",
"warningHelp": "Tällä URLilla kuka tahansa pääsee näkemään ja muokkaamaan kuluja. Jaa harkiten!"
},
"SchemaErrors": {
"min1": "Syötä vähintään yksi merkki.",
"min2": "Syötä vähintään kaksi merkkiä.",
"max5": "Syötä enintään viisi merkkiä.",
"max50": "Syötä enintään 50 merkkiä.",
"duplicateParticipantName": "Tämä nimi on jo toisella osallistujalla.",
"titleRequired": "Otsikko puuttuu.",
"invalidNumber": "Epäkelpo numero.",
"amountRequired": "Summa puuttuu.",
"amountNotZero": "Summa ei voi olla nolla.",
"amountTenMillion": "Summan pitää olla pienempi kuin 10 000 000.",
"paidByRequired": "Osallistuja puuttuu.",
"paidForMin1": "Valitse vähintään yksi osallistuja.",
"noZeroShares": "Jokaisen osuuden täytyy olla suurempi kuin 0.",
"amountSum": "Osuuksien summan täytyy vastata kulun summaa.",
"percentageSum": "Prosenttiosuuksien summan täytyy olla 100."
},
"Categories": {
"search": "Etsi kategoriaa...",
"noCategory": "Kategoriaa ei löydy.",
"Uncategorized": {
"heading": "Yleiset",
"General": "Yleinen",
"Payment": "Maksu"
},
"Entertainment": {
"heading": "Viihde",
"Entertainment": "Viihde",
"Games": "Pelit",
"Movies": "Elokuvat",
"Music": "Musiikki",
"Sports": "Urheilu"
},
"Food and Drink": {
"heading": "Ruoka ja juoma",
"Food and Drink": "Ruoka ja juoma",
"Dining Out": "Ulkona syöminen",
"Groceries": "Marketti",
"Liquor": "Alkoholi"
},
"Home": {
"heading": "Koti",
"Home": "Koti",
"Electronics": "Elektroniikka",
"Furniture": "Huonekalut",
"Household Supplies": "Taloustavarat",
"Maintenance": "Huolto",
"Mortgage": "Laina",
"Pets": "Lemmikit",
"Rent": "Vuokra",
"Services": "Palvelut"
},
"Life": {
"heading": "Elämä",
"Childcare": "Lastenhoito",
"Clothing": "Vaatteet",
"Education": "Opiskelu",
"Gifts": "Lahjat",
"Insurance": "Vakuutukset",
"Medical Expenses": "Terveydenhoito",
"Taxes": "Verot"
},
"Transportation": {
"heading": "Liikenne",
"Transportation": "Liikenne",
"Bicycle": "Polkupyörä",
"Bus/Train": "Bussi/juna",
"Car": "Auto",
"Gas/Fuel": "Polttoaine",
"Hotel": "Hotelli",
"Parking": "Pysäköinti",
"Plane": "Lentäminen",
"Taxi": "Taksi"
},
"Utilities": {
"heading": "Sekalaiset",
"Utilities": "Sekalaiset",
"Cleaning": "Siivous",
"Electricity": "Sähkö",
"Heat/Gas": "Lämmitys",
"Trash": "Jätehuolto",
"TV/Phone/Internet": "TV/Puhelin/Internet",
"Water": "Vesi"
}
}
}

397
messages/fr-FR.json Normal file
View File

@@ -0,0 +1,397 @@
{
"Homepage": {
"title": "Partagez <strong>vos dépenses</strong> avec <strong>vos amis</strong> & <strong>votre famille :)</strong>",
"description": "Bienvenue sur votre instance <strong>Spliit</strong> !",
"button": {
"groups": "Accéder aux groupes",
"github": "GitHub"
}
},
"Header": {
"groups": "Groupes"
},
"Footer": {
"madeIn": "Made in Montréal, Québec 🇨🇦",
"builtBy": "Développé par <author>Sebastien Castiel</author> et <source>contributeurs</source>"
},
"Expenses": {
"title": "Dépenses",
"description": "Voici les dépenses que vous avez créées pour votre groupe.",
"create": "Créer une dépense",
"createFirst": "Créer la première :)",
"noExpenses": "Votre groupe n'a effectué aucune dépense pour le moment.",
"exportJson": "Exporter en JSON",
"searchPlaceholder": "Rechercher une dépense…",
"ActiveUserModal": {
"title": "Qui êtes-vous ?",
"description": "Dites-nous quel participant vous êtes pour personnaliser l'affichage des informations.",
"nobody": "Je ne veux sélectionner personne",
"save": "Sauvegarder les modifications",
"footer": "Ce paramètre peut être modifié plus tard dans les paramètres du groupe."
},
"Groups": {
"upcoming": "À venir",
"thisWeek": "Cette semaine",
"earlierThisMonth": "Plus tôt ce mois-ci",
"lastMonth": "Le mois dernier",
"earlierThisYear": "Plus tôt cette année",
"lastYera": "L'année dernière",
"older": "Plus ancien"
}
},
"ExpenseCard": {
"paidBy": "Payé par <strong>{paidBy}</strong> pour <paidFor></paidFor>",
"receivedBy": "Reçu par <strong>{paidBy}</strong> pour <paidFor></paidFor>",
"yourBalance": "Votre solde :"
},
"Groups": {
"myGroups": "Mes groupes",
"create": "Créer",
"loadingRecent": "Chargement des groupes récents…",
"NoRecent": {
"description": "Vous n'avez visité aucun groupe récemment.",
"create": "Créer un groupe",
"orAsk": "ou demandez à un ami de vous envoyer le lien d'un groupe existant."
},
"recent": "Groupes récents",
"starred": "Groupes favoris",
"archived": "Groupes archivés",
"archive": "Archiver le groupe",
"unarchive": "Désarchiver le groupe",
"removeRecent": "Supprimer des groupes récents",
"RecentRemovedToast": {
"title": "Le groupe a été supprimé",
"description": "Le groupe a été supprimé de votre liste de groupes récents.",
"undoAlt": "Annuler la suppression du groupe",
"undo": "Annuler"
},
"AddByURL": {
"button": "Ajouter par URL",
"title": "Ajouter un groupe par URL",
"description": "Si un groupe a été partagé avec vous, vous pouvez coller son URL ici pour l'ajouter à votre liste.",
"error": "Oups, nous ne pouvons pas trouver le groupe à partir de l'URL que vous avez fournie…"
},
"NotFound": {
"text": "Ce groupe n'existe pas.",
"link": "Aller aux groupes récemment visités"
}
},
"GroupForm": {
"title": "Informations sur le groupe",
"NameField": {
"label": "Nom du groupe",
"placeholder": "Vacances d'été",
"description": "Entrez un nom pour votre groupe."
},
"InformationField": {
"label": "Informations sur le groupe",
"placeholder": "Quelles informations sont pertinentes pour les participants du groupe ?"
},
"CurrencyField": {
"label": "Symbole monétaire",
"placeholder": "$, €, £…",
"description": "Nous l'utiliserons pour afficher les montants."
},
"Participants": {
"title": "Participants",
"description": "Entrez le nom de chaque participant.",
"protectedParticipant": "Ce participant fait partie des dépenses et ne peut pas être supprimé.",
"new": "Nouveau",
"add": "Ajouter un participant",
"John": "John",
"Jane": "Jane",
"Jack": "Jack"
},
"Settings": {
"title": "Paramètres locaux",
"description": "Ces paramètres sont définis par appareil et sont utilisés pour personnaliser votre expérience.",
"ActiveUserField": {
"label": "Utilisateur actif",
"placeholder": "Sélectionner un participant",
"none": "Aucun",
"description": "Utilisateur utilisé comme défaut pour payer les dépenses."
},
"save": "Sauvegarder",
"saving": "Sauvegarde…",
"create": "Créer",
"creating": "Création…",
"cancel": "Annuler"
}
},
"ExpenseForm": {
"Income": {
"create": "Créer un revenu",
"edit": "Modifier le revenu",
"TitleField": {
"label": "Titre du revenu",
"placeholder": "Restaurant du lundi soir",
"description": "Entrez une description pour le revenu."
},
"DateField": {
"label": "Date du revenu",
"description": "Entrez la date à laquelle le revenu a été reçu."
},
"categoryFieldDescription": "Sélectionnez la catégorie de revenu.",
"paidByField": {
"label": "Reçu par",
"description": "Sélectionnez le participant qui a reçu le revenu."
},
"paidFor": {
"title": "Reçu pour",
"description": "Sélectionnez pour qui le revenu a été reçu."
},
"splitModeDescription": "Sélectionnez comment diviser le revenu.",
"attachDescription": "Voir et joindre des reçus au revenu."
},
"Expense": {
"create": "Créer une dépense",
"edit": "Modifier la dépense",
"TitleField": {
"label": "Titre de la dépense",
"placeholder": "Restaurant du lundi soir",
"description": "Entrez une description pour la dépense."
},
"DateField": {
"label": "Date de la dépense",
"description": "Entrez la date à laquelle la dépense a été payée."
},
"categoryFieldDescription": "Sélectionnez la catégorie de dépense.",
"paidByField": {
"label": "Payé par",
"description": "Sélectionnez le participant qui a réglé la dépense."
},
"paidFor": {
"title": "Payé pour",
"description": "Sélectionnez les participants concernés"
},
"splitModeDescription": "Sélectionnez comment diviser la dépense.",
"attachDescription": "Voir et joindre des reçus à la dépense."
},
"amountField": {
"label": "Montant"
},
"isReimbursementField": {
"label": "C'est un remboursement"
},
"categoryField": {
"label": "Catégorie"
},
"notesField": {
"label": "Notes"
},
"selectNone": "Tout désélectionner",
"selectAll": "Tout sélectionner",
"shares": "part(s)",
"advancedOptions": "Options de répartition avancées…",
"SplitModeField": {
"label": "Mode de répartition",
"evenly": "Également",
"byShares": "Inégalement Par parts",
"byPercentage": "Inégalement Par pourcentage",
"byAmount": "Inégalement Par montant",
"saveAsDefault": "Enregistrer comme options de répartition par défaut"
},
"DeletePopup": {
"label": "Supprimer",
"title": "Supprimer cette dépense ?",
"description": "Voulez-vous vraiment supprimer cette dépense ? Cette action est irréversible.",
"yes": "Oui",
"cancel": "Annuler"
},
"attachDocuments": "Joindre des documents",
"create": "Créer",
"creating": "Création…",
"save": "Sauvegarder",
"saving": "Sauvegarde…",
"cancel": "Annuler"
},
"ExpenseDocumentsInput": {
"TooBigToast": {
"title": "Le fichier est trop grand",
"description": "La taille maximale du fichier que vous pouvez télécharger est {maxSize}. La vôtre est ${size}."
},
"ErrorToast": {
"title": "Erreur lors du téléchargement du document",
"description": "Un problème est survenu lors du téléchargement du document. Veuillez réessayer plus tard ou sélectionner un fichier différent.",
"retry": "Réessayer"
}
},
"CreateFromReceipt": {
"Dialog": {
"triggerTitle": "Créer une dépense à partir du reçu",
"title": "Créer à partir du reçu",
"description": "Extraire les informations de la dépense à partir d'une photo de reçu.",
"body": "Téléchargez la photo d'un reçu, et nous l'analyserons pour extraire les informations de la dépense si possible.",
"selectImage": "Sélectionner une image…",
"titleLabel": "Titre :",
"categoryLabel": "Catégorie :",
"amountLabel": "Montant :",
"dateLabel": "Date :",
"editNext": "Vous pourrez modifier les informations de la dépense ensuite.",
"continue": "Continuer"
},
"unknown": "Inconnu",
"TooBigToast": {
"title": "Le fichier est trop grand",
"description": "La taille maximale du fichier que vous pouvez télécharger est {maxSize}. La vôtre est ${size}."
},
"ErrorToast": {
"title": "Erreur lors du téléchargement du document",
"description": "Un problème est survenu lors du téléchargement du document. Veuillez réessayer plus tard ou sélectionner un fichier différent.",
"retry": "Réessayer"
}
},
"Balances": {
"title": "Équilibres",
"description": "Voici le montant que chaque participant a payé ou doit rembourser.",
"Reimbursements": {
"title": "Remboursements suggérés",
"description": "Voici des suggestions pour des remboursements optimisés entre les participants.",
"noImbursements": "Les dépenses effectuées ne nécessitent pas d'équilibrage 😁",
"owes": "<strong>{from}</strong> doit à <strong>{to}</strong>",
"markAsPaid": "Marquer comme payé"
}
},
"Stats": {
"title": "Statistiques",
"Totals": {
"title": "Totaux",
"description": "Résumé des dépenses du groupe entier.",
"groupSpendings": "Total des dépenses du groupe",
"groupEarnings": "Total des revenus du groupe",
"yourSpendings": "Vos dépenses totales",
"yourEarnings": "Vos revenus totaux",
"yourShare": "Votre part totale"
}
},
"Activity": {
"title": "Activité",
"description": "Vue d'ensemble de toute l'activité dans ce groupe.",
"noActivity": "Il n'y a pas encore d'activité dans votre groupe.",
"someone": "Quelqu'un",
"settingsModified": "Les paramètres du groupe ont été modifiés par <strong>{participant}</strong>.",
"expenseCreated": "Dépense <em>{expense}</em> créée par <strong>{participant}</strong>.",
"expenseUpdated": "Dépense <em>{expense}</em> mise à jour par <strong>{participant}</strong>.",
"expenseDeleted": "Dépense <em>{expense}</em> supprimée par <strong>{participant}</strong>.",
"Groups": {
"today": "Aujourd'hui",
"yesterday": "Hier",
"earlierThisWeek": "Plus tôt cette semaine",
"lastWeek": "La semaine dernière",
"earlierThisMonth": "Plus tôt ce mois-ci",
"lastMonth": "Le mois dernier",
"earlierThisYear": "Plus tôt cette année",
"lastYear": "L'année dernière",
"older": "Plus ancien"
}
},
"Information": {
"title": "Information",
"description": "Utilisez cet espace pour ajouter toute information qui pourrait être pertinente pour les participants du groupe.",
"empty": "Aucune information pour le moment."
},
"Settings": {
"title": "Paramètres"
},
"Locale": {
"en-US": "English",
"fi": "Suomi",
"fr-FR": "Français",
"es": "Español",
"de-DE": "Deutsch",
"zh-CN": "Chinese (Simplified)",
"ru-RU": "Русский",
"it-IT": "Italiano"
},
"Share": {
"title": "Partager",
"description": "Pour que d'autres participants puissent voir le groupe et ajouter des dépenses, partagez son URL avec eux.",
"warning": "Avertissement !",
"warningHelp": "Toute personne ayant l'URL du groupe pourra voir et modifier les dépenses. Partagez avec prudence !"
},
"SchemaErrors": {
"min1": "Entrez au moins un caractère.",
"min2": "Entrez au moins deux caractères.",
"max5": "Entrez au maximum cinq caractères.",
"max50": "Entrez au maximum 50 caractères.",
"duplicateParticipantName": "Un autre participant a déjà ce nom.",
"titleRequired": "Veuillez entrer un titre.",
"invalidNumber": "Nombre invalide.",
"amountRequired": "Vous devez entrer un montant.",
"amountNotZero": "Le montant ne doit pas être zéro.",
"amountTenMillion": "Le montant doit être inférieur à 10 000 000.",
"paidByRequired": "Vous devez sélectionner un participant.",
"paidForMin1": "La dépense doit concerner au moins un participant.",
"noZeroShares": "Toutes les parts doivent être supérieures à 0.",
"amountSum": "La somme des montants doit être égale au montant de la dépense.",
"percentageSum": "La somme des pourcentages doit être égale à 100."
},
"Categories": {
"search": "Rechercher une catégorie…",
"noCategory": "Aucune catégorie trouvée.",
"Uncategorized": {
"heading": "Non classé",
"General": "Général",
"Payment": "Paiement"
},
"Entertainment": {
"heading": "Divertissement",
"Entertainment": "Divertissement",
"Games": "Jeux",
"Movies": "Films",
"Music": "Musique",
"Sports": "Sports"
},
"Food and Drink": {
"heading": "Nourriture et boissons",
"Food and Drink": "Nourriture et boissons",
"Dining Out": "Repas au restaurant",
"Groceries": "Épicerie",
"Liquor": "Alcool"
},
"Home": {
"heading": "Maison",
"Home": "Maison",
"Electronics": "Électronique",
"Furniture": "Mobilier",
"Household Supplies": "Fournitures ménagères",
"Maintenance": "Entretien",
"Mortgage": "Hypothèque",
"Pets": "Animaux",
"Rent": "Loyer",
"Services": "Services"
},
"Life": {
"heading": "Vie",
"Childcare": "Garde d'enfants",
"Clothing": "Vêtements",
"Education": "Éducation",
"Gifts": "Cadeaux",
"Insurance": "Assurance",
"Medical Expenses": "Dépenses médicales",
"Taxes": "Impôts"
},
"Transportation": {
"heading": "Transport",
"Transportation": "Transport",
"Bicycle": "Bicyclette",
"Bus/Train": "Bus/Train",
"Car": "Voiture",
"Gas/Fuel": "Essence/Carburant",
"Hotel": "Hôtel",
"Parking": "Parking",
"Plane": "Avion",
"Taxi": "Taxi"
},
"Utilities": {
"heading": "Services publics",
"Utilities": "Services publics",
"Cleaning": "Nettoyage",
"Electricity": "Électricité",
"Heat/Gas": "Chauffage/Gaz",
"Trash": "Poubelle",
"TV/Phone/Internet": "TV/Téléphone/Internet",
"Water": "Eau"
}
}
}

397
messages/it-IT.json Normal file
View File

@@ -0,0 +1,397 @@
{
"Homepage": {
"title": "Condividi <strong>Spese</strong> con <strong>Amici & Familiari</strong>",
"description": "Benvenuto nella tua nuova instanza di <strong>Spliit</strong>!",
"button": {
"groups": "Vai ai gruppi",
"github": "GitHub"
}
},
"Header": {
"groups": "Gruppi"
},
"Footer": {
"madeIn": "Made in Montréal, Québec 🇨🇦",
"builtBy": "Built by <author>Sebastien Castiel</author> and <source>contributors</source>"
},
"Expenses": {
"title": "Spese",
"description": "Ecco le spese che hai creato per il tuo gruppo.",
"create": "Crea spesa",
"createFirst": "Crea la prima",
"noExpenses": "Il tuo gruppo non contiene ancora spese.",
"exportJson": "Esporta file JSON",
"searchPlaceholder": "Cerca una spesa…",
"ActiveUserModal": {
"title": "Chi sei?",
"description": "Dicci quale partecipante sei per consentirci di personalizzare la modalità di visualizzazione delle informazioni.",
"nobody": "Non voglio selezionare nessuno",
"save": "Salva cambiamenti",
"footer": "Questa impostazione può essere modificata successivamente nelle impostazioni del gruppo."
},
"Groups": {
"upcoming": "In arrivo",
"thisWeek": "Questa settimana",
"earlierThisMonth": "All'inizio di questo mese",
"lastMonth": "Ultimo mese",
"earlierThisYear": "All'inizio di quest'anno",
"lastYera": "Ultimo anno",
"older": "Più vecchio"
}
},
"ExpenseCard": {
"paidBy": "Pagato da <strong>{paidBy}</strong> per <paidFor></paidFor>",
"receivedBy": "Ricevuto da <strong>{paidBy}</strong> per <paidFor></paidFor>",
"yourBalance": "Il to bilancio:"
},
"Groups": {
"myGroups": "I miei gruppi",
"create": "Crea",
"loadingRecent": "Caricamento gruppi recenti…",
"NoRecent": {
"description": "Non hai visitato nessun gruppo di recente.",
"create": "Creane una",
"orAsk": "oppure chiedi a un amico di inviarti il collegamento a uno esistente."
},
"recent": "Gruppi recenti",
"starred": "Gruppi speciali",
"archived": "Gruppi archiviati",
"archive": "Archivia gruppo",
"unarchive": "Rimuovi dall'archivio il gruppo",
"removeRecent": "Rimuovi dai gruppi recenti",
"RecentRemovedToast": {
"title": "Il gruppo è stato rimosso",
"description": "Il gruppo è stato rimosso dall'elenco dei gruppi recenti.",
"undoAlt": "Annulla la rimozione del gruppo",
"undo": "Annulla"
},
"AddByURL": {
"button": "Aggiungi tramite URL",
"title": "Aggiungi un gruppo tramite URL",
"description": "Se un gruppo è stato condiviso con te, puoi incollare qui il suo URL per aggiungerlo al tuo elenco.",
"error": "Spiacenti, non siamo in grado di trovare il gruppo dall'URL che hai fornito..."
},
"NotFound": {
"text": "Questo gruppo non esiste.",
"link": "Vai ai gruppi visitati di recente"
}
},
"GroupForm": {
"title": "Informazioni del gruppo",
"NameField": {
"label": "Nome del gruppo",
"placeholder": "Vacanze estive",
"description": "Inserisci il nome del gruppo."
},
"InformationField": {
"label": "Informazioni del gruppo",
"placeholder": "Quali informazioni sono rilevanti per i partecipanti al gruppo?"
},
"CurrencyField": {
"label": "Simbolo valuta",
"placeholder": "$, €, £…",
"description": "Lo useremo per visualizzare gli importi."
},
"Participants": {
"title": "Partecipanti",
"description": "Immettere il nome per ciascun partecipante.",
"protectedParticipant": "Questo partecipante fa parte delle spese e non può essere rimosso.",
"new": "Nuovo",
"add": "Aggiungi partecipante",
"John": "John",
"Jane": "Jane",
"Jack": "Jack"
},
"Settings": {
"title": "Impostazioni locali",
"description": "Queste impostazioni sono impostate per dispositivo e vengono utilizzate per personalizzare la tua esperienza.",
"ActiveUserField": {
"label": "Utente attivo",
"placeholder": "Seleziona un partecipante",
"none": "Nessuno",
"description": "Utente utilizzato come predefinito per il pagamento delle spese."
},
"save": "Salva",
"saving": "Salvataggio…",
"create": "Crea",
"creating": "Sto creando…",
"cancel": "Annulla"
}
},
"ExpenseForm": {
"Income": {
"create": "Crea entrata",
"edit": "Modifica entrata",
"TitleField": {
"label": "Titolo entrata",
"placeholder": "Ristorante del lunedì sera",
"description": "Inserisci una descrizione per l'entrata."
},
"DateField": {
"label": "Data entrata",
"description": "Inserisci la data in cui è stato ricevuta l'entrata."
},
"categoryFieldDescription": "Seleziona categoria entrata.",
"paidByField": {
"label": "Ricevuto da",
"description": "Seleziona partecipante che ha ricevuto l'entrata."
},
"paidFor": {
"title": "Ricevuto per",
"description": "Seleziona per chi è stato ricevuta l'entrata."
},
"splitModeDescription": "Seleziona come dividere l'entrata.",
"attachDescription": "Vedi allegati entrata."
},
"Expense": {
"create": "Crea spesa",
"edit": "Modifica spesa",
"TitleField": {
"label": "Titolo spesa",
"placeholder": "Ristorante del lunedì sera",
"description": "Inserisci una descrizione per l'uscita."
},
"DateField": {
"label": "Data spesa",
"description": "Inserisci la data di quando è stata fatta la spesa"
},
"categoryFieldDescription": "Seleziona una categoria per la spesa.",
"paidByField": {
"label": "Pagato da",
"description": "Seleziona il partecipante che ha pagato la spesa."
},
"paidFor": {
"title": "Pagato per",
"description": "Seleziona per chi è stata pagato."
},
"splitModeDescription": "Seleziona come dividere la spesa.",
"attachDescription": "Vedi allegati spesa."
},
"amountField": {
"label": "Quantità"
},
"isReimbursementField": {
"label": "Questo è un rimborso"
},
"categoryField": {
"label": "Categoria"
},
"notesField": {
"label": "Note"
},
"selectNone": "Seleziona nessuna",
"selectAll": "Seleziona tutto",
"shares": "condividi",
"advancedOptions": "Opzioni di divisione avanzate…",
"SplitModeField": {
"label": "Modalità split",
"evenly": "Uniforme",
"byShares": "Non uniforme Per scelta",
"byPercentage": "Non uniforme Per percentuale",
"byAmount": "Non uniforme Per quantità",
"saveAsDefault": "Salva come opzioni di suddivisione predefinite"
},
"DeletePopup": {
"label": "Rimuovi",
"title": "Rimuovere questa spesa?",
"description": "Vuoi davvero eliminare questa spesa? Questa azione è irreversibile.",
"yes": "Si",
"cancel": "Annulla"
},
"attachDocuments": "Documenti allegati",
"create": "Crea",
"creating": "Sto creando…",
"save": "Salva",
"saving": "Sto salvando…",
"cancel": "Annulla"
},
"ExpenseDocumentsInput": {
"TooBigToast": {
"title": "Il file è troppo grande",
"description": "La dimensione massima del file che puoi caricare è {maxSize}. Il tuo è ${size}."
},
"ErrorToast": {
"title": "Errore durante il caricamento del documento",
"description": "Si è verificato un errore durante il caricamento del documento. Riprova più tardi o seleziona un file diverso.",
"retry": "Riprova"
}
},
"CreateFromReceipt": {
"Dialog": {
"triggerTitle": "Crea spesa dalla ricevuta",
"title": "Crea dalla ricevuta",
"description": "Estrai le informazioni sulla spesa da una foto della ricevuta.",
"body": "Carica la foto di una ricevuta e, se possibile, la scannerizzeremo per estrarre le informazioni sulle spese.",
"selectImage": "Seleziona immagine…",
"titleLabel": "Titolo:",
"categoryLabel": "Categoria:",
"amountLabel": "Quantità:",
"dateLabel": "Data:",
"editNext": "Successivamente potrai modificare le informazioni sulle spese.",
"continue": "Continua"
},
"unknown": "Unknown",
"TooBigToast": {
"title": "Il file è troppo grande",
"description": "La dimensione massima del file che puoi caricare è {maxSize}. Il tuo è ${size}."
},
"ErrorToast": {
"title": "Errore durante il caricamento del documento",
"description": "Si è verificato un errore durante il caricamento del documento. Riprova più tardi o seleziona un file diverso.",
"retry": "Riprova"
}
},
"Balances": {
"title": "Bilanci",
"description": "Questo è l'importo che ciascun partecipante ha pagato o è stato pagato.",
"Reimbursements": {
"title": "Rimborsi suggeriti",
"description": "Ecco alcuni suggerimenti per ottimizzare i rimborsi tra i partecipanti.",
"noImbursements": "Sembra che il tuo gruppo non abbia bisogno di alcun rimborso 😁",
"owes": "<strong>{from}</strong> deve <strong>{to}</strong>",
"markAsPaid": "Marca come pagato"
}
},
"Stats": {
"title": "Statistiche",
"Totals": {
"title": "Totali",
"description": "Riepilogo delle spese dell'intero gruppo.",
"groupSpendings": "Spese totali del gruppo",
"groupEarnings": "Guadagno totale del gruppo",
"yourSpendings": "Le tue spese totali",
"yourEarnings": "I tuoi guadagni totali",
"yourShare": "La tua quota totale"
}
},
"Activity": {
"title": "Attività",
"description": "Panoramica di tutte le attività in questo gruppo.",
"noActivity": "Non c'è ancora alcuna attività nel tuo gruppo.",
"someone": "Qualcuno",
"settingsModified": "Le impostazioni del gruppo sono state modificate da <strong>{participant}</strong>.",
"expenseCreated": "Spesa <em>{expense}</em> creata da <strong>{participant}</strong>.",
"expenseUpdated": "Spesa <em>{expense}</em> aggiornata da <strong>{participant}</strong>.",
"expenseDeleted": "Spesa <em>{expense}</em> cancellata da <strong>{participant}</strong>.",
"Groups": {
"today": "Oggi",
"yesterday": "Ieri",
"earlierThisWeek": "All'inizio di questa settimana",
"lastWeek": "La settimana scorsa",
"earlierThisMonth": "All'inizio di questo mese",
"lastMonth": "Lo scorso mese",
"earlierThisYear": "All'inizio di questo anno",
"lastYear": "Lo scorso anno",
"older": "Più vecchio"
}
},
"Information": {
"title": "Informazioni",
"description": "Utilizza questo posto per aggiungere qualsiasi informazione che possa essere rilevante per i partecipanti al gruppo.",
"empty": "Nessuna informazione sul gruppo ancora."
},
"Settings": {
"title": "Impostazioni"
},
"Locale": {
"en-US": "English",
"fi": "Suomi",
"fr-FR": "Français",
"es": "Español",
"de-DE": "Deutsch",
"zh-CN": "Chinese (Simplified)",
"ru-RU": "Русский",
"it-IT": "Italiano"
},
"Share": {
"title": "Condividi",
"description": "Per consentire agli altri partecipanti di vedere il gruppo e aggiungere spese, condividi il suo URL con loro.",
"warning": "Attenzione!",
"warningHelp": "Ogni persona con l'URL del gruppo potrà vedere e modificare le spese. Condividi con cautela!"
},
"SchemaErrors": {
"min1": "Inserisci almeno un carattere.",
"min2": "Inserisci almeno due caratteri.",
"max5": "Inserisci al massimo cinque caratteri.",
"max50": "Inserisci al massimo cinquanta caratteri.",
"duplicateParticipantName": "Un altro partecipante ha già questo nome.",
"titleRequired": "Inserisci un titolo.",
"invalidNumber": "Numero invalido.",
"amountRequired": "Devi inserire una quanttà",
"amountNotZero": "La quantità non deve essere zero.",
"amountTenMillion": "L'importo deve essere inferiore a 10.000.000.",
"paidByRequired": "È necessario selezionare un partecipante.",
"paidForMin1": "La spesa dovrà essere sostenuta per almeno un partecipante.",
"noZeroShares": "Tutte le condivisioni devono essere superiori a 0.",
"amountSum": "La somma degli importi deve essere uguale all'importo della spesa.",
"percentageSum": "La somma delle percentuali deve essere uguale a 100."
},
"Categories": {
"search": "Cerca categoria...",
"noCategory": "Nessuna categoria trovata.",
"Uncategorized": {
"heading": "Senza categoria",
"General": "Generale",
"Payment": "Pagamento"
},
"Entertainment": {
"heading": "Intrattenimento",
"Entertainment": "Intrattenimento",
"Games": "Games",
"Movies": "Film",
"Music": "Musica",
"Sports": "Sports"
},
"Food and Drink": {
"heading": "Cibo e Bevande",
"Food and Drink": "Cibo e Bevande",
"Dining Out": "Mangiare fuori",
"Groceries": "Generi alimentari",
"Liquor": "Liquori"
},
"Home": {
"heading": "Home",
"Home": "Home",
"Electronics": "Elettronica",
"Furniture": "Mobilia",
"Household Supplies": "Forniture per la casa",
"Maintenance": "Manutenzione",
"Mortgage": "Mutuo",
"Pets": "Animali",
"Rent": "Affitti",
"Services": "Servizi"
},
"Life": {
"heading": "Life",
"Childcare": "Assistenza all'infanzia",
"Clothing": "Vestiti",
"Education": "Educazione",
"Gifts": "Regali",
"Insurance": "Assicurazione",
"Medical Expenses": "Spese Mediche",
"Taxes": "Tasse"
},
"Transportation": {
"heading": "Trasporti",
"Transportation": "Trasporti",
"Bicycle": "Bicicletta",
"Bus/Train": "Bus/Treno",
"Car": "Auto",
"Gas/Fuel": "Gas/Carburante",
"Hotel": "Hotel",
"Parking": "Parcheggio",
"Plane": "Aereo",
"Taxi": "Taxi"
},
"Utilities": {
"heading": "Utilità",
"Utilities": "Utilità",
"Cleaning": "Pulizia",
"Electricity": "Elettricità",
"Heat/Gas": "Riscaldamento/Gas",
"Trash": "Spazzatura",
"TV/Phone/Internet": "TV/Telefono/Internet",
"Water": "Acqua"
}
}
}

397
messages/ru-RU.json Normal file
View File

@@ -0,0 +1,397 @@
{
"Homepage": {
"title": "Делитесь <strong>расходами</strong> с <strong>друзьями и семьей</strong>",
"description": "Добро пожаловать в вашу новую инстанцию <strong>Spliit</strong>!",
"button": {
"groups": "Перейти к группам",
"github": "GitHub"
}
},
"Header": {
"groups": "Группы"
},
"Footer": {
"madeIn": "Сделано в Монреале, Квебек 🇨🇦",
"builtBy": "Создано <author>Sebastien Castiel</author> и <source>соавторами</source>"
},
"Expenses": {
"title": "Расходы",
"description": "В этом разделе находятся расходы вашей группы.",
"create": "Создать расход",
"createFirst": "Создать первый расход",
"noExpenses": "У вашей группы пока что нет расходов.",
"exportJson": "Экспортировать в JSON",
"searchPlaceholder": "Поиск расходов…",
"ActiveUserModal": {
"title": "Кто вы?",
"description": "Скажите нам, кто вы из этого списка, чтобы мы могли подстроить интерфейс под вас.",
"nobody": "Не хочу выбирать",
"save": "Сохранить изменения",
"footer": "Вы сможете изменить это в настройках группы."
},
"Groups": {
"upcoming": "Будущее",
"thisWeek": "На этой неделе",
"earlierThisMonth": "Ранее в этом месяце",
"lastMonth": "В прошлом месяце",
"earlierThisYear": "Ранее в этом году",
"lastYera": "В прошлом году",
"older": "Очень давно"
}
},
"ExpenseCard": {
"paidBy": "Потратил <strong>{paidBy}</strong> за <paidFor></paidFor>",
"receivedBy": "Получил <strong>{paidBy}</strong> за <paidFor></paidFor>",
"yourBalance": "Изменение баланса участника:"
},
"Groups": {
"myGroups": "Мои группы",
"create": "Создать",
"loadingRecent": "Загрузка недавних групп…",
"NoRecent": {
"description": "У вас нет недавних групп.",
"create": "Вы можете создать группу",
"orAsk": "или попросить вашего друга отправить вам ссылку на существующую."
},
"recent": "Недавние группы",
"starred": "Избранные",
"archived": "Архивированные группы",
"archive": "Архивировать группу",
"unarchive": "Восстановить группу",
"removeRecent": "Убрать группу из недавних",
"RecentRemovedToast": {
"title": "Группа убрана",
"description": "Группа была убрана из вашего списка недавних групп.",
"undoAlt": "Отменить удаление группы из этого списка",
"undo": "Отмена"
},
"AddByURL": {
"button": "Добавить по URL",
"title": "Добавить группу по URL",
"description": "Если с вами поделились ссылкой на группу, вставьте ее сюда, чтобы добавить ее в ваш список.",
"error": "К сожалению, мы не смогли найти группу по этому URL."
},
"NotFound": {
"text": "Этой группы не существует",
"link": "Перейти к списку недавних групп"
}
},
"GroupForm": {
"title": "Сведения о группе",
"NameField": {
"label": "Название группы",
"placeholder": "Летние поездки",
"description": "Введите название вашей группы."
},
"InformationField": {
"label": "Информация о группе",
"placeholder": "Что важно знать участникам этой группы?"
},
"CurrencyField": {
"label": "Символ валюты",
"placeholder": "$, €, £…",
"description": "Этот символ будет использован для отображений денежных сумм."
},
"Participants": {
"title": "Участники",
"description": "Введите имя каждого участника.",
"protectedParticipant": "Этот участник — часть расходов, и поэтому не может быть удален.",
"new": "Новый участник",
"add": "Добавить участника",
"John": "Александр",
"Jane": "Михаил",
"Jack": "Иван"
},
"Settings": {
"title": "Локальные настройки",
"description": "Эти настройки хранятся на вашем устройстве и используются для подстройки интерфейса для вас.",
"ActiveUserField": {
"label": "Активный участник",
"placeholder": "Выберите участника",
"none": "Не выбран",
"description": "Этот участник будет автоматически выбран при создании нового расхода."
},
"save": "Сохранить",
"saving": "Сохранение…",
"create": "Создать",
"creating": "Создание…",
"cancel": "Отмена"
}
},
"ExpenseForm": {
"Income": {
"create": "Создать доход",
"edit": "Изменить доход",
"TitleField": {
"label": "Название доходв",
"placeholder": "Поход в ресторан",
"description": "Введите описание для этого дохода."
},
"DateField": {
"label": "Дата дохода",
"description": "Введите дату, когда этот доход был получен."
},
"categoryFieldDescription": "Выберите категорию дохода.",
"paidByField": {
"label": "Получивший",
"description": "Выберите участника, который получил этот доход."
},
"paidFor": {
"title": "Участники",
"description": "Выберите тех, между кем этот доход будет распределен."
},
"splitModeDescription": "Выберите, как доход необходимо распределить между людьми.",
"attachDescription": "Просмотр и прикрепление чеков к этому расходу."
},
"Expense": {
"create": "Создать расход",
"edit": "Изменить расход",
"TitleField": {
"label": "Название расхода",
"placeholder": "Поход в ресторан",
"description": "Введите описание для этого расхода."
},
"DateField": {
"label": "Дата расхода",
"description": "Введите дату, когда этот расход был совершен."
},
"categoryFieldDescription": "Выберите категорию расхода.",
"paidByField": {
"label": "Оплативший",
"description": "Выберите участника, который оплатил этот расход."
},
"paidFor": {
"title": "Участники",
"description": "Выберите тех, между кем этот расход будет распределен. Если этот расход — возмещение участнику (участникам), выберите только его (их)."
},
"splitModeDescription": "Выберите, как расход необходимо распределить между людьми.",
"attachDescription": "Просмотр и прикрепление чеков к этому доходу."
},
"amountField": {
"label": "Сумма"
},
"isReimbursementField": {
"label": "Этот расход является возмещением"
},
"categoryField": {
"label": "Категория"
},
"notesField": {
"label": "Заметки"
},
"selectNone": "Выбрать никого",
"selectAll": "Выбрать всех",
"shares": "доля(и)",
"advancedOptions": "Дополнительные настройки распределения…",
"SplitModeField": {
"label": "Режим разделения",
"evenly": "Равный",
"byShares": "Неравный По долям",
"byPercentage": "Неравный По процентам",
"byAmount": "Неравный По суммам",
"saveAsDefault": "Сделать режимом по умолчанию"
},
"DeletePopup": {
"label": "Удалить",
"title": "Удалить этот расход?",
"description": "Вы действительно хотите удалить этот расход? Это действие нельзя отменить.",
"yes": "Удалить",
"cancel": "Отмена"
},
"attachDocuments": "Прикрепить документы",
"create": "Создать",
"creating": "Создание…",
"save": "Сохранить",
"saving": "Сохранение…",
"cancel": "Отмена"
},
"ExpenseDocumentsInput": {
"TooBigToast": {
"title": "Файл слишком большой",
"description": "Максимальный размер файла, который можно загрузить — {maxSize}. Размер вашего файла — ${size}."
},
"ErrorToast": {
"title": "Ошибка при загрузке документа",
"description": "При загрузке документа что-то пошло не так. Пожалуйста, повторите позднее или попробуйте загрузить другой файл.",
"retry": "Повторить"
}
},
"CreateFromReceipt": {
"Dialog": {
"triggerTitle": "Создать расход из чека",
"title": "Создать из чека",
"description": "Извлечение информации о расходах из фотографии чека",
"body": "Загрузите фотографию чека, и мы попытаемся отсканировать его, чтобы извлечь информацию о расходах.",
"selectImage": "Выбрать изображение…",
"titleLabel": "Название:",
"categoryLabel": "Категория:",
"amountLabel": "Сумма:",
"dateLabel": "Дата:",
"editNext": "Вы сможете изменить эту информацию позднее.",
"continue": "Продолжить"
},
"unknown": "Неизвестно",
"TooBigToast": {
"title": "Файл слишком большой",
"description": "Максимальный размер файла, который можно загрузить — {maxSize}. Размер вашего файла — ${size}."
},
"ErrorToast": {
"title": "Ошибка при загрузке документа",
"description": "При загрузке документа что-то пошло не так. Пожалуйста, повторите позднее или попробуйте загрузить другой файл.",
"retry": "Повторить"
}
},
"Balances": {
"title": "Балансы",
"description": "Это список балансов всех участников группы. Баланс увеличивается у тех, кто оплачивает расход, и уменьшается у тех, между кем он был распределен.",
"Reimbursements": {
"title": "Предложенные возмещения",
"description": "Вот список задолженностей между участниками.",
"noImbursements": "Похоже, все в расчете 😁",
"owes": "<strong>{from}</strong> должен <strong>{to}</strong>",
"markAsPaid": "Пометить оплаченным"
}
},
"Stats": {
"title": "Статистика",
"Totals": {
"title": "Итоговые суммы",
"description": "Общая информация о расходах вашей группы.",
"groupSpendings": "Всего потрачено группой",
"groupEarnings": "Всего заработано группой",
"yourSpendings": "Всего потрачено вами",
"yourEarnings": "Всего заработано вами",
"yourShare": "Ваша суммарная доля"
}
},
"Activity": {
"title": "Активность",
"description": "Обзор действий, совершенных участниками этой группы.",
"noActivity": "История действий пуста.",
"someone": "Аноним",
"settingsModified": "Настройки группы изменены участником <strong>{participant}</strong>.",
"expenseCreated": "Расход <em>{expense}</em> создан участником <strong>{participant}</strong>.",
"expenseUpdated": "Расход <em>{expense}</em> изменен участником <strong>{participant}</strong>.",
"expenseDeleted": "Расход <em>{expense}</em> удален участником <strong>{participant}</strong>.",
"Groups": {
"today": "Сегодня",
"yesterday": "Вчера",
"earlierThisWeek": "Ранее на этой неделе",
"lastWeek": "На прошлой неделе",
"earlierThisMonth": "Ранее в этом месяце",
"lastMonth": "В прошлом месяце",
"earlierThisYear": "Ранее в этом году",
"lastYear": "В прошлом году",
"older": "Очень давно"
}
},
"Information": {
"title": "Информация",
"description": "В этом разделе вы можете добавить важную для участников информацию.",
"empty": "Информации нет."
},
"Settings": {
"title": "Настройки"
},
"Locale": {
"en-US": "English",
"fi": "Suomi",
"fr-FR": "Français",
"es": "Español",
"de-DE": "Deutsch",
"zh-CN": "Chinese (Simplified)",
"ru-RU": "Русский",
"it-IT": "Italiano"
},
"Share": {
"title": "Поделиться",
"description": "Чтобы другие участники получили доступ к этой группе и смогли добавлять расходы, отправьте им этот URL.",
"warning": "Внимание!",
"warningHelp": "Любой человек с доступом к этой ссылке сможет просматривать и редактировать расходы. Будьте осторожны!"
},
"SchemaErrors": {
"min1": "Введите как минимум один символ.",
"min2": "Введите как минимум два символа.",
"max5": "Введите максимум 5 символов.",
"max50": "Введите максимум 50 символов.",
"duplicateParticipantName": "Участник с таким именем уже существует.",
"titleRequired": "Пожалуйста, введите название.",
"invalidNumber": "Неверное число.",
"amountRequired": "Пожалуйста, введите сумму.",
"amountNotZero": "Сумма не может быть нулевой.",
"amountTenMillion": "Сумма должна быть меньше 10 000 000.",
"paidByRequired": "Пожалуйста, выберите участника.",
"paidForMin1": "За этот расход должен заплатить как минимум один участник.",
"noZeroShares": "Все доли должны быть больше 0.",
"amountSum": "Сумма расхода должна быть равна сумме значений, распределенных между участниками.",
"percentageSum": "Сумма процентов должна быть равна 100."
},
"Categories": {
"search": "Поиск категорий...",
"noCategory": "Категорий не нашлось.",
"Uncategorized": {
"heading": "Без категории",
"General": "Общее",
"Payment": "Выплата"
},
"Entertainment": {
"heading": "Развлечения",
"Entertainment": "Развлечения",
"Games": "Игры",
"Movies": "Кино",
"Music": "Музыка",
"Sports": "Спорт"
},
"Food and Drink": {
"heading": "Еда и напитки",
"Food and Drink": "Еда и напитки",
"Dining Out": "Рестораны и кафе",
"Groceries": "Продукты",
"Liquor": "Напитки"
},
"Home": {
"heading": "Дом",
"Home": "Дом",
"Electronics": "Электроника",
"Furniture": "Мебель",
"Household Supplies": "Расходные материалы",
"Maintenance": "Уборка",
"Mortgage": "Ипотека",
"Pets": "Домашние животные",
"Rent": "Аренда",
"Services": "Коммунальные расходы"
},
"Life": {
"heading": "Жизнь",
"Childcare": "Дети",
"Clothing": "Одежда",
"Education": "Образование",
"Gifts": "Подарки",
"Insurance": "Страховки",
"Medical Expenses": "Медицина",
"Taxes": "Налоги"
},
"Transportation": {
"heading": "Транспорт",
"Transportation": "Транспорт",
"Bicycle": "Велосипед",
"Bus/Train": "Автобусы и поезда",
"Car": "Авто",
"Gas/Fuel": "Топливо",
"Hotel": "Отели",
"Parking": "Парковка",
"Plane": "Самолеты",
"Taxi": "Такси"
},
"Utilities": {
"heading": "Коммунальные расходы",
"Utilities": "Коммунальные расходы",
"Cleaning": "Клининг",
"Electricity": "Электричество",
"Heat/Gas": "Отопление/Газ",
"Trash": "Утилизация отходов",
"TV/Phone/Internet": "ТВ/Телефон/Интернет",
"Water": "Вода"
}
}
}

397
messages/zh-CN.json Normal file
View File

@@ -0,0 +1,397 @@
{
"Homepage": {
"title": "与<strong>朋友和家人</strong>共享<strong>开支</strong>",
"description": "欢迎使用你的全新<strong>Spliit</strong>实例!",
"button": {
"groups": "前往群组",
"github": "GitHub"
}
},
"Header": {
"groups": "群组"
},
"Footer": {
"madeIn": "Made in Montréal, Québec 🇨🇦",
"builtBy": "由 <author>Sebastien Castiel</author> 以及 <source>社区贡献者们</source> 共同构建"
},
"Expenses": {
"title": "消费",
"description": "这里有你为你的群组创建的消费。",
"create": "创建消费",
"createFirst": "创建首个消费",
"noExpenses": "你的群组内目前没有任何消费。",
"exportJson": "导出到JSON",
"searchPlaceholder": "查找消费……",
"ActiveUserModal": {
"title": "你是哪位?",
"description": "告诉我们你在群组中的身份,以便定制你的信息呈现方式。",
"nobody": "我不想选择任何人",
"save": "保存变更",
"footer": "此项设定之后可以在群组设定中修改。"
},
"Groups": {
"upcoming": "即将到来",
"thisWeek": "本周",
"earlierThisMonth": "本月早些时候",
"lastMonth": "上个月",
"earlierThisYear": "本年早些时候",
"lastYera": "去年",
"older": "更早"
}
},
"ExpenseCard": {
"paidBy": "<strong>{paidBy}</strong> 为 <paidFor></paidFor> 支付。",
"receivedBy": "<strong>{paidBy}</strong> 为 <paidFor></paidFor> 接收。",
"yourBalance": "你的余额:"
},
"Groups": {
"myGroups": "我的群组",
"create": "创建",
"loadingRecent": "加载最近的群组……",
"NoRecent": {
"description": "你最近没有访问任何群组。",
"create": "创建一个群组",
"orAsk": "或者让你的朋友发给你现有群组的链接。"
},
"recent": "最近的群组",
"starred": "已收藏的群组",
"archived": "已归档的群组",
"archive": "归档群组",
"unarchive": "取消归档群组",
"removeRecent": "从最近的群组中删除",
"RecentRemovedToast": {
"title": "群组已删除",
"description": "群组已从你的最近群组列表中删除。",
"undoAlt": "撤销群组删除",
"undo": "撤销"
},
"AddByURL": {
"button": "使用URL添加",
"title": "使用URL添加一个群组",
"description": "如果你被分享了一个群组你可以将群组的URL粘贴到这里以添加这个群组。",
"error": "哎呀我们没办法根据你的URL找到相应的群组……"
},
"NotFound": {
"text": "该群组不存在。",
"link": "跳转到最近访问过的群组"
}
},
"GroupForm": {
"title": "群组信息",
"NameField": {
"label": "群组名",
"placeholder": "暑假",
"description": "为你的群组输入一个名字。"
},
"InformationField": {
"label": "群组信息",
"placeholder": "哪些信息与群组成员有关?"
},
"CurrencyField": {
"label": "货币标志",
"placeholder": "$, €, £…",
"description": "我们根据这个显示相应的货币金额。"
},
"Participants": {
"title": "群组成员",
"description": "输入每位成员的名字。",
"protectedParticipant": "群组成员是消费的一部分,不可删除。",
"new": "新建",
"add": "添加群组成员",
"John": "John",
"Jane": "Jane",
"Jack": "Jack"
},
"Settings": {
"title": "本地设定",
"description": "这些设定是按设备设定的,用于定制你的使用体验。",
"ActiveUserField": {
"label": "当前用户",
"placeholder": "选择一个群组成员",
"none": "无",
"description": "用于支付消费的默认用户。"
},
"save": "保存",
"saving": "保存中……",
"create": "创建",
"creating": "创建中",
"cancel": "取消"
}
},
"ExpenseForm": {
"Income": {
"create": "创建收入",
"edit": "编辑收入",
"TitleField": {
"label": "收入标题",
"placeholder": "周一晚上的餐厅",
"description": "描述这个收入。"
},
"DateField": {
"label": "收入日期",
"description": "输入收到这笔收入的日期。"
},
"categoryFieldDescription": "选择收入类别。",
"paidByField": {
"label": "接收到",
"description": "选择接收到这笔收入的群组成员。"
},
"paidFor": {
"title": "接收给",
"description": "选择收入是为谁而收。"
},
"splitModeDescription": "选择如何划分这笔收入。",
"attachDescription": "查看并为这笔收入附加收据。"
},
"Expense": {
"create": "创建消费",
"edit": "编辑消费",
"TitleField": {
"label": "消费标题",
"placeholder": "周一晚上的餐厅",
"description": "描述这个消费。"
},
"DateField": {
"label": "消费日期",
"description": "输入支付这笔消费的日期。"
},
"categoryFieldDescription": "选择消费类别。",
"paidByField": {
"label": "支付自",
"description": "选择支付这笔消费的群组成员。"
},
"paidFor": {
"title": "支付给",
"description": "选择消费是为谁而支出。"
},
"splitModeDescription": "选择如何划分这笔消费。",
"attachDescription": "查看并为这笔消费附加收据。"
},
"amountField": {
"label": "金额"
},
"isReimbursementField": {
"label": "这是一笔报销款"
},
"categoryField": {
"label": "类别"
},
"notesField": {
"label": "附注"
},
"selectNone": "取消选中",
"selectAll": "全选",
"shares": "份额",
"advancedOptions": "高级分账选项……",
"SplitModeField": {
"label": "分账模式",
"evenly": "平均分配",
"byShares": "按份额分配",
"byPercentage": "按百分比分配",
"byAmount": "按金额分配",
"saveAsDefault": "保存为默认分账设置"
},
"DeletePopup": {
"label": "删除",
"title": "要删除这项消费吗?",
"description": "你真的确定要删除这项消费吗?此行动不可撤销。",
"yes": "确定",
"cancel": "取消"
},
"attachDocuments": "附加文档",
"create": "创建",
"creating": "创建中……",
"save": "保存",
"saving": "保存中……",
"cancel": "取消"
},
"ExpenseDocumentsInput": {
"TooBigToast": {
"title": "文件过大",
"description": "可上传的最大文件大小为{maxSize},你的文件为${size}。"
},
"ErrorToast": {
"title": "上传文档时发生错误",
"description": "上传文档时发生了一些错误。请稍后重试或更换文件。",
"retry": "重试"
}
},
"CreateFromReceipt": {
"Dialog": {
"triggerTitle": "从收据中创建消费",
"title": "从收据中创建",
"description": "从收据照片上提取消费信息。",
"body": "上传收据的图片,我们会尽可能地从中扫描出消费信息。",
"selectImage": "选择图片……",
"titleLabel": "标题:",
"categoryLabel": "类别:",
"amountLabel": "金额:",
"dateLabel": "日期:",
"editNext": "你之后可以修改消费的信息。",
"continue": "继续"
},
"unknown": "未知",
"TooBigToast": {
"title": "文件过大",
"description": "可上传的最大文件大小为{maxSize},你的文件为${size}。"
},
"ErrorToast": {
"title": "上传文档时发生错误",
"description": "上传文档时发生了一些错误。请稍后重试或更换文件。",
"retry": "重试"
}
},
"Balances": {
"title": "余额",
"description": "这是每位群组成员支付或被支付的金额。",
"Reimbursements": {
"title": "建议报销",
"description": "这里是优化群组成员之间报销的建议。",
"noImbursements": "看起来你的群组不需要任何报销😁",
"owes": "<strong>{from}</strong> 欠 <strong>{to}</strong>",
"markAsPaid": "标记为已支付"
}
},
"Stats": {
"title": "统计",
"Totals": {
"title": "总计",
"description": "整个群组的花费合计。",
"groupSpendings": "群组总计开销",
"groupEarnings": "群组总计收入",
"yourSpendings": "你的总计开销",
"yourEarnings": "你的总计收入",
"yourShare": "你的总计份额"
}
},
"Activity": {
"title": "活动",
"description": "该群组所有活动总览",
"noActivity": "你的群组目前没有任何活动。",
"someone": "某人",
"settingsModified": "群组设定已被<strong>{participant}</strong>更改。",
"expenseCreated": "消费 <em>{expense}</em> 由 <strong>{participant}</strong> 创建。",
"expenseUpdated": "消费 <em>{expense}</em> 由 <strong>{participant}</strong> 更新。",
"expenseDeleted": "消费 <em>{expense}</em> 由 <strong>{participant}</strong> 删除。",
"Groups": {
"today": "今天",
"yesterday": "昨天",
"earlierThisWeek": "这周早些时候",
"lastWeek": "上周",
"earlierThisMonth": "这月早些时候",
"lastMonth": "上月",
"earlierThisYear": "这年早些时候",
"lastYear": "上年",
"older": "更早"
}
},
"Information": {
"title": "信息",
"description": "使用此处以添加与群组成员相关的任何信息。",
"empty": "当前没有群组信息。"
},
"Settings": {
"title": "设定"
},
"Locale": {
"en-US": "English",
"fi": "Suomi",
"fr-FR": "Français",
"es": "Español",
"de-DE": "Deutsch",
"zh-CN": "Chinese (Simplified)",
"ru-RU": "Русский",
"it-IT": "Italiano"
},
"Share": {
"title": "分享",
"description": "请将此URL分享给其他群组成员以使其可以查看群组并添加消费。",
"warning": "警告!",
"warningHelp": "任何持有群组URL的个体都有能够查看并编辑消费。请谨慎分享"
},
"SchemaErrors": {
"min1": "输入至少1个字符。",
"min2": "输入至少2个字符。",
"max5": "输入至少5个字符。",
"max50": "输入至少50个字符。",
"duplicateParticipantName": "此名字已被另一位群组成员占用。",
"titleRequired": "请输入标题。",
"invalidNumber": "无效数值。",
"amountRequired": "你必须输入一个金额。",
"amountNotZero": "金额不可以为0。",
"amountTenMillion": "金额必须小于10,000,000。",
"paidByRequired": "你必须选择一个群组成员。",
"paidForMin1": "这项消费必须支付给至少1名群组成员。",
"noZeroShares": "所有份额必须大于0。",
"amountSum": "金额之和必须等于消费的金额。",
"percentageSum": "百分比之和必须等于100。"
},
"Categories": {
"search": "搜寻类别……",
"noCategory": "未找到类别。",
"Uncategorized": {
"heading": "未分类",
"General": "一般",
"Payment": "支付"
},
"Entertainment": {
"heading": "娱乐",
"Entertainment": "娱乐",
"Games": "游戏",
"Movies": "电影",
"Music": "音乐",
"Sports": "运动"
},
"Food and Drink": {
"heading": "饮食",
"Food and Drink": "饮食",
"Dining Out": "下馆子",
"Groceries": "便利店",
"Liquor": "酒水"
},
"Home": {
"heading": "居家",
"Home": "居家",
"Electronics": "电费",
"Furniture": "家具",
"Household Supplies": "家庭日用品",
"Maintenance": "维护",
"Mortgage": "贷款",
"Pets": "宠物",
"Rent": "租金",
"Services": "服务"
},
"Life": {
"heading": "生活",
"Childcare": "儿童保育",
"Clothing": "衣物",
"Education": "教育",
"Gifts": "礼物",
"Insurance": "保险",
"Medical Expenses": "医疗支出",
"Taxes": "税"
},
"Transportation": {
"heading": "交通",
"Transportation": "交通",
"Bicycle": "自行车",
"Bus/Train": "巴士/列车",
"Car": "汽车",
"Gas/Fuel": "燃料",
"Hotel": "旅馆",
"Parking": "停车",
"Plane": "飞机",
"Taxi": "出租车"
},
"Utilities": {
"heading": "日常账单",
"Utilities": "日常账单",
"Cleaning": "清洁费",
"Electricity": "电费",
"Heat/Gas": "暖气/瓦斯",
"Trash": "垃圾",
"TV/Phone/Internet": "电视/手机/互联网",
"Water": "水"
}
}
}

View File

@@ -1,4 +1,8 @@
/** import createNextIntlPlugin from 'next-intl/plugin'
const withNextIntl = createNextIntlPlugin()
/**
* Undefined entries are not supported. Push optional patterns to this array only if defined. * Undefined entries are not supported. Push optional patterns to this array only if defined.
* @type {import('next/dist/shared/lib/image-config').RemotePattern} * @type {import('next/dist/shared/lib/image-config').RemotePattern}
*/ */
@@ -23,6 +27,12 @@ const nextConfig = {
images: { images: {
remotePatterns remotePatterns
}, },
// Required to run in a codespace (see https://github.com/vercel/next.js/issues/58019)
experimental: {
serverActions: {
allowedOrigins: ['localhost:3000'],
},
},
} }
module.exports = nextConfig export default withNextIntl(nextConfig)

10388
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,9 +12,11 @@
"prettier": "prettier -w src", "prettier": "prettier -w src",
"postinstall": "prisma migrate deploy && prisma generate", "postinstall": "prisma migrate deploy && prisma generate",
"build-image": "./scripts/build-image.sh", "build-image": "./scripts/build-image.sh",
"start-container": "docker compose --env-file container.env up" "start-container": "docker compose --env-file container.env up",
"test": "jest"
}, },
"dependencies": { "dependencies": {
"@formatjs/intl-localematcher": "^0.5.4",
"@hookform/resolvers": "^3.3.2", "@hookform/resolvers": "^3.3.2",
"@prisma/client": "^5.6.0", "@prisma/client": "^5.6.0",
"@radix-ui/react-checkbox": "^1.0.4", "@radix-ui/react-checkbox": "^1.0.4",
@@ -39,27 +41,35 @@
"embla-carousel-react": "^8.0.0-rc21", "embla-carousel-react": "^8.0.0-rc21",
"lucide-react": "^0.290.0", "lucide-react": "^0.290.0",
"nanoid": "^5.0.4", "nanoid": "^5.0.4",
"next": "^14.1.0", "negotiator": "^0.6.3",
"next": "^14.2.5",
"next-intl": "^3.17.2",
"next-s3-upload": "^0.3.4", "next-s3-upload": "^0.3.4",
"next-themes": "^0.2.1", "next-themes": "^0.2.1",
"next13-progressbar": "^1.1.1", "next13-progressbar": "^1.1.1",
"openai": "^4.25.0", "openai": "^4.25.0",
"pg": "^8.11.3", "pg": "^8.11.3",
"react": "^18.2.0", "prisma": "^5.7.0",
"react-dom": "^18.2.0", "react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.47.0", "react-hook-form": "^7.47.0",
"react-intersection-observer": "^9.8.0",
"sharp": "^0.33.2", "sharp": "^0.33.2",
"tailwind-merge": "^1.14.0", "tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"ts-pattern": "^5.0.6", "ts-pattern": "^5.0.6",
"uuid": "^9.0.1", "uuid": "^9.0.1",
"vaul": "^0.8.0", "vaul": "^0.8.0",
"zod": "^3.22.4", "zod": "^3.22.4"
"prisma": "^5.7.0"
}, },
"devDependencies": { "devDependencies": {
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^16.0.0",
"@total-typescript/ts-reset": "^0.5.1", "@total-typescript/ts-reset": "^0.5.1",
"@types/content-disposition": "^0.5.8", "@types/content-disposition": "^0.5.8",
"@types/jest": "^29.5.12",
"@types/negotiator": "^0.6.3",
"@types/node": "^20", "@types/node": "^20",
"@types/pg": "^8.10.9", "@types/pg": "^8.10.9",
"@types/react": "^18.2.48", "@types/react": "^18.2.48",
@@ -69,10 +79,13 @@
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"eslint": "^8", "eslint": "^8",
"eslint-config-next": "^14.1.0", "eslint-config-next": "^14.1.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"postcss": "^8", "postcss": "^8",
"prettier": "^3.0.3", "prettier": "^3.0.3",
"prettier-plugin-organize-imports": "^3.2.3", "prettier-plugin-organize-imports": "^3.2.3",
"tailwindcss": "^3", "tailwindcss": "^3",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0", "tsconfig-paths": "^4.2.0",
"typescript": "^5.3.3" "typescript": "^5.3.3"
} }

View File

@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Expense" ADD COLUMN "notes" TEXT;

View File

@@ -0,0 +1,18 @@
-- CreateEnum
CREATE TYPE "ActivityType" AS ENUM ('UPDATE_GROUP', 'CREATE_EXPENSE', 'UPDATE_EXPENSE', 'DELETE_EXPENSE');
-- CreateTable
CREATE TABLE "Activity" (
"id" TEXT NOT NULL,
"groupId" TEXT NOT NULL,
"time" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"activityType" "ActivityType" NOT NULL,
"participantId" TEXT,
"expenseId" TEXT,
"data" TEXT,
CONSTRAINT "Activity_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "Group"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Group" ADD COLUMN "information" TEXT;

View File

@@ -14,9 +14,11 @@ datasource db {
model Group { model Group {
id String @id id String @id
name String name String
information String? @db.Text
currency String @default("$") currency String @default("$")
participants Participant[] participants Participant[]
expenses Expense[] expenses Expense[]
activities Activity[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
} }
@@ -52,6 +54,7 @@ model Expense {
splitMode SplitMode @default(EVENLY) splitMode SplitMode @default(EVENLY)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
documents ExpenseDocument[] documents ExpenseDocument[]
notes String?
} }
model ExpenseDocument { model ExpenseDocument {
@@ -79,3 +82,21 @@ model ExpensePaidFor {
@@id([expenseId, participantId]) @@id([expenseId, participantId])
} }
model Activity {
id String @id
group Group @relation(fields: [groupId], references: [id])
groupId String
time DateTime @default(now())
activityType ActivityType
participantId String?
expenseId String?
data String?
}
enum ActivityType {
UPDATE_GROUP
CREATE_EXPENSE
UPDATE_EXPENSE
DELETE_EXPENSE
}

View File

@@ -1,4 +1,4 @@
result=$(docker ps | grep postgres) result=$(docker ps | grep spliit-db)
if [ $? -eq 0 ]; if [ $? -eq 0 ];
then then
echo "postgres is already running, doing nothing" echo "postgres is already running, doing nothing"
@@ -6,6 +6,6 @@ else
echo "postgres is not running, starting it" echo "postgres is not running, starting it"
docker rm postgres --force docker rm postgres --force
mkdir -p postgres-data mkdir -p postgres-data
docker run --name postgres -d -p 5432:5432 -e POSTGRES_PASSWORD=1234 -v ./postgres-data:/var/lib/postgresql/data postgres docker run --name spliit-db -d -p 5432:5432 -e POSTGRES_PASSWORD=1234 -v "/$(pwd)/postgres-data:/var/lib/postgresql/data" postgres
sleep 5 # Wait for postgres to start sleep 5 # Wait for postgres to start
fi fi

View File

@@ -0,0 +1,95 @@
'use client'
import { Button } from '@/components/ui/button'
import { getGroupExpenses } from '@/lib/api'
import { DateTimeStyle, cn, formatDate } from '@/lib/utils'
import { Activity, ActivityType, Participant } from '@prisma/client'
import { ChevronRight } from 'lucide-react'
import { useLocale, useTranslations } from 'next-intl'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
type Props = {
groupId: string
activity: Activity
participant?: Participant
expense?: Awaited<ReturnType<typeof getGroupExpenses>>[number]
dateStyle: DateTimeStyle
}
function useSummary(activity: Activity, participantName?: string) {
const t = useTranslations('Activity')
const participant = participantName ?? t('someone')
const expense = activity.data ?? ''
const tr = (key: string) =>
t.rich(key, {
expense,
participant,
em: (chunks) => <em>&ldquo;{chunks}&rdquo;</em>,
strong: (chunks) => <strong>{chunks}</strong>,
})
if (activity.activityType == ActivityType.UPDATE_GROUP) {
return <>{tr('settingsModified')}</>
} else if (activity.activityType == ActivityType.CREATE_EXPENSE) {
return <>{tr('expenseCreated')}</>
} else if (activity.activityType == ActivityType.UPDATE_EXPENSE) {
return <>{tr('expenseUpdated')}</>
} else if (activity.activityType == ActivityType.DELETE_EXPENSE) {
return <>{tr('expenseDeleted')}</>
}
}
export function ActivityItem({
groupId,
activity,
participant,
expense,
dateStyle,
}: Props) {
const router = useRouter()
const locale = useLocale()
const expenseExists = expense !== undefined
const summary = useSummary(activity, participant?.name)
return (
<div
className={cn(
'flex justify-between sm:rounded-lg px-2 sm:pr-1 sm:pl-2 py-2 text-sm hover:bg-accent gap-1 items-stretch',
expenseExists && 'cursor-pointer',
)}
onClick={() => {
if (expenseExists) {
router.push(`/groups/${groupId}/expenses/${activity.expenseId}/edit`)
}
}}
>
<div className="flex flex-col justify-between items-start">
{dateStyle !== undefined && (
<div className="mt-1 text-xs/5 text-muted-foreground">
{formatDate(activity.time, locale, { dateStyle })}
</div>
)}
<div className="my-1 text-xs/5 text-muted-foreground">
{formatDate(activity.time, locale, { timeStyle: 'short' })}
</div>
</div>
<div className="flex-1">
<div className="m-1">{summary}</div>
</div>
{expenseExists && (
<Button
size="icon"
variant="link"
className="self-center hidden sm:flex w-5 h-5"
asChild
>
<Link href={`/groups/${groupId}/expenses/${activity.expenseId}/edit`}>
<ChevronRight className="w-4 h-4" />
</Link>
</Button>
)}
</div>
)
}

View File

@@ -0,0 +1,112 @@
import { ActivityItem } from '@/app/groups/[groupId]/activity/activity-item'
import { getGroupExpenses } from '@/lib/api'
import { Activity, Participant } from '@prisma/client'
import dayjs, { type Dayjs } from 'dayjs'
import { useTranslations } from 'next-intl'
type Props = {
groupId: string
participants: Participant[]
expenses: Awaited<ReturnType<typeof getGroupExpenses>>
activities: Activity[]
}
const DATE_GROUPS = {
TODAY: 'today',
YESTERDAY: 'yesterday',
EARLIER_THIS_WEEK: 'earlierThisWeek',
LAST_WEEK: 'lastWeek',
EARLIER_THIS_MONTH: 'earlierThisMonth',
LAST_MONTH: 'lastMonth',
EARLIER_THIS_YEAR: 'earlierThisYear',
LAST_YEAR: 'lastYear',
OLDER: 'older',
}
function getDateGroup(date: Dayjs, today: Dayjs) {
if (today.isSame(date, 'day')) {
return DATE_GROUPS.TODAY
} else if (today.subtract(1, 'day').isSame(date, 'day')) {
return DATE_GROUPS.YESTERDAY
} else if (today.isSame(date, 'week')) {
return DATE_GROUPS.EARLIER_THIS_WEEK
} else if (today.subtract(1, 'week').isSame(date, 'week')) {
return DATE_GROUPS.LAST_WEEK
} else if (today.isSame(date, 'month')) {
return DATE_GROUPS.EARLIER_THIS_MONTH
} else if (today.subtract(1, 'month').isSame(date, 'month')) {
return DATE_GROUPS.LAST_MONTH
} else if (today.isSame(date, 'year')) {
return DATE_GROUPS.EARLIER_THIS_YEAR
} else if (today.subtract(1, 'year').isSame(date, 'year')) {
return DATE_GROUPS.LAST_YEAR
} else {
return DATE_GROUPS.OLDER
}
}
function getGroupedActivitiesByDate(activities: Activity[]) {
const today = dayjs()
return activities.reduce(
(result: { [key: string]: Activity[] }, activity: Activity) => {
const activityGroup = getDateGroup(dayjs(activity.time), today)
result[activityGroup] = result[activityGroup] ?? []
result[activityGroup].push(activity)
return result
},
{},
)
}
export function ActivityList({
groupId,
participants,
expenses,
activities,
}: Props) {
const t = useTranslations('Activity')
const groupedActivitiesByDate = getGroupedActivitiesByDate(activities)
return activities.length > 0 ? (
<>
{Object.values(DATE_GROUPS).map((dateGroup: string) => {
let groupActivities = groupedActivitiesByDate[dateGroup]
if (!groupActivities || groupActivities.length === 0) return null
const dateStyle =
dateGroup == DATE_GROUPS.TODAY || dateGroup == DATE_GROUPS.YESTERDAY
? undefined
: 'medium'
return (
<div key={dateGroup}>
<div
className={
'text-muted-foreground text-xs py-1 font-semibold sticky top-16 bg-white dark:bg-[#1b1917]'
}
>
{t(`Groups.${dateGroup}`)}
</div>
{groupActivities.map((activity: Activity) => {
const participant =
activity.participantId !== null
? participants.find((p) => p.id === activity.participantId)
: undefined
const expense =
activity.expenseId !== null
? expenses.find((e) => e.id === activity.expenseId)
: undefined
return (
<ActivityItem
key={activity.id}
{...{ groupId, activity, participant, expense, dateStyle }}
/>
)
})}
</div>
)
})}
</>
) : (
<p className="px-6 text-sm py-6">{t('noActivity')}</p>
)
}

View File

@@ -0,0 +1,51 @@
import { cached } from '@/app/cached-functions'
import { ActivityList } from '@/app/groups/[groupId]/activity/activity-list'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import { getActivities, getGroupExpenses } from '@/lib/api'
import { Metadata } from 'next'
import { getTranslations } from 'next-intl/server'
import { notFound } from 'next/navigation'
export const metadata: Metadata = {
title: 'Activity',
}
export default async function ActivityPage({
params: { groupId },
}: {
params: { groupId: string }
}) {
const t = await getTranslations('Activity')
const group = await cached.getGroup(groupId)
if (!group) notFound()
const expenses = await getGroupExpenses(groupId)
const activities = await getActivities(groupId)
return (
<>
<Card className="mb-4">
<CardHeader>
<CardTitle>{t('title')}</CardTitle>
<CardDescription>{t('description')}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col space-y-4">
<ActivityList
{...{
groupId,
participants: group.participants,
expenses,
activities,
}}
/>
</CardContent>
</Card>
</>
)
}

View File

@@ -1,6 +1,7 @@
import { Balances } from '@/lib/balances' import { Balances } from '@/lib/balances'
import { cn, formatCurrency } from '@/lib/utils' import { cn, formatCurrency } from '@/lib/utils'
import { Participant } from '@prisma/client' import { Participant } from '@prisma/client'
import { useLocale } from 'next-intl'
type Props = { type Props = {
balances: Balances balances: Balances
@@ -9,6 +10,7 @@ type Props = {
} }
export function BalancesList({ balances, participants, currency }: Props) { export function BalancesList({ balances, participants, currency }: Props) {
const locale = useLocale()
const maxBalance = Math.max( const maxBalance = Math.max(
...Object.values(balances).map((b) => Math.abs(b.total)), ...Object.values(balances).map((b) => Math.abs(b.total)),
) )
@@ -28,7 +30,7 @@ export function BalancesList({ balances, participants, currency }: Props) {
</div> </div>
<div className={cn('w-1/2 relative', isLeft || 'text-right')}> <div className={cn('w-1/2 relative', isLeft || 'text-right')}>
<div className="absolute inset-0 p-2 z-20"> <div className="absolute inset-0 p-2 z-20">
{formatCurrency(currency, balance)} {formatCurrency(currency, balance, locale)}
</div> </div>
{balance !== 0 && ( {balance !== 0 && (
<div <div

View File

@@ -15,6 +15,7 @@ import {
getSuggestedReimbursements, getSuggestedReimbursements,
} from '@/lib/balances' } from '@/lib/balances'
import { Metadata } from 'next' import { Metadata } from 'next'
import { getTranslations } from 'next-intl/server'
import { notFound } from 'next/navigation' import { notFound } from 'next/navigation'
export const metadata: Metadata = { export const metadata: Metadata = {
@@ -26,6 +27,7 @@ export default async function GroupPage({
}: { }: {
params: { groupId: string } params: { groupId: string }
}) { }) {
const t = await getTranslations('Balances')
const group = await cached.getGroup(groupId) const group = await cached.getGroup(groupId)
if (!group) notFound() if (!group) notFound()
@@ -38,10 +40,8 @@ export default async function GroupPage({
<> <>
<Card className="mb-4"> <Card className="mb-4">
<CardHeader> <CardHeader>
<CardTitle>Balances</CardTitle> <CardTitle>{t('title')}</CardTitle>
<CardDescription> <CardDescription>{t('description')}</CardDescription>
This is the amount that each participant paid or was paid for.
</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<BalancesList <BalancesList
@@ -53,11 +53,8 @@ export default async function GroupPage({
</Card> </Card>
<Card className="mb-4"> <Card className="mb-4">
<CardHeader> <CardHeader>
<CardTitle>Suggested reimbursements</CardTitle> <CardTitle>{t('Reimbursements.title')}</CardTitle>
<CardDescription> <CardDescription>{t('Reimbursements.description')}</CardDescription>
Here are suggestions for optimized reimbursements between
participants.
</CardDescription>
</CardHeader> </CardHeader>
<CardContent className="p-0"> <CardContent className="p-0">
<ReimbursementList <ReimbursementList

View File

@@ -17,10 +17,10 @@ export default async function EditGroupPage({
const group = await cached.getGroup(groupId) const group = await cached.getGroup(groupId)
if (!group) notFound() if (!group) notFound()
async function updateGroupAction(values: unknown) { async function updateGroupAction(values: unknown, participantId?: string) {
'use server' 'use server'
const groupFormValues = groupFormSchema.parse(values) const groupFormValues = groupFormSchema.parse(values)
const group = await updateGroup(groupId, groupFormValues) const group = await updateGroup(groupId, groupFormValues, participantId)
redirect(`/groups/${group.id}`) redirect(`/groups/${group.id}`)
} }

View File

@@ -27,16 +27,16 @@ export default async function EditExpensePage({
const expense = await getExpense(groupId, expenseId) const expense = await getExpense(groupId, expenseId)
if (!expense) notFound() if (!expense) notFound()
async function updateExpenseAction(values: unknown) { async function updateExpenseAction(values: unknown, participantId?: string) {
'use server' 'use server'
const expenseFormValues = expenseFormSchema.parse(values) const expenseFormValues = expenseFormSchema.parse(values)
await updateExpense(groupId, expenseId, expenseFormValues) await updateExpense(groupId, expenseId, expenseFormValues, participantId)
redirect(`/groups/${groupId}`) redirect(`/groups/${groupId}`)
} }
async function deleteExpenseAction() { async function deleteExpenseAction(participantId?: string) {
'use server' 'use server'
await deleteExpense(expenseId) await deleteExpense(groupId, expenseId, participantId)
redirect(`/groups/${groupId}`) redirect(`/groups/${groupId}`)
} }

View File

@@ -0,0 +1,45 @@
'use client'
import { Money } from '@/components/money'
import { getBalances } from '@/lib/balances'
import { useActiveUser } from '@/lib/hooks'
import { useTranslations } from 'next-intl'
type Props = {
groupId: string
currency: string
expense: Parameters<typeof getBalances>[0][number]
}
export function ActiveUserBalance({ groupId, currency, expense }: Props) {
const t = useTranslations('ExpenseCard')
const activeUserId = useActiveUser(groupId)
if (activeUserId === null || activeUserId === '' || activeUserId === 'None') {
return null
}
const balances = getBalances([expense])
let fmtBalance = <>You are not involved</>
if (Object.hasOwn(balances, activeUserId)) {
const balance = balances[activeUserId]
let balanceDetail = <></>
if (balance.paid > 0 && balance.paidFor > 0) {
balanceDetail = (
<>
{' ('}
<Money {...{ currency, amount: balance.paid }} />
{' - '}
<Money {...{ currency, amount: balance.paidFor }} />
{')'}
</>
)
}
fmtBalance = (
<>
{t('yourBalance')}{' '}
<Money {...{ currency, amount: balance.total }} bold colored />
{balanceDetail}
</>
)
}
return <div className="text-xs text-muted-foreground">{fmtBalance}</div>
}

View File

@@ -12,7 +12,6 @@ import {
import { import {
Drawer, Drawer,
DrawerContent, DrawerContent,
DrawerDescription,
DrawerFooter, DrawerFooter,
DrawerHeader, DrawerHeader,
DrawerTitle, DrawerTitle,
@@ -22,6 +21,7 @@ import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { getGroup } from '@/lib/api' import { getGroup } from '@/lib/api'
import { useMediaQuery } from '@/lib/hooks' import { useMediaQuery } from '@/lib/hooks'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { useTranslations } from 'next-intl'
import { ComponentProps, useEffect, useState } from 'react' import { ComponentProps, useEffect, useState } from 'react'
type Props = { type Props = {
@@ -29,6 +29,7 @@ type Props = {
} }
export function ActiveUserModal({ group }: Props) { export function ActiveUserModal({ group }: Props) {
const t = useTranslations('Expenses.ActiveUserModal')
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const isDesktop = useMediaQuery('(min-width: 768px)') const isDesktop = useMediaQuery('(min-width: 768px)')
@@ -52,16 +53,13 @@ export function ActiveUserModal({ group }: Props) {
<Dialog open={open} onOpenChange={updateOpen}> <Dialog open={open} onOpenChange={updateOpen}>
<DialogContent className="sm:max-w-[425px]"> <DialogContent className="sm:max-w-[425px]">
<DialogHeader> <DialogHeader>
<DialogTitle>Who are you?</DialogTitle> <DialogTitle>{t('title')}</DialogTitle>
<DialogDescription> <DialogDescription>{t('description')}</DialogDescription>
Tell us which participant you are to let us customize how the
information is displayed.
</DialogDescription>
</DialogHeader> </DialogHeader>
<ActiveUserForm group={group} close={() => setOpen(false)} /> <ActiveUserForm group={group} close={() => setOpen(false)} />
<DialogFooter className="sm:justify-center"> <DialogFooter className="sm:justify-center">
<p className="text-sm text-center text-muted-foreground"> <p className="text-sm text-center text-muted-foreground">
This setting can be changed later in the group settings. {t('footer')}
</p> </p>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
@@ -73,11 +71,8 @@ export function ActiveUserModal({ group }: Props) {
<Drawer open={open} onOpenChange={updateOpen}> <Drawer open={open} onOpenChange={updateOpen}>
<DrawerContent> <DrawerContent>
<DrawerHeader className="text-left"> <DrawerHeader className="text-left">
<DrawerTitle>Who are you?</DrawerTitle> <DrawerTitle>{t('title')}</DrawerTitle>
<DrawerDescription> <DialogDescription>{t('description')}</DialogDescription>
Tell us which participant you are to let us customize how the
information is displayed.
</DrawerDescription>
</DrawerHeader> </DrawerHeader>
<ActiveUserForm <ActiveUserForm
className="px-4" className="px-4"
@@ -86,7 +81,7 @@ export function ActiveUserModal({ group }: Props) {
/> />
<DrawerFooter className="pt-2"> <DrawerFooter className="pt-2">
<p className="text-sm text-center text-muted-foreground"> <p className="text-sm text-center text-muted-foreground">
This setting can be changed later in the group settings. {t('footer')}
</p> </p>
</DrawerFooter> </DrawerFooter>
</DrawerContent> </DrawerContent>
@@ -99,6 +94,7 @@ function ActiveUserForm({
close, close,
className, className,
}: ComponentProps<'form'> & { group: Props['group']; close: () => void }) { }: ComponentProps<'form'> & { group: Props['group']; close: () => void }) {
const t = useTranslations('Expenses.ActiveUserModal')
const [selected, setSelected] = useState('None') const [selected, setSelected] = useState('None')
return ( return (
@@ -115,7 +111,7 @@ function ActiveUserForm({
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<RadioGroupItem value="none" id="none" /> <RadioGroupItem value="none" id="none" />
<Label htmlFor="none" className="italic font-normal flex-1"> <Label htmlFor="none" className="italic font-normal flex-1">
I dont want to select anyone {t('nobody')}
</Label> </Label>
</div> </div>
{group.participants.map((participant) => ( {group.participants.map((participant) => (
@@ -128,7 +124,7 @@ function ActiveUserForm({
))} ))}
</div> </div>
</RadioGroup> </RadioGroup>
<Button type="submit">Save changes</Button> <Button type="submit">{t('save')}</Button>
</form> </form>
) )
} }

View File

@@ -12,7 +12,7 @@ export async function extractExpenseInformationFromImage(imageUrl: string) {
const categories = await getCategories() const categories = await getCategories()
const body: ChatCompletionCreateParamsNonStreaming = { const body: ChatCompletionCreateParamsNonStreaming = {
model: 'gpt-4-vision-preview', model: 'gpt-4-turbo',
messages: [ messages: [
{ {
role: 'user', role: 'user',

View File

@@ -26,9 +26,10 @@ import {
import { ToastAction } from '@/components/ui/toast' import { ToastAction } from '@/components/ui/toast'
import { useToast } from '@/components/ui/use-toast' import { useToast } from '@/components/ui/use-toast'
import { useMediaQuery } from '@/lib/hooks' import { useMediaQuery } from '@/lib/hooks'
import { formatCurrency, formatExpenseDate, formatFileSize } from '@/lib/utils' import { formatCurrency, formatDate, formatFileSize } from '@/lib/utils'
import { Category } from '@prisma/client' import { Category } from '@prisma/client'
import { ChevronRight, FileQuestion, Loader2, Receipt } from 'lucide-react' import { ChevronRight, FileQuestion, Loader2, Receipt } from 'lucide-react'
import { useLocale, useTranslations } from 'next-intl'
import { getImageData, usePresignedUpload } from 'next-s3-upload' import { getImageData, usePresignedUpload } from 'next-s3-upload'
import Image from 'next/image' import Image from 'next/image'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
@@ -47,6 +48,8 @@ export function CreateFromReceiptButton({
groupCurrency, groupCurrency,
categories, categories,
}: Props) { }: Props) {
const locale = useLocale()
const t = useTranslations('CreateFromReceipt')
const [pending, setPending] = useState(false) const [pending, setPending] = useState(false)
const { uploadToS3, FileInput, openFileDialog } = usePresignedUpload() const { uploadToS3, FileInput, openFileDialog } = usePresignedUpload()
const { toast } = useToast() const { toast } = useToast()
@@ -60,10 +63,11 @@ export function CreateFromReceiptButton({
const handleFileChange = async (file: File) => { const handleFileChange = async (file: File) => {
if (file.size > MAX_FILE_SIZE) { if (file.size > MAX_FILE_SIZE) {
toast({ toast({
title: 'The file is too big', title: t('TooBigToast.title'),
description: `The maximum file size you can upload is ${formatFileSize( description: t('TooBigToast.description', {
MAX_FILE_SIZE, maxSize: formatFileSize(MAX_FILE_SIZE, locale),
)}. Yours is ${formatFileSize(file.size)}.`, size: formatFileSize(file.size, locale),
}),
variant: 'destructive', variant: 'destructive',
}) })
return return
@@ -82,13 +86,15 @@ export function CreateFromReceiptButton({
} catch (err) { } catch (err) {
console.error(err) console.error(err)
toast({ toast({
title: 'Error while uploading document', title: t('ErrorToast.title'),
description: description: t('ErrorToast.description'),
'Something wrong happened when uploading the document. Please retry later or select a different file.',
variant: 'destructive', variant: 'destructive',
action: ( action: (
<ToastAction altText="Retry" onClick={() => upload()}> <ToastAction
Retry altText={t('ErrorToast.retry')}
onClick={() => upload()}
>
{t('ErrorToast.retry')}
</ToastAction> </ToastAction>
), ),
}) })
@@ -114,26 +120,23 @@ export function CreateFromReceiptButton({
<Button <Button
size="icon" size="icon"
variant="secondary" variant="secondary"
title="Create expense from receipt" title={t('Dialog.triggerTitle')}
> >
<Receipt className="w-4 h-4" /> <Receipt className="w-4 h-4" />
</Button> </Button>
} }
title={ title={
<> <>
<span>Create from receipt</span> <span>{t('Dialog.title')}</span>
<Badge className="bg-pink-700 hover:bg-pink-600 dark:bg-pink-500 dark:hover:bg-pink-600"> <Badge className="bg-pink-700 hover:bg-pink-600 dark:bg-pink-500 dark:hover:bg-pink-600">
Beta Beta
</Badge> </Badge>
</> </>
} }
description={<>Extract the expense information from a receipt photo.</>} description={<>{t('Dialog.description')}</>}
> >
<div className="prose prose-sm dark:prose-invert"> <div className="prose prose-sm dark:prose-invert">
<p> <p>{t('Dialog.body')}</p>
Upload the photo of a receipt, and well scan it to extract the
expense information if we can.
</p>
<div> <div>
<FileInput <FileInput
onChange={handleFileChange} onChange={handleFileChange}
@@ -161,16 +164,16 @@ export function CreateFromReceiptButton({
</div> </div>
) : ( ) : (
<span className="text-xs sm:text-sm text-muted-foreground"> <span className="text-xs sm:text-sm text-muted-foreground">
Select image {t('Dialog.selectImage')}
</span> </span>
)} )}
</Button> </Button>
<div className="col-span-2"> <div className="col-span-2">
<strong>Title:</strong> <strong>{t('Dialog.titleLabel')}</strong>
<div>{receiptInfo ? receiptInfo.title ?? <Unknown /> : '…'}</div> <div>{receiptInfo ? receiptInfo.title ?? <Unknown /> : '…'}</div>
</div> </div>
<div className="col-span-2"> <div className="col-span-2">
<strong>Category:</strong> <strong>{t('Dialog.categoryLabel')}</strong>
<div> <div>
{receiptInfo ? ( {receiptInfo ? (
receiptInfoCategory ? ( receiptInfoCategory ? (
@@ -194,11 +197,18 @@ export function CreateFromReceiptButton({
</div> </div>
</div> </div>
<div> <div>
<strong>Amount:</strong> <strong>{t('Dialog.amountLabel')}</strong>
<div> <div>
{receiptInfo ? ( {receiptInfo ? (
receiptInfo.amount ? ( receiptInfo.amount ? (
<>{formatCurrency(groupCurrency, receiptInfo.amount)}</> <>
{formatCurrency(
groupCurrency,
receiptInfo.amount,
locale,
true,
)}
</>
) : ( ) : (
<Unknown /> <Unknown />
) )
@@ -208,12 +218,14 @@ export function CreateFromReceiptButton({
</div> </div>
</div> </div>
<div> <div>
<strong>Date:</strong> <strong>{t('Dialog.dateLabel')}</strong>
<div> <div>
{receiptInfo ? ( {receiptInfo ? (
receiptInfo.date ? ( receiptInfo.date ? (
formatExpenseDate( formatDate(
new Date(`${receiptInfo?.date}T12:00:00.000Z`), new Date(`${receiptInfo?.date}T12:00:00.000Z`),
locale,
{ dateStyle: 'medium' },
) )
) : ( ) : (
<Unknown /> <Unknown />
@@ -225,7 +237,7 @@ export function CreateFromReceiptButton({
</div> </div>
</div> </div>
</div> </div>
<p>Youll be able to edit the expense information next.</p> <p>{t('Dialog.editNext')}</p>
<div className="text-center"> <div className="text-center">
<Button <Button
disabled={pending || !receiptInfo} disabled={pending || !receiptInfo}
@@ -244,7 +256,7 @@ export function CreateFromReceiptButton({
) )
}} }}
> >
Continue {t('Dialog.continue')}
</Button> </Button>
</div> </div>
</div> </div>
@@ -253,10 +265,11 @@ export function CreateFromReceiptButton({
} }
function Unknown() { function Unknown() {
const t = useTranslations('CreateFromReceipt')
return ( return (
<div className="flex gap-1 items-center text-muted-foreground"> <div className="flex gap-1 items-center text-muted-foreground">
<FileQuestion className="w-4 h-4" /> <FileQuestion className="w-4 h-4" />
<em>Unknown</em> <em>{t('unknown')}</em>
</div> </div>
) )
} }

View File

@@ -20,10 +20,10 @@ export default async function ExpensePage({
const group = await cached.getGroup(groupId) const group = await cached.getGroup(groupId)
if (!group) notFound() if (!group) notFound()
async function createExpenseAction(values: unknown) { async function createExpenseAction(values: unknown, participantId?: string) {
'use server' 'use server'
const expenseFormValues = expenseFormSchema.parse(values) const expenseFormValues = expenseFormSchema.parse(values)
await createExpense(expenseFormValues, groupId) await createExpense(expenseFormValues, groupId, participantId)
redirect(`/groups/${groupId}`) redirect(`/groups/${groupId}`)
} }

View File

@@ -0,0 +1,94 @@
'use client'
import { ActiveUserBalance } from '@/app/groups/[groupId]/expenses/active-user-balance'
import { CategoryIcon } from '@/app/groups/[groupId]/expenses/category-icon'
import { Button } from '@/components/ui/button'
import { getGroupExpenses } from '@/lib/api'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import { ChevronRight } from 'lucide-react'
import { useLocale, useTranslations } from 'next-intl'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Fragment } from 'react'
type Expense = Awaited<ReturnType<typeof getGroupExpenses>>[number]
function Participants({ expense }: { expense: Expense }) {
const t = useTranslations('ExpenseCard')
const key = expense.amount > 0 ? 'paidBy' : 'receivedBy'
const paidFor = expense.paidFor.map((paidFor, index) => (
<Fragment key={index}>
{index !== 0 && <>, </>}
<strong>{paidFor.participant.name}</strong>
</Fragment>
))
const participants = t.rich(key, {
strong: (chunks) => <strong>{chunks}</strong>,
paidBy: expense.paidBy.name,
paidFor: () => paidFor,
forCount: expense.paidFor.length,
})
return <>{participants}</>
}
type Props = {
expense: Expense
currency: string
groupId: string
}
export function ExpenseCard({ expense, currency, groupId }: Props) {
const router = useRouter()
const locale = useLocale()
return (
<div
key={expense.id}
className={cn(
'flex justify-between sm:mx-6 px-4 sm:rounded-lg sm:pr-2 sm:pl-4 py-4 text-sm cursor-pointer hover:bg-accent gap-1 items-stretch',
expense.isReimbursement && 'italic',
)}
onClick={() => {
router.push(`/groups/${groupId}/expenses/${expense.id}/edit`)
}}
>
<CategoryIcon
category={expense.category}
className="w-4 h-4 mr-2 mt-0.5 text-muted-foreground"
/>
<div className="flex-1">
<div className={cn('mb-1', expense.isReimbursement && 'italic')}>
{expense.title}
</div>
<div className="text-xs text-muted-foreground">
<Participants expense={expense} />
</div>
<div className="text-xs text-muted-foreground">
<ActiveUserBalance {...{ groupId, currency, expense }} />
</div>
</div>
<div className="flex flex-col justify-between items-end">
<div
className={cn(
'tabular-nums whitespace-nowrap',
expense.isReimbursement ? 'italic' : 'font-bold',
)}
>
{formatCurrency(currency, expense.amount, locale)}
</div>
<div className="text-xs text-muted-foreground">
{formatDate(expense.expenseDate, locale, { dateStyle: 'medium' })}
</div>
</div>
<Button
size="icon"
variant="link"
className="self-center hidden sm:flex"
asChild
>
<Link href={`/groups/${groupId}/expenses/${expense.id}/edit`}>
<ChevronRight className="w-4 h-4" />
</Link>
</Button>
</div>
)
}

View File

@@ -0,0 +1,16 @@
'use server'
import { getGroupExpenses } from '@/lib/api'
export async function getGroupExpensesAction(
groupId: string,
options?: { offset: number; length: number },
) {
'use server'
try {
return getGroupExpenses(groupId, options)
} catch {
return null
}
}

View File

@@ -1,31 +1,37 @@
'use client' 'use client'
import { CategoryIcon } from '@/app/groups/[groupId]/expenses/category-icon' import { ExpenseCard } from '@/app/groups/[groupId]/expenses/expense-card'
import { getGroupExpensesAction } from '@/app/groups/[groupId]/expenses/expense-list-fetch-action'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { SearchBar } from '@/components/ui/search-bar' import { SearchBar } from '@/components/ui/search-bar'
import { getGroupExpenses } from '@/lib/api' import { Skeleton } from '@/components/ui/skeleton'
import { cn, formatCurrency, formatExpenseDate } from '@/lib/utils' import { normalizeString } from '@/lib/utils'
import { Expense, Participant } from '@prisma/client' import { Participant } from '@prisma/client'
import dayjs, { type Dayjs } from 'dayjs' import dayjs, { type Dayjs } from 'dayjs'
import { ChevronRight } from 'lucide-react' import { useTranslations } from 'next-intl'
import Link from 'next/link' import Link from 'next/link'
import { useRouter } from 'next/navigation' import { useEffect, useMemo, useState } from 'react'
import { Fragment, useEffect, useState } from 'react' import { useInView } from 'react-intersection-observer'
type ExpensesType = NonNullable<
Awaited<ReturnType<typeof getGroupExpensesAction>>
>
type Props = { type Props = {
expenses: Awaited<ReturnType<typeof getGroupExpenses>> expensesFirstPage: ExpensesType
expenseCount: number
participants: Participant[] participants: Participant[]
currency: string currency: string
groupId: string groupId: string
} }
const EXPENSE_GROUPS = { const EXPENSE_GROUPS = {
UPCOMING: 'Upcoming', UPCOMING: 'upcoming',
THIS_WEEK: 'This week', THIS_WEEK: 'thisWeek',
EARLIER_THIS_MONTH: 'Earlier this month', EARLIER_THIS_MONTH: 'earlierThisMonth',
LAST_MONTH: 'Last month', LAST_MONTH: 'lastMonth',
EARLIER_THIS_YEAR: 'Earlier this year', EARLIER_THIS_YEAR: 'earlierThisYear',
LAST_YEAR: 'Last year', LAST_YEAR: 'lastYear',
OLDER: 'Older', OLDER: 'older',
} }
function getExpenseGroup(date: Dayjs, today: Dayjs) { function getExpenseGroup(date: Dayjs, today: Dayjs) {
@@ -46,28 +52,33 @@ function getExpenseGroup(date: Dayjs, today: Dayjs) {
} }
} }
function getGroupedExpensesByDate( function getGroupedExpensesByDate(expenses: ExpensesType) {
expenses: Awaited<ReturnType<typeof getGroupExpenses>>,
) {
const today = dayjs() const today = dayjs()
return expenses.reduce( return expenses.reduce((result: { [key: string]: ExpensesType }, expense) => {
(result: { [key: string]: Expense[] }, expense: Expense) => { const expenseGroup = getExpenseGroup(dayjs(expense.expenseDate), today)
const expenseGroup = getExpenseGroup(dayjs(expense.expenseDate), today) result[expenseGroup] = result[expenseGroup] ?? []
result[expenseGroup] = result[expenseGroup] ?? [] result[expenseGroup].push(expense)
result[expenseGroup].push(expense) return result
return result }, {})
},
{},
)
} }
export function ExpenseList({ export function ExpenseList({
expenses, expensesFirstPage,
expenseCount,
currency, currency,
participants, participants,
groupId, groupId,
}: Props) { }: Props) {
const firstLen = expensesFirstPage.length
const [searchText, setSearchText] = useState('') const [searchText, setSearchText] = useState('')
const [dataIndex, setDataIndex] = useState(firstLen)
const [dataLen, setDataLen] = useState(firstLen)
const [hasMoreData, setHasMoreData] = useState(expenseCount > firstLen)
const [isFetching, setIsFetching] = useState(false)
const [expenses, setExpenses] = useState(expensesFirstPage)
const { ref, inView } = useInView()
const t = useTranslations('Expenses')
useEffect(() => { useEffect(() => {
const activeUser = localStorage.getItem('newGroup-activeUser') const activeUser = localStorage.getItem('newGroup-activeUser')
const newUser = localStorage.getItem(`${groupId}-newUser`) const newUser = localStorage.getItem(`${groupId}-newUser`)
@@ -87,19 +98,54 @@ export function ExpenseList({
} }
}, [groupId, participants]) }, [groupId, participants])
const getParticipant = (id: string) => participants.find((p) => p.id === id) useEffect(() => {
const router = useRouter() const fetchNextPage = async () => {
setIsFetching(true)
const newExpenses = await getGroupExpensesAction(groupId, {
offset: dataIndex,
length: dataLen,
})
if (newExpenses !== null) {
const exp = expenses.concat(newExpenses)
setExpenses(exp)
setHasMoreData(exp.length < expenseCount)
setDataIndex(dataIndex + dataLen)
setDataLen(Math.ceil(1.5 * dataLen))
}
setTimeout(() => setIsFetching(false), 500)
}
if (inView && hasMoreData && !isFetching) fetchNextPage()
}, [
dataIndex,
dataLen,
expenseCount,
expenses,
groupId,
hasMoreData,
inView,
isFetching,
])
const groupedExpensesByDate = useMemo(
() => getGroupedExpensesByDate(expenses),
[expenses],
)
const groupedExpensesByDate = getGroupedExpensesByDate(expenses)
return expenses.length > 0 ? ( return expenses.length > 0 ? (
<> <>
<SearchBar onChange={(e) => setSearchText(e.target.value)} /> <SearchBar
onValueChange={(value) => setSearchText(normalizeString(value))}
/>
{Object.values(EXPENSE_GROUPS).map((expenseGroup: string) => { {Object.values(EXPENSE_GROUPS).map((expenseGroup: string) => {
let groupExpenses = groupedExpensesByDate[expenseGroup] let groupExpenses = groupedExpensesByDate[expenseGroup]
if (!groupExpenses) return null if (!groupExpenses) return null
groupExpenses = groupExpenses.filter(({ title }) => groupExpenses = groupExpenses.filter(({ title }) =>
title.toLowerCase().includes(searchText.toLowerCase()), normalizeString(title).includes(searchText),
) )
if (groupExpenses.length === 0) return null if (groupExpenses.length === 0) return null
@@ -111,82 +157,42 @@ export function ExpenseList({
'text-muted-foreground text-xs pl-4 sm:pl-6 py-1 font-semibold sticky top-16 bg-white dark:bg-[#1b1917]' 'text-muted-foreground text-xs pl-4 sm:pl-6 py-1 font-semibold sticky top-16 bg-white dark:bg-[#1b1917]'
} }
> >
{expenseGroup} {t(`Groups.${expenseGroup}`)}
</div> </div>
{groupExpenses.map((expense: any) => ( {groupExpenses.map((expense) => (
<div <ExpenseCard
key={expense.id} key={expense.id}
className={cn( expense={expense}
'flex justify-between sm:mx-6 px-4 sm:rounded-lg sm:pr-2 sm:pl-4 py-4 text-sm cursor-pointer hover:bg-accent gap-1 items-stretch', currency={currency}
expense.isReimbursement && 'italic', groupId={groupId}
)} />
onClick={() => {
router.push(`/groups/${groupId}/expenses/${expense.id}/edit`)
}}
>
<CategoryIcon
category={expense.category}
className="w-4 h-4 mr-2 mt-0.5 text-muted-foreground"
/>
<div className="flex-1">
<div
className={cn('mb-1', expense.isReimbursement && 'italic')}
>
{expense.title}
</div>
<div className="text-xs text-muted-foreground">
Paid by{' '}
<strong>{getParticipant(expense.paidById)?.name}</strong>{' '}
for{' '}
{expense.paidFor.map((paidFor: any, index: number) => (
<Fragment key={index}>
{index !== 0 && <>, </>}
<strong>
{
participants.find(
(p) => p.id === paidFor.participantId,
)?.name
}
</strong>
</Fragment>
))}
</div>
</div>
<div className="flex flex-col justify-between items-end">
<div
className={cn(
'tabular-nums whitespace-nowrap',
expense.isReimbursement ? 'italic' : 'font-bold',
)}
>
{formatCurrency(currency, expense.amount)}
</div>
<div className="text-xs text-muted-foreground">
{formatExpenseDate(expense.expenseDate)}
</div>
</div>
<Button
size="icon"
variant="link"
className="self-center hidden sm:flex"
asChild
>
<Link href={`/groups/${groupId}/expenses/${expense.id}/edit`}>
<ChevronRight className="w-4 h-4" />
</Link>
</Button>
</div>
))} ))}
</div> </div>
) )
})} })}
{expenses.length < expenseCount &&
[0, 1, 2].map((i) => (
<div
key={i}
className="border-t flex justify-between items-center px-6 py-4 text-sm"
ref={i === 0 ? ref : undefined}
>
<div className="flex flex-col gap-2">
<Skeleton className="h-4 w-16 rounded-full" />
<Skeleton className="h-4 w-32 rounded-full" />
</div>
<div>
<Skeleton className="h-4 w-16 rounded-full" />
</div>
</div>
))}
</> </>
) : ( ) : (
<p className="px-6 text-sm py-6"> <p className="px-6 text-sm py-6">
Your group doesnt contain any expense yet.{' '} {t('noExpenses')}{' '}
<Button variant="link" asChild className="-m-4"> <Button variant="link" asChild className="-m-4">
<Link href={`/groups/${groupId}/expenses/create`}> <Link href={`/groups/${groupId}/expenses/create`}>
Create the first one {t('createFirst')}
</Link> </Link>
</Button> </Button>
</p> </p>

View File

@@ -1,4 +1,4 @@
import { getPrisma } from '@/lib/prisma' import { prisma } from '@/lib/prisma'
import contentDisposition from 'content-disposition' import contentDisposition from 'content-disposition'
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
@@ -6,7 +6,6 @@ export async function GET(
req: Request, req: Request,
{ params: { groupId } }: { params: { groupId: string } }, { params: { groupId } }: { params: { groupId: string } },
) { ) {
const prisma = await getPrisma()
const group = await prisma.group.findUnique({ const group = await prisma.group.findUnique({
where: { id: groupId }, where: { id: groupId },
select: { select: {

View File

@@ -11,10 +11,15 @@ import {
CardTitle, CardTitle,
} from '@/components/ui/card' } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton' import { Skeleton } from '@/components/ui/skeleton'
import { getCategories, getGroupExpenses } from '@/lib/api' import {
getCategories,
getGroupExpenseCount,
getGroupExpenses,
} from '@/lib/api'
import { env } from '@/lib/env' import { env } from '@/lib/env'
import { Download, Plus } from 'lucide-react' import { Download, Plus } from 'lucide-react'
import { Metadata } from 'next' import { Metadata } from 'next'
import { getTranslations } from 'next-intl/server'
import Link from 'next/link' import Link from 'next/link'
import { notFound } from 'next/navigation' import { notFound } from 'next/navigation'
import { Suspense } from 'react' import { Suspense } from 'react'
@@ -30,6 +35,7 @@ export default async function GroupExpensesPage({
}: { }: {
params: { groupId: string } params: { groupId: string }
}) { }) {
const t = await getTranslations('Expenses')
const group = await cached.getGroup(groupId) const group = await cached.getGroup(groupId)
if (!group) notFound() if (!group) notFound()
@@ -40,10 +46,8 @@ export default async function GroupExpensesPage({
<Card className="mb-4 rounded-none -mx-4 border-x-0 sm:border-x sm:rounded-lg sm:mx-0"> <Card className="mb-4 rounded-none -mx-4 border-x-0 sm:border-x sm:rounded-lg sm:mx-0">
<div className="flex flex-1"> <div className="flex flex-1">
<CardHeader className="flex-1 p-4 sm:p-6"> <CardHeader className="flex-1 p-4 sm:p-6">
<CardTitle>Expenses</CardTitle> <CardTitle>{t('title')}</CardTitle>
<CardDescription> <CardDescription>{t('description')}</CardDescription>
Here are the expenses that you created for your group.
</CardDescription>
</CardHeader> </CardHeader>
<CardHeader className="p-4 sm:p-6 flex flex-row space-y-0 gap-2"> <CardHeader className="p-4 sm:p-6 flex flex-row space-y-0 gap-2">
<Button variant="secondary" size="icon" asChild> <Button variant="secondary" size="icon" asChild>
@@ -51,6 +55,7 @@ export default async function GroupExpensesPage({
prefetch={false} prefetch={false}
href={`/groups/${groupId}/expenses/export/json`} href={`/groups/${groupId}/expenses/export/json`}
target="_blank" target="_blank"
title={t('exportJson')}
> >
<Download className="w-4 h-4" /> <Download className="w-4 h-4" />
</Link> </Link>
@@ -63,7 +68,10 @@ export default async function GroupExpensesPage({
/> />
)} )}
<Button asChild size="icon"> <Button asChild size="icon">
<Link href={`/groups/${groupId}/expenses/create`}> <Link
href={`/groups/${groupId}/expenses/create`}
title={t('create')}
>
<Plus className="w-4 h-4" /> <Plus className="w-4 h-4" />
</Link> </Link>
</Button> </Button>
@@ -87,7 +95,7 @@ export default async function GroupExpensesPage({
</div> </div>
))} ))}
> >
<Expenses groupId={groupId} /> <Expenses group={group} />
</Suspense> </Suspense>
</CardContent> </CardContent>
</Card> </Card>
@@ -97,14 +105,22 @@ export default async function GroupExpensesPage({
) )
} }
async function Expenses({ groupId }: { groupId: string }) { type Props = {
const group = await cached.getGroup(groupId) group: NonNullable<Awaited<ReturnType<typeof cached.getGroup>>>
if (!group) notFound() }
const expenses = await getGroupExpenses(group.id)
async function Expenses({ group }: Props) {
const expenseCount = await getGroupExpenseCount(group.id)
const expenses = await getGroupExpenses(group.id, {
offset: 0,
length: 200,
})
return ( return (
<ExpenseList <ExpenseList
expenses={expenses} expensesFirstPage={expenses}
expenseCount={expenseCount}
groupId={group.id} groupId={group.id}
currency={group.currency} currency={group.currency}
participants={group.participants} participants={group.participants}

View File

@@ -1,5 +1,6 @@
'use client' 'use client'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs' import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useTranslations } from 'next-intl'
import { usePathname, useRouter } from 'next/navigation' import { usePathname, useRouter } from 'next/navigation'
type Props = { type Props = {
@@ -7,6 +8,7 @@ type Props = {
} }
export function GroupTabs({ groupId }: Props) { export function GroupTabs({ groupId }: Props) {
const t = useTranslations()
const pathname = usePathname() const pathname = usePathname()
const value = const value =
pathname.replace(/\/groups\/[^\/]+\/([^/]+).*/, '$1') || 'expenses' pathname.replace(/\/groups\/[^\/]+\/([^/]+).*/, '$1') || 'expenses'
@@ -15,16 +17,18 @@ export function GroupTabs({ groupId }: Props) {
return ( return (
<Tabs <Tabs
value={value} value={value}
className="[&>*]:border" className="[&>*]:border overflow-x-auto"
onValueChange={(value) => { onValueChange={(value) => {
router.push(`/groups/${groupId}/${value}`) router.push(`/groups/${groupId}/${value}`)
}} }}
> >
<TabsList> <TabsList>
<TabsTrigger value="expenses">Expenses</TabsTrigger> <TabsTrigger value="expenses">{t('Expenses.title')}</TabsTrigger>
<TabsTrigger value="balances">Balances</TabsTrigger> <TabsTrigger value="balances">{t('Balances.title')}</TabsTrigger>
<TabsTrigger value="stats">Stats</TabsTrigger> <TabsTrigger value="information">{t('Information.title')}</TabsTrigger>
<TabsTrigger value="edit">Settings</TabsTrigger> <TabsTrigger value="stats">{t('Stats.title')}</TabsTrigger>
<TabsTrigger value="activity">{t('Activity.title')}</TabsTrigger>
<TabsTrigger value="edit">{t('Settings.title')}</TabsTrigger>
</TabsList> </TabsList>
</Tabs> </Tabs>
) )

View File

@@ -0,0 +1,54 @@
import { cached } from '@/app/cached-functions'
import { Button } from '@/components/ui/button'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import { Pencil } from 'lucide-react'
import { Metadata } from 'next'
import { getTranslations } from 'next-intl/server'
import Link from 'next/link'
import { notFound } from 'next/navigation'
export const metadata: Metadata = {
title: 'Totals',
}
export default async function InformationPage({
params: { groupId },
}: {
params: { groupId: string }
}) {
const group = await cached.getGroup(groupId)
if (!group) notFound()
const t = await getTranslations('Information')
return (
<>
<Card className="mb-4">
<CardHeader>
<CardTitle className="flex justify-between">
<span>{t('title')}</span>
<Button size="icon" asChild className="-mb-12">
<Link href={`/groups/${groupId}/edit`}>
<Pencil className="w-4 h-4" />
</Link>
</Button>
</CardTitle>
<CardDescription className="mr-12">
{t('description')}
</CardDescription>
</CardHeader>
<CardContent className="prose prose-sm sm:prose-base max-w-full whitespace-break-spaces">
{group.information || (
<p className="text-muted-foreground italic">{t('empty')}</p>
)}
</CardContent>
</Card>
</>
)
}

View File

@@ -35,7 +35,7 @@ export default async function GroupLayout({
return ( return (
<> <>
<div className="flex flex-col sm:flex-row justify-between sm:items-center gap-3"> <div className="flex flex-col justify-between gap-3">
<h1 className="font-bold text-2xl"> <h1 className="font-bold text-2xl">
<Link href={`/groups/${groupId}`}>{group.name}</Link> <Link href={`/groups/${groupId}`}>{group.name}</Link>
</h1> </h1>

View File

@@ -2,6 +2,7 @@ import { Button } from '@/components/ui/button'
import { Reimbursement } from '@/lib/balances' import { Reimbursement } from '@/lib/balances'
import { formatCurrency } from '@/lib/utils' import { formatCurrency } from '@/lib/utils'
import { Participant } from '@prisma/client' import { Participant } from '@prisma/client'
import { useLocale, useTranslations } from 'next-intl'
import Link from 'next/link' import Link from 'next/link'
type Props = { type Props = {
@@ -17,12 +18,10 @@ export function ReimbursementList({
currency, currency,
groupId, groupId,
}: Props) { }: Props) {
const locale = useLocale()
const t = useTranslations('Balances.Reimbursements')
if (reimbursements.length === 0) { if (reimbursements.length === 0) {
return ( return <p className="px-6 text-sm pb-6">{t('noImbursements')}</p>
<p className="px-6 text-sm pb-6">
It looks like your group doesnt need any reimbursement 😁
</p>
)
} }
const getParticipant = (id: string) => participants.find((p) => p.id === id) const getParticipant = (id: string) => participants.find((p) => p.id === id)
@@ -32,18 +31,21 @@ export function ReimbursementList({
<div className="border-t px-6 py-4 flex justify-between" key={index}> <div className="border-t px-6 py-4 flex justify-between" key={index}>
<div className="flex flex-col gap-1 items-start sm:flex-row sm:items-baseline sm:gap-4"> <div className="flex flex-col gap-1 items-start sm:flex-row sm:items-baseline sm:gap-4">
<div> <div>
<strong>{getParticipant(reimbursement.from)?.name}</strong> owes{' '} {t.rich('owes', {
<strong>{getParticipant(reimbursement.to)?.name}</strong> from: getParticipant(reimbursement.from)?.name,
to: getParticipant(reimbursement.to)?.name,
strong: (chunks) => <strong>{chunks}</strong>,
})}
</div> </div>
<Button variant="link" asChild className="-mx-4 -my-3"> <Button variant="link" asChild className="-mx-4 -my-3">
<Link <Link
href={`/groups/${groupId}/expenses/create?reimbursement=yes&from=${reimbursement.from}&to=${reimbursement.to}&amount=${reimbursement.amount}`} href={`/groups/${groupId}/expenses/create?reimbursement=yes&from=${reimbursement.from}&to=${reimbursement.to}&amount=${reimbursement.amount}`}
> >
Mark as paid {t('markAsPaid')}
</Link> </Link>
</Button> </Button>
</div> </div>
<div>{formatCurrency(currency, reimbursement.amount)}</div> <div>{formatCurrency(currency, reimbursement.amount, locale)}</div>
</div> </div>
))} ))}
</div> </div>

View File

@@ -11,27 +11,26 @@ import {
import { useBaseUrl } from '@/lib/hooks' import { useBaseUrl } from '@/lib/hooks'
import { Group } from '@prisma/client' import { Group } from '@prisma/client'
import { Share } from 'lucide-react' import { Share } from 'lucide-react'
import { useTranslations } from 'next-intl'
type Props = { type Props = {
group: Group group: Group
} }
export function ShareButton({ group }: Props) { export function ShareButton({ group }: Props) {
const t = useTranslations('Share')
const baseUrl = useBaseUrl() const baseUrl = useBaseUrl()
const url = baseUrl && `${baseUrl}/groups/${group.id}/expenses?ref=share` const url = baseUrl && `${baseUrl}/groups/${group.id}/expenses?ref=share`
return ( return (
<Popover> <Popover>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<Button size="icon"> <Button title={t('title')} size="icon" className="flex-shrink-0">
<Share className="w-4 h-4" /> <Share className="w-4 h-4" />
</Button> </Button>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent align="end" className="[&_p]:text-sm flex flex-col gap-3"> <PopoverContent align="end" className="[&_p]:text-sm flex flex-col gap-3">
<p> <p>{t('description')}</p>
For other participants to see the group and add expenses, share its
URL with them.
</p>
{url && ( {url && (
<div className="flex gap-2"> <div className="flex gap-2">
<Input className="flex-1" defaultValue={url} readOnly /> <Input className="flex-1" defaultValue={url} readOnly />
@@ -43,8 +42,7 @@ export function ShareButton({ group }: Props) {
</div> </div>
)} )}
<p> <p>
<strong>Warning!</strong> Every person with the group URL will be able <strong>{t('warning')}</strong> {t('warningHelp')}
to see and edit expenses. Share with caution!
</p> </p>
</PopoverContent> </PopoverContent>
</Popover> </Popover>

View File

@@ -10,6 +10,7 @@ import {
import { getGroupExpenses } from '@/lib/api' import { getGroupExpenses } from '@/lib/api'
import { getTotalGroupSpending } from '@/lib/totals' import { getTotalGroupSpending } from '@/lib/totals'
import { Metadata } from 'next' import { Metadata } from 'next'
import { getTranslations } from 'next-intl/server'
import { notFound } from 'next/navigation' import { notFound } from 'next/navigation'
export const metadata: Metadata = { export const metadata: Metadata = {
@@ -21,6 +22,7 @@ export default async function TotalsPage({
}: { }: {
params: { groupId: string } params: { groupId: string }
}) { }) {
const t = await getTranslations('Stats')
const group = await cached.getGroup(groupId) const group = await cached.getGroup(groupId)
if (!group) notFound() if (!group) notFound()
@@ -31,10 +33,8 @@ export default async function TotalsPage({
<> <>
<Card className="mb-4"> <Card className="mb-4">
<CardHeader> <CardHeader>
<CardTitle>Totals</CardTitle> <CardTitle>{t('Totals.title')}</CardTitle>
<CardDescription> <CardDescription>{t('Totals.description')}</CardDescription>
Spending summary of the entire group.
</CardDescription>
</CardHeader> </CardHeader>
<CardContent className="flex flex-col space-y-4"> <CardContent className="flex flex-col space-y-4">
<Totals <Totals

View File

@@ -1,4 +1,5 @@
import { formatCurrency } from '@/lib/utils' import { formatCurrency } from '@/lib/utils'
import { useLocale, useTranslations } from 'next-intl'
type Props = { type Props = {
totalGroupSpendings: number totalGroupSpendings: number
@@ -6,11 +7,14 @@ type Props = {
} }
export function TotalsGroupSpending({ totalGroupSpendings, currency }: Props) { export function TotalsGroupSpending({ totalGroupSpendings, currency }: Props) {
const locale = useLocale()
const t = useTranslations('Stats.Totals')
const balance = totalGroupSpendings < 0 ? 'groupEarnings' : 'groupSpendings'
return ( return (
<div> <div>
<div className="text-muted-foreground">Total group spendings</div> <div className="text-muted-foreground">{t(balance)}</div>
<div className="text-lg"> <div className="text-lg">
{formatCurrency(currency, totalGroupSpendings)} {formatCurrency(currency, Math.abs(totalGroupSpendings), locale)}
</div> </div>
</div> </div>
) )

View File

@@ -1,7 +1,8 @@
'use client' 'use client'
import { getGroup, getGroupExpenses } from '@/lib/api' import { getGroup, getGroupExpenses } from '@/lib/api'
import { getTotalActiveUserShare } from '@/lib/totals' import { getTotalActiveUserShare } from '@/lib/totals'
import { formatCurrency } from '@/lib/utils' import { cn, formatCurrency } from '@/lib/utils'
import { useLocale, useTranslations } from 'next-intl'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
type Props = { type Props = {
@@ -10,6 +11,8 @@ type Props = {
} }
export function TotalsYourShare({ group, expenses }: Props) { export function TotalsYourShare({ group, expenses }: Props) {
const locale = useLocale()
const t = useTranslations('Stats.Totals')
const [activeUser, setActiveUser] = useState('') const [activeUser, setActiveUser] = useState('')
useEffect(() => { useEffect(() => {
@@ -25,9 +28,14 @@ export function TotalsYourShare({ group, expenses }: Props) {
return ( return (
<div> <div>
<div className="text-muted-foreground">Your total share</div> <div className="text-muted-foreground">{t('yourShare')}</div>
<div className="text-lg"> <div
{formatCurrency(currency, totalActiveUserShare)} className={cn(
'text-lg',
totalActiveUserShare < 0 ? 'text-green-600' : 'text-red-600',
)}
>
{formatCurrency(currency, Math.abs(totalActiveUserShare), locale)}
</div> </div>
</div> </div>
) )

View File

@@ -2,7 +2,8 @@
import { getGroup, getGroupExpenses } from '@/lib/api' import { getGroup, getGroupExpenses } from '@/lib/api'
import { useActiveUser } from '@/lib/hooks' import { useActiveUser } from '@/lib/hooks'
import { getTotalActiveUserPaidFor } from '@/lib/totals' import { getTotalActiveUserPaidFor } from '@/lib/totals'
import { formatCurrency } from '@/lib/utils' import { cn, formatCurrency } from '@/lib/utils'
import { useLocale, useTranslations } from 'next-intl'
type Props = { type Props = {
group: NonNullable<Awaited<ReturnType<typeof getGroup>>> group: NonNullable<Awaited<ReturnType<typeof getGroup>>>
@@ -10,6 +11,8 @@ type Props = {
} }
export function TotalsYourSpendings({ group, expenses }: Props) { export function TotalsYourSpendings({ group, expenses }: Props) {
const locale = useLocale()
const t = useTranslations('Stats.Totals')
const activeUser = useActiveUser(group.id) const activeUser = useActiveUser(group.id)
const totalYourSpendings = const totalYourSpendings =
@@ -17,13 +20,19 @@ export function TotalsYourSpendings({ group, expenses }: Props) {
? 0 ? 0
: getTotalActiveUserPaidFor(activeUser, expenses) : getTotalActiveUserPaidFor(activeUser, expenses)
const currency = group.currency const currency = group.currency
const balance = totalYourSpendings < 0 ? 'yourEarnings' : 'yourSpendings'
return ( return (
<div> <div>
<div className="text-muted-foreground">Total you paid for</div> <div className="text-muted-foreground">{t(balance)}</div>
<div className="text-lg"> <div
{formatCurrency(currency, totalYourSpendings)} className={cn(
'text-lg',
totalYourSpendings < 0 ? 'text-green-600' : 'text-red-600',
)}
>
{formatCurrency(currency, Math.abs(totalYourSpendings), locale)}
</div> </div>
</div> </div>
) )

View File

@@ -9,6 +9,7 @@ import {
} from '@/components/ui/popover' } from '@/components/ui/popover'
import { useMediaQuery } from '@/lib/hooks' import { useMediaQuery } from '@/lib/hooks'
import { Loader2, Plus } from 'lucide-react' import { Loader2, Plus } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { useState } from 'react' import { useState } from 'react'
type Props = { type Props = {
@@ -16,6 +17,7 @@ type Props = {
} }
export function AddGroupByUrlButton({ reload }: Props) { export function AddGroupByUrlButton({ reload }: Props) {
const t = useTranslations('Groups.AddByURL')
const isDesktop = useMediaQuery('(min-width: 640px)') const isDesktop = useMediaQuery('(min-width: 640px)')
const [url, setUrl] = useState('') const [url, setUrl] = useState('')
const [error, setError] = useState(false) const [error, setError] = useState(false)
@@ -27,18 +29,15 @@ export function AddGroupByUrlButton({ reload }: Props) {
<PopoverTrigger asChild> <PopoverTrigger asChild>
<Button variant="secondary"> <Button variant="secondary">
{/* <Plus className="w-4 h-4 mr-2" /> */} {/* <Plus className="w-4 h-4 mr-2" /> */}
<>Add by URL</> {t('button')}
</Button> </Button>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent <PopoverContent
align={isDesktop ? 'end' : 'start'} align={isDesktop ? 'end' : 'start'}
className="[&_p]:text-sm flex flex-col gap-3" className="[&_p]:text-sm flex flex-col gap-3"
> >
<h3 className="font-bold">Add a group by URL</h3> <h3 className="font-bold">{t('title')}</h3>
<p> <p>{t('description')}</p>
If a group was shared with you, you can paste its URL here to add it
to your list.
</p>
<form <form
className="flex gap-2" className="flex gap-2"
onSubmit={async (event) => { onSubmit={async (event) => {
@@ -80,11 +79,7 @@ export function AddGroupByUrlButton({ reload }: Props) {
)} )}
</Button> </Button>
</form> </form>
{error && ( {error && <p className="text-destructive">{t('error')}</p>}
<p className="text-destructive">
Oops, we are not able to find the group from the URL you provided
</p>
)}
</PopoverContent> </PopoverContent>
</Popover> </Popover>
) )

View File

@@ -1,13 +1,15 @@
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { useTranslations } from 'next-intl'
import Link from 'next/link' import Link from 'next/link'
export default function NotFound() { export default function NotFound() {
const t = useTranslations('Groups.NotFound')
return ( return (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<p>This group does not exist.</p> <p>{t('text')}</p>
<p> <p>
<Button asChild variant="secondary"> <Button asChild variant="secondary">
<Link href="/groups">Go to recently visited groups</Link> <Link href="/groups">{t('link')}</Link>
</Button> </Button>
</p> </p>
</div> </div>

View File

@@ -23,6 +23,7 @@ import { ToastAction } from '@/components/ui/toast'
import { useToast } from '@/components/ui/use-toast' import { useToast } from '@/components/ui/use-toast'
import { StarFilledIcon } from '@radix-ui/react-icons' import { StarFilledIcon } from '@radix-ui/react-icons'
import { Calendar, MoreHorizontal, Star, Users } from 'lucide-react' import { Calendar, MoreHorizontal, Star, Users } from 'lucide-react'
import { useLocale, useTranslations } from 'next-intl'
import Link from 'next/link' import Link from 'next/link'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { SetStateAction } from 'react' import { SetStateAction } from 'react'
@@ -37,7 +38,9 @@ export function RecentGroupListCard({
setState: (state: SetStateAction<RecentGroupsState>) => void setState: (state: SetStateAction<RecentGroupsState>) => void
}) { }) {
const router = useRouter() const router = useRouter()
const locale = useLocale()
const toast = useToast() const toast = useToast()
const t = useTranslations('Groups')
const details = const details =
state.status === 'complete' state.status === 'complete'
@@ -118,12 +121,11 @@ export function RecentGroupListCard({
groups: state.groups.filter((g) => g.id !== group.id), groups: state.groups.filter((g) => g.id !== group.id),
}) })
toast.toast({ toast.toast({
title: 'Group has been removed', title: t('RecentRemovedToast.title'),
description: description: t('RecentRemovedToast.description'),
'The group was removed from your recent groups list.',
action: ( action: (
<ToastAction <ToastAction
altText="Undo group removal" altText={t('RecentRemovedToast.undoAlt')}
onClick={() => { onClick={() => {
saveRecentGroup(group) saveRecentGroup(group)
setState({ setState({
@@ -132,13 +134,13 @@ export function RecentGroupListCard({
}) })
}} }}
> >
Undo {t('RecentRemovedToast.undo')}
</ToastAction> </ToastAction>
), ),
}) })
}} }}
> >
Remove from recent groups {t('removeRecent')}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem <DropdownMenuItem
onClick={(event) => { onClick={(event) => {
@@ -152,7 +154,7 @@ export function RecentGroupListCard({
refreshGroupsFromStorage() refreshGroupsFromStorage()
}} }}
> >
{isArchived ? <>Unarchive group</> : <>Archive group</>} {t(isArchived ? 'unarchive' : 'archive')}
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
@@ -168,7 +170,7 @@ export function RecentGroupListCard({
<div className="flex items-center"> <div className="flex items-center">
<Calendar className="w-3 h-3 inline mx-1" /> <Calendar className="w-3 h-3 inline mx-1" />
<span> <span>
{new Date(details.createdAt).toLocaleDateString('en-US', { {new Date(details.createdAt).toLocaleDateString(locale, {
dateStyle: 'medium', dateStyle: 'medium',
})} })}
</span> </span>

View File

@@ -10,6 +10,7 @@ import {
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { getGroups } from '@/lib/api' import { getGroups } from '@/lib/api'
import { Loader2 } from 'lucide-react' import { Loader2 } from 'lucide-react'
import { useTranslations } from 'next-intl'
import Link from 'next/link' import Link from 'next/link'
import { PropsWithChildren, SetStateAction, useEffect, useState } from 'react' import { PropsWithChildren, SetStateAction, useEffect, useState } from 'react'
import { RecentGroupListCard } from './recent-group-list-card' import { RecentGroupListCard } from './recent-group-list-card'
@@ -53,6 +54,7 @@ function sortGroups(
} }
export function RecentGroupList() { export function RecentGroupList() {
const t = useTranslations('Groups')
const [state, setState] = useState<RecentGroupsState>({ status: 'pending' }) const [state, setState] = useState<RecentGroupsState>({ status: 'pending' })
function loadGroups() { function loadGroups() {
@@ -84,8 +86,8 @@ export function RecentGroupList() {
return ( return (
<GroupsPage reload={loadGroups}> <GroupsPage reload={loadGroups}>
<p> <p>
<Loader2 className="w-4 m-4 mr-2 inline animate-spin" /> Loading <Loader2 className="w-4 m-4 mr-2 inline animate-spin" />{' '}
recent groups {t('loadingRecent')}
</p> </p>
</GroupsPage> </GroupsPage>
) )
@@ -95,12 +97,12 @@ export function RecentGroupList() {
return ( return (
<GroupsPage reload={loadGroups}> <GroupsPage reload={loadGroups}>
<div className="text-sm space-y-2"> <div className="text-sm space-y-2">
<p>You have not visited any group recently.</p> <p>{t('NoRecent.description')}</p>
<p> <p>
<Button variant="link" asChild className="-m-4"> <Button variant="link" asChild className="-m-4">
<Link href={`/groups/create`}>Create one</Link> <Link href={`/groups/create`}>{t('NoRecent.create')}</Link>
</Button>{' '} </Button>{' '}
or ask a friend to send you the link to an existing one. {t('NoRecent.orAsk')}
</p> </p>
</div> </div>
</GroupsPage> </GroupsPage>
@@ -113,7 +115,7 @@ export function RecentGroupList() {
<GroupsPage reload={loadGroups}> <GroupsPage reload={loadGroups}>
{starredGroupInfo.length > 0 && ( {starredGroupInfo.length > 0 && (
<> <>
<h2 className="mb-2">Starred groups</h2> <h2 className="mb-2">{t('starred')}</h2>
<GroupList <GroupList
groups={starredGroupInfo} groups={starredGroupInfo}
state={state} state={state}
@@ -124,14 +126,14 @@ export function RecentGroupList() {
{groupInfo.length > 0 && ( {groupInfo.length > 0 && (
<> <>
<h2 className="mt-6 mb-2">Recent groups</h2> <h2 className="mt-6 mb-2">{t('recent')}</h2>
<GroupList groups={groupInfo} state={state} setState={setState} /> <GroupList groups={groupInfo} state={state} setState={setState} />
</> </>
)} )}
{archivedGroupInfo.length > 0 && ( {archivedGroupInfo.length > 0 && (
<> <>
<h2 className="mt-6 mb-2 opacity-50">Archived groups</h2> <h2 className="mt-6 mb-2 opacity-50">{t('archived')}</h2>
<div className="opacity-50"> <div className="opacity-50">
<GroupList <GroupList
groups={archivedGroupInfo} groups={archivedGroupInfo}
@@ -172,18 +174,19 @@ function GroupsPage({
children, children,
reload, reload,
}: PropsWithChildren<{ reload: () => void }>) { }: PropsWithChildren<{ reload: () => void }>) {
const t = useTranslations('Groups')
return ( return (
<> <>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2"> <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<h1 className="font-bold text-2xl flex-1"> <h1 className="font-bold text-2xl flex-1">
<Link href="/groups">My groups</Link> <Link href="/groups">{t('myGroups')}</Link>
</h1> </h1>
<div className="flex gap-2"> <div className="flex gap-2">
<AddGroupByUrlButton reload={reload} /> <AddGroupByUrlButton reload={reload} />
<Button asChild> <Button asChild>
<Link href="/groups/create"> <Link href="/groups/create">
{/* <Plus className="w-4 h-4 mr-2" /> */} {/* <Plus className="w-4 h-4 mr-2" /> */}
<>Create</> {t('create')}
</Link> </Link>
</Button> </Button>
</div> </div>

View File

@@ -1,29 +0,0 @@
'use client'
import { AddGroupByUrlButton } from '@/app/groups/add-group-by-url-button'
import { RecentGroupList } from '@/app/groups/recent-group-list'
import { Button } from '@/components/ui/button'
import Link from 'next/link'
export function RecentGroupsPage() {
return (
<>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<h1 className="font-bold text-2xl flex-1">
<Link href="/groups">My groups</Link>
</h1>
<div className="flex gap-2">
<AddGroupByUrlButton reload={() => {}} />
<Button asChild>
<Link href="/groups/create">
{/* <Plus className="w-4 h-4 mr-2" /> */}
<>Create</>
</Link>
</Button>
</div>
</div>
<div>
<RecentGroupList />
</div>
</>
)
}

View File

@@ -1,4 +1,5 @@
import { ApplePwaSplash } from '@/app/apple-pwa-splash' import { ApplePwaSplash } from '@/app/apple-pwa-splash'
import { LocaleSwitcher } from '@/components/locale-switcher'
import { ProgressBar } from '@/components/progress-bar' import { ProgressBar } from '@/components/progress-bar'
import { ThemeProvider } from '@/components/theme-provider' import { ThemeProvider } from '@/components/theme-provider'
import { ThemeToggle } from '@/components/theme-toggle' import { ThemeToggle } from '@/components/theme-toggle'
@@ -6,6 +7,8 @@ import { Button } from '@/components/ui/button'
import { Toaster } from '@/components/ui/toaster' import { Toaster } from '@/components/ui/toaster'
import { env } from '@/lib/env' import { env } from '@/lib/env'
import type { Metadata, Viewport } from 'next' import type { Metadata, Viewport } from 'next'
import { NextIntlClientProvider, useTranslations } from 'next-intl'
import { getLocale, getMessages } from 'next-intl/server'
import Image from 'next/image' import Image from 'next/image'
import Link from 'next/link' import Link from 'next/link'
import { Suspense } from 'react' import { Suspense } from 'react'
@@ -59,93 +62,114 @@ export const viewport: Viewport = {
themeColor: '#047857', themeColor: '#047857',
} }
export default function RootLayout({ function Content({ children }: { children: React.ReactNode }) {
children, const t = useTranslations()
}: {
children: React.ReactNode
}) {
return ( return (
<html lang="en" suppressHydrationWarning> <>
<ApplePwaSplash icon="/logo-with-text.png" color="#027756" /> <header className="fixed top-0 left-0 right-0 h-16 flex justify-between bg-white dark:bg-gray-950 bg-opacity-50 dark:bg-opacity-50 p-2 border-b backdrop-blur-sm z-50">
<body className="pt-16 min-h-[100dvh] flex flex-col items-stretch bg-slate-50 bg-opacity-30 dark:bg-background"> <Link
<ThemeProvider className="flex items-center gap-2 hover:scale-105 transition-transform"
attribute="class" href="/"
defaultTheme="system"
enableSystem
disableTransitionOnChange
> >
<Suspense> <h1>
<ProgressBar /> <Image
</Suspense> src="/logo-with-text.png"
<header className="fixed top-0 left-0 right-0 h-16 flex justify-between bg-white dark:bg-gray-950 bg-opacity-50 dark:bg-opacity-50 p-2 border-b backdrop-blur-sm z-50"> className="m-1 h-auto w-auto"
<Link width={(35 * 522) / 180}
className="flex items-center gap-2 hover:scale-105 transition-transform" height={35}
href="/" alt="Spliit"
> />
<h1> </h1>
<Image </Link>
src="/logo-with-text.png" <div role="navigation" aria-label="Menu" className="flex">
className="m-1 h-auto w-auto" <ul className="flex items-center text-sm">
width={(35 * 522) / 180} <li>
height={35} <Button
alt="Spliit" variant="ghost"
/> size="sm"
</h1> asChild
className="-my-3 text-primary"
>
<Link href="/groups">{t('Header.groups')}</Link>
</Button>
</li>
<li>
<LocaleSwitcher />
</li>
<li>
<ThemeToggle />
</li>
</ul>
</div>
</header>
<div className="flex-1 flex flex-col">{children}</div>
<footer className="sm:p-8 md:p-16 sm:mt-16 sm:text-sm md:text-base md:mt-32 bg-slate-50 dark:bg-card border-t p-6 mt-8 flex flex-col sm:flex-row sm:justify-between gap-4 text-xs [&_a]:underline">
<div className="flex flex-col space-y-2">
<div className="sm:text-lg font-semibold text-base flex space-x-2 items-center">
<Link className="flex items-center gap-2" href="/">
<Image
src="/logo-with-text.png"
className="m-1 h-auto w-auto"
width={(35 * 522) / 180}
height={35}
alt="Spliit"
/>
</Link> </Link>
<div role="navigation" aria-label="Menu" className="flex"> </div>
<ul className="flex items-center text-sm"> <div className="flex flex-col space-y a--no-underline-text-white">
<li> <span>{t('Footer.madeIn')}</span>
<Button <span>
variant="ghost" {t.rich('Footer.builtBy', {
asChild author: (txt) => (
className="-my-3 text-primary"
>
<Link href="/groups">Groups</Link>
</Button>
</li>
<li>
<ThemeToggle />
</li>
</ul>
</div>
</header>
<div className="flex-1 flex flex-col">{children}</div>
<footer className="sm:p-8 md:p-16 sm:mt-16 sm:text-sm md:text-base md:mt-32 bg-slate-50 dark:bg-card border-t p-6 mt-8 flex flex-col sm:flex-row sm:justify-between gap-4 text-xs [&_a]:underline">
<div className="flex flex-col space-y-2">
<div className="sm:text-lg font-semibold text-base flex space-x-2 items-center">
<Link className="flex items-center gap-2" href="/">
<Image
src="/logo-with-text.png"
className="m-1 h-auto w-auto"
width={(35 * 522) / 180}
height={35}
alt="Spliit"
/>
</Link>
</div>
<div className="flex flex-col space-y a--no-underline-text-white">
<span>Made in Montréal, Québec 🇨🇦</span>
<span>
Built by{' '}
<a href="https://scastiel.dev" target="_blank" rel="noopener"> <a href="https://scastiel.dev" target="_blank" rel="noopener">
Sebastien Castiel {txt}
</a>{' '} </a>
and{' '} ),
source: (txt) => (
<a <a
href="https://github.com/spliit-app/spliit/graphs/contributors" href="https://github.com/spliit-app/spliit/graphs/contributors"
target="_blank" target="_blank"
rel="noopener" rel="noopener"
> >
contributors {txt}
</a> </a>
</span> ),
</div> })}
</div> </span>
</footer> </div>
<Toaster /> </div>
</ThemeProvider> </footer>
<Toaster />
</>
)
}
export default async function RootLayout({
children,
}: {
children: React.ReactNode
}) {
const locale = await getLocale()
const messages = await getMessages()
return (
<html lang={locale} suppressHydrationWarning>
<ApplePwaSplash icon="/logo-with-text.png" color="#027756" />
<body className="pt-16 min-h-[100dvh] flex flex-col items-stretch bg-slate-50 bg-opacity-30 dark:bg-background">
<NextIntlClientProvider messages={messages}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<Suspense>
<ProgressBar />
</Suspense>
<Content>{children}</Content>
</ThemeProvider>
</NextIntlClientProvider>
</body> </body>
</html> </html>
) )

View File

@@ -1,31 +1,35 @@
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Github } from 'lucide-react' import { Github } from 'lucide-react'
import { useTranslations } from 'next-intl'
import Link from 'next/link' import Link from 'next/link'
// FIX for https://github.com/vercel/next.js/issues/58615 // FIX for https://github.com/vercel/next.js/issues/58615
// export const dynamic = 'force-dynamic' // export const dynamic = 'force-dynamic'
export default function HomePage() { export default function HomePage() {
const t = useTranslations()
return ( return (
<main> <main>
<section className="py-16 md:py-24 lg:py-32"> <section className="py-16 md:py-24 lg:py-32">
<div className="container flex max-w-screen-md flex-col items-center gap-4 text-center"> <div className="container flex max-w-screen-md flex-col items-center gap-4 text-center">
<h1 className="!leading-none font-bold text-3xl sm:text-5xl md:text-6xl lg:text-7xl landing-header py-2"> <h1 className="!leading-none font-bold text-2xl sm:text-3xl md:text-4xl lg:text-5xl landing-header py-2">
Share <strong>Expenses</strong> <br /> with <strong>Friends</strong>{' '} {t.rich('Homepage.title', {
& <strong>Family</strong> strong: (chunks) => <strong>{chunks}</strong>,
})}
</h1> </h1>
<p className="max-w-[42rem] leading-normal text-muted-foreground sm:text-xl sm:leading-8"> <p className="max-w-[42rem] leading-normal text-muted-foreground sm:text-xl sm:leading-8">
Welcome to your new <strong>Spliit</strong> instance! <br /> {t.rich('Homepage.description', {
Customize this page by editing <em>src/app/page.tsx</em>. strong: (chunks) => <strong>{chunks}</strong>,
})}
</p> </p>
<div className="flex gap-2"> <div className="flex gap-2">
<Button asChild> <Button asChild>
<Link href="/groups">Go to groups</Link> <Link href="/groups">{t('Homepage.button.groups')}</Link>
</Button> </Button>
<Button asChild variant="secondary"> <Button asChild variant="secondary">
<Link href="https://github.com/spliit-app/spliit"> <Link href="https://github.com/spliit-app/spliit">
<Github className="w-4 h-4 mr-2" /> <Github className="w-4 h-4 mr-2" />
GitHub {t('Homepage.button.github')}
</Link> </Link>
</Button> </Button>
</div> </div>

View File

@@ -17,6 +17,7 @@ import {
} from '@/components/ui/popover' } from '@/components/ui/popover'
import { useMediaQuery } from '@/lib/hooks' import { useMediaQuery } from '@/lib/hooks'
import { Category } from '@prisma/client' import { Category } from '@prisma/client'
import { useTranslations } from 'next-intl'
import { forwardRef, useEffect, useState } from 'react' import { forwardRef, useEffect, useState } from 'react'
type Props = { type Props = {
@@ -100,6 +101,7 @@ function CategoryCommand({
categories: Category[] categories: Category[]
onValueChange: (categoryId: Category['id']) => void onValueChange: (categoryId: Category['id']) => void
}) { }) {
const t = useTranslations('Categories')
const categoriesByGroup = categories.reduce<Record<string, Category[]>>( const categoriesByGroup = categories.reduce<Record<string, Category[]>>(
(acc, category) => ({ (acc, category) => ({
...acc, ...acc,
@@ -110,16 +112,18 @@ function CategoryCommand({
return ( return (
<Command> <Command>
<CommandInput placeholder="Search category..." className="text-base" /> <CommandInput placeholder={t('search')} className="text-base" />
<CommandEmpty>No category found.</CommandEmpty> <CommandEmpty>{t('noCategory')}</CommandEmpty>
<div className="w-full max-h-[300px] overflow-y-auto"> <div className="w-full max-h-[300px] overflow-y-auto">
{Object.entries(categoriesByGroup).map( {Object.entries(categoriesByGroup).map(
([group, groupCategories], index) => ( ([group, groupCategories], index) => (
<CommandGroup key={index} heading={group}> <CommandGroup key={index} heading={t(`${group}.heading`)}>
{groupCategories.map((category) => ( {groupCategories.map((category) => (
<CommandItem <CommandItem
key={category.id} key={category.id}
value={`${category.id} ${category.grouping} ${category.name}`} value={`${category.id} ${t(
`${category.grouping}.heading`,
)} ${t(`${category.grouping}.${category.name}`)}`}
onSelect={(currentValue) => { onSelect={(currentValue) => {
const id = Number(currentValue.split(' ')[0]) const id = Number(currentValue.split(' ')[0])
onValueChange(id) onValueChange(id)
@@ -169,10 +173,11 @@ const CategoryButton = forwardRef<HTMLButtonElement, CategoryButtonProps>(
CategoryButton.displayName = 'CategoryButton' CategoryButton.displayName = 'CategoryButton'
function CategoryLabel({ category }: { category: Category }) { function CategoryLabel({ category }: { category: Category }) {
const t = useTranslations('Categories')
return ( return (
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<CategoryIcon category={category} className="w-4 h-4" /> <CategoryIcon category={category} className="w-4 h-4" />
{category.name} {t(`${category.grouping}.${category.name}`)}
</div> </div>
) )
} }

View File

@@ -1,6 +1,7 @@
'use client' 'use client'
import { Trash2 } from 'lucide-react' import { Trash2 } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { AsyncButton } from './async-button' import { AsyncButton } from './async-button'
import { Button } from './ui/button' import { Button } from './ui/button'
import { import {
@@ -14,20 +15,18 @@ import {
} from './ui/dialog' } from './ui/dialog'
export function DeletePopup({ onDelete }: { onDelete: () => Promise<void> }) { export function DeletePopup({ onDelete }: { onDelete: () => Promise<void> }) {
const t = useTranslations('ExpenseForm.DeletePopup')
return ( return (
<Dialog> <Dialog>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button variant="destructive"> <Button variant="destructive">
<Trash2 className="w-4 h-4 mr-2" /> <Trash2 className="w-4 h-4 mr-2" />
Delete {t('label')}
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent> <DialogContent>
<DialogTitle>Delete this expense?</DialogTitle> <DialogTitle>{t('title')}</DialogTitle>
<DialogDescription> <DialogDescription>{t('description')}</DialogDescription>
Do you really want to delete this expense? This action is
irreversible.
</DialogDescription>
<DialogFooter className="flex flex-col gap-2"> <DialogFooter className="flex flex-col gap-2">
<AsyncButton <AsyncButton
type="button" type="button"
@@ -35,10 +34,10 @@ export function DeletePopup({ onDelete }: { onDelete: () => Promise<void> }) {
loadingContent="Deleting…" loadingContent="Deleting…"
action={onDelete} action={onDelete}
> >
Yes {t('yes')}
</AsyncButton> </AsyncButton>
<DialogClose asChild> <DialogClose asChild>
<Button variant={'secondary'}>Cancel</Button> <Button variant={'secondary'}>{t('cancel')}</Button>
</DialogClose> </DialogClose>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>

View File

@@ -19,6 +19,7 @@ import { randomId } from '@/lib/api'
import { ExpenseFormValues } from '@/lib/schemas' import { ExpenseFormValues } from '@/lib/schemas'
import { formatFileSize } from '@/lib/utils' import { formatFileSize } from '@/lib/utils'
import { Loader2, Plus, Trash, X } from 'lucide-react' import { Loader2, Plus, Trash, X } from 'lucide-react'
import { useLocale, useTranslations } from 'next-intl'
import { getImageData, usePresignedUpload } from 'next-s3-upload' import { getImageData, usePresignedUpload } from 'next-s3-upload'
import Image from 'next/image' import Image from 'next/image'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
@@ -31,6 +32,8 @@ type Props = {
const MAX_FILE_SIZE = 5 * 1024 ** 2 const MAX_FILE_SIZE = 5 * 1024 ** 2
export function ExpenseDocumentsInput({ documents, updateDocuments }: Props) { export function ExpenseDocumentsInput({ documents, updateDocuments }: Props) {
const locale = useLocale()
const t = useTranslations('ExpenseDocumentsInput')
const [pending, setPending] = useState(false) const [pending, setPending] = useState(false)
const { FileInput, openFileDialog, uploadToS3 } = usePresignedUpload() // use presigned uploads to addtionally support providers other than AWS const { FileInput, openFileDialog, uploadToS3 } = usePresignedUpload() // use presigned uploads to addtionally support providers other than AWS
const { toast } = useToast() const { toast } = useToast()
@@ -38,10 +41,11 @@ export function ExpenseDocumentsInput({ documents, updateDocuments }: Props) {
const handleFileChange = async (file: File) => { const handleFileChange = async (file: File) => {
if (file.size > MAX_FILE_SIZE) { if (file.size > MAX_FILE_SIZE) {
toast({ toast({
title: 'The file is too big', title: t('TooBigToast.title'),
description: `The maximum file size you can upload is ${formatFileSize( description: t('TooBigToast.description', {
MAX_FILE_SIZE, maxSize: formatFileSize(MAX_FILE_SIZE, locale),
)}. Yours is ${formatFileSize(file.size)}.`, size: formatFileSize(file.size, locale),
}),
variant: 'destructive', variant: 'destructive',
}) })
return return
@@ -57,13 +61,15 @@ export function ExpenseDocumentsInput({ documents, updateDocuments }: Props) {
} catch (err) { } catch (err) {
console.error(err) console.error(err)
toast({ toast({
title: 'Error while uploading document', title: t('ErrorToast.title'),
description: description: t('ErrorToast.description'),
'Something wrong happened when uploading the document. Please retry later or select a different file.',
variant: 'destructive', variant: 'destructive',
action: ( action: (
<ToastAction altText="Retry" onClick={() => upload()}> <ToastAction
Retry altText={t('ErrorToast.retry')}
onClick={() => upload()}
>
{t('ErrorToast.retry')}
</ToastAction> </ToastAction>
), ),
}) })

View File

@@ -35,6 +35,7 @@ import {
} from '@/components/ui/select' } from '@/components/ui/select'
import { getCategories, getExpense, getGroup, randomId } from '@/lib/api' import { getCategories, getExpense, getGroup, randomId } from '@/lib/api'
import { RuntimeFeatureFlags } from '@/lib/featureFlags' import { RuntimeFeatureFlags } from '@/lib/featureFlags'
import { useActiveUser } from '@/lib/hooks'
import { import {
ExpenseFormValues, ExpenseFormValues,
SplittingOptions, SplittingOptions,
@@ -43,33 +44,33 @@ import {
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import { Save } from 'lucide-react' import { Save } from 'lucide-react'
import { useTranslations } from 'next-intl'
import Link from 'next/link' import Link from 'next/link'
import { useSearchParams } from 'next/navigation' import { useSearchParams } from 'next/navigation'
import { useState } from 'react' import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form' import { useForm } from 'react-hook-form'
import { match } from 'ts-pattern' import { match } from 'ts-pattern'
import { DeletePopup } from './delete-popup' import { DeletePopup } from './delete-popup'
import { extractCategoryFromTitle } from './expense-form-actions' import { extractCategoryFromTitle } from './expense-form-actions'
import { Textarea } from './ui/textarea'
export type Props = { export type Props = {
group: NonNullable<Awaited<ReturnType<typeof getGroup>>> group: NonNullable<Awaited<ReturnType<typeof getGroup>>>
expense?: NonNullable<Awaited<ReturnType<typeof getExpense>>> expense?: NonNullable<Awaited<ReturnType<typeof getExpense>>>
categories: NonNullable<Awaited<ReturnType<typeof getCategories>>> categories: NonNullable<Awaited<ReturnType<typeof getCategories>>>
onSubmit: (values: ExpenseFormValues) => Promise<void> onSubmit: (values: ExpenseFormValues, participantId?: string) => Promise<void>
onDelete?: () => Promise<void> onDelete?: (participantId?: string) => Promise<void>
runtimeFeatureFlags: RuntimeFeatureFlags runtimeFeatureFlags: RuntimeFeatureFlags
} }
const enforceCurrencyPattern = (value: string) => const enforceCurrencyPattern = (value: string) =>
value value
// replace first comma with # .replace(/^\s*-/, '_') // replace leading minus with _
.replace(/[.,]/, '#') .replace(/[.,]/, '#') // replace first comma with #
// remove all other commas .replace(/[-.,]/g, '') // remove other minus and commas characters
.replace(/[.,]/g, '') .replace(/_/, '-') // change back _ to minus
// change back # to dot .replace(/#/, '.') // change back # to dot
.replace(/#/, '.') .replace(/[^-\d.]/g, '') // remove all non-numeric characters
// remove all non-numeric and non-dot characters
.replace(/[^\d.]/g, '')
const getDefaultSplittingOptions = (group: Props['group']) => { const getDefaultSplittingOptions = (group: Props['group']) => {
const defaultValue = { const defaultValue = {
@@ -151,12 +152,13 @@ export function ExpenseForm({
onDelete, onDelete,
runtimeFeatureFlags, runtimeFeatureFlags,
}: Props) { }: Props) {
const t = useTranslations('ExpenseForm')
const isCreate = expense === undefined const isCreate = expense === undefined
const searchParams = useSearchParams() const searchParams = useSearchParams()
const getSelectedPayer = (field?: { value: string }) => { const getSelectedPayer = (field?: { value: string }) => {
if (isCreate && typeof window !== 'undefined') { if (isCreate && typeof window !== 'undefined') {
const activeUser = localStorage.getItem(`${group.id}-activeUser`) const activeUser = localStorage.getItem(`${group.id}-activeUser`)
if (activeUser && activeUser !== 'None') { if (activeUser && activeUser !== 'None' && field?.value === undefined) {
return activeUser return activeUser
} }
} }
@@ -180,6 +182,7 @@ export function ExpenseForm({
saveDefaultSplittingOptions: false, saveDefaultSplittingOptions: false,
isReimbursement: expense.isReimbursement, isReimbursement: expense.isReimbursement,
documents: expense.documents, documents: expense.documents,
notes: expense.notes ?? '',
} }
: searchParams.get('reimbursement') : searchParams.get('reimbursement')
? { ? {
@@ -202,6 +205,7 @@ export function ExpenseForm({
splitMode: defaultSplittingOptions.splitMode, splitMode: defaultSplittingOptions.splitMode,
saveDefaultSplittingOptions: false, saveDefaultSplittingOptions: false,
documents: [], documents: [],
notes: '',
} }
: { : {
title: searchParams.get('title') ?? '', title: searchParams.get('title') ?? '',
@@ -228,22 +232,90 @@ export function ExpenseForm({
}, },
] ]
: [], : [],
notes: '',
}, },
}) })
const [isCategoryLoading, setCategoryLoading] = useState(false) const [isCategoryLoading, setCategoryLoading] = useState(false)
const activeUserId = useActiveUser(group.id)
const submit = async (values: ExpenseFormValues) => { const submit = async (values: ExpenseFormValues) => {
await persistDefaultSplittingOptions(group.id, values) await persistDefaultSplittingOptions(group.id, values)
return onSubmit(values) return onSubmit(values, activeUserId ?? undefined)
} }
const [isIncome, setIsIncome] = useState(Number(form.getValues().amount) < 0)
const [manuallyEditedParticipants, setManuallyEditedParticipants] = useState<
Set<string>
>(new Set())
const sExpense = isIncome ? 'Income' : 'Expense'
const sPaid = isIncome ? 'received' : 'paid'
useEffect(() => {
setManuallyEditedParticipants(new Set())
}, [form.watch('splitMode'), form.watch('amount')])
useEffect(() => {
const splitMode = form.getValues().splitMode
// Only auto-balance for split mode 'Unevenly - By amount'
if (
splitMode === 'BY_AMOUNT' &&
(form.getFieldState('paidFor').isDirty ||
form.getFieldState('amount').isDirty)
) {
const totalAmount = Number(form.getValues().amount) || 0
const paidFor = form.getValues().paidFor
let newPaidFor = [...paidFor]
const editedParticipants = Array.from(manuallyEditedParticipants)
let remainingAmount = totalAmount
let remainingParticipants = newPaidFor.length - editedParticipants.length
newPaidFor = newPaidFor.map((participant) => {
if (editedParticipants.includes(participant.participant)) {
const participantShare = Number(participant.shares) || 0
if (splitMode === 'BY_AMOUNT') {
remainingAmount -= participantShare
}
return participant
}
return participant
})
if (remainingParticipants > 0) {
let amountPerRemaining = 0
if (splitMode === 'BY_AMOUNT') {
amountPerRemaining = remainingAmount / remainingParticipants
}
newPaidFor = newPaidFor.map((participant) => {
if (!editedParticipants.includes(participant.participant)) {
return {
...participant,
shares: String(
Number(amountPerRemaining.toFixed(2)),
) as unknown as number,
}
}
return participant
})
}
form.setValue('paidFor', newPaidFor, { shouldValidate: true })
}
}, [
manuallyEditedParticipants,
form.watch('amount'),
form.watch('splitMode'),
])
return ( return (
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(submit)}> <form onSubmit={form.handleSubmit(submit)}>
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle> <CardTitle>
{isCreate ? <>Create expense</> : <>Edit expense</>} {t(`${sExpense}.${isCreate ? 'create' : 'edit'}`)}
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="grid sm:grid-cols-2 gap-6"> <CardContent className="grid sm:grid-cols-2 gap-6">
@@ -252,10 +324,10 @@ export function ExpenseForm({
name="title" name="title"
render={({ field }) => ( render={({ field }) => (
<FormItem className=""> <FormItem className="">
<FormLabel>Expense title</FormLabel> <FormLabel>{t(`${sExpense}.TitleField.label`)}</FormLabel>
<FormControl> <FormControl>
<Input <Input
placeholder="Monday evening restaurant" placeholder={t(`${sExpense}.TitleField.placeholder`)}
className="text-base" className="text-base"
{...field} {...field}
onBlur={async () => { onBlur={async () => {
@@ -272,7 +344,7 @@ export function ExpenseForm({
/> />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
Enter a description for the expense. {t(`${sExpense}.TitleField.description`)}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -284,7 +356,7 @@ export function ExpenseForm({
name="expenseDate" name="expenseDate"
render={({ field }) => ( render={({ field }) => (
<FormItem className="sm:order-1"> <FormItem className="sm:order-1">
<FormLabel>Expense date</FormLabel> <FormLabel>{t(`${sExpense}.DateField.label`)}</FormLabel>
<FormControl> <FormControl>
<Input <Input
className="date-base" className="date-base"
@@ -296,7 +368,7 @@ export function ExpenseForm({
/> />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
Enter the date the expense was made. {t(`${sExpense}.DateField.description`)}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -308,44 +380,54 @@ export function ExpenseForm({
name="amount" name="amount"
render={({ field: { onChange, ...field } }) => ( render={({ field: { onChange, ...field } }) => (
<FormItem className="sm:order-3"> <FormItem className="sm:order-3">
<FormLabel>Amount</FormLabel> <FormLabel>{t('amountField.label')}</FormLabel>
<div className="flex items-baseline gap-2"> <div className="flex items-baseline gap-2">
<span>{group.currency}</span> <span>{group.currency}</span>
<FormControl> <FormControl>
<Input <Input
{...field}
className="text-base max-w-[120px]" className="text-base max-w-[120px]"
type="text" type="text"
inputMode="decimal" inputMode="decimal"
step={0.01}
placeholder="0.00" placeholder="0.00"
onChange={(event) => onChange={(event) => {
onChange(enforceCurrencyPattern(event.target.value)) const v = enforceCurrencyPattern(event.target.value)
} const income = Number(v) < 0
onClick={(e) => e.currentTarget.select()} setIsIncome(income)
if (income) form.setValue('isReimbursement', false)
onChange(v)
}}
onFocus={(e) => {
// we're adding a small delay to get around safaris issue with onMouseUp deselecting things again
const target = e.currentTarget
setTimeout(() => target.select(), 1)
}}
{...field} {...field}
/> />
</FormControl> </FormControl>
</div> </div>
<FormMessage /> <FormMessage />
<FormField {!isIncome && (
control={form.control} <FormField
name="isReimbursement" control={form.control}
render={({ field }) => ( name="isReimbursement"
<FormItem className="flex flex-row gap-2 items-center space-y-0 pt-2"> render={({ field }) => (
<FormControl> <FormItem className="flex flex-row gap-2 items-center space-y-0 pt-2">
<Checkbox <FormControl>
checked={field.value} <Checkbox
onCheckedChange={field.onChange} checked={field.value}
/> onCheckedChange={field.onChange}
</FormControl> />
<div> </FormControl>
<FormLabel>This is a reimbursement</FormLabel> <div>
</div> <FormLabel>
</FormItem> {t('isReimbursementField.label')}
)} </FormLabel>
/> </div>
</FormItem>
)}
/>
)}
</FormItem> </FormItem>
)} )}
/> />
@@ -355,7 +437,7 @@ export function ExpenseForm({
name="category" name="category"
render={({ field }) => ( render={({ field }) => (
<FormItem className="order-3 sm:order-2"> <FormItem className="order-3 sm:order-2">
<FormLabel>Category</FormLabel> <FormLabel>{t('categoryField.label')}</FormLabel>
<CategorySelector <CategorySelector
categories={categories} categories={categories}
defaultValue={ defaultValue={
@@ -365,7 +447,7 @@ export function ExpenseForm({
isLoading={isCategoryLoading} isLoading={isCategoryLoading}
/> />
<FormDescription> <FormDescription>
Select the expense category. {t(`${sExpense}.categoryFieldDescription`)}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -377,7 +459,7 @@ export function ExpenseForm({
name="paidBy" name="paidBy"
render={({ field }) => ( render={({ field }) => (
<FormItem className="sm:order-5"> <FormItem className="sm:order-5">
<FormLabel>Paid by</FormLabel> <FormLabel>{t(`${sExpense}.paidByField.label`)}</FormLabel>
<Select <Select
onValueChange={field.onChange} onValueChange={field.onChange}
defaultValue={getSelectedPayer(field)} defaultValue={getSelectedPayer(field)}
@@ -394,19 +476,31 @@ export function ExpenseForm({
</SelectContent> </SelectContent>
</Select> </Select>
<FormDescription> <FormDescription>
Select the participant who paid the expense. {t(`${sExpense}.paidByField.description`)}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )}
/> />
<FormField
control={form.control}
name="notes"
render={({ field }) => (
<FormItem className="sm:order-6">
<FormLabel>{t('notesField.label')}</FormLabel>
<FormControl>
<Textarea className="text-base" {...field} />
</FormControl>
</FormItem>
)}
/>
</CardContent> </CardContent>
</Card> </Card>
<Card className="mt-4"> <Card className="mt-4">
<CardHeader> <CardHeader>
<CardTitle className="flex justify-between"> <CardTitle className="flex justify-between">
<span>Paid for</span> <span>{t(`${sExpense}.paidFor.title`)}</span>
<Button <Button
variant="link" variant="link"
type="button" type="button"
@@ -432,14 +526,14 @@ export function ExpenseForm({
> >
{form.getValues().paidFor.length === {form.getValues().paidFor.length ===
group.participants.length ? ( group.participants.length ? (
<>Select none</> <>{t('selectNone')}</>
) : ( ) : (
<>Select all</> <>{t('selectAll')}</>
)} )}
</Button> </Button>
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
Select who the expense was paid for. {t(`${sExpense}.paidFor.description`)}
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
@@ -468,18 +562,29 @@ export function ExpenseForm({
({ participant }) => participant === id, ({ participant }) => participant === id,
)} )}
onCheckedChange={(checked) => { onCheckedChange={(checked) => {
return checked const options = {
? field.onChange([ shouldDirty: true,
...field.value, shouldTouch: true,
{ shouldValidate: true,
participant: id, }
shares: '1', checked
}, ? form.setValue(
]) 'paidFor',
: field.onChange( [
...field.value,
{
participant: id,
shares: '1' as unknown as number,
},
],
options,
)
: form.setValue(
'paidFor',
field.value?.filter( field.value?.filter(
(value) => value.participant !== id, (value) => value.participant !== id,
), ),
options,
) )
}} }}
/> />
@@ -504,7 +609,9 @@ export function ExpenseForm({
})} })}
> >
{match(form.getValues().splitMode) {match(form.getValues().splitMode)
.with('BY_SHARES', () => <>share(s)</>) .with('BY_SHARES', () => (
<>{t('shares')}</>
))
.with('BY_PERCENTAGE', () => <>%</>) .with('BY_PERCENTAGE', () => <>%</>)
.with('BY_AMOUNT', () => ( .with('BY_AMOUNT', () => (
<>{group.currency}</> <>{group.currency}</>
@@ -541,7 +648,7 @@ export function ExpenseForm({
participant === id, participant === id,
)?.shares )?.shares
} }
onChange={(event) => onChange={(event) => {
field.onChange( field.onChange(
field.value.map((p) => field.value.map((p) =>
p.participant === id p.participant === id
@@ -555,7 +662,10 @@ export function ExpenseForm({
: p, : p,
), ),
) )
} setManuallyEditedParticipants(
(prev) => new Set(prev).add(id),
)
}}
inputMode={ inputMode={
form.getValues().splitMode === form.getValues().splitMode ===
'BY_AMOUNT' 'BY_AMOUNT'
@@ -599,7 +709,7 @@ export function ExpenseForm({
> >
<CollapsibleTrigger asChild> <CollapsibleTrigger asChild>
<Button variant="link" className="-mx-4"> <Button variant="link" className="-mx-4">
Advanced splitting options {t('advancedOptions')}
</Button> </Button>
</CollapsibleTrigger> </CollapsibleTrigger>
<CollapsibleContent> <CollapsibleContent>
@@ -609,7 +719,7 @@ export function ExpenseForm({
name="splitMode" name="splitMode"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>Split mode</FormLabel> <FormLabel>{t('SplitModeField.label')}</FormLabel>
<FormControl> <FormControl>
<Select <Select
onValueChange={(value) => { onValueChange={(value) => {
@@ -625,21 +735,23 @@ export function ExpenseForm({
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="EVENLY">Evenly</SelectItem> <SelectItem value="EVENLY">
{t('SplitModeField.evenly')}
</SelectItem>
<SelectItem value="BY_SHARES"> <SelectItem value="BY_SHARES">
Unevenly By shares {t('SplitModeField.byShares')}
</SelectItem> </SelectItem>
<SelectItem value="BY_PERCENTAGE"> <SelectItem value="BY_PERCENTAGE">
Unevenly By percentage {t('SplitModeField.byPercentage')}
</SelectItem> </SelectItem>
<SelectItem value="BY_AMOUNT"> <SelectItem value="BY_AMOUNT">
Unevenly By amount {t('SplitModeField.byAmount')}
</SelectItem> </SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</FormControl> </FormControl>
<FormDescription> <FormDescription>
Select how to split the expense. {t(`${sExpense}.splitModeDescription`)}
</FormDescription> </FormDescription>
</FormItem> </FormItem>
)} )}
@@ -657,7 +769,7 @@ export function ExpenseForm({
</FormControl> </FormControl>
<div> <div>
<FormLabel> <FormLabel>
Save as default splitting options {t('SplitModeField.saveAsDefault')}
</FormLabel> </FormLabel>
</div> </div>
</FormItem> </FormItem>
@@ -673,10 +785,10 @@ export function ExpenseForm({
<Card className="mt-4"> <Card className="mt-4">
<CardHeader> <CardHeader>
<CardTitle className="flex justify-between"> <CardTitle className="flex justify-between">
<span>Attach documents</span> <span>{t('attachDocuments')}</span>
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
See and attach receipts to the expense. {t(`${sExpense}.attachDescription`)}
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
@@ -695,17 +807,17 @@ export function ExpenseForm({
)} )}
<div className="flex mt-4 gap-2"> <div className="flex mt-4 gap-2">
<SubmitButton <SubmitButton loadingContent={t(isCreate ? 'creating' : 'saving')}>
loadingContent={isCreate ? <>Creating</> : <>Saving</>}
>
<Save className="w-4 h-4 mr-2" /> <Save className="w-4 h-4 mr-2" />
{isCreate ? <>Create</> : <>Save</>} {t(isCreate ? 'create' : 'save')}
</SubmitButton> </SubmitButton>
{!isCreate && onDelete && ( {!isCreate && onDelete && (
<DeletePopup onDelete={onDelete}></DeletePopup> <DeletePopup
onDelete={() => onDelete(activeUserId ?? undefined)}
></DeletePopup>
)} )}
<Button variant="ghost" asChild> <Button variant="ghost" asChild>
<Link href={`/groups/${group.id}`}>Cancel</Link> <Link href={`/groups/${group.id}`}>{t('cancel')}</Link>
</Button> </Button>
</div> </div>
</form> </form>

View File

@@ -35,13 +35,18 @@ import { getGroup } from '@/lib/api'
import { GroupFormValues, groupFormSchema } from '@/lib/schemas' import { GroupFormValues, groupFormSchema } from '@/lib/schemas'
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import { Save, Trash2 } from 'lucide-react' import { Save, Trash2 } from 'lucide-react'
import { useTranslations } from 'next-intl'
import Link from 'next/link' import Link from 'next/link'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useFieldArray, useForm } from 'react-hook-form' import { useFieldArray, useForm } from 'react-hook-form'
import { Textarea } from './ui/textarea'
export type Props = { export type Props = {
group?: NonNullable<Awaited<ReturnType<typeof getGroup>>> group?: NonNullable<Awaited<ReturnType<typeof getGroup>>>
onSubmit: (groupFormValues: GroupFormValues) => Promise<void> onSubmit: (
groupFormValues: GroupFormValues,
participantId?: string,
) => Promise<void>
protectedParticipantIds?: string[] protectedParticipantIds?: string[]
} }
@@ -50,18 +55,25 @@ export function GroupForm({
onSubmit, onSubmit,
protectedParticipantIds = [], protectedParticipantIds = [],
}: Props) { }: Props) {
const t = useTranslations('GroupForm')
const form = useForm<GroupFormValues>({ const form = useForm<GroupFormValues>({
resolver: zodResolver(groupFormSchema), resolver: zodResolver(groupFormSchema),
defaultValues: group defaultValues: group
? { ? {
name: group.name, name: group.name,
information: group.information ?? '',
currency: group.currency, currency: group.currency,
participants: group.participants, participants: group.participants,
} }
: { : {
name: '', name: '',
information: '',
currency: '', currency: '',
participants: [{ name: 'John' }, { name: 'Jane' }, { name: 'Jack' }], participants: [
{ name: t('Participants.John') },
{ name: t('Participants.Jane') },
{ name: t('Participants.Jack') },
],
}, },
}) })
const { fields, append, remove } = useFieldArray({ const { fields, append, remove } = useFieldArray({
@@ -76,10 +88,10 @@ export function GroupForm({
const currentActiveUser = const currentActiveUser =
fields.find( fields.find(
(f) => f.id === localStorage.getItem(`${group?.id}-activeUser`), (f) => f.id === localStorage.getItem(`${group?.id}-activeUser`),
)?.name || 'None' )?.name || t('Settings.ActiveUserField.none')
setActiveUser(currentActiveUser) setActiveUser(currentActiveUser)
} }
}, [activeUser, fields, group?.id]) }, [t, activeUser, fields, group?.id])
const updateActiveUser = () => { const updateActiveUser = () => {
if (!activeUser) return if (!activeUser) return
@@ -99,12 +111,16 @@ export function GroupForm({
<Form {...form}> <Form {...form}>
<form <form
onSubmit={form.handleSubmit(async (values) => { onSubmit={form.handleSubmit(async (values) => {
await onSubmit(values) await onSubmit(
values,
group?.participants.find((p) => p.name === activeUser)?.id ??
undefined,
)
})} })}
> >
<Card className="mb-4"> <Card className="mb-4">
<CardHeader> <CardHeader>
<CardTitle>Group information</CardTitle> <CardTitle>{t('title')}</CardTitle>
</CardHeader> </CardHeader>
<CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4"> <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<FormField <FormField
@@ -112,16 +128,16 @@ export function GroupForm({
name="name" name="name"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>Group name</FormLabel> <FormLabel>{t('NameField.label')}</FormLabel>
<FormControl> <FormControl>
<Input <Input
className="text-base" className="text-base"
placeholder="Summer vacations" placeholder={t('NameField.placeholder')}
{...field} {...field}
/> />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
Enter a name for your group. {t('NameField.description')}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
@@ -133,31 +149,50 @@ export function GroupForm({
name="currency" name="currency"
render={({ field }) => ( render={({ field }) => (
<FormItem> <FormItem>
<FormLabel>Currency symbol</FormLabel> <FormLabel>{t('CurrencyField.label')}</FormLabel>
<FormControl> <FormControl>
<Input <Input
className="text-base" className="text-base"
placeholder="$, €, £…" placeholder={t('CurrencyField.placeholder')}
max={5} max={5}
{...field} {...field}
/> />
</FormControl> </FormControl>
<FormDescription> <FormDescription>
Well use it to display amounts. {t('CurrencyField.description')}
</FormDescription> </FormDescription>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
)} )}
/> />
<div className="col-span-2">
<FormField
control={form.control}
name="information"
render={({ field }) => (
<FormItem>
<FormLabel>{t('InformationField.label')}</FormLabel>
<FormControl>
<Textarea
rows={10}
className="text-base"
{...field}
placeholder={t('InformationField.placeholder')}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</CardContent> </CardContent>
</Card> </Card>
<Card className="mb-4"> <Card className="mb-4">
<CardHeader> <CardHeader>
<CardTitle>Participants</CardTitle> <CardTitle>{t('Participants.title')}</CardTitle>
<CardDescription> <CardDescription>{t('Participants.description')}</CardDescription>
Enter the name for each participant
</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ul className="flex flex-col gap-2"> <ul className="flex flex-col gap-2">
@@ -173,7 +208,11 @@ export function GroupForm({
</FormLabel> </FormLabel>
<FormControl> <FormControl>
<div className="flex gap-2"> <div className="flex gap-2">
<Input className="text-base" {...field} /> <Input
className="text-base"
{...field}
placeholder={t('Participants.new')}
/>
{item.id && {item.id &&
protectedParticipantIds.includes(item.id) ? ( protectedParticipantIds.includes(item.id) ? (
<HoverCard> <HoverCard>
@@ -192,8 +231,7 @@ export function GroupForm({
align="end" align="end"
className="text-sm" className="text-sm"
> >
This participant is part of expenses, and can {t('Participants.protectedParticipant')}
not be removed.
</HoverCardContent> </HoverCardContent>
</HoverCard> </HoverCard>
) : ( ) : (
@@ -221,28 +259,25 @@ export function GroupForm({
<Button <Button
variant="secondary" variant="secondary"
onClick={() => { onClick={() => {
append({ name: 'New' }) append({ name: '' })
}} }}
type="button" type="button"
> >
Add participant {t('Participants.add')}
</Button> </Button>
</CardFooter> </CardFooter>
</Card> </Card>
<Card className="mb-4"> <Card className="mb-4">
<CardHeader> <CardHeader>
<CardTitle>Local settings</CardTitle> <CardTitle>{t('Settings.title')}</CardTitle>
<CardDescription> <CardDescription>{t('Settings.description')}</CardDescription>
These settings are set per-device, and are used to customize your
experience.
</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="grid sm:grid-cols-2 gap-4"> <div className="grid sm:grid-cols-2 gap-4">
{activeUser !== null && ( {activeUser !== null && (
<FormItem> <FormItem>
<FormLabel>Active user</FormLabel> <FormLabel>{t('Settings.ActiveUserField.label')}</FormLabel>
<FormControl> <FormControl>
<Select <Select
onValueChange={(value) => { onValueChange={(value) => {
@@ -251,10 +286,17 @@ export function GroupForm({
defaultValue={activeUser} defaultValue={activeUser}
> >
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Select a participant" /> <SelectValue
placeholder={t(
'Settings.ActiveUserField.placeholder',
)}
/>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{[{ name: 'None' }, ...form.watch('participants')] {[
{ name: t('Settings.ActiveUserField.none') },
...form.watch('participants'),
]
.filter((item) => item.name.length > 0) .filter((item) => item.name.length > 0)
.map(({ name }) => ( .map(({ name }) => (
<SelectItem key={name} value={name}> <SelectItem key={name} value={name}>
@@ -265,7 +307,7 @@ export function GroupForm({
</Select> </Select>
</FormControl> </FormControl>
<FormDescription> <FormDescription>
User used as default for paying expenses. {t('Settings.ActiveUserField.description')}
</FormDescription> </FormDescription>
</FormItem> </FormItem>
)} )}
@@ -275,14 +317,15 @@ export function GroupForm({
<div className="flex mt-4 gap-2"> <div className="flex mt-4 gap-2">
<SubmitButton <SubmitButton
loadingContent={group ? 'Saving' : 'Creating'} loadingContent={t(group ? 'Settings.saving' : 'Settings.creating')}
onClick={updateActiveUser} onClick={updateActiveUser}
> >
<Save className="w-4 h-4 mr-2" /> {group ? <>Save</> : <> Create</>} <Save className="w-4 h-4 mr-2" />{' '}
{t(group ? 'Settings.save' : 'Settings.create')}
</SubmitButton> </SubmitButton>
{!group && ( {!group && (
<Button variant="ghost" asChild> <Button variant="ghost" asChild>
<Link href="/groups">Cancel</Link> <Link href="/groups">{t('Settings.cancel')}</Link>
</Button> </Button>
)} )}
</div> </div>

View File

@@ -0,0 +1,33 @@
'use client'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { locales } from '@/i18n'
import { setUserLocale } from '@/lib/locale'
import { useLocale, useTranslations } from 'next-intl'
export function LocaleSwitcher() {
const t = useTranslations('Locale')
const locale = useLocale()
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" className="-my-3 text-primary">
<span>{t(locale)}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
{locales.map((locale) => (
<DropdownMenuItem key={locale} onClick={() => setUserLocale(locale)}>
{t(locale)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
)
}

33
src/components/money.tsx Normal file
View File

@@ -0,0 +1,33 @@
'use client'
import { cn, formatCurrency } from '@/lib/utils'
import { useLocale } from 'next-intl'
type Props = {
currency: string
amount: number
bold?: boolean
colored?: boolean
}
export function Money({
currency,
amount,
bold = false,
colored = false,
}: Props) {
const locale = useLocale()
return (
<span
className={cn(
colored && amount <= 1
? 'text-red-600'
: colored && amount >= 1
? 'text-green-600'
: '',
bold && 'font-bold',
)}
>
{formatCurrency(currency, amount, locale)}
</span>
)
}

View File

@@ -12,6 +12,7 @@ import {
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label" import { Label } from "@/components/ui/label"
import { useMessages } from "next-intl"
const Form = FormProvider const Form = FormProvider
@@ -78,7 +79,7 @@ const FormItem = React.forwardRef<
return ( return (
<FormItemContext.Provider value={{ id }}> <FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} /> <div ref={ref} className={cn("col-span-2 md:col-span-1 space-y-2", className)} {...props} />
</FormItemContext.Provider> </FormItemContext.Provider>
) )
}) })
@@ -144,8 +145,18 @@ const FormMessage = React.forwardRef<
HTMLParagraphElement, HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement> React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => { >(({ className, children, ...props }, ref) => {
const messages = useMessages()
const { error, formMessageId } = useFormField() const { error, formMessageId } = useFormField()
const body = error ? String(error?.message) : children let body
if (error) {
body = String(error?.message)
const translation = (messages.SchemaErrors as any)[body]
if (translation) {
body = translation
}
} else {
body = children
}
if (!body) { if (!body) {
return null return null

View File

@@ -1,33 +1,51 @@
import * as React from "react" import * as React from 'react'
import {Input} from "@/components/ui/input"; import { Input } from '@/components/ui/input'
import {cn} from "@/lib/utils"; import { cn } from '@/lib/utils'
import { import { useTranslations } from 'next-intl'
Search import { Search, XCircle } from 'lucide-react'
} from 'lucide-react'
export interface InputProps export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {} extends React.InputHTMLAttributes<HTMLInputElement> {
onValueChange?: (value: string) => void
}
const SearchBar = React.forwardRef<HTMLInputElement, InputProps>( const SearchBar = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => { ({ className, type, onValueChange, ...props }, ref) => {
const t = useTranslations('Expenses')
const [value, _setValue] = React.useState('')
const setValue = (v: string) => {
_setValue(v)
onValueChange && onValueChange(v)
}
return ( return (
<div className="mx-4 sm:mx-6 flex relative"> <div className="mx-4 sm:mx-6 flex relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input <Input
type={type} type={type}
className={cn( className={cn(
"pl-10 text-sm focus:text-base bg-muted border-none text-muted-foreground", 'pl-10 text-sm focus:text-base bg-muted border-none text-muted-foreground',
className className,
)} )}
ref={ref} ref={ref}
placeholder="Search for an expense…" placeholder={t("searchPlaceholder")}
value={value}
onChange={(e) => setValue(e.target.value)}
{...props} {...props}
/> />
<XCircle
className={cn(
'absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 cursor-pointer',
!value && 'hidden',
)}
onClick={() => setValue('')}
/>
</div> </div>
) )
} },
) )
SearchBar.displayName = "SearchBar" SearchBar.displayName = 'SearchBar'
export { SearchBar } export { SearchBar }

25
src/i18n.ts Normal file
View File

@@ -0,0 +1,25 @@
import { getRequestConfig } from 'next-intl/server'
import { getUserLocale } from './lib/locale'
export const locales = [
'en-US',
'fi',
'fr-FR',
'es',
'de-DE',
'zh-CN',
'ru-RU',
'it-IT',
] as const
export type Locale = (typeof locales)[number]
export type Locales = ReadonlyArray<Locale>
export const defaultLocale: Locale = 'en-US'
export default getRequestConfig(async () => {
const locale = await getUserLocale()
return {
locale,
messages: (await import(`../messages/${locale}.json`)).default,
}
})

View File

@@ -1,6 +1,6 @@
import { getPrisma } from '@/lib/prisma' import { prisma } from '@/lib/prisma'
import { ExpenseFormValues, GroupFormValues } from '@/lib/schemas' import { ExpenseFormValues, GroupFormValues } from '@/lib/schemas'
import { Expense } from '@prisma/client' import { ActivityType, Expense } from '@prisma/client'
import { nanoid } from 'nanoid' import { nanoid } from 'nanoid'
export function randomId() { export function randomId() {
@@ -8,11 +8,11 @@ export function randomId() {
} }
export async function createGroup(groupFormValues: GroupFormValues) { export async function createGroup(groupFormValues: GroupFormValues) {
const prisma = await getPrisma()
return prisma.group.create({ return prisma.group.create({
data: { data: {
id: randomId(), id: randomId(),
name: groupFormValues.name, name: groupFormValues.name,
information: groupFormValues.information,
currency: groupFormValues.currency, currency: groupFormValues.currency,
participants: { participants: {
createMany: { createMany: {
@@ -30,6 +30,7 @@ export async function createGroup(groupFormValues: GroupFormValues) {
export async function createExpense( export async function createExpense(
expenseFormValues: ExpenseFormValues, expenseFormValues: ExpenseFormValues,
groupId: string, groupId: string,
participantId?: string,
): Promise<Expense> { ): Promise<Expense> {
const group = await getGroup(groupId) const group = await getGroup(groupId)
if (!group) throw new Error(`Invalid group ID: ${groupId}`) if (!group) throw new Error(`Invalid group ID: ${groupId}`)
@@ -42,10 +43,16 @@ export async function createExpense(
throw new Error(`Invalid participant ID: ${participant}`) throw new Error(`Invalid participant ID: ${participant}`)
} }
const prisma = await getPrisma() const expenseId = randomId()
await logActivity(groupId, ActivityType.CREATE_EXPENSE, {
participantId,
expenseId,
data: expenseFormValues.title,
})
return prisma.expense.create({ return prisma.expense.create({
data: { data: {
id: randomId(), id: expenseId,
groupId, groupId,
expenseDate: expenseFormValues.expenseDate, expenseDate: expenseFormValues.expenseDate,
categoryId: expenseFormValues.category, categoryId: expenseFormValues.category,
@@ -72,12 +79,23 @@ export async function createExpense(
})), })),
}, },
}, },
notes: expenseFormValues.notes,
}, },
}) })
} }
export async function deleteExpense(expenseId: string) { export async function deleteExpense(
const prisma = await getPrisma() groupId: string,
expenseId: string,
participantId?: string,
) {
const existingExpense = await getExpense(groupId, expenseId)
await logActivity(groupId, ActivityType.DELETE_EXPENSE, {
participantId,
expenseId,
data: existingExpense?.title,
})
await prisma.expense.delete({ await prisma.expense.delete({
where: { id: expenseId }, where: { id: expenseId },
include: { paidFor: true, paidBy: true }, include: { paidFor: true, paidBy: true },
@@ -89,15 +107,14 @@ export async function getGroupExpensesParticipants(groupId: string) {
return Array.from( return Array.from(
new Set( new Set(
expenses.flatMap((e) => [ expenses.flatMap((e) => [
e.paidById, e.paidBy.id,
...e.paidFor.map((pf) => pf.participantId), ...e.paidFor.map((pf) => pf.participant.id),
]), ]),
), ),
) )
} }
export async function getGroups(groupIds: string[]) { export async function getGroups(groupIds: string[]) {
const prisma = await getPrisma()
return ( return (
await prisma.group.findMany({ await prisma.group.findMany({
where: { id: { in: groupIds } }, where: { id: { in: groupIds } },
@@ -113,6 +130,7 @@ export async function updateExpense(
groupId: string, groupId: string,
expenseId: string, expenseId: string,
expenseFormValues: ExpenseFormValues, expenseFormValues: ExpenseFormValues,
participantId?: string,
) { ) {
const group = await getGroup(groupId) const group = await getGroup(groupId)
if (!group) throw new Error(`Invalid group ID: ${groupId}`) if (!group) throw new Error(`Invalid group ID: ${groupId}`)
@@ -128,7 +146,12 @@ export async function updateExpense(
throw new Error(`Invalid participant ID: ${participant}`) throw new Error(`Invalid participant ID: ${participant}`)
} }
const prisma = await getPrisma() await logActivity(groupId, ActivityType.UPDATE_EXPENSE, {
participantId,
expenseId,
data: expenseFormValues.title,
})
return prisma.expense.update({ return prisma.expense.update({
where: { id: expenseId }, where: { id: expenseId },
data: { data: {
@@ -185,6 +208,7 @@ export async function updateExpense(
id: doc.id, id: doc.id,
})), })),
}, },
notes: expenseFormValues.notes,
}, },
}) })
} }
@@ -192,15 +216,18 @@ export async function updateExpense(
export async function updateGroup( export async function updateGroup(
groupId: string, groupId: string,
groupFormValues: GroupFormValues, groupFormValues: GroupFormValues,
participantId?: string,
) { ) {
const existingGroup = await getGroup(groupId) const existingGroup = await getGroup(groupId)
if (!existingGroup) throw new Error('Invalid group ID') if (!existingGroup) throw new Error('Invalid group ID')
const prisma = await getPrisma() await logActivity(groupId, ActivityType.UPDATE_GROUP, { participantId })
return prisma.group.update({ return prisma.group.update({
where: { id: groupId }, where: { id: groupId },
data: { data: {
name: groupFormValues.name, name: groupFormValues.name,
information: groupFormValues.information,
currency: groupFormValues.currency, currency: groupFormValues.currency,
participants: { participants: {
deleteMany: existingGroup.participants.filter( deleteMany: existingGroup.participants.filter(
@@ -228,7 +255,6 @@ export async function updateGroup(
} }
export async function getGroup(groupId: string) { export async function getGroup(groupId: string) {
const prisma = await getPrisma()
return prisma.group.findUnique({ return prisma.group.findUnique({
where: { id: groupId }, where: { id: groupId },
include: { participants: true }, include: { participants: true },
@@ -236,27 +262,67 @@ export async function getGroup(groupId: string) {
} }
export async function getCategories() { export async function getCategories() {
const prisma = await getPrisma()
return prisma.category.findMany() return prisma.category.findMany()
} }
export async function getGroupExpenses(groupId: string) { export async function getGroupExpenses(
const prisma = await getPrisma() groupId: string,
options?: { offset: number; length: number },
) {
return prisma.expense.findMany({ return prisma.expense.findMany({
where: { groupId }, select: {
include: { amount: true,
paidFor: { include: { participant: true } },
paidBy: true,
category: true, category: true,
createdAt: true,
expenseDate: true,
id: true,
isReimbursement: true,
paidBy: { select: { id: true, name: true } },
paidFor: {
select: {
participant: { select: { id: true, name: true } },
shares: true,
},
},
splitMode: true,
title: true,
}, },
where: { groupId },
orderBy: [{ expenseDate: 'desc' }, { createdAt: 'desc' }], orderBy: [{ expenseDate: 'desc' }, { createdAt: 'desc' }],
skip: options && options.offset,
take: options && options.length,
}) })
} }
export async function getGroupExpenseCount(groupId: string) {
return prisma.expense.count({ where: { groupId } })
}
export async function getExpense(groupId: string, expenseId: string) { export async function getExpense(groupId: string, expenseId: string) {
const prisma = await getPrisma()
return prisma.expense.findUnique({ return prisma.expense.findUnique({
where: { id: expenseId }, where: { id: expenseId },
include: { paidBy: true, paidFor: true, category: true, documents: true }, include: { paidBy: true, paidFor: true, category: true, documents: true },
}) })
} }
export async function getActivities(groupId: string) {
return prisma.activity.findMany({
where: { groupId },
orderBy: [{ time: 'desc' }],
})
}
export async function logActivity(
groupId: string,
activityType: ActivityType,
extra?: { participantId?: string; expenseId?: string; data?: string },
) {
return prisma.activity.create({
data: {
id: randomId(),
groupId,
activityType,
...extra,
},
})
}

View File

@@ -19,7 +19,7 @@ export function getBalances(
const balances: Balances = {} const balances: Balances = {}
for (const expense of expenses) { for (const expense of expenses) {
const paidBy = expense.paidById const paidBy = expense.paidBy.id
const paidFors = expense.paidFor const paidFors = expense.paidFor
if (!balances[paidBy]) balances[paidBy] = { paid: 0, paidFor: 0, total: 0 } if (!balances[paidBy]) balances[paidBy] = { paid: 0, paidFor: 0, total: 0 }
@@ -31,8 +31,8 @@ export function getBalances(
) )
let remaining = expense.amount let remaining = expense.amount
paidFors.forEach((paidFor, index) => { paidFors.forEach((paidFor, index) => {
if (!balances[paidFor.participantId]) if (!balances[paidFor.participant.id])
balances[paidFor.participantId] = { paid: 0, paidFor: 0, total: 0 } balances[paidFor.participant.id] = { paid: 0, paidFor: 0, total: 0 }
const isLast = index === paidFors.length - 1 const isLast = index === paidFors.length - 1
@@ -47,7 +47,7 @@ export function getBalances(
? remaining ? remaining
: (expense.amount * shares) / totalShares : (expense.amount * shares) / totalShares
remaining -= dividedAmount remaining -= dividedAmount
balances[paidFor.participantId].paidFor += dividedAmount balances[paidFor.participant.id].paidFor += dividedAmount
}) })
} }
@@ -82,13 +82,29 @@ export function getPublicBalances(reimbursements: Reimbursement[]): Balances {
return balances return balances
} }
/**
* A comparator that is stable across reimbursements.
* This ensures that a participant executing a suggested reimbursement
* does not result in completely new repayment suggestions.
*/
function compareBalancesForReimbursements(b1: any, b2: any): number {
// positive balances come before negative balances
if (b1.total > 0 && 0 > b2.total) {
return -1
} else if (b2.total > 0 && 0 > b1.total) {
return 1
}
// if signs match, sort based on userid
return b1.participantId < b2.participantId ? -1 : 1
}
export function getSuggestedReimbursements( export function getSuggestedReimbursements(
balances: Balances, balances: Balances,
): Reimbursement[] { ): Reimbursement[] {
const balancesArray = Object.entries(balances) const balancesArray = Object.entries(balances)
.map(([participantId, { total }]) => ({ participantId, total })) .map(([participantId, { total }]) => ({ participantId, total }))
.filter((b) => b.total !== 0) .filter((b) => b.total !== 0)
balancesArray.sort((b1, b2) => b2.total - b1.total) balancesArray.sort(compareBalancesForReimbursements)
const reimbursements: Reimbursement[] = [] const reimbursements: Reimbursement[] = []
while (balancesArray.length > 1) { while (balancesArray.length > 1) {
const first = balancesArray[0] const first = balancesArray[0]

42
src/lib/locale.ts Normal file
View File

@@ -0,0 +1,42 @@
'use server'
import { Locale, Locales, defaultLocale, locales } from '@/i18n'
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
import { cookies, headers } from 'next/headers'
const COOKIE_NAME = 'NEXT_LOCALE'
function getAcceptLanguageLocale(requestHeaders: Headers, locales: Locales) {
let locale
const languages = new Negotiator({
headers: {
'accept-language': requestHeaders.get('accept-language') || undefined,
},
}).languages()
try {
locale = match(languages, locales, defaultLocale)
} catch (e) {
// invalid language
}
return locale
}
export async function getUserLocale() {
let locale
// Prio 1: use existing cookie
locale = cookies().get(COOKIE_NAME)?.value
// Prio 2: use `accept-language` header
// Prio 3: use default locale
if (!locale) {
locale = getAcceptLanguageLocale(headers(), locales)
}
return locale
}
export async function setUserLocale(locale: Locale) {
cookies().set(COOKIE_NAME, locale)
}

View File

@@ -1,20 +1,21 @@
import { PrismaClient } from '@prisma/client' import { PrismaClient } from '@prisma/client'
let prisma: PrismaClient declare const global: Global & { prisma?: PrismaClient }
export async function getPrisma() { export let p: PrismaClient = undefined as any as PrismaClient
if (typeof window === 'undefined') {
// await delay(1000) // await delay(1000)
if (!prisma) { if (process.env['NODE_ENV'] === 'production') {
if (process.env.NODE_ENV === 'production') { p = new PrismaClient()
prisma = new PrismaClient() } else {
} else { if (!global.prisma) {
if (!(global as any).prisma) { global.prisma = new PrismaClient({
;(global as any).prisma = new PrismaClient({ // log: [{ emit: 'stdout', level: 'query' }],
// log: [{ emit: 'stdout', level: 'query' }], })
})
}
prisma = (global as any).prisma
} }
p = global.prisma
} }
return prisma
} }
export const prisma = p

View File

@@ -3,22 +3,14 @@ import * as z from 'zod'
export const groupFormSchema = z export const groupFormSchema = z
.object({ .object({
name: z name: z.string().min(2, 'min2').max(50, 'max50'),
.string() information: z.string().optional(),
.min(2, 'Enter at least two characters.') currency: z.string().min(1, 'min1').max(5, 'max5'),
.max(50, 'Enter at most 50 characters.'),
currency: z
.string()
.min(1, 'Enter at least one character.')
.max(5, 'Enter at most five characters.'),
participants: z participants: z
.array( .array(
z.object({ z.object({
id: z.string().optional(), id: z.string().optional(),
name: z name: z.string().min(2, 'min2').max(50, 'max50'),
.string()
.min(2, 'Enter at least two characters.')
.max(50, 'Enter at most 50 characters.'),
}), }),
) )
.min(1), .min(1),
@@ -29,7 +21,7 @@ export const groupFormSchema = z
if (otherParticipant.name === participant.name) { if (otherParticipant.name === participant.name) {
ctx.addIssue({ ctx.addIssue({
code: 'custom', code: 'custom',
message: 'Another participant already has this name.', message: 'duplicateParticipantName',
path: ['participants', i, 'name'], path: ['participants', i, 'name'],
}) })
} }
@@ -42,9 +34,7 @@ export type GroupFormValues = z.infer<typeof groupFormSchema>
export const expenseFormSchema = z export const expenseFormSchema = z
.object({ .object({
expenseDate: z.coerce.date(), expenseDate: z.coerce.date(),
title: z title: z.string({ required_error: 'titleRequired' }).min(2, 'min2'),
.string({ required_error: 'Please enter a title.' })
.min(2, 'Enter at least two characters.'),
category: z.coerce.number().default(0), category: z.coerce.number().default(0),
amount: z amount: z
.union( .union(
@@ -55,19 +45,16 @@ export const expenseFormSchema = z
if (Number.isNaN(valueAsNumber)) if (Number.isNaN(valueAsNumber))
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Invalid number.', message: 'invalidNumber',
}) })
return Math.round(valueAsNumber * 100) return Math.round(valueAsNumber * 100)
}), }),
], ],
{ required_error: 'You must enter an amount.' }, { required_error: 'amountRequired' },
) )
.refine((amount) => amount >= 1, 'The amount must be higher than 0.01.') .refine((amount) => amount != 1, 'amountNotZero')
.refine( .refine((amount) => amount <= 10_000_000_00, 'amountTenMillion'),
(amount) => amount <= 10_000_000_00, paidBy: z.string({ required_error: 'paidByRequired' }),
'The amount must be lower than 10,000,000.',
),
paidBy: z.string({ required_error: 'You must select a participant.' }),
paidFor: z paidFor: z
.array( .array(
z.object({ z.object({
@@ -80,14 +67,14 @@ export const expenseFormSchema = z
if (Number.isNaN(valueAsNumber)) if (Number.isNaN(valueAsNumber))
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Invalid number.', message: 'invalidNumber',
}) })
return Math.round(valueAsNumber * 100) return Math.round(valueAsNumber * 100)
}), }),
]), ]),
}), }),
) )
.min(1, 'The expense must be paid for at least one participant.') .min(1, 'paidForMin1')
.superRefine((paidFor, ctx) => { .superRefine((paidFor, ctx) => {
let sum = 0 let sum = 0
for (const { shares } of paidFor) { for (const { shares } of paidFor) {
@@ -95,7 +82,7 @@ export const expenseFormSchema = z
if (shares < 1) { if (shares < 1) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'All shares must be higher than 0.', message: 'noZeroShares',
}) })
} }
} }
@@ -117,6 +104,7 @@ export const expenseFormSchema = z
}), }),
) )
.default([]), .default([]),
notes: z.string().optional(),
}) })
.superRefine((expense, ctx) => { .superRefine((expense, ctx) => {
let sum = 0 let sum = 0
@@ -137,7 +125,7 @@ export const expenseFormSchema = z
: `${((sum - expense.amount) / 100).toFixed(2)} surplus` : `${((sum - expense.amount) / 100).toFixed(2)} surplus`
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: `Sum of amounts must equal the expense amount (${detail}).`, message: 'amountSum',
path: ['paidFor'], path: ['paidFor'],
}) })
} }
@@ -151,7 +139,7 @@ export const expenseFormSchema = z
: `${((sum - 10000) / 100).toFixed(0)}% surplus` : `${((sum - 10000) / 100).toFixed(0)}% surplus`
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: `Sum of percentages must equal 100 (${detail})`, message: 'percentageSum',
path: ['paidFor'], path: ['paidFor'],
}) })
} }

View File

@@ -34,7 +34,7 @@ export function getTotalActiveUserShare(
const paidFors = expense.paidFor const paidFors = expense.paidFor
const userPaidFor = paidFors.find( const userPaidFor = paidFors.find(
(paidFor) => paidFor.participantId === activeUserId, (paidFor) => paidFor.participant.id === activeUserId,
) )
if (!userPaidFor) { if (!userPaidFor) {

71
src/lib/utils.test.ts Normal file
View File

@@ -0,0 +1,71 @@
import { formatCurrency } from './utils'
describe('formatCurrency', () => {
const currency = 'CUR'
/** For testing decimals */
const partialAmount = 1.23
/** For testing small full amounts */
const smallAmount = 1
/** For testing large full amounts */
const largeAmount = 10000
/** Non-breaking space */
const nbsp = '\xa0'
interface variation {
amount: number
locale: string
result: string
}
/**
* Variations to be tested, chosen as follows
* - `en-US` is a very common i18n fallback
* - `de-DE` exhibited faulty behavior in previous versions
*/
const variations: variation[] = [
{
amount: partialAmount,
locale: `en-US`,
result: `${currency}1.23`,
},
{
amount: smallAmount,
locale: `en-US`,
result: `${currency}1.00`,
},
{
amount: largeAmount,
locale: `en-US`,
result: `${currency}10,000.00`,
},
{
amount: partialAmount,
locale: `de-DE`,
result: `1,23${nbsp}${currency}`,
},
{
amount: smallAmount,
locale: `de-DE`,
result: `1,00${nbsp}${currency}`,
},
{
amount: largeAmount,
locale: `de-DE`,
result: `10.000,00${nbsp}${currency}`,
},
]
for (const variation of variations) {
it(`formats ${variation.amount} in ${variation.locale} without fractions`, () => {
expect(
formatCurrency(currency, variation.amount * 100, variation.locale),
).toBe(variation.result)
})
it(`formats ${variation.amount} in ${variation.locale} with fractions`, () => {
expect(
formatCurrency(currency, variation.amount, variation.locale, true),
).toBe(variation.result)
})
}
})

View File

@@ -10,9 +10,16 @@ export function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms)) return new Promise((resolve) => setTimeout(resolve, ms))
} }
export function formatExpenseDate(date: Date) { export type DateTimeStyle = NonNullable<
return date.toLocaleDateString('en-US', { ConstructorParameters<typeof Intl.DateTimeFormat>[1]
dateStyle: 'medium', >['dateStyle']
export function formatDate(
date: Date,
locale: string,
options: { dateStyle?: DateTimeStyle; timeStyle?: DateTimeStyle } = {},
) {
return date.toLocaleString(locale, {
...options,
timeZone: 'UTC', timeZone: 'UTC',
}) })
} }
@@ -21,18 +28,31 @@ export function formatCategoryForAIPrompt(category: Category) {
return `"${category.grouping}/${category.name}" (ID: ${category.id})` return `"${category.grouping}/${category.name}" (ID: ${category.id})`
} }
export function formatCurrency(currency: string, amount: number) { /**
const format = new Intl.NumberFormat('en-US', { * @param fractions Financial values in this app are generally processed in cents (or equivalent).
* They are are therefore integer representations of the amount (e.g. 100 for USD 1.00).
* Set this to `true` if you need to pass a value with decimal fractions instead (e.g. 1.00 for USD 1.00).
*/
export function formatCurrency(
currency: string,
amount: number,
locale: string,
fractions?: boolean,
) {
const format = new Intl.NumberFormat(locale, {
minimumFractionDigits: 2, minimumFractionDigits: 2,
maximumFractionDigits: 2, maximumFractionDigits: 2,
style: 'currency',
// '€' will be placed in correct position
currency: 'EUR',
}) })
const formattedAmount = format.format(amount / 100) const formattedAmount = format.format(fractions ? amount : amount / 100)
return `${currency} ${formattedAmount}` return formattedAmount.replace('€', currency)
} }
export function formatFileSize(size: number) { export function formatFileSize(size: number, locale: string) {
const formatNumber = (num: number) => const formatNumber = (num: number) =>
num.toLocaleString('en-US', { num.toLocaleString(locale, {
minimumFractionDigits: 0, minimumFractionDigits: 0,
maximumFractionDigits: 1, maximumFractionDigits: 1,
}) })
@@ -42,3 +62,13 @@ export function formatFileSize(size: number) {
if (size > 1024) return `${formatNumber(size / 1024)} kB` if (size > 1024) return `${formatNumber(size / 1024)} kB`
return `${formatNumber(size)} B` return `${formatNumber(size)} B`
} }
export function normalizeString(input: string): string {
// Replaces special characters
// Input: áäåèéę
// Output: aaaeee
return input
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
}

View File

@@ -1,6 +1,6 @@
// @ts-nocheck // @ts-nocheck
import { randomId } from '@/lib/api' import { randomId } from '@/lib/api'
import { getPrisma } from '@/lib/prisma' import { prisma } from '@/lib/prisma'
import { Prisma } from '@prisma/client' import { Prisma } from '@prisma/client'
import { Client } from 'pg' import { Client } from 'pg'
@@ -8,8 +8,6 @@ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
async function main() { async function main() {
withClient(async (client) => { withClient(async (client) => {
const prisma = await getPrisma()
// console.log('Deleting all groups…') // console.log('Deleting all groups…')
// await prisma.group.deleteMany({}) // await prisma.group.deleteMany({})