From ae7b6111269394e04304aea0e00064921a1f3efe Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Tue, 24 Nov 2026 13:32:46 +0200 Subject: [PATCH] Add a CSV download of created billing materials Management downloads a created billing material as a semicolon CSV with decimal commas and a UTF-8 BOM for Excel: one row per invoice line with the invoice's customer, billing unit, e-invoice details and reference, the job, the line and its net, VAT and gross amounts. Consumers' full personal identity codes are included only for those who may see them, the response is not cached, and cells Excel would read as formulas are escaped. The columns follow Fennoa's import format once a sample exists. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- .../Contracts/BillingCustomers.php | 18 +++ .../DTOs/CustomerBillingDetails.php | 25 +++ .../Billing/Application/DTOs/ExportRow.php | 36 +++++ .../Application/Services/ExportRows.php | 77 +++++++++ .../Domain/Exceptions/ExportNotCreated.php | 15 ++ .../Infrastructure/CustomersForBilling.php | 35 ++++ .../Providers/BillingServiceProvider.php | 3 + .../Http/Controllers/DownloadBillingCsv.php | 117 ++++++++++++++ .../Presentation/Livewire/⚡export.blade.php | 7 + .../Presentation/Livewire/⚡index.blade.php | 7 + .../Billing/Presentation/Routes/web.php | 2 + docs/maarittely.md | 5 +- lang/fi/billing.php | 21 +++ tests/Browser/BillingAccessibilityTest.php | 1 + .../Modules/Billing/BillingCsvTest.php | 152 ++++++++++++++++++ 16 files changed, 520 insertions(+), 3 deletions(-) create mode 100644 app/Modules/Billing/Application/Contracts/BillingCustomers.php create mode 100644 app/Modules/Billing/Application/DTOs/CustomerBillingDetails.php create mode 100644 app/Modules/Billing/Application/DTOs/ExportRow.php create mode 100644 app/Modules/Billing/Application/Services/ExportRows.php create mode 100644 app/Modules/Billing/Domain/Exceptions/ExportNotCreated.php create mode 100644 app/Modules/Billing/Infrastructure/CustomersForBilling.php create mode 100644 app/Modules/Billing/Presentation/Http/Controllers/DownloadBillingCsv.php create mode 100644 tests/Feature/Modules/Billing/BillingCsvTest.php diff --git a/CLAUDE.md b/CLAUDE.md index eface27..a7a251b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project -An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material: a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots; reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). +An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material: a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots, downloadable as a semicolon CSV (`billing.csv`, with consumers' identity codes for those who may see them); reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). - **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec. - **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start. diff --git a/app/Modules/Billing/Application/Contracts/BillingCustomers.php b/app/Modules/Billing/Application/Contracts/BillingCustomers.php new file mode 100644 index 0000000..db28777 --- /dev/null +++ b/app/Modules/Billing/Application/Contracts/BillingCustomers.php @@ -0,0 +1,18 @@ +netCents + $this->vatCents; + } +} diff --git a/app/Modules/Billing/Application/Services/ExportRows.php b/app/Modules/Billing/Application/Services/ExportRows.php new file mode 100644 index 0000000..339b280 --- /dev/null +++ b/app/Modules/Billing/Application/Services/ExportRows.php @@ -0,0 +1,77 @@ + + * + * @throws BillingExportNotFound + * @throws ExportNotCreated + */ + public function of(int $exportId, bool $withIdentityCodes): array + { + $export = $this->exports->findById($exportId) ?? throw new BillingExportNotFound($exportId); + + if ($export->isDraft()) { + throw new ExportNotCreated; + } + + $jobs = $this->jobs->find($export->jobIds()); + $rows = []; + + foreach ($export->invoices() as $index => $invoice) { + $customer = $this->customers->billingDetails($invoice->customerId(), $invoice->billingUnitId(), $withIdentityCodes); + $reference = $invoice->reference() ?? $customer->billingUnitReference; + + foreach ($invoice->lines() as $line) { + $job = $jobs[$line->jobId] ?? null; + $vat = Money::fromCents($line->netCents)->addVat(new VatPercentage($line->vatBasisPoints))->cents - $line->netCents; + + $rows[] = new ExportRow( + $index + 1, + $customer, + $reference, + $job->number ?? '', + $job->name ?? '', + $line->kind, + $line->description, + $line->recordedQuarters, + $line->quantityQuarters, + $line->unitPriceCents, + $line->vatBasisPoints, + $line->netCents, + $vat, + ); + } + } + + return $rows; + } +} diff --git a/app/Modules/Billing/Domain/Exceptions/ExportNotCreated.php b/app/Modules/Billing/Domain/Exceptions/ExportNotCreated.php new file mode 100644 index 0000000..3d4b375 --- /dev/null +++ b/app/Modules/Billing/Domain/Exceptions/ExportNotCreated.php @@ -0,0 +1,15 @@ +customers->findSummary($customerId); + $isConsumer = $customer?->type === CustomerType::Consumer; + $unit = $billingUnitId === null ? null : $this->customers->findBillingUnit($customerId, $billingUnitId); + + return new CustomerBillingDetails( + $customer->name ?? '', + $isConsumer, + $customer?->businessId, + $isConsumer && $withIdentityCode ? $this->customers->personalIdentityCodeOf($customerId) : null, + $unit?->name, + $unit?->billingAddress, + $unit?->eInvoiceAddress, + $unit?->eInvoiceOperator, + $unit?->reference, + ); + } +} diff --git a/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php b/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php index 52b61d9..78b0c10 100644 --- a/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php +++ b/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php @@ -3,12 +3,14 @@ namespace App\Modules\Billing\Infrastructure\Providers; use App\Models\User; +use App\Modules\Billing\Application\Contracts\BillingCustomers; use App\Modules\Billing\Application\Contracts\BillingExpenses; use App\Modules\Billing\Application\Contracts\BillingHours; use App\Modules\Billing\Application\Contracts\BillingJobs; use App\Modules\Billing\Application\Contracts\BillingPrices; use App\Modules\Billing\Application\Contracts\BillingQueries; use App\Modules\Billing\Domain\Contracts\BillingExportRepository; +use App\Modules\Billing\Infrastructure\CustomersForBilling; use App\Modules\Billing\Infrastructure\ExpensesForBilling; use App\Modules\Billing\Infrastructure\HoursForBilling; use App\Modules\Billing\Infrastructure\JobsForBilling; @@ -36,6 +38,7 @@ class BillingServiceProvider extends ServiceProvider BillingHours::class => HoursForBilling::class, BillingExpenses::class => ExpensesForBilling::class, BillingPrices::class => PricesForBilling::class, + BillingCustomers::class => CustomersForBilling::class, ]; public function boot(): void diff --git a/app/Modules/Billing/Presentation/Http/Controllers/DownloadBillingCsv.php b/app/Modules/Billing/Presentation/Http/Controllers/DownloadBillingCsv.php new file mode 100644 index 0000000..e67f4c7 --- /dev/null +++ b/app/Modules/Billing/Presentation/Http/Controllers/DownloadBillingCsv.php @@ -0,0 +1,117 @@ +of($export, Gate::allows('customers.view-personal-identity-code')); + } catch (BillingExportNotFound|ExportNotCreated) { + abort(404); + } + + return response()->streamDownload(function () use ($rows): void { + $out = fopen('php://output', 'w'); + + if ($out === false) { + return; + } + + fwrite($out, "\u{FEFF}"); + fputcsv($out, array_values(__('billing.csv.columns')), ';', '"', ''); + + foreach ($rows as $row) { + fputcsv($out, array_map(self::cell(...), $this->cells($row)), ';', '"', ''); + } + + fclose($out); + }, __('billing.csv.file', ['number' => $export]), [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'no-store, private', + ]); + } + + /** + * @return list + */ + private function cells(ExportRow $row): array + { + $customer = $row->customer; + + return [ + (string) $row->invoiceNumber, + $customer->name, + __($customer->isConsumer ? 'billing.csv.consumer' : 'billing.csv.company'), + (string) $customer->businessId, + (string) $customer->personalIdentityCode, + (string) $customer->billingUnitName, + (string) $customer->billingAddress, + (string) $customer->eInvoiceAddress, + (string) $customer->eInvoiceOperator, + (string) $row->reference, + $row->jobNumber, + $row->jobName, + __('billing.kinds.'.$row->kind->value), + $row->description, + $row->recordedQuarters === null ? '' : self::hours($row->recordedQuarters), + $row->quantityQuarters === null ? '1' : self::hours($row->quantityQuarters), + __('billing.csv.units.'.match ($row->kind) { + LineKind::Hours => 'hours', + LineKind::MonthlyFee => 'month', + default => 'piece', + }), + self::money($row->unitPriceCents), + self::decimal($row->vatBasisPoints, 100), + self::money($row->netCents), + self::money($row->vatCents), + self::money($row->grossCents()), + ]; + } + + /** + * Guards against formula injection: a cell that Excel would read as a + * formula gets a leading apostrophe. + */ + public static function cell(string $value): string + { + return preg_match('/^[=+\-@\t\r\n]/', $value) === 1 ? "'".$value : $value; + } + + private static function money(int $cents): string + { + return ($cents < 0 ? '-' : '').intdiv(abs($cents), 100).','.str_pad((string) (abs($cents) % 100), 2, '0', STR_PAD_LEFT); + } + + private static function hours(int $quarters): string + { + return self::decimal($quarters * 25, 100); + } + + /** + * E.g. 2550 / 100 → "25,5", 1000 / 100 → "10". + */ + private static function decimal(int $value, int $divisor): string + { + $text = number_format($value / $divisor, 2, ',', ''); + + return rtrim(rtrim($text, '0'), ','); + } +} diff --git a/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php b/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php index 871b9ab..676c3fb 100644 --- a/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php +++ b/app/Modules/Billing/Presentation/Livewire/⚡export.blade.php @@ -321,6 +321,13 @@ new class extends Component

