Intial commit

This commit is contained in:
EssDeeBee committed 2026-10-18 14:24:14 +04:00
commit 8c0328a679
24 files changed
+16625

No files matched your search

Whitespace-only changes.
+16
View File
@@ -0,0 +1,16 @@
node_modules/
.expo/
dist/
coverage/
.npm-cache/
*.log
.env
.env.*
!.env.example
# Local financial reference; keep private when Git is initialized.
/Subscriptions.xlsx
# Generated native projects (Expo managed workflow).
/android/
/ios/
+1
View File
@@ -0,0 +1 @@
engine-strict=true
+1
View File
@@ -0,0 +1 @@
22
+51
View File
@@ -0,0 +1,51 @@
# Repository Guidelines
## Project Structure & Module Organization
Recyvio is an Expo subscription tracker for iOS, Android, and web. The home screen displays a static example subscription; storage and calculations are planned.
- `src/app/`: Expo Router routes. `index.tsx` serves `/`; `_layout.tsx` provides shared safe-area and status-bar setup.
- `src/features/subscriptions/components/`: subscription UI, including `SubscriptionCard`.
- `src/__tests__/`: route and UI tests.
- `docs/IMPLEMENTATION_PLAN.md`: planned architecture, milestones, and workbook analysis.
- Root configuration: `app.json`, `tsconfig.json`, `eslint.config.js`, and `jest.config.js`.
## Build, Test, and Development Commands
Use Node.js 22.13.0 or newer and npm 10 or newer; `.nvmrc` selects Node 22.
- `npm ci`: install dependencies from the committed or supplied `package-lock.json`.
- `npm start`: start the Expo development server.
- `npm run web`: launch web development.
- `npm run android`: launch with a configured Android emulator or device.
- `npm run typecheck`: check TypeScript without emitting files.
- `npm run lint`: run ESLint with Expo rules.
- `npm test`: run Jest serially.
- `npm run export:web`: generate the production web export in `dist/`.
## Coding Style & Naming Conventions
Use two-space indentation, single-quoted strings, semicolons, trailing commas, and double-quoted JSX attributes. Use functional TypeScript components, PascalCase component names, and camelCase variables/functions. Preserve Expo Router filenames.
Strict TypeScript and unchecked-index checks are enabled; explicit `any` is forbidden. Use `StyleSheet.create`. No separate formatter is configured.
## Testing Guidelines
Use Jest (`jest-expo`), React Native Testing Library, and Expo Router testing utilities. Name tests `*.test.ts` or `*.test.tsx` under `src/`, preferably `src/__tests__/`. Test observable behavior and business logic. No coverage threshold is configured. Run typecheck, lint, tests, and web export; report actual results, failures, and unexecuted checks.
## Commit & Pull Request Guidelines
Git is not initialized; no historical convention exists. Use imperative subjects, e.g. `Add subscription list screen`. PRs should describe changes, link issues or milestones, list validation, and include UI screenshots. Never commit or push without an explicit request.
## Security & Configuration
Keep `Subscriptions.xlsx` private and unchanged; use synthetic subscription data in tests. Do not commit `.env` files, caches, generated native projects, or build output. Maintain `package-lock.json` alongside dependency changes.
## Collaboration & Business Rules
- Communicate with the user in Russian; keep all project content in English, including UI, documentation, comments, and tests.
- Work in the smallest complete steps. Explain significant changes beforehand; avoid unrelated refactoring.
- Explain new React patterns for a developer experienced in Java/Kotlin who is learning React.
- Treat Excel as a reference, not an unquestionable specification. Discuss ambiguous financial and billing rules before implementing them; keep calculations independent of React.
- Summarize what changed, why, verification, and remaining limitations.
- Propose additions to this guide when important, lasting agreements emerge. Keep temporary issues in task documentation; obtain agreement before adding new standing rules.
+105
View File
@@ -0,0 +1,105 @@
# Recyvio
A cross-platform subscription tracker for iOS, Android, and web.
The application has one Expo Router screen for adding, editing, and deleting subscriptions
in memory. SQLite initialization is connected; persistent subscription storage and financial
calculations are not implemented yet.
## Language
Use English for all UI text, documentation, comments, and other project content.
Support for additional languages may be added later.
## Environment
- Windows / PowerShell.
- Node.js 22 LTS, version 22.13.0 or newer; npm 10 or newer.
- Expo SDK 57, React 19.2.3, React Native 0.86.3.
Base dependency versions follow the [official SDK 57 template](https://github.com/expo/expo/blob/sdk-57/templates/expo-template-default/package.json).
The minimum Node.js version is listed in the [Expo compatibility table](https://docs.expo.dev/versions/v57.0.0/).
Routing follows the [Expo Router installation guide](https://docs.expo.dev/router/installation/).
## Getting started
After installing Node.js 22, open a new terminal in the project root:
```powershell
node --version
npm ci
npx expo install --check
npx expo-doctor
npm run web
```
Use `npm ci` to install dependencies from `package-lock.json`. When changing dependencies,
use `npm install` and keep the lockfile in sync.
For Android with a configured emulator, run `npm run android`.
For a physical phone, run `npm start` and open the project in a compatible Expo Go app.
The phone and computer must be able to reach each other over the network. Confirm that the
installed Expo Go version supports SDK 57 on the device. On Windows, test iOS on a physical
iPhone; future custom builds can use EAS cloud builds.
## Local database
`DatabaseProvider` opens `recyvio.db` and runs `SELECT 1` before displaying the application.
It shows a loading screen during initialization and offers `Try again` if opening fails.
The database connection is shared through React Context and closed when the provider unmounts.
No subscription tables or repository implementation exist yet; subscriptions still live only
in memory and are lost on reload.
Web uses WASM support configured in `metro.config.js`. The application currently uses
asynchronous SQLite APIs. Synchronous APIs additionally require cross-origin isolation:
serve HTML with `Cross-Origin-Embedder-Policy: credentialless` and
`Cross-Origin-Opener-Policy: same-origin`. Header settings are included for Metro and Expo
hosting, but verify the actual HTML response before using synchronous APIs; the SPA
development server does not apply these headers to HTML.
See the [Expo SQLite web setup](https://docs.expo.dev/versions/v57.0.0/sdk/sqlite/#web-setup).
Web uses client-side rendering (`web.output: "single"` in `app.json`). This avoids the
`Worker chunk not found` development bundler error affecting static output in the installed
SDK 57 packages. Run `npm run web` for development with automatic updates after code changes.
Restart the Expo server after changing `app.json` or Metro configuration.
To preview a production build instead:
```powershell
npm run web:preview
```
Open the URL printed by Expo. This exports and serves `dist/`; rerun it after code changes.
Native device initialization must be verified separately on Android and iOS.
## Checks
```powershell
npm run typecheck
npm run lint
npm test
npm run export:web
```
## Application structure
- `src/app/_layout.tsx`: shared route layout. `Slot` renders the current screen;
`SafeAreaProvider` supplies information about safe areas on mobile devices.
- `src/app/index.tsx`: the screen at `/`. A React component describes the UI using JSX.
`useColorScheme` subscribes the component to the system theme; React updates the screen
when the theme changes.
- `src/__tests__/home-route.test.tsx`: verifies that the root route opens and displays an accessible heading.
- `tsconfig.json`: strict type checking; ESLint also prohibits explicit `any`.
The screen uses local React state; the root layout provides the initialized database through Context.
See [docs/IMPLEMENTATION_PLAN.md](docs/IMPLEMENTATION_PLAN.md) for planned milestones.
## Project status
The application shell runs, as confirmed by the project owner. Dependencies and
`package-lock.json` are present. The initial setup limitations recorded in the implementation
plan describe the environment on 2026-10-17, rather than the current setup.
Use the validation commands above to check your environment; device compatibility still
needs to be checked on each target platform.
The original `Subscriptions.xlsx` is preserved and excluded from future Git tracking through
`.gitignore`. Git is not initialized; no commits or pushes have been made.
+28
View File
@@ -0,0 +1,28 @@
{
"expo": {
"name": "Recyvio",
"slug": "recyvio",
"version": "0.1.0",
"scheme": "recyvio",
"userInterfaceStyle": "automatic",
"plugins": [
[
"expo-router",
{
"headers": {
"Cross-Origin-Embedder-Policy": "credentialless",
"Cross-Origin-Opener-Policy": "same-origin"
}
}
],
"expo-sqlite"
],
"ios": {
"supportsTablet": true
},
"web": {
"bundler": "metro",
"output": "single"
}
}
}
+262
View File
@@ -0,0 +1,262 @@
# Subscription Tracker — implementation plan
Date: 2026-10-17. Initial plan reviewed; user authorized starting with the minimum application shell.
Implementation status: milestone 1 source/configuration files have been prepared. Installation and runtime verification are pending: this environment has Node.js 20.20.2 (SDK 57 requires at least 22.13), and npm registry requests fail with EACCES. There is no lockfile yet. No later milestone has been implemented. See `README.md` for setup and verification commands.
## 1. Inspection findings and scope
The supplied project directory is `C:\Users\dzebo\ser\wrk\essdeebee\dev\recyvio`.
Initial read-only inspection, including hidden entries, found an empty directory. The workbook appeared during this planning task and was then inspected. There is no existing application, package manifest, lockfile, Git repository, or project instruction file. No ancestor `AGENTS.md` was found.
`Subscriptions.xlsx` is now available (24,892 bytes). Its ZIP/XML contents were inspected read-only using .NET, including shared strings, worksheet cells/formulas, cached values, styles, validation, and workbook metadata. No Excel recalculation or visual workbook review was performed. Recommendations below intentionally require approval where workbook behavior is incomplete or inconsistent.
### Workbook findings
One visible sheet, `Sheet1`, contains 22 populated subscriptions in rows 3–24; rows 25–32 are reserved numbered slots, not additional subscriptions. There are 20 `Active` and 2 `Cancelled` records, 16 `Yearly` and 6 `Monthly` records. No custom interval is represented. Status validation covers N3:N24 (`Active,Cancelled`); interval validation covers D3:D24 (`Yearly,Monthly`). There are no defined names or external-link parts in the package. Row 34 is hidden; no hidden columns were found. The workbook does not enable the 1904 date system.
| Cells | Observed meaning |
| --- | --- |
| A2:D24 | Number, Service, Subscription, Period. Service and subscription are distinct names, not category/description fields. |
| E1:G24 | Annual equivalents in USD, EUR, GEL. |
| H1:J24 | Monthly equivalents in USD, EUR, GEL. |
| K2:M24 | Month, day, and calculated next-payment date. No complete original start date is stored. |
| N2:N24 | Status. No cancellation timestamp, paid-through date, or reactivation history. |
| O2:O32 | `Onetime Pay ₾`: amount per billing occurrence in GEL, not evidence of a one-time subscription. |
| P2:R32 | Upcoming schedule: date, subscription name, amount in GEL; Q/R have no independent headers. |
| S2:S32 | Month-based schedule total repeated for entries in that month. |
| T2:U4 | EUR→GEL and USD→GEL rates, with adjusted values in row 3 and raw values in row 4. |
| E33:J34 | Active-only annual/monthly totals and hidden reconciliation back to GEL. |
**Financial formulas.** Annual/monthly conversion is multiplication/division by 12, e.g. G5=`J5*12`, H3=`E3/12`. O3:O32 uses the shared formula `IF(D3="Yearly",G3,G3/12)`, translated per row. Totals E33:J33 use `SUMIF($N$3:$N$32,"Active",E3:E32)` translated across columns, so cancelled records retain costs but are excluded from headline totals. Cached GEL totals are G33=8863.377896 annually and J33=738.6148247 monthly; these are saved results, not a current recalculation or confirmed expenses.
**Original amounts are implicit.** Hardcoded cells vary by row: G3 is annual GEL, H6 monthly USD, F11 annual EUR, and I12 monthly EUR even though D12 says Yearly. A monthly entry may therefore be an annual contract quoted monthly. The app must explicitly store billed amount/currency/interval; an importer must preview the source mapping rather than infer it solely from cell formatting or whichever value is hardcoded. There is no category, description, actual-payment ledger, or explicit billing-currency column.
**FX and precision.** T3/U3 contain exported `GOOGLEFINANCE` formula text plus additive adjustments of 0.04 GEL/EUR and 0.03 GEL/USD. Cached adjusted rates are 2.948152 and 2.62; raw T4/U4 values are 2.908152 and 2.59. The reason for the adjustments (bank spread, fees, or another rule) and their validity period are unknown. No dedicated rate timestamp is stored. Cross-currency amounts generally convert through GEL. Formula wrappers use `IFERROR(__xludf.DUMMYFUNCTION(...),savedFallback)`, so successful Excel evaluation may return an old fallback rather than a live rate. No `ROUND(...)` formula was found; currency formats include both zero and two displayed decimals while underlying calculations retain more precision. This does not establish an intended rounding policy.
**Scheduling.** M3:M24 shares the formula `IF(TODAY()<=DATE(YEAR(TODAY()),K3,L3),DATE(YEAR(TODAY()),K3,L3),DATE(YEAR(TODAY())+1,K3,L3))`. Monthly rows calculate K using `IF(DAY(TODAY())<=L,MONTH(TODAY()),MONTH(TODAY())+1)`; annual rows supply a fixed month. Due today is included. Excel DATE normalizes overflowing days instead of clamping: an invalid February day can roll into March. December monthly rollover is especially suspect: K=13 advances the year once inside DATE, while the alternative branch also increments YEAR. No month-end or leap-day example in the populated rows validates the desired behavior. M ignores status; cancelled rows still have dates. Only one next date per subscription is modeled, not a series of future recurring charges.
**Upcoming schedule defects.** P3 contains exported `SORT(FILTER(M3:M32,MONTH(M3:M32)<=MONTH(TODAY())+3,N3:N32="Active"))`. Month-number comparison lacks a lower date bound and year comparison, so it is not a reliable next-three-month window, especially across year-end. P4 onward contains exported computed-value placeholders, rather than independently usable recurrence formulas. Q/R match all subscriptions by equal next date without retaining subscription IDs or filtering status. Multiple same-day matches can cause spill conflicts; cached Q7:R8 contains literal `#REF!` strings. S groups only by month number, not year, and omits later occurrences of monthly subscriptions. These behaviors should be corrected after approval, not reproduced as requirements.
**Cancellation ambiguity.** N6 and N16 are cancelled; their computed costs and next dates remain, while totals/schedule filter for Active. There is no evidence whether billing stops immediately or only after a paid period. The absence of dates makes lifecycle reconstruction impossible.
**Import implications.** Preserve Service separately from Subscription (propose an optional `providerName` field), trim whitespace only in the imported copy, and preview apparent spelling differences rather than silently renaming services. Start dates, cancellation cutoffs, and the original billed amount may require user input. Never import exported schedule/error/fallback cells as authoritative actual payments.
Source evidence above is from `Subscriptions.xlsx`, Sheet1, at the indicated cells. Inspection fingerprint: SHA-256 `0A5BD053218513E0224FBC0EF0777696D001E26EDCC91BEAD80A40FE5BCEB53E`. No source file writes were performed.
The initial planning task created only this plan. The subsequent approved shell step added application source and configuration; dependencies are not installed. Git has not been initialized; no commits, pushes, or spreadsheet modifications were performed. TypeScript, lint, application tests, and platform builds have not been verified.
### Remaining workbook review
Continue inspecting the original read-only; perform any recalculation experiments on a disposable copy. The initial findings are above; expand them into `docs/WORKBOOK_ANALYSIS.md` when approving import or deeper workbook parity work. Do not publish personal subscription data in fixtures without review.
Review:
- Sheets, tables, hidden rows/columns, headers, data types, named ranges, validations, external links, and Excel's 1900/1904 date system.
- Subscription fields, all distinct status values, missing values, duplicates, and whether cancellation dates or paid-through dates exist.
- Monthly/annual formulas, custom periods, total inclusion rules, intermediate versus display rounding, and formula errors.
- Original versus converted amounts, rate direction, rate source, effective date, fetched timestamp, and whether formulas fetch live values.
- Start dates, manual next-payment overrides, future recurrence, overdue handling, month-end behavior, leap years, and annual renewals.
- Whether rows describe contracts, projected charges, or actual paid transactions; whether price/status changes rewrite history.
Create an approval table: workbook behavior and location → ambiguity → proposed app rule → user decision. Compare representative results only after the rules are agreed. A cached Excel result alone does not prove current formula behavior. Exported formulas and missing lifecycle fields prevent full parity verification, but need not block a separately approved empty app shell.
## 2. Minimal architecture
Use one Expo application with TypeScript strict mode, Expo Router, React Native, and React Native Web. Keep one codebase and a single npm package. No backend is required for the MVP.
```text
src/
app/ # Router layouts and thin route entry components
features/
subscriptions/
domain/ # Subscription types, validation, lifecycle rules
application/ # Create/edit/cancel/reactivate use cases, repository port
data/ # SQLite repository and row mapping
ui/ # Screens, form, subscription-specific hooks
payments/
domain/ # Recurrence and projected-payment calculations
ui/ # Upcoming-payment screen and rows
dashboard/
application/ # Aggregate subscriptions and projections
ui/ # Summary cards and spending breakdowns
settings/
ui/ # Theme, reporting currency, manual rate settings
shared/
domain/ # Money, currencies, local dates, FX conversion
data/ # Database initialization, migrations, settings/rate storage
ui/ # Button, field, card, state views, theme tokens
integrations/ # Add Excel reader / external rate provider only when needed
docs/
```
Create directories only as their first files become necessary. Colocate tests with the logic outside `src/app` so the router cannot interpret tests as routes.
Dependency direction: routes and UI → application functions → domain functions. Data adapters implement application repository interfaces and depend on domain types. Domain code imports neither React nor Expo nor SQLite. Compose concrete repositories at the root layout; do not introduce a generic dependency injection container.
Use a small `SubscriptionRepository` interface with list/get/create/update/delete operations, extended for atomic lifecycle changes when needed. Async functions return domain records or explicit errors. Avoid generic repositories, event buses, CQRS, an ORM, and a synchronization engine at this stage.
### React patterns and data flow
- Components describe the UI for current props and state. Use local `useState` for form drafts, validation feedback, and loading state.
- A feature hook calls application functions and exposes data, pending state, errors, and explicit refresh/mutation operations. Hooks adapt business logic to React; calculations stay in plain functions.
- A small Context provider makes repositories, settings, and shared subscription state available without passing them through every screen. Context is a way to supply values, not a replacement database. Start with one shared subscription read model and reload after successful writes so dashboard and list agree.
- Effects synchronize with external systems, such as initial database loading or app focus. Do not use effects to store calculated monthly totals or trigger writes from rendering. Ignore stale async responses and prevent duplicate submission.
- Derive totals and upcoming payments from loaded records with pure functions. Introduce memoization only when useful. Refresh the date reference on foregrounding and calendar-day rollover so an open dashboard does not stay on yesterday.
### Trade-offs
Direct SQL keeps migrations and persistence behavior visible, at the cost of writing row mappings. React state plus Context is enough for a small local dataset; a query cache can be added if actual loading/invalidation complexity warrants it. Shared React Native primitives reduce UI duplication, while a few platform-specific controls may improve keyboard, date-entry, and navigation behavior.
Future Kotlin/Ktor integration can reuse application boundaries, stable UUID identifiers, ISO date strings, decimal strings, and explicit DTO mapping. Local SQLite remains useful as a cache. Synchronization will still require authentication, server revisions, conflict resolution, deletion tombstones, and offline operation rules; timestamps alone do not solve conflicts. Do not build those systems now.
## 3. Dependencies and platform decisions
Use Node.js LTS supported by the selected Expo SDK and npm with a committed `package-lock.json` once Git is explicitly set up. Install native/Expo packages with `npx expo install` to resolve SDK-compatible versions; use npm for ordinary JavaScript dependencies. Record the actual versions at scaffolding and use `npm ci` for reproducible installs.
As checked on 2026-10-17, Expo's project guide describes an SDK 58 transition and recommends SDK 57 for physical-device Expo Go. **Provisional choice: SDK 57 for the initial shell**, then verify the versioned documentation and installed Expo Go compatibility before scaffolding. Avoid accidentally selecting a different SDK through an unqualified template. The latest SQLite reference currently describes SDK 58; validate its requirements against the chosen SDK rather than copying APIs across versions. [Expo project setup](https://docs.expo.dev/get-started/create-a-project/)
| Dependency | Purpose / introduction point |
| --- | --- |
| `expo`, `react`, `react-native`, `expo-router` | Core runtime and shared navigation; scaffold with compatible template versions. |
| `react-native-web`, `react-dom`, `@expo/metro-runtime` | Web rendering/bundling as required by the selected template. |
| `react-native-safe-area-context`, `react-native-screens` | SDK-compatible navigation and safe-area dependencies required by the chosen router setup. |
| `expo-sqlite` | Async local database API and versioned SQL migrations; prove web behavior early. |
| `decimal.js` | Exact decimal inputs and controlled decimal rounding for money, normalization, and FX. Add with the money slice. |
| `expo-crypto` | Platform-compatible UUID generation when persistence needs identifiers. |
| TypeScript, React types, ESLint, `eslint-config-expo` | Strict typing and Expo-compatible linting. |
| Jest, `jest-expo`, `@types/jest` | One test runner for pure domain tests and later Expo-aware tests. |
| `@testing-library/react-native` | Add when interactive screens need behavioral component tests. |
Expo documents `jest-expo` and React Native Testing Library for testing. Native mocks are useful for UI tests, but cannot establish real SQLite persistence. [Expo testing guide](https://docs.expo.dev/develop/unit-testing/)
Use `decimal.js` through a small money module with explicit precision and rounding configuration, constructing decimals from strings. It supports configurable decimal arithmetic; the application's rounding policy still needs approval. [decimal.js API](https://mikemcl.github.io/decimal.js/)
Initially use small typed validation functions and controlled React Native inputs. Do not add Redux, a UI framework, chart library, form library, date library, HTTP client, or Excel parser without a concrete need. Native `fetch` can support a future rate integration. Basic breakdowns can use accessible labeled bars and lists. Consider a date picker only when implementing the form, with separate web and native adapters if required.
### SQLite on the web: early acceptance gate
Plan to use `expo-sqlite` across all platforms. Expo documents WebAssembly bundling and COOP/COEP headers for web. Static web hosting is compatible with the no-backend goal, provided it supports the required headers. [Expo SQLite web setup](https://docs.expo.dev/versions/latest/sdk/sqlite/#web-setup)
Before main UI work, prove create/read/update/delete and persistence across reloads on the selected SDK, desktop browsers, Android Chrome, and iOS Safari. Verify secure-context deployment, worker/WASM loading, storage-denied/private-mode errors, schema upgrades, and concurrent tabs. Validate actual target-host headers, not just local development. Browser storage is scoped to the origin/profile and can be cleared or evicted; it is not a backup.
If web SQLite fails the agreed browser matrix, stop that milestone and review options: restrict supported browsers, resolve the SQLite adapter, or explicitly approve IndexedDB behind the same interface. Do not silently change the persistence requirement. Avoid native-only transaction APIs in shared code; serialize writes and verify rollback using the chosen platform's supported transaction mechanism.
### Windows workflow
Develop web in local browsers and Android using an emulator or physical device. Preview iOS on a physical iPhone with a compatible Expo Go release, then use an EAS cloud development build when needed. EAS builds iOS binaries on hosted macOS infrastructure, so no local Mac is required. Cloud builds are a development service, not an application backend. Account, signing, device registration, and Apple program requirements must be checked before distribution. An iOS simulator is unavailable locally on Windows; web success does not establish iOS success. [EAS Build](https://docs.expo.dev/build/introduction/)
Offline database operation is in scope. Installing/launching the website without connectivity after a browser restart needs an explicit PWA caching decision; local persistence alone does not provide offline app-shell delivery.
## 4. Proposed domain model
These are conceptual contracts, not implemented TypeScript or a finalized database schema. Lifecycle and scheduling details are subject to section 5 decisions.
| Type | Fields and meaning |
| --- | --- |
| `Currency` | Closed union `USD`, `EUR`, `GEL`. No mixed-currency arithmetic without conversion. |
| `Money` | `amount`: canonical decimal string with at most two fractional digits for these currencies; `currency`. Validate input before normalization. Proposed: zero allowed, negative prices rejected; refunds deferred. |
| `LocalDate` | Validated Gregorian `YYYY-MM-DD`, without time or UTC conversion. Validate leap days and actual month lengths. |
| `Instant` | UTC ISO timestamp for creation, update, and observation metadata. |
| `BillingInterval` | Positive integer `count` plus `unit: day / month / year`; monthly = 1 month, yearly = 1 year, custom = N units. Supported custom units need approval. |
| `Subscription` | UUID `id`, trimmed `name`, optional `providerName` (workbook Service), optional `description`, optional `category`, original `price: Money`, `billingInterval`, `billingStartDate`, `scheduleAnchorDate`, optional `billingEndsBefore`, optional `cancellationRequestedAt`, optional `accessEndsOn`, `createdAt`, `updatedAt`. |
| `SubscriptionStatus` | UI projection `active / cancellationScheduled / cancelled`, derived at an explicit as-of date from lifecycle fields. A scheduled cancellation keeps the next boundary visible. Exact cutoff semantics need approval. |
| `ScheduledPayment` | Derived occurrence key (subscription ID plus schedule version/anchor and occurrence index), `subscriptionId`, `dueDate`, projected `originalAmount`, and optional converted valuation. Never implies money was paid. |
| `ExchangeRate` | UUID, `baseCurrency`, `quoteCurrency`, positive decimal `rate`, `effectiveDate`, `recordedAt`, `source` (manual initially). Meaning: one base unit equals rate quote units. |
| `ConvertedValuation` | Original money, target currency, unrounded decimal result, rounded display result, rate ID(s), and valuation timestamp. A derived estimate with provenance. |
| `AppSettings` | Reporting currency, system/light/dark theme preference, and selected manual rate set or valuation date policy. |
| `PaymentRecord` (deferred) | If actual expense history is requested: UUID, subscription ID, due date, paid timestamp, original amount snapshot, and optional historical conversion snapshot. Never create records merely because a due date passed. |
`billingStartDate` preserves the initial contract date; `scheduleAnchorDate` defines the current recurrence, including a confirmed reactivation or next-payment correction. Preserve the anchor day across short months. `nextPaymentDate` is derived from that schedule and an explicit date reference, rather than stored as a second competing schedule. If a user edits next payment, treat it as an explicit schedule change with validation, not a hidden field override.
The initial MVP tracks forecast subscription expenses and upcoming charges. Actual transaction history, payment reconciliation, and historical price versions are a separate scope decision. Current-price projections must be labeled as estimates; they cannot reconstruct historical spending.
### Persistence proposal
Start with `subscriptions`, `exchange_rates`, `settings`, and a schema version. Store price/rate decimals as TEXT, currency/status-unit values with constraints, counts as positive integers, local dates as ISO date text, and timestamps as UTC text. Validate database rows at the boundary; TypeScript types do not validate stored data. Domain decimal instances never cross serialization boundaries.
Use bound SQL parameters for user values, transactional migrations, explicit constraints, and atomic writes. Surface initialization/migration failures with recovery guidance; do not erase a failed database automatically. UUIDs are generated outside pure domain calculations. Derived schedules and totals are not persisted initially. Add an actual-payment table only if that scope is approved.
## 5. Decisions required before corresponding business logic
All recommendations below are proposals, not inferred workbook behavior. Record approved choices before implementing each affected slice.
| Decision | Recommendation for review | Why it matters |
| --- | --- | --- |
| Cancellation | Let the user choose immediate cessation of projected billing or a specified future cutoff. Model `billingEndsBefore` as exclusive: no charge on or after it. Track access end separately. | Cancelling renewal does not necessarily end prepaid access; the app does not cancel services with vendors. |
| Reactivation | Require an explicit next charge/anchor date. Retain existing subscription identity; do not backfill charges during a cancelled gap. | Avoid phantom arrears or an accidental restart on the old schedule. |
| Month-end | Clamp an anchor day to the last valid day of a short month, retaining the original anchor for later occurrences: Jan 31 → Feb 28/29 → Mar 31. Explicit end-of-month intent would be a separate rule. | Iteratively adding to a clamped date causes drift. Apr 30 does not necessarily imply May 31. |
| Leap-day annual renewal | Propose Feb 28 in non-leap years, returning to Feb 29 in leap years. Obtain approval versus Mar 1. | Different providers behave differently. |
| Custom recurrence | Start with every N days/months/years, positive integer N. Confirm whether weeks, irregular dates, trials, or one-time charges are needed. | “Custom” alone does not define a calculation. |
| Date reference and today | Use device-local calendar dates for MVP and include charges due today. Pass `asOfDate` explicitly into calculations; reconsider a fixed account timezone if travel should not move the view. | Prevent UTC parsing and DST from changing billing dates. |
| Past scheduled dates | Treat them as past projections, not unpaid debts. Show next on/after today; do not mark anything paid. | There is no actual payment ledger in the proposed MVP. |
| Schedule edits | Editing next payment explicitly replaces the current schedule anchor; price/interval changes affect future estimates only. Discuss history before adding actual payments. | Prevent conflicting stored and derived dates or fabricated history. |
| Dashboard totals | Show normalized current recurring cost for subscriptions still eligible for future billing; show dated cash-flow forecasts separately. Exclude cancelled renewals even if access remains. | Monthly equivalents differ from charges actually falling in a month. Scheduled cancellations need clear labels. |
| Normalization | For every N months: monthly = price/N, annual = monthly×12. Every N years: annual = price/N, monthly = annual/12. For day intervals, propose annual = price×365/N and monthly = annual/12, labeled an estimate. | A 365-day approximation is not a calendar cash-flow forecast; leap-year forecasts use actual occurrences. |
| Rounding | Propose round-half-up to 2 decimals for displayed amounts. Preserve extra precision during normalization/conversion, sum unrounded values, then round the total once. | Rounded rows can differ from a rounded aggregate; document that display behavior. |
| FX configuration | User selects reporting currency. Start with manually entered, timestamped rates; do not default real conversions to invented rates. | Keeps MVP offline and avoids credentials/CORS/rate-provider dependencies. |
| FX selection | Propose a single explicit valuation date/rate set for current estimates; use latest effective rate on/before it and show source/date. Confirm stale-rate threshold. | Historical and current valuations answer different questions. |
| Missing FX | Always show original-currency subtotals; mark converted grand total incomplete if any necessary rate is missing. Propose direct pairs first, with no implicit triangulation. | Missing rates must never be treated as zero or silently omitted. |
| Delete versus cancel | Cancellation preserves the record. Deletion requires explicit confirmation and removes the local record; add tombstones if synchronization is later introduced. | Prevent accidental loss and distinguish lifecycle from removal. |
Financial implementation must set and test a sufficient decimal precision (propose 40 significant digits with explicit magnitude bounds). Reject nonfinite values, unsafe counts, excessive precision, invalid dates, and ambiguous locale input. Currency formatting uses `Intl.NumberFormat`; formatted text is never used as the numeric source. Identity conversion uses rate 1 without a rate record. Do not mix different FX valuation dates within a total without making that policy explicit.
Generate occurrences from the original schedule anchor and index, with a finite date window and result limit. Avoid repeatedly adding intervals to the last output. Deterministically sort by due date then stable subscription ID. Choose a supported date range and maximum forecast horizon before accepting arbitrary inputs.
## 6. UI and accessibility approach
Initial routes: Dashboard, Subscriptions, subscription detail/create/edit, Upcoming, and Settings. Use mobile tabs and a wider desktop navigation/layout variant if it improves use; preserve route URLs and browser back behavior. A detail form can be a full screen on mobile and a constrained panel on desktop.
Use React Native primitives and `StyleSheet` with small reusable components and tokens for color, type, spacing, and focus. Honor system theme with a persisted override. Use width-driven layouts, readable content widths, and flexible cards; do not identify desktop by operating system alone.
Include database startup loading/retry, first-use empty states, no-search-results states, form field errors, failed-save retry, and incomplete FX states. Keep drafts after a failed save. Explain cancellation cutoff and original/converted amounts directly in the UI.
Provide accessible labels and roles, visible keyboard focus on web, logical reading/focus order, sufficient contrast, text scaling, usable touch targets, and text labels for status/breakdowns. Test screen reader output and keyboard navigation on actual targets. Do not communicate currency gaps or cancellation using color alone.
## 7. Small implementation milestones
Each milestone is a separate reviewable change. Before starting, explain intended files, behavior, and relevant React concepts. Afterward report changes, reasons, commands actually executed, results, and remaining limitations. No automatic commits or pushes.
| Milestone | Focus | Acceptance evidence |
| --- | --- | --- |
| 0. Workbook and decision review | Review the initial findings above; resolve source-amount mapping, FX adjustment intent, and rules from section 5 in relevant groups. | Approved example inputs/outputs and explicit decisions about workbook defects. No workbook modification. |
| 1. Empty application shell | Expo Router template, strict TS, npm scripts/lockfile, lint/test tooling, one accessible placeholder route. Preserve docs during scaffolding. | Typecheck, lint, minimal route render test, successful web export, Android and iPhone preview results recorded separately. |
| 2. Persistence feasibility | One temporary diagnostic flow using the actual Expo SQLite adapter; initialization and one migration. No subscription features yet. | Real create/read/update/delete, restart persistence, migration rollback, target browser/host header checks; results recorded per platform. |
| 3a. Money primitives | Currency validation, decimal parsing and formatting under approved rules. | Boundary tests for 0, 0.1+0.2, invalid inputs, excess precision, half-cent ties, and magnitude bounds. |
| 3b. Billing recurrence | Validated dates and anchor-based monthly/yearly/custom schedules. | Jan 29/30/31, Feb 29, leap-century rules, custom intervals, inclusive today, exclusive cutoff, horizon bounds, deterministic ordering. |
| 3c. Cost and FX | Approved normalization and manual-rate selection/conversion. | Monthly/yearly/custom examples, mixed currencies, missing/stale rates, rate direction, rounding order, and cancelled inclusion. |
| 4a. Read subscriptions | Minimal subscription schema, repository, list/detail UI, loading/error/empty states. | Real persisted fixture reads and mapping tests; no production sample financial data. |
| 4b. Create and edit | Controlled form, validation, application operations, save-and-refresh behavior. | Behavioral tests for invalid input, successful save, failed save retaining draft; persistence survives reload. |
| 4c. Lifecycle actions | Cancel, reactivate with chosen anchor, and confirmed delete. | Tests at cutoff boundaries, cancelled gaps, repeated actions, and shared-screen refresh consistency. |
| 5a. Upcoming payments | Windowed chronological forecasts, original currencies, next payment display. | Approved recurrence fixtures appear consistently in list/detail/upcoming views; clearly labeled forecasts. |
| 5b. Dashboard and rates | Manual rate settings, monthly/annual equivalents, active count, category breakdowns. | Domain totals reconcile to approved examples; missing FX is visible; normalized cost differs clearly from dated forecast. |
| 6. Release preparation | Finish theme/responsive/accessibility review; document backup/recovery and platform support. | Device/browser matrix, web production headers, restart/upgrade behavior, release-build checks, known limitations recorded. |
| Later, separately approved | Excel import preview/mapping/validation, duplicate handling, transactional import and backup export; then actual payment history or Ktor/PostgreSQL synchronization if desired. | Import never overwrites source workbook; preview errors and duplicates before writes; synchronization gets its own design. |
Milestone 0 may proceed alongside a separately approved shell. Domain implementation requires agreement on its relevant rules; no financial default becomes accepted merely because the UI needs it.
### Verification discipline
Configure `npm run typecheck` (`tsc --noEmit`), `npm run lint` (Expo-compatible ESLint), and `npm test -- --runInBand` (non-watch Jest). Run these for implementation changes, plus `npx expo-doctor` and `npx expo install --check` when dependencies/configuration change. Use web export and targeted device checks when platform integration changes. These commands are future work, not executed checks for this planning task.
Domain tests use fixed dates and explicit rates, without database, network, or React. Prefer examples and invariants that expose errors: schedule dates remain increasing, short-month clamping does not drift, missing-rate totals stay incomplete, and changing display currency never changes original money. Use approved workbook examples as regression fixtures once available.
Repository integration tests must use real SQLite for migrations/transactions; mock-based tests do not satisfy platform persistence acceptance. Add a small number of component behavior tests for important user actions. Record unavailable physical devices as unverified rather than reporting a universal pass.
## 8. Risks and boundaries
- **Incomplete business evidence:** the workbook lacks lifecycle dates, explicit source currencies, and reliably executable exported schedule/rate formulas. Full parity and import mapping remain pending decisions. Review section 5 before corresponding logic.
- **Web storage compatibility and durability:** early SQLite feasibility gate, explicit browser support, and a reviewed backup/recovery story are needed before relying on real data. Multiple tabs need tested write coordination.
- **Financial interpretation:** normalized expense, projected cash flow, and actual paid expense need distinct labels. Neither expiry nor cancellation implies a refund.
- **Platform coverage:** Windows enables development but physical iOS validation still requires an iPhone. Cloud build/signing setup is an external dependency.
- **Local-only data:** each installation/browser profile has independent data; uninstalling or clearing browser storage can lose it. No automatic multi-device continuity is promised.
- **Forecast scope:** current terms project future charges; provider-specific proration, tax, fees, price history, irregular schedules, notifications, and automatic vendor cancellation are deferred unless explicitly added.
- **Release scope:** polished UI does not establish production readiness. Storage migration/recovery, accessibility, supported platform checks, and backup decisions are part of release preparation.
## 9. Recommended smallest first implementation task
After approval, implement **milestone 1 only: a minimal Expo Router shell with one placeholder screen, strict TypeScript, linting, Jest configuration, and one route render test**. No subscription model, financial rules, database, or dashboard in that change. Confirm the exact SDK and Windows/device setup first; scaffold without overwriting this `docs` directory.
Success means the agreed shell checks actually run and their outcomes are reported, with unavailable device checks explicitly pending. The next separately reviewable task is the SQLite persistence feasibility check. Resolving workbook ambiguities can proceed alongside these foundation tasks.
The original planning approval gate has been satisfied for the minimal shell. Finish its installation and verification before considering it complete or starting the SQLite milestone.
+15
View File
@@ -0,0 +1,15 @@
const { defineConfig } = require('eslint/config');
const expoConfig = require('eslint-config-expo/flat');
module.exports = defineConfig([
expoConfig,
{
ignores: ['dist/**', '.expo/**', '.npm-cache/**', 'coverage/**'],
},
{
files: ['**/*.ts', '**/*.tsx'],
rules: {
'@typescript-eslint/no-explicit-any': 'error',
},
},
]);
+4
View File
@@ -0,0 +1,4 @@
module.exports = {
preset: 'jest-expo',
testMatch: ['<rootDir>/src/**/*.test.ts', '<rootDir>/src/**/*.test.tsx'],
};
+18
View File
@@ -0,0 +1,18 @@
const { getDefaultConfig } = require('expo/metro-config');
const config = getDefaultConfig(__dirname);
if (!config.resolver.assetExts.includes('wasm')) {
config.resolver.assetExts.push('wasm');
}
const enhanceMiddleware = config.server.enhanceMiddleware;
config.server.enhanceMiddleware = (middleware, server) => {
const handler = enhanceMiddleware ? enhanceMiddleware(middleware, server) : middleware;
return (request, response, next) => {
response.setHeader('Cross-Origin-Embedder-Policy', 'credentialless');
response.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
return handler(request, response, next);
};
};
module.exports = config;
+15195
View File
File diff suppressed because it is too large. Load diff
+48
View File
@@ -0,0 +1,48 @@
{
"name": "recyvio",
"version": "0.1.0",
"private": true,
"main": "expo-router/entry",
"engines": {
"node": ">=22.13.0",
"npm": ">=10"
},
"scripts": {
"start": "expo start",
"android": "expo start --android",
"web": "expo start --web",
"web:preview": "expo export --platform web && expo serve",
"typecheck": "tsc --noEmit",
"lint": "eslint .",
"test": "jest --runInBand",
"export:web": "expo export --platform web"
},
"dependencies": {
"@expo/metro-runtime": "~57.0.17",
"expo": "~57.0.30",
"expo-constants": "~57.0.22",
"expo-linking": "~57.0.13",
"expo-router": "~57.0.28",
"expo-sqlite": "~57.0.4",
"expo-status-bar": "~57.0.1",
"expo-system-ui": "~57.0.4",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-native": "0.86.3",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "~4.26.0",
"react-native-web": "~0.21.0"
},
"devDependencies": {
"@react-native/jest-preset": "0.86.3",
"@testing-library/react-native": "^13.3.0",
"@types/jest": "^29.5.14",
"@types/react": "~19.2.2",
"eslint": "^9.18.0",
"eslint-config-expo": "~57.0.2",
"jest": "^29.7.0",
"jest-expo": "~57.0.6",
"react-test-renderer": "19.2.3",
"typescript": "~6.0.3"
}
}
+18
View File
@@ -0,0 +1,18 @@
import { isValidAmount } from '../features/subscriptions/validation/isValidAmount';
describe('Amount validation', () => {
for (const amount of ['10', '10.5', '10.50', '0.01', ' 10.50 ', '9007199254740993.01']) {
it(`accepts the positive decimal string ${JSON.stringify(amount)}`, () => {
expect(isValidAmount(amount)).toBe(true);
});
}
for (const amount of [
'', ' ', '0', '0.0', '0.00', '00.00', '-10', '+10', '10.001', '10.', '.50',
'10,50', '1,000.00', '1e2', 'Infinity', 'NaN', 'abc', '10 USD', '1 0',
]) {
it(`rejects the invalid amount ${JSON.stringify(amount)}`, () => {
expect(isValidAmount(amount)).toBe(false);
});
}
});
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it, jest } from '@jest/globals';
import { render, screen, userEvent, waitFor } from '@testing-library/react-native';
import { openDatabaseAsync } from 'expo-sqlite';
import { Text } from 'react-native';
import { DatabaseProvider } from '../data/DatabaseProvider';
jest.mock('expo-sqlite', () => ({
openDatabaseAsync: jest.fn(async () => ({
getFirstAsync: jest.fn(async () => ({ ready: 1 })),
closeAsync: jest.fn(async () => {}),
})),
}));
describe('Database initialization', () => {
it('shows loading until a query succeeds and closes the database on unmount', async () => {
const view = render(<DatabaseProvider><Text>Application ready</Text></DatabaseProvider>);
expect(screen.getByText('Loading your subscriptions...')).toBeVisible();
expect(await screen.findByText('Application ready')).toBeVisible();
expect(openDatabaseAsync).toHaveBeenCalledWith('recyvio.db');
const db = await jest.mocked(openDatabaseAsync).mock.results[0]?.value as
Awaited<ReturnType<typeof openDatabaseAsync>> | undefined;
expect(db?.getFirstAsync).toHaveBeenCalledWith('SELECT 1 AS ready');
view.unmount();
await waitFor(() => expect(db?.closeAsync).toHaveBeenCalled());
});
it('shows an error and opens the database again when retrying', async () => {
const user = userEvent.setup();
const errorLog = jest.spyOn(console, 'error').mockImplementation(() => {});
jest.mocked(openDatabaseAsync).mockRejectedValueOnce(new Error('Storage unavailable'));
try {
render(<DatabaseProvider><Text>Application ready</Text></DatabaseProvider>);
expect(await screen.findByRole('alert')).toHaveTextContent('Could not open local storage. Please try again.');
expect(screen.queryByText('Application ready')).toBeNull();
await user.press(screen.getByRole('button', { name: 'Try again' }));
expect(await screen.findByText('Application ready')).toBeVisible();
expect(screen.queryByRole('alert')).toBeNull();
} finally {
errorLog.mockRestore();
}
});
});
+411
View File
@@ -0,0 +1,411 @@
import { jest } from '@jest/globals';
import { userEvent } from '@testing-library/react-native';
import { renderRouter, screen } from 'expo-router/testing-library';
import RootLayout from '../app/_layout';
import HomeScreen from '../app/index';
jest.mock('expo-sqlite', () => ({
openDatabaseAsync: jest.fn(async () => ({
getFirstAsync: jest.fn(async () => ({ ready: 1 })),
closeAsync: jest.fn(async () => {}),
})),
}));
async function renderHomeWithExamples(user: ReturnType<typeof userEvent.setup>) {
renderRouter(
{ _layout: RootLayout, index: HomeScreen },
{ initialUrl: '/' },
);
await screen.findByRole('header', { name: 'Recyvio' });
const examples = [
{ name: 'Example subscription', amount: '10.00', currency: 'USD', interval: 'Monthly' },
{ name: 'Cloud storage', amount: '24.00', currency: 'EUR', interval: 'Yearly' },
{ name: 'Fitness membership', amount: '30.00', currency: 'GEL', interval: 'Monthly' },
];
for (const example of examples) {
await user.type(screen.getByLabelText('Subscription name'), example.name);
await user.type(screen.getByLabelText('Amount'), example.amount);
await user.press(screen.getByRole('radio', { name: example.currency }));
await user.press(screen.getByRole('radio', { name: example.interval }));
await user.press(screen.getByRole('button', { name: 'Add subscription' }));
}
}
describe('Home route', () => {
it('opens the root route with an empty list and blank amount', async () => {
renderRouter(
{ _layout: RootLayout, index: HomeScreen },
{ initialUrl: '/' },
);
expect(await screen.findByRole('header', { name: 'Recyvio' })).toBeVisible();
expect(screen).toHavePathname('/');
expect(screen.getByRole('header', { name: 'No subscriptions yet' })).toBeVisible();
expect(screen.getByText('Add your first subscription above.')).toBeVisible();
expect(screen.getByLabelText('Subscription name')).toHaveDisplayValue('');
expect(screen.getByLabelText('Amount')).toHaveDisplayValue('');
expect(screen.getByRole('button', { name: 'Add subscription' })).toBeDisabled();
expect(screen.queryAllByRole('button', { name: /^Edit |^Delete / })).toHaveLength(0);
const user = userEvent.setup();
await user.type(screen.getByLabelText('Subscription name'), 'Music plan');
expect(screen.getByRole('button', { name: 'Add subscription' })).toBeDisabled();
await user.type(screen.getByLabelText('Amount'), '12.50');
await user.press(screen.getByRole('button', { name: 'Add subscription' }));
expect(screen.getByRole('header', { name: 'Music plan' })).toBeVisible();
expect(screen.getByText('12.50 USD')).toBeVisible();
expect(screen.queryByText('No subscriptions yet')).toBeNull();
expect(screen.getByLabelText('Amount')).toHaveDisplayValue('');
});
it('adds subscriptions with trimmed names and clears the input', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
const addButton = await screen.findByRole('button', { name: 'Add subscription' });
const nameInput = screen.getByLabelText('Subscription name');
await user.type(nameInput, ' Music plan ');
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.press(addButton);
expect(screen.getByRole('header', { name: 'Music plan' })).toHaveTextContent(/^Music plan$/);
expect(nameInput).toHaveDisplayValue('');
expect(screen.getAllByText('10.00 USD')).toHaveLength(2);
expect(screen.getAllByText('Monthly')).toHaveLength(4);
await user.type(nameInput, 'Video plan');
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.press(addButton);
expect(screen.getByRole('header', { name: 'Music plan' })).toBeVisible();
expect(screen.getByRole('header', { name: 'Video plan' })).toBeVisible();
expect(nameInput).toHaveDisplayValue('');
expect(screen.getAllByText('10.00 USD')).toHaveLength(3);
expect(screen.getAllByText('Monthly')).toHaveLength(5);
expect(screen.getByRole('header', { name: 'Cloud storage' })).toBeVisible();
expect(screen.getByRole('header', { name: 'Fitness membership' })).toBeVisible();
});
it('deletes the selected subscription and keeps the others', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await user.press(await screen.findByRole('button', { name: 'Delete Cloud storage' }));
expect(screen.queryByRole('header', { name: 'Cloud storage' })).toBeNull();
expect(screen.getByRole('header', { name: 'Example subscription' })).toBeVisible();
expect(screen.getByRole('header', { name: 'Fitness membership' })).toBeVisible();
});
it('deletes duplicate names independently and keeps IDs unique after adding again', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
const addButton = await screen.findByRole('button', { name: 'Add subscription' });
const nameInput = screen.getByLabelText('Subscription name');
await user.type(nameInput, 'Music plan');
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.press(addButton);
await user.type(nameInput, 'Music plan');
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.press(addButton);
expect(screen.getAllByRole('header', { name: 'Music plan' })).toHaveLength(2);
const [firstDeleteButton] = screen.getAllByRole('button', { name: 'Delete Music plan' });
if (!firstDeleteButton) {
throw new Error('Expected a delete button for Music plan');
}
await user.press(firstDeleteButton);
expect(screen.getAllByRole('header', { name: 'Music plan' })).toHaveLength(1);
await user.type(nameInput, 'Video plan');
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.press(addButton);
await user.press(screen.getByRole('button', { name: 'Delete Music plan' }));
expect(screen.queryByRole('header', { name: 'Music plan' })).toBeNull();
expect(screen.getByRole('header', { name: 'Video plan' })).toBeVisible();
expect(screen.getByRole('header', { name: 'Cloud storage' })).toBeVisible();
});
it('shows an empty state after deleting all subscriptions and hides it after adding one', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await screen.findByRole('header', { name: 'Recyvio' });
expect(screen.queryByText('No subscriptions yet')).toBeNull();
await user.press(screen.getByRole('button', { name: 'Delete Example subscription' }));
await user.press(screen.getByRole('button', { name: 'Delete Cloud storage' }));
expect(screen.queryByText('No subscriptions yet')).toBeNull();
await user.press(screen.getByRole('button', { name: 'Delete Fitness membership' }));
expect(screen.getByRole('header', { name: 'No subscriptions yet' })).toBeVisible();
expect(screen.getByText('Add your first subscription above.')).toBeVisible();
expect(screen.queryAllByRole('button', { name: /^Delete / })).toHaveLength(0);
await user.type(screen.getByLabelText('Subscription name'), 'Music plan');
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.press(screen.getByRole('button', { name: 'Add subscription' }));
expect(screen.getByRole('header', { name: 'Music plan' })).toBeVisible();
expect(screen.queryByText('No subscriptions yet')).toBeNull();
expect(screen.queryByText('Add your first subscription above.')).toBeNull();
});
it('edits a name without adding a card or changing its price and interval', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await user.press(await screen.findByRole('button', { name: 'Edit Cloud storage' }));
const nameInput = screen.getByLabelText('Subscription name');
expect(nameInput).toHaveDisplayValue('Cloud storage');
await user.clear(nameInput);
await user.type(nameInput, ' Cloud backup ');
expect(screen.getByRole('header', { name: 'Cloud storage' })).toBeVisible();
await user.press(screen.getByRole('button', { name: 'Save changes' }));
expect(screen.queryByRole('header', { name: 'Cloud storage' })).toBeNull();
expect(screen.getByRole('header', { name: 'Cloud backup' })).toHaveTextContent(/^Cloud backup$/);
expect(screen.getByText('24.00 EUR')).toBeVisible();
expect(screen.getAllByText('Yearly')).toHaveLength(2);
expect(screen.getAllByRole('header')).toHaveLength(4);
expect(screen.getByRole('header', { name: 'Example subscription' })).toBeVisible();
expect(screen.getByRole('header', { name: 'Fitness membership' })).toBeVisible();
expect(nameInput).toHaveDisplayValue('');
expect(screen.getByRole('button', { name: 'Add subscription' })).toBeDisabled();
expect(screen.queryByRole('button', { name: 'Cancel' })).toBeNull();
});
it('cancels editing without changing the subscription', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await user.press(await screen.findByRole('button', { name: 'Edit Cloud storage' }));
const nameInput = screen.getByLabelText('Subscription name');
await user.clear(nameInput);
await user.type(nameInput, 'Unsaved name');
expect(screen.getByRole('radio', { name: 'EUR' })).toBeChecked();
await user.press(screen.getByRole('radio', { name: 'GEL' }));
await user.press(screen.getByRole('radio', { name: 'Monthly' }));
await user.press(screen.getByRole('button', { name: 'Cancel' }));
expect(screen.getByRole('header', { name: 'Cloud storage' })).toBeVisible();
expect(screen.queryByRole('header', { name: 'Unsaved name' })).toBeNull();
expect(nameInput).toHaveDisplayValue('');
expect(screen.getByRole('button', { name: 'Add subscription' })).toBeDisabled();
expect(screen.getByRole('radio', { name: 'Monthly' })).toBeChecked();
expect(screen.getByRole('radio', { name: 'USD' })).toBeChecked();
expect(screen.getByText('24.00 EUR')).toBeVisible();
await user.press(screen.getByRole('button', { name: 'Edit Cloud storage' }));
expect(screen.getByRole('radio', { name: 'Yearly' })).toBeChecked();
expect(screen.getByRole('radio', { name: 'EUR' })).toBeChecked();
});
it('adds subscriptions in each supported currency and resets the selection', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await screen.findByRole('header', { name: 'Recyvio' });
expect(screen.getByRole('radio', { name: 'USD' })).toBeChecked();
for (const currency of ['USD', 'EUR', 'GEL']) {
await user.type(screen.getByLabelText('Subscription name'), `${currency} plan`);
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.press(screen.getByRole('radio', { name: currency }));
expect(screen.getByRole('radio', { name: currency })).toBeChecked();
await user.press(screen.getByRole('button', { name: 'Add subscription' }));
expect(screen.getByRole('header', { name: `${currency} plan` })).toBeVisible();
expect(screen.getAllByText(`10.00 ${currency}`)).toHaveLength(currency === 'USD' ? 2 : 1);
expect(screen.getByRole('radio', { name: 'USD' })).toBeChecked();
}
});
it('edits currency without converting the amount or changing other subscriptions', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await user.press(await screen.findByRole('button', { name: 'Edit Cloud storage' }));
expect(screen.getByRole('radio', { name: 'EUR' })).toBeChecked();
await user.press(screen.getByRole('radio', { name: 'GEL' }));
expect(screen.getByText('24.00 EUR')).toBeVisible();
await user.press(screen.getByRole('button', { name: 'Save changes' }));
expect(screen.queryByText('24.00 EUR')).toBeNull();
expect(screen.getByText('24.00 GEL')).toBeVisible();
expect(screen.getByText('10.00 USD')).toBeVisible();
expect(screen.getByText('30.00 GEL')).toBeVisible();
expect(screen.getAllByText('Yearly')).toHaveLength(2);
expect(screen.getAllByRole('header')).toHaveLength(4);
expect(screen.getByRole('radio', { name: 'USD' })).toBeChecked();
await user.press(screen.getByRole('button', { name: 'Edit Cloud storage' }));
expect(screen.getByRole('radio', { name: 'GEL' })).toBeChecked();
});
it('adds and edits the selected billing interval and resets the form after saving', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await screen.findByRole('header', { name: 'Recyvio' });
expect(screen.getByRole('radio', { name: 'Monthly' })).toBeChecked();
await user.type(screen.getByLabelText('Subscription name'), 'Music plan');
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.press(screen.getByRole('radio', { name: 'Yearly' }));
expect(screen.getByRole('radio', { name: 'Yearly' })).toBeChecked();
expect(screen.getByRole('radio', { name: 'Monthly' })).not.toBeChecked();
await user.press(screen.getByRole('button', { name: 'Add subscription' }));
expect(screen.getByRole('header', { name: 'Music plan' })).toBeVisible();
expect(screen.getAllByText('Yearly')).toHaveLength(3);
expect(screen.getByRole('radio', { name: 'Monthly' })).toBeChecked();
await user.press(screen.getByRole('button', { name: 'Edit Music plan' }));
expect(screen.getByRole('radio', { name: 'Yearly' })).toBeChecked();
await user.press(screen.getByRole('radio', { name: 'Monthly' }));
await user.press(screen.getByRole('button', { name: 'Save changes' }));
expect(screen.getAllByText('Yearly')).toHaveLength(2);
expect(screen.getAllByText('Monthly')).toHaveLength(4);
expect(screen.getAllByRole('header')).toHaveLength(5);
await user.press(screen.getByRole('button', { name: 'Edit Music plan' }));
expect(screen.getByRole('radio', { name: 'Monthly' })).toBeChecked();
});
it('rejects empty and whitespace-only names when editing', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await user.press(await screen.findByRole('button', { name: 'Edit Cloud storage' }));
const nameInput = screen.getByLabelText('Subscription name');
await user.clear(nameInput);
const saveButton = screen.getByRole('button', { name: 'Save changes' });
expect(saveButton).toBeDisabled();
await user.press(saveButton);
await user.type(nameInput, ' ');
expect(saveButton).toBeDisabled();
await user.press(saveButton);
expect(screen.getByRole('header', { name: 'Cloud storage' })).toBeVisible();
expect(screen.getAllByRole('header')).toHaveLength(4);
});
it('returns to adding when the subscription being edited is deleted', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await user.press(await screen.findByRole('button', { name: 'Edit Cloud storage' }));
await user.press(screen.getByRole('button', { name: 'Delete Cloud storage' }));
expect(screen.getByLabelText('Subscription name')).toHaveDisplayValue('');
expect(screen.getByRole('button', { name: 'Add subscription' })).toBeDisabled();
expect(screen.queryByRole('button', { name: 'Save changes' })).toBeNull();
expect(screen.queryByRole('button', { name: 'Cancel' })).toBeNull();
await user.type(screen.getByLabelText('Subscription name'), 'Music plan');
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.press(screen.getByRole('button', { name: 'Add subscription' }));
expect(screen.getByRole('header', { name: 'Music plan' })).toBeVisible();
expect(screen.queryByRole('header', { name: 'Cloud storage' })).toBeNull();
});
it('adds and edits an amount as a decimal string', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await screen.findByRole('header', { name: 'Recyvio' });
const amountInput = screen.getByLabelText('Amount');
await user.type(screen.getByLabelText('Subscription name'), 'Music plan');
await user.type(screen.getByLabelText('Amount'), '10.00');
await user.clear(amountInput);
await user.type(amountInput, ' 12.50 ');
await user.press(screen.getByRole('radio', { name: 'EUR' }));
await user.press(screen.getByRole('button', { name: 'Add subscription' }));
expect(screen.getByText('12.50 EUR')).toBeVisible();
expect(amountInput).toHaveDisplayValue('');
await user.press(screen.getByRole('button', { name: 'Edit Music plan' }));
expect(amountInput).toHaveDisplayValue('12.50');
await user.clear(amountInput);
await user.type(amountInput, '15.5');
await user.press(screen.getByRole('button', { name: 'Save changes' }));
expect(screen.getByText('15.5 EUR')).toBeVisible();
expect(screen.queryByText('12.50 EUR')).toBeNull();
expect(screen.getByText('24.00 EUR')).toBeVisible();
expect(screen.getAllByRole('header')).toHaveLength(5);
});
it('blocks invalid amounts when adding and editing, and clears the error after correction', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await screen.findByRole('header', { name: 'Recyvio' });
const amountInput = screen.getByLabelText('Amount');
await user.type(screen.getByLabelText('Subscription name'), 'Music plan');
await user.type(screen.getByLabelText('Amount'), '10.00');
const addButton = screen.getByRole('button', { name: 'Add subscription' });
for (const invalidAmount of ['', '0', '-5', '10.001']) {
await user.clear(amountInput);
if (invalidAmount) {
await user.type(amountInput, invalidAmount);
}
expect(screen.getByRole('alert')).toBeVisible();
expect(addButton).toBeDisabled();
await user.press(addButton);
expect(screen.queryByRole('header', { name: 'Music plan' })).toBeNull();
}
await user.press(screen.getByRole('button', { name: 'Edit Cloud storage' }));
expect(amountInput).toHaveDisplayValue('24.00');
expect(screen.queryByRole('alert')).toBeNull();
await user.clear(amountInput);
await user.type(amountInput, '0.00');
const saveButton = screen.getByRole('button', { name: 'Save changes' });
expect(saveButton).toBeDisabled();
await user.press(saveButton);
expect(screen.getByText('24.00 EUR')).toBeVisible();
await user.clear(amountInput);
await user.type(amountInput, '0.01');
expect(saveButton).toBeEnabled();
expect(screen.queryByRole('alert')).toBeNull();
await user.press(saveButton);
expect(screen.getByText('0.01 EUR')).toBeVisible();
});
it('discards amount changes when editing is cancelled', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
await user.press(await screen.findByRole('button', { name: 'Edit Cloud storage' }));
const amountInput = screen.getByLabelText('Amount');
expect(amountInput).toHaveDisplayValue('24.00');
await user.clear(amountInput);
await user.type(amountInput, '50.00');
await user.press(screen.getByRole('button', { name: 'Cancel' }));
expect(screen.getByText('24.00 EUR')).toBeVisible();
expect(screen.queryByText('50.00 EUR')).toBeNull();
expect(amountInput).toHaveDisplayValue('');
await user.press(screen.getByRole('button', { name: 'Edit Cloud storage' }));
expect(amountInput).toHaveDisplayValue('24.00');
});
it('does not add subscriptions with empty or whitespace-only names', async () => {
const user = userEvent.setup();
await renderHomeWithExamples(user);
const addButton = await screen.findByRole('button', { name: 'Add subscription' });
expect(addButton).toBeDisabled();
await user.press(addButton);
expect(screen.getAllByRole('header')).toHaveLength(4);
await user.type(screen.getByLabelText('Subscription name'), ' ');
await user.type(screen.getByLabelText('Amount'), '10.00');
expect(addButton).toBeDisabled();
await user.press(addButton);
expect(screen.getAllByRole('header')).toHaveLength(4);
});
});
+16
View File
@@ -0,0 +1,16 @@
import { Slot } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { DatabaseProvider } from '../data/DatabaseProvider';
export default function RootLayout() {
return (
<SafeAreaProvider>
<StatusBar style="auto" />
<DatabaseProvider>
<Slot />
</DatabaseProvider>
</SafeAreaProvider>
);
}
+239
View File
@@ -0,0 +1,239 @@
import { useRef, useState } from 'react';
import { Button, Pressable, ScrollView, StyleSheet, Text, TextInput, useColorScheme, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { SubscriptionCard } from '../features/subscriptions/components/SubscriptionCard';
import { billingIntervals, currencies } from '../features/subscriptions/model/Subscription';
import type { BillingInterval, Currency, Subscription } from '../features/subscriptions/model/Subscription';
import { isValidAmount } from '../features/subscriptions/validation/isValidAmount';
export default function HomeScreen() {
const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
const [subscriptionName, setSubscriptionName] = useState('');
const [amount, setAmount] = useState('');
const [billingInterval, setBillingInterval] = useState<BillingInterval>('Monthly');
const [currency, setCurrency] = useState<Currency>('USD');
const [editingId, setEditingId] = useState<string | null>(null);
const nameInput = useRef<TextInput>(null);
const nextSubscriptionId = useRef(1);
const amountIsValid = isValidAmount(amount);
const isDark = useColorScheme() === 'dark';
const colors = isDark
? { background: '#101720', surface: '#1b2633', text: '#f1f5f9', muted: '#b5c3d2' }
: { background: '#f4f7fa', surface: '#ffffff', text: '#162332', muted: '#4c6074' };
function resetForm() {
setSubscriptionName('');
setAmount('');
setBillingInterval('Monthly');
setCurrency('USD');
setEditingId(null);
}
function editSubscription(subscription: Subscription) {
setEditingId(subscription.id);
setSubscriptionName(subscription.name);
setAmount(subscription.amountLabel);
setBillingInterval(subscription.billingIntervalLabel);
setCurrency(subscription.currency);
nameInput.current?.focus();
}
function saveSubscription() {
const name = subscriptionName.trim();
if (!name || !amountIsValid) {
return;
}
if (editingId !== null) {
setSubscriptions((currentSubscriptions) =>
currentSubscriptions.map((subscription) =>
subscription.id === editingId
? { ...subscription, name, amountLabel: amount.trim(), currency, billingIntervalLabel: billingInterval }
: subscription,
),
);
resetForm();
return;
}
const id = `new-subscription-${nextSubscriptionId.current}`;
nextSubscriptionId.current += 1;
setSubscriptions((currentSubscriptions) => [
...currentSubscriptions,
{
id,
name,
amountLabel: amount.trim(),
currency,
billingIntervalLabel: billingInterval,
},
]);
resetForm();
}
function deleteSubscription(id: string) {
setSubscriptions((currentSubscriptions) =>
currentSubscriptions.filter((subscription) => subscription.id !== id),
);
if (editingId === id) {
resetForm();
}
}
return (
<SafeAreaView style={[styles.screen, { backgroundColor: colors.background }]}>
<ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
<View style={[styles.card, { backgroundColor: colors.surface }]}>
<Text accessibilityRole="header" style={[styles.title, { color: colors.text }]}>
Recyvio
</Text>
<Text style={[styles.subtitle, { color: colors.text }]}>
All your subscriptions in one place
</Text>
<View style={styles.form}>
<Text style={[styles.label, { color: colors.text }]}>Subscription name</Text>
<TextInput
ref={nameInput}
accessibilityLabel="Subscription name"
value={subscriptionName}
onChangeText={setSubscriptionName}
style={[
styles.input,
{ color: colors.text, borderColor: colors.muted, backgroundColor: colors.background },
]}
/>
<Text style={[styles.label, { color: colors.text }]}>Amount</Text>
<TextInput
accessibilityLabel="Amount"
accessibilityHint="Enter a positive amount using a decimal point and up to two decimal places."
value={amount}
onChangeText={setAmount}
keyboardType="decimal-pad"
style={[
styles.input,
{ color: colors.text, borderColor: colors.muted, backgroundColor: colors.background },
]}
/>
{!amountIsValid && (
<Text accessibilityRole="alert" style={[styles.emptyDescription, { color: colors.text }]}>
Enter an amount greater than zero, using a decimal point and up to two decimal places.
</Text>
)}
<Text style={[styles.label, { color: colors.text }]}>Currency</Text>
<View accessibilityRole="radiogroup" accessibilityLabel="Currency" style={styles.intervals}>
{currencies.map((option) => (
<Pressable
key={option}
accessibilityRole="radio"
accessibilityState={{ checked: currency === option }}
onPress={() => setCurrency(option)}
style={[
styles.intervalOption,
{
borderColor: colors.muted,
backgroundColor: currency === option ? colors.text : colors.background,
},
]}
>
<Text style={{ color: currency === option ? colors.background : colors.text }}>
{option}
</Text>
</Pressable>
))}
</View>
<Text style={[styles.label, { color: colors.text }]}>Billing interval</Text>
<View accessibilityRole="radiogroup" accessibilityLabel="Billing interval" style={styles.intervals}>
{billingIntervals.map((interval) => (
<Pressable
key={interval}
accessibilityRole="radio"
accessibilityState={{ checked: billingInterval === interval }}
onPress={() => setBillingInterval(interval)}
style={[
styles.intervalOption,
{
borderColor: colors.muted,
backgroundColor: billingInterval === interval ? colors.text : colors.background,
},
]}
>
<Text style={{ color: billingInterval === interval ? colors.background : colors.text }}>
{interval}
</Text>
</Pressable>
))}
</View>
<Button
title={editingId === null ? 'Add subscription' : 'Save changes'}
onPress={saveSubscription}
disabled={!subscriptionName.trim() || !amountIsValid}
/>
{editingId !== null && <Button title="Cancel" onPress={resetForm} />}
</View>
{subscriptions.length === 0 && (
<View style={styles.emptyState}>
<Text accessibilityRole="header" style={[styles.label, { color: colors.text }]}>
No subscriptions yet
</Text>
<Text style={[styles.emptyDescription, { color: colors.muted }]}>
Add your first subscription above.
</Text>
</View>
)}
{subscriptions.map((subscription) => (
<SubscriptionCard
key={subscription.id}
name={subscription.name}
priceLabel={`${subscription.amountLabel} ${subscription.currency}`}
billingIntervalLabel={subscription.billingIntervalLabel}
colors={colors}
onDelete={() => deleteSubscription(subscription.id)}
onEdit={() => editSubscription(subscription)}
/>
))}
</View>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
screen: { flex: 1 },
content: {
flexGrow: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 24,
},
card: {
width: '100%',
maxWidth: 560,
borderRadius: 24,
padding: 32,
gap: 16,
},
title: { fontSize: 36, fontWeight: '700' },
subtitle: { fontSize: 22, fontWeight: '600' },
form: { gap: 8 },
intervals: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
intervalOption: {
minHeight: 48,
paddingHorizontal: 16,
justifyContent: 'center',
borderWidth: 1,
borderRadius: 8,
},
emptyState: { gap: 8, paddingVertical: 20 },
emptyDescription: { fontSize: 16, lineHeight: 24 },
label: { fontSize: 16, fontWeight: '600' },
input: {
borderWidth: 1,
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 12,
fontSize: 16,
minHeight: 48,
},
});
+69
View File
@@ -0,0 +1,69 @@
import { openDatabaseAsync } from 'expo-sqlite';
import type { SQLiteDatabase } from 'expo-sqlite';
import { createContext, useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { Button, StyleSheet, Text, useColorScheme, View } from 'react-native';
export const DatabaseContext = createContext<SQLiteDatabase | null>(null);
async function openDatabase() {
const database = await openDatabaseAsync('recyvio.db');
try {
await database.getFirstAsync('SELECT 1 AS ready');
return database;
} catch (error) {
await database.closeAsync();
throw error;
}
}
export function DatabaseProvider({ children }: { children: ReactNode }) {
const [database, setDatabase] = useState<SQLiteDatabase | null>(null);
const [failed, setFailed] = useState(false);
const [attempt, setAttempt] = useState(0);
const isDark = useColorScheme() === 'dark';
useEffect(() => {
let active = true;
const connection = openDatabase();
connection.then(
(db) => {
if (active) {
setDatabase(db);
}
},
(error: unknown) => {
if (active) {
console.error('Could not open the local database.', error);
setFailed(true);
}
},
);
return () => {
active = false;
void connection.then((db) => db.closeAsync(), () => {}).catch(console.error);
};
}, [attempt]);
if (!database) {
return (
<View style={[styles.status, { backgroundColor: isDark ? '#101720' : '#f4f7fa' }]}>
<Text accessibilityRole={failed ? 'alert' : undefined} style={{ color: isDark ? '#f1f5f9' : '#162332' }}>
{failed ? 'Could not open local storage. Please try again.' : 'Loading your subscriptions...'}
</Text>
{failed && (
<Button title="Try again" onPress={() => {
setFailed(false);
setAttempt((current) => current + 1);
}} />
)}
</View>
);
}
return <DatabaseContext.Provider value={database}>{children}</DatabaseContext.Provider>;
}
const styles = StyleSheet.create({
status: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 24, gap: 16 },
});
@@ -0,0 +1,46 @@
import { Button, StyleSheet, Text, View } from 'react-native';
type SubscriptionCardProps = {
name: string;
priceLabel: string;
billingIntervalLabel: string;
onDelete: () => void;
onEdit: () => void;
colors: {
background: string;
text: string;
muted: string;
};
};
export function SubscriptionCard({
name,
priceLabel,
billingIntervalLabel,
colors,
onDelete,
onEdit,
}: SubscriptionCardProps) {
return (
<View style={[styles.card, { backgroundColor: colors.background }]}>
<Text accessibilityRole="header" style={[styles.name, { color: colors.text }]}>
{name}
</Text>
<Text style={[styles.price, { color: colors.text }]}>{priceLabel}</Text>
<Text style={[styles.interval, { color: colors.muted }]}>{billingIntervalLabel}</Text>
<Button title="Edit" accessibilityLabel={`Edit ${name}`} onPress={onEdit} />
<Button title="Delete" accessibilityLabel={`Delete ${name}`} onPress={onDelete} />
</View>
);
}
const styles = StyleSheet.create({
card: {
borderRadius: 16,
padding: 20,
gap: 8,
},
name: { fontSize: 20, fontWeight: '600' },
price: { fontSize: 18, fontWeight: '600' },
interval: { fontSize: 16 },
});
@@ -0,0 +1,13 @@
export const billingIntervals = ['Monthly', 'Yearly'] as const;
export type BillingInterval = (typeof billingIntervals)[number];
export const currencies = ['USD', 'EUR', 'GEL'] as const;
export type Currency = (typeof currencies)[number];
export type Subscription = {
id: string;
name: string;
amountLabel: string;
currency: Currency;
billingIntervalLabel: BillingInterval;
};
@@ -0,0 +1,10 @@
import type { Subscription } from './Subscription';
export interface SubscriptionRepository {
getAll(): Promise<Subscription[]>;
/** Adds a subscription or updates the existing record with the same ID. */
save(subscription: Subscription): Promise<void>;
delete(id: string): Promise<void>;
}
@@ -0,0 +1,4 @@
export function isValidAmount(value: string): boolean {
const amount = value.trim();
return /^\d+(?:\.\d{1,2})?$/.test(amount) && /[1-9]/.test(amount);
}
+12
View File
@@ -0,0 +1,12 @@
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noFallthroughCasesInSwitch": true
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}