diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index b9541d9..95862ca 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -5,7 +5,7 @@ Settle ships as two images built from `docker/Dockerfile`, run with Docker Compo - `ghcr.io/ame180/settle-php` (`prod` target): PHP-FPM with the app, vendor dependencies and the built frontend. Applies migrations on start. - `ghcr.io/ame180/settle-web` (`web` target): nginx serving `public/` and passing PHP requests to the `php` service. -`deploy/compose.yaml` runs both with MariaDB. TLS and the public hostname come from a reverse proxy in front of `web`. +`deploy/compose.yaml` runs both with MariaDB, plus a `scheduler` service on the php image (see [Scheduled jobs](#scheduled-jobs)). TLS and the public hostname come from a reverse proxy in front of `web`. | Environment | Deployed by | Image tag | | --- | --- | --- | @@ -137,6 +137,8 @@ On the server, point `IMAGE_TAG` in `.env` at an earlier tag and restart: cd ~/settle-staging && sed -i 's/^IMAGE_TAG=.*/IMAGE_TAG=v0.1.0/' .env && docker compose up -d --wait ``` +v0.1.0 has no `scheduler`, so it restarts in a loop on that image. When rolling back to it, add `--scale scheduler=0` to the `up` command above and to any later `up` until the next deploy. + Rolling back code does not roll back the database. Migrations run on every start of `php`, so they must stay backward-compatible: the previous release has to work against the newer schema. A failing migration keeps `php` restarting (and `web` waiting) until it is fixed or rolled back. ## Backups @@ -152,14 +154,28 @@ docker compose exec -T mariadb sh -c 'mariadb-dump -uroot -p"$MARIADB_ROOT_PASSW To restore a dump (from that command or the nightly backups), stop the app so nothing writes, empty the database, load the dump and start again: ```bash -docker compose stop web php +docker compose stop web scheduler php docker compose exec -T mariadb sh -c 'mariadb -uroot -p"$MARIADB_ROOT_PASSWORD" -e "DROP DATABASE \`$MARIADB_DATABASE\`; CREATE DATABASE \`$MARIADB_DATABASE\`"' gunzip -c .sql.gz | docker compose exec -T mariadb sh -c 'mariadb -uroot -p"$MARIADB_ROOT_PASSWORD" "$MARIADB_DATABASE"' -docker compose start php web +docker compose start php scheduler web ``` On start, `php` applies any migrations newer than the dump, as on a deploy. +## Scheduled jobs + +The `scheduler` service creates repeating expenses when they fall due. It runs `bin/console app:recurring:run` once on start, then `messenger:consume scheduler_default`, which runs the same job every hour. Each run creates every occurrence that is due, including ones missed while the service was down, each dated on its own schedule date, so stopping it only delays them. It doesn't run migrations; it starts once `php` is healthy. + +Dates follow the container's timezone, UTC, so an occurrence due on a given day appears within an hour after midnight UTC. + +To use a host cron instead, remove the service and run the job from the environment's directory, hourly or more often: + +```bash +docker compose exec -T php bin/console app:recurring:run +``` + +Runs are safe to overlap, so a manual run alongside the service creates nothing twice. + ## Adding users Sign-up claims the account of anyone a user added as a contact by email, without checking that the email belongs to the person signing up. So public sign-up is off unless enabled: `POST /api/register` answers 403 and the app hides its sign-up link. Set `APP_REGISTRATION_ENABLED=1` in the server's `.env` only where that's acceptable, such as a private staging host. @@ -176,7 +192,7 @@ If someone already added them as a contact, this claims that account, so their s All commands run in the environment's directory. -- Status and logs: `docker compose ps`, `docker compose logs -f php` +- Status and logs: `docker compose ps`, `docker compose logs -f php` (`scheduler` for repeating expenses) - Stop and start (e.g. staging between test sessions): `docker compose stop`, `docker compose start` - Reset the staging database (after a branch's migrations left it out of step): diff --git a/README.md b/README.md index b0a8c43..4f0f6a1 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Expense sharing for ad-hoc groups of friends. Symfony 7.4 JSON API plus a React 1. Copy `.env.example` to `.env` and fill in the values. 2. `docker login ghcr.io -u -p ` (nginx/mariadb images live there). -3. `docker compose up -d` starts PHP, nginx (port `NGINX_PORT`, default 80) and the database. The PHP container installs Composer dependencies and runs migrations on start. +3. `docker compose up -d` starts PHP, nginx (port `NGINX_PORT`, default 80), the database and the `scheduler` that creates repeating expenses. The PHP container installs Composer dependencies and runs migrations on start; restart `scheduler` to pick up code changes. 4. Create a user: `docker compose exec php bin/console app:user:create `. 5. Frontend: `cd frontend && npm install && npm run dev`, then open http://localhost:5173. The Vite dev server proxies `/api` to nginx (override with `VITE_API_PROXY`). diff --git a/compose.yaml b/compose.yaml index 12d573d..f4756a8 100644 --- a/compose.yaml +++ b/compose.yaml @@ -9,10 +9,32 @@ services: - .:/app env_file: .env entrypoint: docker/entrypoint.sh + # php-fpm only listens once dependencies are installed and migrations have run. + healthcheck: + test: ["CMD", "php", "-r", "exit(@fsockopen('127.0.0.1', 9000) ? 0 : 1);"] + start_period: 300s + interval: 10s + timeout: 5s + retries: 3 depends_on: mysql: condition: service_healthy + # Long-running: restart it to pick up code changes. + scheduler: + build: + context: . + dockerfile: docker/Dockerfile + target: base + volumes: + - .:/app + env_file: .env + entrypoint: ["sh", "-c", "bin/console app:recurring:run && exec bin/console messenger:consume scheduler_default --memory-limit=128M"] + restart: unless-stopped + depends_on: + php: + condition: service_healthy + nginx: image: ghcr.io/ame180/nginx-php:latest environment: diff --git a/composer.json b/composer.json index c3067f4..9520203 100644 --- a/composer.json +++ b/composer.json @@ -14,6 +14,7 @@ "doctrine/orm": "^3.8.0", "phpdocumentor/reflection-docblock": "^5.6.7", "phpstan/phpdoc-parser": "^2.4.1", + "symfony/clock": "7.4.*", "symfony/console": "7.4.*", "symfony/doctrine-messenger": "7.4.*", "symfony/dotenv": "7.4.*", @@ -31,6 +32,7 @@ "symfony/property-info": "7.4.*", "symfony/rate-limiter": "7.4.*", "symfony/runtime": "7.4.*", + "symfony/scheduler": "7.4.*", "symfony/security-bundle": "7.4.*", "symfony/serializer": "7.4.*", "symfony/string": "7.4.*", diff --git a/composer.lock b/composer.lock index 50af1a1..474fc28 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "570dd79b058a0ab462ec347ac4507f1a", + "content-hash": "90b574720a733e727081bb3c5d7d91d6", "packages": [ { "name": "doctrine/collections", @@ -5733,6 +5733,92 @@ "time": "2026-11-01T08:32:25+00:00", "published-time": "2026-11-04T11:28:46+00:00" }, + { + "name": "symfony/scheduler", + "version": "v7.4.22", + "source": { + "type": "git", + "url": "https://github.com/symfony/scheduler.git", + "reference": "1d5bd2461087b5658484186a469f80b49093fb4c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/scheduler/zipball/1d5bd2461087b5658484186a469f80b49093fb4c", + "reference": "1d5bd2461087b5658484186a469f80b49093fb4c", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "symfony/clock": "^6.4|^7.0|^8.0" + }, + "require-dev": { + "dragonmantank/cron-expression": "^3.1", + "symfony/cache": "^6.4.36|^7.4.8|^8.0.8", + "symfony/console": "^6.4|^7.0|^8.0", + "symfony/dependency-injection": "^6.4|^7.0|^8.0", + "symfony/event-dispatcher": "^6.4|^7.0|^8.0", + "symfony/lock": "^6.4|^7.0|^8.0", + "symfony/messenger": "^6.4|^7.0|^8.0", + "symfony/serializer": "^6.4|^7.1|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Scheduler\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Sergey Rabochiy", + "email": "upyx.00@gmail.com" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides scheduling through Symfony Messenger", + "homepage": "https://symfony.com", + "keywords": [ + "cron", + "schedule", + "scheduler" + ], + "support": { + "source": "https://github.com/symfony/scheduler/tree/v7.4.22" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-10-26T21:52:50+00:00", + "published-time": "2026-10-28T18:21:21+00:00" + }, { "name": "symfony/security-bundle", "version": "v7.4.23", diff --git a/config/packages/messenger.yaml b/config/packages/messenger.yaml index 270f3c7..43a79ed 100644 --- a/config/packages/messenger.yaml +++ b/config/packages/messenger.yaml @@ -18,7 +18,10 @@ framework: default_bus: messenger.bus.default buses: - messenger.bus.default: [] + # The scheduler worker idles between hourly ticks, long enough for the DB to drop the connection. + messenger.bus.default: + middleware: + - doctrine_ping_connection routing: Symfony\Component\Mailer\Messenger\SendEmailMessage: async diff --git a/config/reference.php b/config/reference.php index 47141e6..0dba400 100644 --- a/config/reference.php +++ b/config/reference.php @@ -468,7 +468,7 @@ * }>, * }, * scheduler?: bool|array{ // Scheduler configuration - * enabled?: bool|Param, // Default: false + * enabled?: bool|Param, // Default: true * }, * disallow_search_engine_index?: bool|Param, // Enabled by default when debug is enabled. // Default: true * http_client?: bool|array{ // HTTP Client configuration diff --git a/deploy/compose.yaml b/deploy/compose.yaml index 1bdb986..281a45f 100644 --- a/deploy/compose.yaml +++ b/deploy/compose.yaml @@ -3,7 +3,7 @@ services: php: image: ghcr.io/ame180/settle-php:${IMAGE_TAG:?set IMAGE_TAG} # Explicit list rather than env_file, so the DB root password never reaches the app. - environment: + environment: &php-environment APP_SECRET: ${APP_SECRET:?set APP_SECRET} MYSQL_HOST: mariadb MYSQL_PORT: 3306 @@ -11,7 +11,7 @@ services: MYSQL_USER: ${MYSQL_USER:?set MYSQL_USER} MYSQL_PASSWORD: ${MYSQL_PASSWORD:?set MYSQL_PASSWORD} SYMFONY_TRUSTED_PROXIES: private_ranges - # Required by the messenger and mailer config, though nothing sends messages or mail yet. + # Required by the messenger and mailer config, though nothing queues messages or sends mail yet. MESSENGER_TRANSPORT_DSN: doctrine://default?auto_setup=0 MAILER_DSN: null://null APP_REGISTRATION_ENABLED: ${APP_REGISTRATION_ENABLED:-} @@ -29,6 +29,16 @@ services: mariadb: condition: service_healthy + # Skips the image's entrypoint, so only `php` runs migrations. + scheduler: + image: ghcr.io/ame180/settle-php:${IMAGE_TAG:?set IMAGE_TAG} + environment: *php-environment + entrypoint: ["sh", "-c", "bin/console app:recurring:run && exec bin/console messenger:consume scheduler_default --memory-limit=128M"] + restart: unless-stopped + depends_on: + php: + condition: service_healthy + web: image: ghcr.io/ame180/settle-web:${IMAGE_TAG:?set IMAGE_TAG} environment: diff --git a/migrations/Version20261126221928.php b/migrations/Version20261126221928.php new file mode 100644 index 0000000..0395e06 --- /dev/null +++ b/migrations/Version20261126221928.php @@ -0,0 +1,32 @@ +addSql("CREATE TABLE recurring_series (id INT AUTO_INCREMENT NOT NULL, unit VARCHAR(8) NOT NULL, every SMALLINT NOT NULL, anchor_on DATE NOT NULL COMMENT '(DC2Type:date_immutable)', next_run_on DATE NOT NULL COMMENT '(DC2Type:date_immutable)', active TINYINT(1) NOT NULL, created_at DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)', updated_at DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)', INDEX idx_recurring_series_due (active, next_run_on), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB"); + $this->addSql('ALTER TABLE expense ADD series_id INT DEFAULT NULL'); + $this->addSql('ALTER TABLE expense ADD CONSTRAINT FK_2D3A8DA65278319C FOREIGN KEY (series_id) REFERENCES recurring_series (id)'); + $this->addSql('CREATE INDEX IDX_2D3A8DA65278319C ON expense (series_id)'); + } + + public function down(Schema $schema): void + { + $this->addSql('ALTER TABLE expense DROP FOREIGN KEY FK_2D3A8DA65278319C'); + $this->addSql('DROP INDEX IDX_2D3A8DA65278319C ON expense'); + $this->addSql('ALTER TABLE expense DROP series_id'); + $this->addSql('DROP TABLE recurring_series'); + } +} diff --git a/src/Command/RecurringRunCommand.php b/src/Command/RecurringRunCommand.php new file mode 100644 index 0000000..2d77509 --- /dev/null +++ b/src/Command/RecurringRunCommand.php @@ -0,0 +1,34 @@ +runner->run(); + + (new SymfonyStyle($input, $output))->success(sprintf('Created %d repeating expense(s).', $created)); + + return Command::SUCCESS; + } +} diff --git a/src/Controller/Api/ExpenseApiController.php b/src/Controller/Api/ExpenseApiController.php index 98a1748..c25f958 100644 --- a/src/Controller/Api/ExpenseApiController.php +++ b/src/Controller/Api/ExpenseApiController.php @@ -108,6 +108,9 @@ private function toResponse(User $viewer, Expense $expense): ExpenseResponse $participants[] = $debt->getPayer(); } - return ExpenseResponse::fromExpense($expense, $this->personRefFactory->createMany($viewer, $participants)); + $series = $expense->getSeries(); + $seriesLatestId = null === $series ? null : $this->expenseRepository->findLatestIdInSeries($series); + + return ExpenseResponse::fromExpense($expense, $this->personRefFactory->createMany($viewer, $participants), $seriesLatestId); } } diff --git a/src/Dto/ActivityItem.php b/src/Dto/ActivityItem.php index fee3a84..e9c5b5c 100644 --- a/src/Dto/ActivityItem.php +++ b/src/Dto/ActivityItem.php @@ -21,6 +21,7 @@ public function __construct( public PersonRef $payee, public ?PersonRef $payer, public ?ExpenseCategory $category, + public bool $recurring = false, ) { } } diff --git a/src/Dto/ExpenseRequest.php b/src/Dto/ExpenseRequest.php index f2c11a4..afa9efd 100644 --- a/src/Dto/ExpenseRequest.php +++ b/src/Dto/ExpenseRequest.php @@ -41,6 +41,9 @@ public function __construct( public ExpenseCategory $category = ExpenseCategory::General, public ?string $description = null, + + #[Assert\Valid] + public ?RepeatRequest $repeat = null, ) { } } diff --git a/src/Dto/ExpenseResponse.php b/src/Dto/ExpenseResponse.php index 9da946a..3a003df 100644 --- a/src/Dto/ExpenseResponse.php +++ b/src/Dto/ExpenseResponse.php @@ -24,14 +24,18 @@ public function __construct( public SplitType $splitType, public ExpenseCategory $category, public array $debts, + public ?RepeatResponse $repeat, + public ?SeriesResponse $series, ) { } /** * @param array $people keyed by user id, must cover the payee and every debtor */ - public static function fromExpense(Expense $expense, array $people): self + public static function fromExpense(Expense $expense, array $people, ?int $seriesLatestId): self { + $series = $expense->getSeries(); + $debts = array_map( fn ($debt) => new ExpenseDebtResponse( payer: $people[$debt->getPayer()->getId()], @@ -52,6 +56,8 @@ public static function fromExpense(Expense $expense, array $people): self splitType: $expense->getSplitType(), category: $expense->getCategory(), debts: array_values($debts), + repeat: null === $series ? null : RepeatResponse::fromSeries($series), + series: null === $seriesLatestId ? null : new SeriesResponse($seriesLatestId, $seriesLatestId === $expense->getId()), ); } } diff --git a/src/Dto/RepeatRequest.php b/src/Dto/RepeatRequest.php new file mode 100644 index 0000000..bc05b5d --- /dev/null +++ b/src/Dto/RepeatRequest.php @@ -0,0 +1,36 @@ +value => [1, 2], + RepeatUnit::Month->value => [1], + RepeatUnit::Year->value => [1], + ]; + + public function __construct( + public RepeatUnit $unit, + public int $every = 1, + ) { + } + + #[Assert\Callback] + public function validateFrequency(ExecutionContextInterface $context): void + { + if (in_array($this->every, self::ALLOWED_EVERY[$this->unit->value], true)) { + return; + } + + $context->buildViolation('This repeat frequency is not supported.') + ->atPath('every') + ->addViolation(); + } +} diff --git a/src/Dto/RepeatResponse.php b/src/Dto/RepeatResponse.php new file mode 100644 index 0000000..b1402eb --- /dev/null +++ b/src/Dto/RepeatResponse.php @@ -0,0 +1,29 @@ +getUnit(), + every: $series->getEvery(), + nextOn: $series->isActive() ? $series->getNextRunOn() : null, + active: $series->isActive(), + ); + } +} diff --git a/src/Dto/SeriesResponse.php b/src/Dto/SeriesResponse.php new file mode 100644 index 0000000..9f324d5 --- /dev/null +++ b/src/Dto/SeriesResponse.php @@ -0,0 +1,14 @@ +payee = $payee; @@ -212,6 +216,18 @@ public function removeDebt(Debt $debt): static return $this; } + public function getSeries(): ?RecurringSeries + { + return $this->series; + } + + public function setSeries(?RecurringSeries $series): static + { + $this->series = $series; + + return $this; + } + public function involves(User $user): bool { if ($this->payee->isSameAs($user)) { diff --git a/src/Entity/RecurringSeries.php b/src/Entity/RecurringSeries.php new file mode 100644 index 0000000..1e63a92 --- /dev/null +++ b/src/Entity/RecurringSeries.php @@ -0,0 +1,116 @@ +unit = $unit; + $this->every = $every; + $this->anchorOn = $anchorOn; + $this->nextRunOn = $nextRunOn; + $this->createdAt = new \DateTimeImmutable(); + $this->updatedAt = new \DateTimeImmutable(); + } + + public function getId(): ?int + { + return $this->id; + } + + public function getUnit(): RepeatUnit + { + return $this->unit; + } + + public function getEvery(): int + { + return $this->every; + } + + public function getAnchorOn(): \DateTimeImmutable + { + return $this->anchorOn; + } + + public function getNextRunOn(): \DateTimeImmutable + { + return $this->nextRunOn; + } + + public function isActive(): bool + { + return $this->active; + } + + public function hasFrequency(RepeatUnit $unit, int $every): bool + { + return $this->unit === $unit && $this->every === $every; + } + + public function reschedule(RepeatUnit $unit, int $every, \DateTimeImmutable $anchorOn, \DateTimeImmutable $nextRunOn): void + { + $this->unit = $unit; + $this->every = $every; + $this->anchorOn = $anchorOn; + $this->nextRunOn = $nextRunOn; + $this->active = true; + } + + public function advanceTo(\DateTimeImmutable $nextRunOn): void + { + $this->nextRunOn = $nextRunOn; + } + + public function stop(): void + { + $this->active = false; + } + + #[ORM\PreUpdate] + public function refreshUpdatedAt(): void + { + $this->updatedAt = new \DateTimeImmutable(); + } +} diff --git a/src/Enum/RepeatUnit.php b/src/Enum/RepeatUnit.php new file mode 100644 index 0000000..0c5abf2 --- /dev/null +++ b/src/Enum/RepeatUnit.php @@ -0,0 +1,12 @@ +runner->run(); + } +} diff --git a/src/Repository/ExpenseRepository.php b/src/Repository/ExpenseRepository.php index 122e147..7db511b 100644 --- a/src/Repository/ExpenseRepository.php +++ b/src/Repository/ExpenseRepository.php @@ -6,6 +6,7 @@ use App\Entity\Debt; use App\Entity\Expense; +use App\Entity\RecurringSeries; use App\Entity\User; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; @@ -89,4 +90,19 @@ public function findLastCreatedAtByCounterpart(User $user): array return $lastCreatedAt; } + + /** + * The latest expense of a series is the one created last, whatever its date. + */ + public function findLatestIdInSeries(RecurringSeries $series): ?int + { + $latestId = $this->createQueryBuilder('e') + ->select('MAX(e.id)') + ->where('e.series = :series') + ->setParameter('series', $series) + ->getQuery() + ->getSingleScalarResult(); + + return null === $latestId ? null : (int) $latestId; + } } diff --git a/src/Repository/RecurringSeriesRepository.php b/src/Repository/RecurringSeriesRepository.php new file mode 100644 index 0000000..c81b89c --- /dev/null +++ b/src/Repository/RecurringSeriesRepository.php @@ -0,0 +1,38 @@ + + */ +class RecurringSeriesRepository extends ServiceEntityRepository +{ + public function __construct(ManagerRegistry $registry) + { + parent::__construct($registry, RecurringSeries::class); + } + + /** + * @return list + */ + public function findDueIds(\DateTimeImmutable $today): array + { + /** @var list $rows */ + $rows = $this->createQueryBuilder('s') + ->select('s.id') + ->where('s.active = true') + ->andWhere('s.nextRunOn <= :today') + ->setParameter('today', $today->format('Y-m-d')) + ->orderBy('s.id') + ->getQuery() + ->getArrayResult(); + + return array_map(static fn (array $row): int => (int) $row['id'], $rows); + } +} diff --git a/src/Schedule.php b/src/Schedule.php new file mode 100644 index 0000000..bf1181f --- /dev/null +++ b/src/Schedule.php @@ -0,0 +1,25 @@ +add(RecurringMessage::every('1 hour', new RunRecurringExpenses())); + } +} diff --git a/src/Services/ActivityFeedService.php b/src/Services/ActivityFeedService.php index f9f84f5..5851b06 100644 --- a/src/Services/ActivityFeedService.php +++ b/src/Services/ActivityFeedService.php @@ -197,6 +197,7 @@ private function buildExpenseItem(?Expense $expense, User $user, ?User $counterp payee: $people[(int) $expense->getPayee()->getId()], payer: null, category: $expense->getCategory(), + recurring: null !== $expense->getSeries(), ); } diff --git a/src/Services/ExpenseCreateService.php b/src/Services/ExpenseCreateService.php index 589a459..8ad95a0 100644 --- a/src/Services/ExpenseCreateService.php +++ b/src/Services/ExpenseCreateService.php @@ -18,6 +18,7 @@ public function __construct( private readonly UserRepository $userRepository, private readonly EntityManagerInterface $entityManager, private readonly SplitCalculator $splitCalculator, + private readonly RecurringSeriesService $recurringSeriesService, ) { } @@ -49,6 +50,7 @@ public function create(User $creator, ExpenseRequest $request): Expense $expense = new Expense($payee, $request->title, $request->description, $request->amount, $request->occurredOn, splitType: $request->splitType, category: $request->category); $this->entityManager->persist($expense); + $this->recurringSeriesService->applyOnCreate($expense, $request->repeat); $splits = $this->splitCalculator->calculate($request->splitType, $request->amount, $request->debts); diff --git a/src/Services/ExpenseDeleteService.php b/src/Services/ExpenseDeleteService.php index 0c0a561..0cd7cc8 100644 --- a/src/Services/ExpenseDeleteService.php +++ b/src/Services/ExpenseDeleteService.php @@ -12,11 +12,14 @@ class ExpenseDeleteService { public function __construct( private readonly EntityManagerInterface $entityManager, + private readonly RecurringSeriesService $recurringSeriesService, ) { } public function delete(Expense $expense): void { + $this->recurringSeriesService->applyOnDelete($expense); + $existingDebts = $this->entityManager->getRepository(Debt::class)->findBy(['expense' => $expense]); foreach ($existingDebts as $debt) { $expense->removeDebt($debt); diff --git a/src/Services/ExpenseUpdateService.php b/src/Services/ExpenseUpdateService.php index b5d4a85..b9c669b 100644 --- a/src/Services/ExpenseUpdateService.php +++ b/src/Services/ExpenseUpdateService.php @@ -18,6 +18,7 @@ public function __construct( private readonly UserRepository $userRepository, private readonly EntityManagerInterface $entityManager, private readonly SplitCalculator $splitCalculator, + private readonly RecurringSeriesService $recurringSeriesService, ) { } @@ -45,6 +46,8 @@ public function update(User $editor, Expense $expense, ExpenseRequest $request): } } + $this->recurringSeriesService->assertCanSetRepeat($expense, $request->repeat); + $splits = $this->splitCalculator->calculate($request->splitType, $request->amount, $request->debts); $existingDebts = $this->entityManager->getRepository(Debt::class)->findBy(['expense' => $expense]); @@ -53,6 +56,7 @@ public function update(User $editor, Expense $expense, ExpenseRequest $request): $this->entityManager->remove($debt); } + $previousOccurredOn = $expense->getOccurredOn(); $expense ->setPayee($usersById[$request->payeeId]) ->setTitle($request->title) @@ -68,6 +72,8 @@ public function update(User $editor, Expense $expense, ExpenseRequest $request): $this->entityManager->persist($debt); } + $this->recurringSeriesService->applyOnUpdate($expense, $request->repeat, $previousOccurredOn); + $this->entityManager->flush(); return $expense; diff --git a/src/Services/RecurringExpenseRunner.php b/src/Services/RecurringExpenseRunner.php new file mode 100644 index 0000000..10cc5a8 --- /dev/null +++ b/src/Services/RecurringExpenseRunner.php @@ -0,0 +1,121 @@ +clock->now()); + $created = 0; + + foreach ($this->seriesRepository->findDueIds($today) as $seriesId) { + try { + $created += $this->runSeries($seriesId, $today); + } catch (\Throwable $exception) { + $this->logger->error('Recurring series {seriesId} failed; it will be retried on the next run.', [ + 'seriesId' => $seriesId, + 'exception' => $exception, + ]); + $this->doctrine->resetManager(); + } + } + + return $created; + } + + private function runSeries(int $seriesId, \DateTimeImmutable $today): int + { + $entityManager = $this->entityManager(); + $entityManager->clear(); + + return $entityManager->wrapInTransaction(function (EntityManagerInterface $entityManager) use ($seriesId, $today): int { + $series = $entityManager->find(RecurringSeries::class, $seriesId, LockMode::PESSIMISTIC_WRITE); + if (null === $series || !$series->isActive() || $series->getNextRunOn() > $today) { + return 0; + } + + $latest = $entityManager->getRepository(Expense::class)->findOneBy(['series' => $series], ['id' => 'DESC']); + if (null === $latest) { + $this->logger->warning('Recurring series {seriesId} has no expenses to copy.', ['seriesId' => $seriesId]); + + return 0; + } + + $created = 0; + while ($series->getNextRunOn() <= $today) { + $latest = $this->copy($entityManager, $latest, $series->getNextRunOn()); + ++$created; + + $series->advanceTo($this->schedule->firstAfter($series->getAnchorOn(), $series->getUnit(), $series->getEvery(), $series->getNextRunOn())); + } + + return $created; + }); + } + + /** + * Copies everything but comments. Same amount and split values, so the split comes out the same. + */ + private function copy(EntityManagerInterface $entityManager, Expense $latest, \DateTimeImmutable $occurredOn): Expense + { + $copy = new Expense( + $latest->getPayee(), + $latest->getTitle(), + $latest->getDescription(), + $latest->getAmount(), + $occurredOn, + $latest->getCurrency(), + $latest->getSplitType(), + $latest->getCategory(), + ); + $copy->setSeries($latest->getSeries()); + $entityManager->persist($copy); + + foreach ($latest->getDebts() as $debt) { + $debtCopy = new Debt($debt->getPayer(), $copy, $debt->getAmount(), $copy->getCurrency(), $debt->getSplitValue()); + $copy->addDebt($debtCopy); + $entityManager->persist($debtCopy); + } + + return $copy; + } + + private function entityManager(): EntityManagerInterface + { + $entityManager = $this->doctrine->getManagerForClass(RecurringSeries::class); + if (!$entityManager instanceof EntityManagerInterface) { + throw new \LogicException('No entity manager handles RecurringSeries.'); + } + + return $entityManager; + } +} diff --git a/src/Services/RecurringSeriesService.php b/src/Services/RecurringSeriesService.php new file mode 100644 index 0000000..809766e --- /dev/null +++ b/src/Services/RecurringSeriesService.php @@ -0,0 +1,128 @@ +getSeries() || $this->isLatest($expense)) { + return; + } + + throw new UnprocessableEntityHttpException('Only the latest expense in a repeat can change it.'); + } + + public function applyOnCreate(Expense $expense, ?RepeatRequest $repeat): void + { + if (null === $repeat) { + return; + } + + $anchorOn = RepeatSchedule::toDate($expense->getOccurredOn()); + $series = new RecurringSeries($repeat->unit, $repeat->every, $anchorOn, $this->nextRunOn($anchorOn, $repeat, $expense)); + $this->entityManager->persist($series); + $expense->setSeries($series); + } + + /** + * Call with the expense already updated; `$previousOccurredOn` is its date before the edit. + * The schedule keeps its anchor while the latest's date is one of its dates, so a clamped + * 28 Feb still returns to the 31st. + */ + public function applyOnUpdate(Expense $expense, ?RepeatRequest $repeat, \DateTimeImmutable $previousOccurredOn): void + { + $series = $expense->getSeries(); + if (null === $series) { + $this->applyOnCreate($expense, $repeat); + + return; + } + + if (!$this->isLatest($expense)) { + return; + } + + if (null === $repeat) { + $series->stop(); + + return; + } + + $keepsAnchor = $series->hasFrequency($repeat->unit, $repeat->every) + && $this->schedule->isOnSchedule($series->getAnchorOn(), $repeat->unit, $repeat->every, $expense->getOccurredOn()); + $dateChanged = $previousOccurredOn->format('Y-m-d') !== $expense->getOccurredOn()->format('Y-m-d'); + if ($keepsAnchor && !$dateChanged && $series->isActive()) { + return; + } + + $anchorOn = $keepsAnchor ? $series->getAnchorOn() : RepeatSchedule::toDate($expense->getOccurredOn()); + $series->reschedule($repeat->unit, $repeat->every, $anchorOn, $this->nextRunOn($anchorOn, $repeat, $expense)); + } + + /** + * Call before removing the expense. Deleting the latest stops the series; the one before becomes its latest. + */ + public function applyOnDelete(Expense $expense): void + { + $series = $expense->getSeries(); + if (null === $series || !$this->isLatest($expense)) { + return; + } + + if ($this->isOnlyMember($expense)) { + $this->entityManager->remove($series); + + return; + } + + $series->stop(); + } + + private function isLatest(Expense $expense): bool + { + $series = $expense->getSeries(); + + return null !== $series && $this->expenseRepository->findLatestIdInSeries($series) === $expense->getId(); + } + + private function isOnlyMember(Expense $expense): bool + { + return 1 === $this->expenseRepository->count(['series' => $expense->getSeries()]); + } + + /** + * No backfill: a past date starts from the first schedule date after today. + */ + private function nextRunOn(\DateTimeImmutable $anchorOn, RepeatRequest $repeat, Expense $latest): \DateTimeImmutable + { + $today = RepeatSchedule::toDate($this->clock->now()); + $latestOn = RepeatSchedule::toDate($latest->getOccurredOn()); + + return $this->schedule->firstAfter($anchorOn, $repeat->unit, $repeat->every, max($latestOn, $today)); + } +} diff --git a/src/Services/RepeatSchedule.php b/src/Services/RepeatSchedule.php new file mode 100644 index 0000000..f7aeb44 --- /dev/null +++ b/src/Services/RepeatSchedule.php @@ -0,0 +1,82 @@ +estimateStepsBefore($anchorOn, $unit, $every, $after); + while (($date = $this->occurrence($anchorOn, $unit, $every, $step)) <= $after) { + ++$step; + } + + return $date; + } + + public function isOnSchedule(\DateTimeImmutable $anchorOn, RepeatUnit $unit, int $every, \DateTimeImmutable $date): bool + { + $date = self::toDate($date); + + return $this->firstAfter($anchorOn, $unit, $every, $date->modify('-1 day')) == $date; + } + + /** + * The value's own calendar date, at midnight in the default timezone. + */ + public static function toDate(\DateTimeImmutable $dateTime): \DateTimeImmutable + { + return new \DateTimeImmutable($dateTime->format('Y-m-d')); + } + + private function occurrence(\DateTimeImmutable $anchorOn, RepeatUnit $unit, int $every, int $step): \DateTimeImmutable + { + if (RepeatUnit::Week === $unit) { + return $anchorOn->modify(sprintf('+%d days', 7 * $every * $step)); + } + + $monthIndex = $this->monthIndex($anchorOn) + $step * $this->monthsPerStep($unit, $every); + $year = intdiv($monthIndex, 12); + $month = $monthIndex % 12 + 1; + $daysInMonth = (int) $anchorOn->setDate($year, $month, 1)->format('t'); + + return $anchorOn->setDate($year, $month, min((int) $anchorOn->format('j'), $daysInMonth)); + } + + /** + * A lower bound on the step count, so long gaps don't walk the schedule one step at a time. + */ + private function estimateStepsBefore(\DateTimeImmutable $anchorOn, RepeatUnit $unit, int $every, \DateTimeImmutable $after): int + { + if (RepeatUnit::Week === $unit) { + return intdiv((int) $anchorOn->diff($after)->days, 7 * $every); + } + + return intdiv($this->monthIndex($after) - $this->monthIndex($anchorOn), $this->monthsPerStep($unit, $every)); + } + + private function monthIndex(\DateTimeImmutable $date): int + { + return (int) $date->format('Y') * 12 + (int) $date->format('n') - 1; + } + + private function monthsPerStep(RepeatUnit $unit, int $every): int + { + return RepeatUnit::Year === $unit ? 12 * $every : $every; + } +} diff --git a/symfony.lock b/symfony.lock index 02045f1..760e827 100644 --- a/symfony.lock +++ b/symfony.lock @@ -238,6 +238,18 @@ "config/routes.yaml" ] }, + "symfony/scheduler": { + "version": "7.4", + "recipe": { + "repo": "github.com/symfony/recipes", + "branch": "main", + "version": "7.2", + "ref": "caea3c928ee9e1b21288fd76aef36f16ea355515" + }, + "files": [ + "src/Schedule.php" + ] + }, "symfony/security-bundle": { "version": "7.2", "recipe": { diff --git a/tests/Api/RecurringExpenseApiTest.php b/tests/Api/RecurringExpenseApiTest.php new file mode 100644 index 0000000..9fb11b9 --- /dev/null +++ b/tests/Api/RecurringExpenseApiTest.php @@ -0,0 +1,249 @@ +client = static::createClient(); + $entityManager = static::getContainer()->get(EntityManagerInterface::class); + + $this->user = UserFactory::createUser(); + $this->friend = UserFactory::createUser(); + $entityManager->persist($this->user); + $entityManager->persist($this->friend); + $entityManager->flush(); + + $this->client->loginUser($this->user); + self::mockTime('2026-11-26 10:00'); + } + + public function testCreateWithRepeatStartsAfterToday(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-10', ['unit' => 'month', 'every' => 1])); + + $this->assertJsonResponseIsSuccessful(201); + $response = $this->getJsonResponse(); + $this->assertJsonStructure(['repeat' => ['unit', 'every', 'nextOn', 'active'], 'series' => ['latestId', 'isLatest']], $response); + $this->assertSame('month', $response['repeat']['unit']); + $this->assertSame(1, $response['repeat']['every']); + $this->assertStringStartsWith('2026-12-10', $response['repeat']['nextOn']); + $this->assertTrue($response['repeat']['active']); + $this->assertSame(['latestId' => $response['id'], 'isLatest' => true], $response['series']); + } + + public function testCreateWithoutRepeat(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-10', null)); + + $this->assertJsonResponseIsSuccessful(201); + $response = $this->getJsonResponse(); + $this->assertNull($response['repeat']); + $this->assertNull($response['series']); + } + + public function testRejectsUnsupportedFrequency(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-10', ['unit' => 'month', 'every' => 2])); + + $this->assertResponseStatusCodeSame(400); + $this->assertSame('repeat.every', $this->getJsonResponse()['violations'][0]['propertyPath']); + } + + public function testOlderMemberCannotSetRepeatButCanBeEdited(): void + { + [$olderId, $latestId] = $this->createSeriesWithTwoMembers(); + + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$olderId, $this->payload('2026-11-26', ['unit' => 'week', 'every' => 1])); + $this->assertResponseStatusCodeSame(422); + + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$olderId, $this->payload('2026-11-25', null, '90.00')); + $this->assertJsonResponseIsSuccessful(200); + $response = $this->getJsonResponse(); + $this->assertSame('90.00', $response['amount']); + $this->assertSame(['latestId' => $latestId, 'isLatest' => false], $response['series']); + $this->assertTrue($response['repeat']['active']); + } + + public function testTurningTheLatestOffAndOnAgain(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-10', ['unit' => 'month', 'every' => 1])); + $id = $this->getJsonResponse()['id']; + + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$id, $this->payload('2026-11-10', null)); + $this->assertJsonResponseIsSuccessful(200); + $response = $this->getJsonResponse(); + $this->assertFalse($response['repeat']['active']); + $this->assertNull($response['repeat']['nextOn']); + + self::mockTime('2027-01-20'); + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$id, $this->payload('2026-11-10', ['unit' => 'month', 'every' => 1])); + $this->assertJsonResponseIsSuccessful(200); + $response = $this->getJsonResponse(); + $this->assertTrue($response['repeat']['active']); + $this->assertStringStartsWith('2027-02-10', $response['repeat']['nextOn']); + } + + public function testChangingTheLatestsFrequencyResetsTheSchedule(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-20', ['unit' => 'month', 'every' => 1])); + $id = $this->getJsonResponse()['id']; + + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$id, $this->payload('2026-11-20', ['unit' => 'week', 'every' => 1])); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertStringStartsWith('2026-11-27', $this->getJsonResponse()['repeat']['nextOn']); + } + + public function testMovingTheLatestsDateMovesTheSchedule(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-10', ['unit' => 'month', 'every' => 1])); + $id = $this->getJsonResponse()['id']; + + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$id, $this->payload('2026-11-15', ['unit' => 'month', 'every' => 1])); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertStringStartsWith('2026-12-15', $this->getJsonResponse()['repeat']['nextOn']); + } + + public function testMovingTheLatestOntoALaterScheduleDateCreatesNoDuplicate(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-10', ['unit' => 'month', 'every' => 1])); + $id = $this->getJsonResponse()['id']; + + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$id, $this->payload('2027-01-10', ['unit' => 'month', 'every' => 1])); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertStringStartsWith('2027-02-10', $this->getJsonResponse()['repeat']['nextOn']); + } + + public function testMovingTheLatestBackOntoAnEarlierScheduleDateSkipsNothing(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-12-10', ['unit' => 'month', 'every' => 1])); + $id = $this->getJsonResponse()['id']; + + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$id, $this->payload('2026-11-10', ['unit' => 'month', 'every' => 1])); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertStringStartsWith('2026-12-10', $this->getJsonResponse()['repeat']['nextOn']); + } + + public function testADateMovedWhileStoppedCountsOnRestart(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-10', ['unit' => 'month', 'every' => 1])); + $id = $this->getJsonResponse()['id']; + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$id, $this->payload('2026-11-10', null)); + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$id, $this->payload('2026-11-15', null)); + + $this->requestJson($this->client, 'PUT', '/api/expenses/'.$id, $this->payload('2026-11-15', ['unit' => 'month', 'every' => 1])); + + $this->assertJsonResponseIsSuccessful(200); + $this->assertStringStartsWith('2026-12-15', $this->getJsonResponse()['repeat']['nextOn']); + } + + public function testDeletingAnOlderMemberKeepsTheSeries(): void + { + [$olderId, $latestId] = $this->createSeriesWithTwoMembers(); + + $this->client->request('DELETE', '/api/expenses/'.$olderId); + $this->assertResponseStatusCodeSame(204); + + $this->client->request('GET', '/api/expenses/'.$latestId); + $response = $this->getJsonResponse(); + $this->assertSame(['latestId' => $latestId, 'isLatest' => true], $response['series']); + $this->assertTrue($response['repeat']['active']); + } + + public function testDeletingTheLatestStopsTheSeries(): void + { + [$olderId, $latestId] = $this->createSeriesWithTwoMembers(); + + $this->client->request('DELETE', '/api/expenses/'.$latestId); + $this->assertResponseStatusCodeSame(204); + + $this->client->request('GET', '/api/expenses/'.$olderId); + $response = $this->getJsonResponse(); + $this->assertSame(['latestId' => $olderId, 'isLatest' => true], $response['series']); + $this->assertFalse($response['repeat']['active']); + } + + public function testDeletingTheOnlyMemberRemovesTheSeries(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-10', ['unit' => 'month', 'every' => 1])); + $id = $this->getJsonResponse()['id']; + + $this->client->request('DELETE', '/api/expenses/'.$id); + $this->assertResponseStatusCodeSame(204); + + $this->assertSame(0, static::getContainer()->get(EntityManagerInterface::class)->getRepository(RecurringSeries::class)->count([])); + } + + public function testActivityMarksRecurringExpenses(): void + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-10', ['unit' => 'month', 'every' => 1])); + $recurringId = $this->getJsonResponse()['id']; + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-11', null)); + $plainId = $this->getJsonResponse()['id']; + + $this->client->request('GET', '/api/activity'); + + $this->assertJsonResponseIsSuccessful(200); + $recurringById = array_column($this->getJsonResponse(), 'recurring', 'id'); + $this->assertSame([$plainId => false, $recurringId => true], $recurringById); + } + + /** + * @return array{int, int} the older and the latest expense id + */ + private function createSeriesWithTwoMembers(): array + { + $this->requestJson($this->client, 'POST', '/api/expenses', $this->payload('2026-11-19', ['unit' => 'week', 'every' => 1])); + $olderId = $this->getJsonResponse()['id']; + + self::mockTime('2026-12-03 10:00'); + $this->assertSame(1, static::getContainer()->get(RecurringExpenseRunner::class)->run()); + + $this->client->request('GET', '/api/expenses/'.$olderId); + + return [$olderId, $this->getJsonResponse()['series']['latestId']]; + } + + /** + * @param array{unit: string, every: int}|null $repeat + * + * @return array + */ + private function payload(string $occurredOn, ?array $repeat, string $amount = '100.00'): array + { + return [ + 'title' => 'Rent', + 'amount' => $amount, + 'payeeId' => $this->user->getId(), + 'occurredOn' => $occurredOn, + 'splitType' => 'equal', + 'debts' => [ + ['payerId' => $this->user->getId()], + ['payerId' => $this->friend->getId()], + ], + 'repeat' => $repeat, + ]; + } +} diff --git a/tests/Integration/Command/RecurringRunCommandTest.php b/tests/Integration/Command/RecurringRunCommandTest.php new file mode 100644 index 0000000..e5efb3b --- /dev/null +++ b/tests/Integration/Command/RecurringRunCommandTest.php @@ -0,0 +1,49 @@ +get(EntityManagerInterface::class); + $user = UserFactory::createUser(); + $entityManager->persist($user); + $entityManager->flush(); + + self::mockTime('2026-11-01'); + static::getContainer()->get(ExpenseCreateService::class)->create($user, new ExpenseRequest( + title: 'Gym', + amount: '50.00', + payeeId: (int) $user->getId(), + debts: [new ExpenseDebtRequest((int) $user->getId(), '50.00')], + occurredOn: new \DateTimeImmutable('2026-11-01'), + repeat: new RepeatRequest(RepeatUnit::Week), + )); + + self::mockTime('2026-11-15'); + $commandTester = new CommandTester((new Application($kernel))->find('app:recurring:run')); + $commandTester->execute([]); + + $this->assertSame(Command::SUCCESS, $commandTester->getStatusCode()); + $this->assertStringContainsString('Created 2 repeating expense(s).', $commandTester->getDisplay()); + } +} diff --git a/tests/Integration/Services/RecurringExpenseRunnerTest.php b/tests/Integration/Services/RecurringExpenseRunnerTest.php new file mode 100644 index 0000000..50238d0 --- /dev/null +++ b/tests/Integration/Services/RecurringExpenseRunnerTest.php @@ -0,0 +1,223 @@ +entityManager = static::getContainer()->get(EntityManagerInterface::class); + $this->runner = static::getContainer()->get(RecurringExpenseRunner::class); + + $this->payee = UserFactory::createUser(); + $this->friend = UserFactory::createUser(); + $this->entityManager->persist($this->payee); + $this->entityManager->persist($this->friend); + $this->entityManager->flush(); + } + + public function testCreatesEveryMissedOccurrenceOnItsOwnDate(): void + { + self::mockTime('2026-08-15 12:00'); + $first = $this->createExpense('2026-08-10', new RepeatRequest(RepeatUnit::Month)); + $this->entityManager->persist(new Comment($first, $this->payee, 'Paid by card')); + $this->entityManager->flush(); + $seriesId = (int) $first->getSeries()?->getId(); + + self::mockTime('2026-11-26 03:00'); + $this->assertSame(3, $this->runner->run()); + + $this->entityManager->clear(); + $members = $this->membersOf($seriesId); + $this->assertSame(['2026-08-10', '2026-09-10', '2026-10-10', '2026-11-10'], $this->dates($members)); + + foreach (array_slice($members, 1) as $copy) { + $this->assertSame('Rent', $copy->getTitle()); + $this->assertSame('Flat', $copy->getDescription()); + $this->assertSame('100.00', $copy->getAmount()); + $this->assertSame(SplitType::Shares, $copy->getSplitType()); + $this->assertSame(ExpenseCategory::HomeAndBills, $copy->getCategory()); + $this->assertSame($this->payee->getId(), $copy->getPayee()->getId()); + $this->assertSame( + [[$this->payee->getId(), '33.33', '1.00'], [$this->friend->getId(), '66.67', '2.00']], + $this->debtsOf($copy), + ); + $this->assertSame(0, $this->entityManager->getRepository(Comment::class)->count(['expense' => $copy])); + } + + $series = $this->entityManager->find(RecurringSeries::class, $seriesId); + $this->assertSame('2026-12-10', $series?->getNextRunOn()->format('Y-m-d')); + } + + public function testRunningAgainCreatesNothing(): void + { + self::mockTime('2026-10-15'); + $first = $this->createExpense('2026-10-10', new RepeatRequest(RepeatUnit::Week)); + $seriesId = (int) $first->getSeries()?->getId(); + + self::mockTime('2026-10-24'); + $this->assertSame(2, $this->runner->run()); + $this->assertSame(0, $this->runner->run()); + + $this->entityManager->clear(); + $this->assertSame(['2026-10-10', '2026-10-17', '2026-10-24'], $this->dates($this->membersOf($seriesId))); + } + + public function testNothingIsDueBeforeTheNextDate(): void + { + self::mockTime('2026-11-26'); + $this->createExpense('2026-10-26', new RepeatRequest(RepeatUnit::Month)); + + $this->assertSame(0, $this->runner->run()); + } + + public function testCopiesTheLatestAndKeepsTheAnchorDay(): void + { + self::mockTime('2027-01-31'); + $first = $this->createExpense('2027-01-31', new RepeatRequest(RepeatUnit::Month)); + $seriesId = (int) $first->getSeries()?->getId(); + + self::mockTime('2027-02-28'); + $this->assertSame(1, $this->runner->run()); + + $this->entityManager->clear(); + $february = $this->membersOf($seriesId)[1]; + $this->updateExpense($february, '2027-02-28', '120.00', new RepeatRequest(RepeatUnit::Month)); + + self::mockTime('2027-03-31'); + $this->assertSame(1, $this->runner->run()); + + $this->entityManager->clear(); + $members = $this->membersOf($seriesId); + $this->assertSame(['2027-01-31', '2027-02-28', '2027-03-31'], $this->dates($members)); + $this->assertSame('120.00', $members[2]->getAmount()); + } + + public function testSkipsAStoppedSeries(): void + { + self::mockTime('2026-11-01'); + $first = $this->createExpense('2026-11-01', new RepeatRequest(RepeatUnit::Week)); + $seriesId = (int) $first->getSeries()?->getId(); + $this->updateExpense($first, '2026-11-01', '100.00', null); + + self::mockTime('2026-12-01'); + $this->assertSame(0, $this->runner->run()); + + $this->entityManager->clear(); + $this->assertCount(1, $this->membersOf($seriesId)); + } + + public function testAFailingSeriesIsSkippedAndKeptForTheNextRun(): void + { + $connection = $this->entityManager->getConnection(); + $connection->executeStatement( + "INSERT INTO recurring_series (unit, every, anchor_on, next_run_on, active, created_at, updated_at) VALUES ('decade', 1, '2026-10-01', '2026-11-01', 1, NOW(), NOW())", + ); + $brokenId = (int) $connection->lastInsertId(); + + self::mockTime('2026-11-01'); + $first = $this->createExpense('2026-11-01', new RepeatRequest(RepeatUnit::Week)); + $seriesId = (int) $first->getSeries()?->getId(); + + self::mockTime('2026-11-08'); + $this->assertSame(1, $this->runner->run()); + + $entityManager = static::getContainer()->get(EntityManagerInterface::class); + $this->assertCount(2, $entityManager->getRepository(Expense::class)->findBy(['series' => $seriesId])); + $this->assertSame( + ['next_run_on' => '2026-11-01', 'active' => 1], + $connection->fetchAssociative('SELECT next_run_on, active FROM recurring_series WHERE id = ?', [$brokenId]), + ); + } + + private function createExpense(string $occurredOn, ?RepeatRequest $repeat): Expense + { + return static::getContainer()->get(ExpenseCreateService::class)->create($this->payee, $this->request($occurredOn, '100.00', $repeat)); + } + + private function updateExpense(Expense $expense, string $occurredOn, string $amount, ?RepeatRequest $repeat): void + { + $expense = $this->entityManager->find(Expense::class, $expense->getId()); + $payee = $this->entityManager->find(User::class, $this->payee->getId()); + static::getContainer()->get(ExpenseUpdateService::class)->update($payee, $expense, $this->request($occurredOn, $amount, $repeat)); + } + + private function request(string $occurredOn, string $amount, ?RepeatRequest $repeat): ExpenseRequest + { + return new ExpenseRequest( + title: 'Rent', + amount: $amount, + payeeId: (int) $this->payee->getId(), + debts: [ + new ExpenseDebtRequest((int) $this->payee->getId(), '1'), + new ExpenseDebtRequest((int) $this->friend->getId(), '2'), + ], + occurredOn: new \DateTimeImmutable($occurredOn), + splitType: SplitType::Shares, + category: ExpenseCategory::HomeAndBills, + description: 'Flat', + repeat: $repeat, + ); + } + + /** + * @return list + */ + private function membersOf(int $seriesId): array + { + return $this->entityManager->getRepository(Expense::class)->findBy(['series' => $seriesId], ['id' => 'ASC']); + } + + /** + * @param list $expenses + * + * @return list + */ + private function dates(array $expenses): array + { + return array_map(static fn (Expense $expense): string => $expense->getOccurredOn()->format('Y-m-d'), $expenses); + } + + /** + * @return list + */ + private function debtsOf(Expense $expense): array + { + $debts = []; + foreach ($expense->getDebts() as $debt) { + $debts[] = [$debt->getPayer()->getId(), $debt->getAmount(), $debt->getSplitValue()]; + } + usort($debts, static fn (array $a, array $b): int => $a[0] <=> $b[0]); + + return $debts; + } +} diff --git a/tests/Unit/Services/RepeatScheduleTest.php b/tests/Unit/Services/RepeatScheduleTest.php new file mode 100644 index 0000000..c99e7f8 --- /dev/null +++ b/tests/Unit/Services/RepeatScheduleTest.php @@ -0,0 +1,86 @@ + + */ + public static function cases(): iterable + { + yield 'monthly, past anchor' => ['2026-11-10', RepeatUnit::Month, 1, '2026-11-26', '2026-12-10']; + yield 'monthly, strictly after a schedule date' => ['2026-10-26', RepeatUnit::Month, 1, '2026-11-26', '2026-12-26']; + yield 'monthly, future anchor counts from itself' => ['2026-12-05', RepeatUnit::Month, 1, '2026-12-05', '2027-01-05']; + yield 'monthly, 31st clamps to February' => ['2027-01-31', RepeatUnit::Month, 1, '2027-01-31', '2027-02-28']; + yield 'monthly, 31st returns after a short month' => ['2027-01-31', RepeatUnit::Month, 1, '2027-02-28', '2027-03-31']; + yield 'monthly, 31st clamps to 30-day month' => ['2027-03-31', RepeatUnit::Month, 1, '2027-03-31', '2027-04-30']; + yield 'monthly, 31st in a leap February' => ['2028-01-31', RepeatUnit::Month, 1, '2028-01-31', '2028-02-29']; + yield 'monthly, across a year end' => ['2026-12-15', RepeatUnit::Month, 1, '2026-12-15', '2027-01-15']; + yield 'monthly, long gap' => ['2020-01-10', RepeatUnit::Month, 1, '2026-11-26', '2026-12-10']; + yield 'yearly, 29 Feb clamps' => ['2028-02-29', RepeatUnit::Year, 1, '2028-02-29', '2029-02-28']; + yield 'yearly, 29 Feb returns in a leap year' => ['2028-02-29', RepeatUnit::Year, 1, '2031-02-28', '2032-02-29']; + yield 'weekly' => ['2026-11-20', RepeatUnit::Week, 1, '2026-11-26', '2026-11-27']; + yield 'weekly, on a schedule date' => ['2026-11-20', RepeatUnit::Week, 1, '2026-11-27', '2026-12-04']; + yield 'every 2 weeks' => ['2026-11-20', RepeatUnit::Week, 2, '2026-11-26', '2026-12-04']; + yield 'every 2 weeks, long gap' => ['2026-01-02', RepeatUnit::Week, 2, '2026-11-26', '2026-12-04']; + yield 'after is before the anchor' => ['2026-12-05', RepeatUnit::Month, 1, '2026-11-26', '2026-12-05']; + } + + /** + * @dataProvider cases + */ + public function testFirstAfter(string $anchorOn, RepeatUnit $unit, int $every, string $after, string $expected): void + { + $next = (new RepeatSchedule())->firstAfter(new \DateTimeImmutable($anchorOn), $unit, $every, new \DateTimeImmutable($after)); + + $this->assertSame($expected, $next->format('Y-m-d')); + } + + /** + * @return iterable + */ + public static function onScheduleCases(): iterable + { + yield 'the anchor itself' => ['2027-01-31', RepeatUnit::Month, 1, '2027-01-31', true]; + yield 'a clamped date' => ['2027-01-31', RepeatUnit::Month, 1, '2027-02-28', true]; + yield 'another day in a short month' => ['2027-01-31', RepeatUnit::Month, 1, '2027-02-27', false]; + yield 'before the anchor' => ['2027-01-31', RepeatUnit::Month, 1, '2026-12-31', false]; + yield 'every 2 weeks, off week' => ['2026-11-02', RepeatUnit::Week, 2, '2026-11-09', false]; + yield 'every 2 weeks, on week' => ['2026-11-02', RepeatUnit::Week, 2, '2026-11-16', true]; + } + + /** + * @dataProvider onScheduleCases + */ + public function testIsOnSchedule(string $anchorOn, RepeatUnit $unit, int $every, string $date, bool $expected): void + { + $this->assertSame($expected, (new RepeatSchedule())->isOnSchedule(new \DateTimeImmutable($anchorOn), $unit, $every, new \DateTimeImmutable($date))); + } + + public function testUsesTheCalendarDateWhateverTheOffset(): void + { + $date = RepeatSchedule::toDate(new \DateTimeImmutable('2026-11-10T00:00:00+02:00')); + + $this->assertSame('2026-11-10', $date->format('Y-m-d')); + $this->assertEquals(new \DateTimeImmutable('2026-11-10'), $date); + } + + public function testIgnoresTimeOfDay(): void + { + $next = (new RepeatSchedule())->firstAfter( + new \DateTimeImmutable('2026-11-10 18:00'), + RepeatUnit::Month, + 1, + new \DateTimeImmutable('2026-12-10 09:30'), + ); + + $this->assertSame('2027-01-10 00:00', $next->format('Y-m-d H:i')); + } +}