{{ __('billing.export.summary', ['invoices' => count($export->invoices), 'jobs' => $export->jobCount(), 'net' => $this->money($export->totals->netCents)]) }}

+ + @if (! $export->isDraft()) +
+ +

{{ __('billing.csv.sensitive') }}

+
+ @endif

{{ $statusMessage }}

diff --git a/app/Modules/Billing/Presentation/Livewire/⚡index.blade.php b/app/Modules/Billing/Presentation/Livewire/⚡index.blade.php index 1cc89a0..771c4bf 100644 --- a/app/Modules/Billing/Presentation/Livewire/⚡index.blade.php +++ b/app/Modules/Billing/Presentation/Livewire/⚡index.blade.php @@ -74,6 +74,7 @@ new class extends Component ['index' => 'invoices', 'label' => __('billing.index.columns.invoices'), 'sortable' => false, 'align' => 'right'], ['index' => 'jobs', 'label' => __('billing.index.columns.jobs'), 'sortable' => false, 'align' => 'right'], ['index' => 'net', 'label' => __('billing.index.columns.net'), 'sortable' => false, 'align' => 'right'], + ['index' => 'file', 'label' => __('billing.index.columns.file'), 'sortable' => false], ]; } @@ -138,6 +139,12 @@ new class extends Component @interact('column_net', $export) {{ $export->netCents === null ? '' : $this->money($export->netCents) }} @endinteract + + @interact('column_file', $export) + @if ($export->status->value === 'created') + {{ __('billing.csv.download_short') }} + @endif + @endinteract @endif diff --git a/app/Modules/Billing/Presentation/Routes/web.php b/app/Modules/Billing/Presentation/Routes/web.php index bf15e1e..ea3f743 100644 --- a/app/Modules/Billing/Presentation/Routes/web.php +++ b/app/Modules/Billing/Presentation/Routes/web.php @@ -1,5 +1,6 @@ group(function () { Route::livewire('/', 'billing::index')->name('index'); Route::livewire('/{export}', 'billing::export')->whereNumber('export')->name('export'); + Route::get('/{export}/csv', DownloadBillingCsv::class)->whereNumber('export')->name('csv'); }); diff --git a/docs/maarittely.md b/docs/maarittely.md index 067729b..d489f27 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -323,6 +323,7 @@ Hierarkiaa muokataan pohjatietojen hallinnasta. - Aineistoon tulevat vain **hyväksytyt** tunnit. Hyväksymättömät tunnit näytetään luonnoksessa varoituksena linkillä hyväksyntään; ne jäävät laskuttamatta, kun työ siirtyy tilaan Lasku luotu *(valmis)*. - **Kiinteä tarjous**: laskulle tulee yksi rivi, jonka summa on työn tarjoussumma (veroton), vain kerran. Hyväksytyt tunnit näytetään tietona ja merkitään laskutetuiksi. Kulut tulevat eriteltyinä *(valmis)*. - Laskuttamatta jätetään työt, joiden maksuperuste on "ei laskuteta", sisäisen asiakkaan työt, kuluttajat ilman henkilötunnusta ja työt, joiden työtehtävältä puuttuu tuntihinta; syy näytetään johdolle *(valmis)*. +- **CSV-lataus** *(valmis)*: muodostetun aineiston saa ladattua CSV-tiedostona (Excel-yhteensopiva: puolipiste, desimaalipilkku, UTF-8 BOM). Jokainen laskurivi on oma rivinsä, ja siinä on laskun numero aineistossa, asiakas, asiakastyyppi, Y-tunnus, kuluttajan henkilötunnus, laskutusyksikkö, laskutusosoite, verkkolaskuosoite ja välittäjä, viite (laskun tai laskutusyksikön), työ, rivin laji, kuvaus, kirjatut tunnit, määrä ja yksikkö (h, kk, kpl), à-hinta, ALV %, veroton, ALV ja verollinen. Rivin ALV lasketaan riviltä, joten laskun ALV-summa voi erota sivun kannoittaisesta summasta sentillä. Henkilötunnus kirjoitetaan vain, jos lataajalla on oikeus nähdä se; tiedostoa ei välimuisteta, ja kaavaksi tulkittavat solut saavat eteensä heittomerkin. Sarakkeet sovitetaan Fennoan tuontimuotoon, kun esimerkki saadaan (avoin kysymys 4). - Laskutetut tunnit pysyvät hyväksyttyinä (hyväksynnän peruminen ohittaa ne), eikä laskutettua kulua voi muuttaa tai poistaa *(valmis)*. ## 13. Ilmoitukset ja raportit *(K52, K53)* @@ -487,12 +488,12 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t - Valikon "Pikamyynti" (`/sales/new`) puhelimelle sopiva lomake: tuotepainikkeet, myynnin lista määrineen (muutokset ja yhteissumma ilmoitetaan ruudunlukijalle), maksutapa ja vapaaehtoinen asiakas. Tallennuksen jälkeen lomake tyhjenee ja ilmoitus kertoo myynnin numeron, summan ja kirjatut tunnit sekä linkin PDF-kuittiin. Myynnit-sivulla on kuittilinkki jokaisella rivillä. - Myynnit-sivu (`/sales?paiva=VVVV-KK-PP`): päivän myynnit (työntekijä näkee omansa, johto kaikkien ja voi suodattaa myyjän mukaan), hyvitys vahvistusdialogissa, kassapäivän tila, saldo ja ALV-erittely, päättäminen ja johdolle uudelleen avaaminen vahvistusdialogissa, muistutus päättämättömistä aiemmista päivistä. -### 17.7 Laskuaineisto *(valmis, Fennoa-vienti tulossa)* +### 17.7 Laskuaineisto *(valmis, Fennoan tuontimuoto tulossa)* - Valikon "Laskutus" (`/billing`, pääkäyttäjä ja johto): laskuaineistot (tila, laskujen ja töiden määrä, veroton summa) sekä uuden luonnoksen aloitus tai avoimen jatkaminen. - Luonnos (`/billing/{aineisto}`): valmiit työt lisätään yksitellen, ja jokainen on aluksi oma laskunsa. Työn voi siirtää toiselle laskulle, jos asiakas, laskutusyksikkö ja viite sallivat (luku 12), tehdä siitä taas oman laskun tai poistaa. Laskutettavat tunnit kirjataan työtehtävittäin (oletuksena hyväksytyt tunnit). Jokaisella laskulla on veroton summa, ALV kannoittain ja verollinen summa (oletus-ALV-kanta). Muutokset tallentuvat heti. - "Muodosta aineisto" vahvistusdialogissa tarkistaa työt uudelleen, merkitsee hyväksytyt tunnit ja laskutettavat kulut laskutetuiksi, muodostaa rivit hinnan ja ALV:n tilannekuvineen ja siirtää työt tilaan Lasku luotu. Muodostettu aineisto näytetään lukutilassa riveineen. Luonnoksen voi hylätä, jolloin mitään ei laskuteta. - Luonnoksella on laskutuskuukausi (oletuksena kuluva kuukausi), johon asti kk-laskutuksen työt laskutetaan; kuukauden vaihto laskee esikatselun uudelleen (5.5). -- Tulossa: CSV/Excel-vienti Fennoan tuontimuotoon (avoin kysymys 4). +- Muodostetun aineiston sivulla ja Laskutus-listalla on CSV-lataus (luku 12). Tulossa: sarakkeiden sovitus Fennoan tuontimuotoon (avoin kysymys 4). ## 18. Avoimet kysymykset diff --git a/lang/fi/billing.php b/lang/fi/billing.php index e53d690..a3d39f3 100644 --- a/lang/fi/billing.php +++ b/lang/fi/billing.php @@ -3,6 +3,26 @@ return [ 'expense_line' => ':category :day: :what', + 'csv' => [ + 'file' => 'laskuaineisto-:number.csv', + 'download' => 'Lataa CSV', + 'download_short' => 'CSV', + 'download_named' => 'Lataa CSV: Aineisto :number', + 'sensitive' => 'Tiedostossa voi olla kuluttaja-asiakkaiden henkilötunnuksia. Käsittele sitä luottamuksellisena ja poista se, kun tiedot on siirretty laskutukseen.', + 'company' => 'Yritys', + 'consumer' => 'Kuluttaja', + 'units' => [ + 'hours' => 'h', + 'month' => 'kk', + 'piece' => 'kpl', + ], + 'columns' => [ + 'Lasku', 'Asiakas', 'Asiakastyyppi', 'Y-tunnus', 'Henkilötunnus', 'Laskutusyksikkö', 'Laskutusosoite', + 'Verkkolaskuosoite', 'Välittäjä', 'Viite', 'Työ', 'Työn nimi', 'Rivin laji', 'Kuvaus', 'Kirjatut h', + 'Määrä', 'Yksikkö', 'À-hinta', 'ALV %', 'Veroton', 'ALV', 'Verollinen', + ], + ], + 'statuses' => [ 'draft' => 'Luonnos', 'created' => 'Muodostettu', @@ -54,6 +74,7 @@ return [ 'invoices' => 'Laskuja', 'jobs' => 'Töitä', 'net' => 'Veroton summa', + 'file' => 'Tiedosto', ], 'export_label' => 'Aineisto :number', ], diff --git a/tests/Browser/BillingAccessibilityTest.php b/tests/Browser/BillingAccessibilityTest.php index b50676f..3821f38 100644 --- a/tests/Browser/BillingAccessibilityTest.php +++ b/tests/Browser/BillingAccessibilityTest.php @@ -83,6 +83,7 @@ it('adds and combines jobs and creates the material', function () { ->click('#finalize-dialog button:last-child') ->assertSee('Laskuaineisto muodostettu: 2 laskua.') ->assertSee('Laskutetut h') + ->assertSee('Lataa CSV') ->assertNoAccessibilityIssues(level: 2); expect($first->refresh()->status)->toBe(JobStatus::Invoiced); diff --git a/tests/Feature/Modules/Billing/BillingCsvTest.php b/tests/Feature/Modules/Billing/BillingCsvTest.php new file mode 100644 index 0000000..9d48ca6 --- /dev/null +++ b/tests/Feature/Modules/Billing/BillingCsvTest.php @@ -0,0 +1,152 @@ +manager = User::factory()->management()->create(); + $this->actingAs($this->manager); + $this->layout = WorkTypeModel::factory()->create(['name' => 'Taitto', 'hourly_rate_cents' => 8050]); +}); + +/** + * @param array $attributes + */ +function billedJob(CustomerModel $customer, array $attributes = [], float $hours = 2.5): CustomerJobModel +{ + $job = CustomerJobModel::factory()->create(array_merge([ + 'customer_id' => $customer->id, + 'status' => JobStatus::Done, + 'payment_basis' => 'hourly', + ], $attributes)); + + $task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'work_type_id' => test()->layout->id]); + TimeEntryModel::factory()->approved()->create(['task_id' => $task->id, 'hours' => $hours]); + + return $job; +} + +/** + * @param list $jobs + */ +function createdExport(array $jobs): int +{ + $exportId = app(OpenBillingDraft::class)->execute(test()->manager->id); + + foreach ($jobs as $job) { + app(AddJobToDraft::class)->execute($exportId, $job->id); + } + + app(FinalizeBillingExport::class)->execute($exportId, test()->manager->id); + + return $exportId; +} + +/** + * @return list> + */ +function csvRows(string $content): array +{ + $handle = fopen('php://memory', 'r+'); + fwrite($handle, $content); + rewind($handle); + $rows = []; + + while (($row = fgetcsv($handle, null, ';', '"', '')) !== false) { + $rows[] = $row; + } + + return $rows; +} + +it('downloads a created billing material as a CSV file for Excel', function () { + $company = CustomerModel::factory()->company('0737546-2')->create(['name' => 'Asiakas Oy']); + $unit = BillingUnitModel::factory()->create([ + 'customer_id' => $company->id, + 'name' => 'Talous', + 'billing_address' => "PL 10\n40100 Jyväskylä", + 'e_invoice_address' => '003707375462', + 'e_invoice_operator' => 'E204503', + 'reference' => 'KP-77', + ]); + $first = billedJob($company, ['name' => 'Esite', 'billing_unit_id' => $unit->id, 'customer_reference' => 'PO-1']); + ExpenseModel::factory()->create(['customer_job_id' => $first->id, 'description' => 'Paperi', 'billed_amount_cents' => 1000]); + $consumer = CustomerModel::factory()->consumer()->create(['name' => 'Kalle Kuluttaja', 'personal_identity_code' => '131052-308T']); + $second = billedJob($consumer, ['name' => '=HYPERLINK("x")'], 1); + + $exportId = createdExport([$first, $second]); + + $response = $this->get(route('billing.csv', $exportId)) + ->assertOk() + ->assertHeader('Content-Type', 'text/csv; charset=UTF-8') + ->assertDownload("laskuaineisto-{$exportId}.csv"); + + expect($response->headers->get('Cache-Control'))->toContain('no-store'); + + $content = $response->streamedContent(); + expect($content)->toStartWith("\u{FEFF}"); + + $rows = csvRows(substr($content, 3)); + expect($rows[0])->toBe(array_values(__('billing.csv.columns'))) + ->and($rows)->toHaveCount(4) + ->and($rows[1])->toBe([ + '1', 'Asiakas Oy', 'Yritys', '0737546-2', '', 'Talous', "PL 10\n40100 Jyväskylä", '003707375462', 'E204503', 'PO-1', + $first->number, 'Esite', 'Tunnit', 'Taitto', '2,5', '2,5', 'h', '80,50', '25,5', '201,25', '51,32', '252,57', + ]) + ->and($rows[2][12])->toBe('Kulu') + ->and($rows[2][13])->toEndWith(': Paperi') + ->and(array_slice($rows[2], 15))->toBe(['1', 'kpl', '10,00', '25,5', '10,00', '2,55', '12,55']) + ->and(array_slice($rows[3], 0, 6))->toBe(['2', 'Kalle Kuluttaja', 'Kuluttaja', '', '131052-308T', '']) + ->and($rows[3][11])->toBe("'=HYPERLINK(\"x\")") + ->and($rows[3][19])->toBe('80,50'); +}); + +it('uses the billing unit reference when the jobs have none and offers the file on the pages', function () { + $company = CustomerModel::factory()->company()->create(); + $unit = BillingUnitModel::factory()->create(['customer_id' => $company->id, 'reference' => 'KP-77']); + $exportId = createdExport([billedJob($company, ['billing_unit_id' => $unit->id])]); + + expect(csvRows(substr($this->get(route('billing.csv', $exportId))->streamedContent(), 3))[1][9])->toBe('KP-77'); + + $this->get(route('billing.export', $exportId))->assertSee('Lataa CSV')->assertSee('henkilötunnuksia'); + $this->get(route('billing.index'))->assertSee(route('billing.csv', $exportId)); +}); + +it('does not download a draft', function () { + $exportId = app(OpenBillingDraft::class)->execute($this->manager->id); + + $this->get(route('billing.csv', $exportId))->assertNotFound(); + $this->get(route('billing.csv', 999))->assertNotFound(); +}); + +it('keeps everyone but management out of the file', function () { + $exportId = createdExport([billedJob(CustomerModel::factory()->company()->create())]); + $this->actingAs(User::factory()->employee()->create()); + + $this->get(route('billing.csv', $exportId))->assertForbidden(); +}); + +it('guards cells against formula injection', function (string $value, string $cell) { + expect(DownloadBillingCsv::cell($value))->toBe($cell); +})->with([ + ['=1+1', "'=1+1"], + ['+358 40', "'+358 40"], + ['-5', "'-5"], + ['@IMPORT', "'@IMPORT"], + ['Taitto', 'Taitto'], + ['12,50', '12,50'], +]);