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 <[email protected]>
This commit is contained in:
2026-11-24 13:32:46 +02:00
co-authored by Claude Opus 5.5
parent 5f9423a3c3
commit ae7b611126
16 changed files with 520 additions and 3 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project ## 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: `<x-input>`, `<x-button>`), 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: `<x-input>`, `<x-button>`), 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. - **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. - **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.
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Contracts;
use App\Modules\Billing\Application\DTOs\CustomerBillingDetails;
/**
* Customers' invoicing details for billing files, from the Customers module.
*/
interface BillingCustomers
{
/**
* @param bool $withIdentityCode Whether a consumer's full personal identity code is included; the caller checks the permission.
*/
public function billingDetails(int $customerId, ?int $billingUnitId, bool $withIdentityCode): CustomerBillingDetails;
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
/**
* Who an invoice goes to and where. The personal identity code of a
* consumer is sensitive: it is filled in only when the caller may see it,
* and never logged or shown on a page.
*/
final readonly class CustomerBillingDetails
{
public function __construct(
public string $name,
public bool $isConsumer,
public ?string $businessId,
public ?string $personalIdentityCode,
public ?string $billingUnitName,
public ?string $billingAddress,
public ?string $eInvoiceAddress,
public ?string $eInvoiceOperator,
public ?string $billingUnitReference,
) {}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
use App\Modules\Billing\Domain\Enums\LineKind;
/**
* One invoice line of a created billing material for a billing file, with
* its invoice's customer details. Amounts are in cents; the quantity is in
* quarters of an hour for hours, otherwise in pieces (a month is one).
*/
final readonly class ExportRow
{
public function __construct(
public int $invoiceNumber,
public CustomerBillingDetails $customer,
public ?string $reference,
public string $jobNumber,
public string $jobName,
public LineKind $kind,
public string $description,
public ?int $recordedQuarters,
public ?int $quantityQuarters,
public int $unitPriceCents,
public int $vatBasisPoints,
public int $netCents,
public int $vatCents,
) {}
public function grossCents(): int
{
return $this->netCents + $this->vatCents;
}
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Services;
use App\Modules\Billing\Application\Contracts\BillingCustomers;
use App\Modules\Billing\Application\Contracts\BillingJobs;
use App\Modules\Billing\Application\DTOs\ExportRow;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportNotCreated;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
/**
* The lines of a created billing material for a billing file, in the
* order of its invoices, each with its invoice's customer details. A
* line's VAT is counted from the line (rounded half up), so an invoice's
* VAT summed from its lines may differ by a cent from the page, which
* counts it from each rate's total.
*/
final class ExportRows
{
public function __construct(
private BillingExportRepository $exports,
private BillingJobs $jobs,
private BillingCustomers $customers,
) {}
/**
* @param bool $withIdentityCodes Whether consumers' personal identity codes are included; the caller checks the permission.
* @return list<ExportRow>
*
* @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;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ExportNotCreated extends DomainException
{
public function __construct()
{
parent::__construct('The billing material is still a draft.');
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Modules\Billing\Infrastructure;
use App\Modules\Billing\Application\Contracts\BillingCustomers;
use App\Modules\Billing\Application\DTOs\CustomerBillingDetails;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Domain\Enums\CustomerType;
/**
* Customers' invoicing details through the Customers module's queries.
*/
class CustomersForBilling implements BillingCustomers
{
public function __construct(private CustomerQueries $customers) {}
public function billingDetails(int $customerId, ?int $billingUnitId, bool $withIdentityCode): CustomerBillingDetails
{
$customer = $this->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,
);
}
}
@@ -3,12 +3,14 @@
namespace App\Modules\Billing\Infrastructure\Providers; namespace App\Modules\Billing\Infrastructure\Providers;
use App\Models\User; use App\Models\User;
use App\Modules\Billing\Application\Contracts\BillingCustomers;
use App\Modules\Billing\Application\Contracts\BillingExpenses; use App\Modules\Billing\Application\Contracts\BillingExpenses;
use App\Modules\Billing\Application\Contracts\BillingHours; use App\Modules\Billing\Application\Contracts\BillingHours;
use App\Modules\Billing\Application\Contracts\BillingJobs; use App\Modules\Billing\Application\Contracts\BillingJobs;
use App\Modules\Billing\Application\Contracts\BillingPrices; use App\Modules\Billing\Application\Contracts\BillingPrices;
use App\Modules\Billing\Application\Contracts\BillingQueries; use App\Modules\Billing\Application\Contracts\BillingQueries;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository; use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Infrastructure\CustomersForBilling;
use App\Modules\Billing\Infrastructure\ExpensesForBilling; use App\Modules\Billing\Infrastructure\ExpensesForBilling;
use App\Modules\Billing\Infrastructure\HoursForBilling; use App\Modules\Billing\Infrastructure\HoursForBilling;
use App\Modules\Billing\Infrastructure\JobsForBilling; use App\Modules\Billing\Infrastructure\JobsForBilling;
@@ -36,6 +38,7 @@ class BillingServiceProvider extends ServiceProvider
BillingHours::class => HoursForBilling::class, BillingHours::class => HoursForBilling::class,
BillingExpenses::class => ExpensesForBilling::class, BillingExpenses::class => ExpensesForBilling::class,
BillingPrices::class => PricesForBilling::class, BillingPrices::class => PricesForBilling::class,
BillingCustomers::class => CustomersForBilling::class,
]; ];
public function boot(): void public function boot(): void
@@ -0,0 +1,117 @@
<?php
namespace App\Modules\Billing\Presentation\Http\Controllers;
use App\Modules\Billing\Application\DTOs\ExportRow;
use App\Modules\Billing\Application\Services\ExportRows;
use App\Modules\Billing\Domain\Enums\LineKind;
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
use App\Modules\Billing\Domain\Exceptions\ExportNotCreated;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Downloads a created billing material as a CSV file for Excel and the
* invoicing program: one row per invoice line, semicolons, decimal
* commas and a UTF-8 BOM. Consumers' personal identity codes are included
* for those who may see them, so the response is never cached.
*/
class DownloadBillingCsv
{
public function __invoke(int $export, ExportRows $exportRows): StreamedResponse
{
Gate::authorize('billing.manage');
try {
$rows = $exportRows->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<string>
*/
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'), ',');
}
}
@@ -321,6 +321,13 @@ new class extends Component
<p class="text-sm font-medium"> <p class="text-sm font-medium">
{{ __('billing.export.summary', ['invoices' => count($export->invoices), 'jobs' => $export->jobCount(), 'net' => $this->money($export->totals->netCents)]) }} {{ __('billing.export.summary', ['invoices' => count($export->invoices), 'jobs' => $export->jobCount(), 'net' => $this->money($export->totals->netCents)]) }}
</p> </p>
@if (! $export->isDraft())
<div class="space-y-2">
<x-button :href="route('billing.csv', $export->id)" icon="arrow-down-tray" :text="__('billing.csv.download')" />
<p class="max-w-3xl text-sm">{{ __('billing.csv.sensitive') }}</p>
</div>
@endif
</div> </div>
<p id="billing-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $statusMessage }}</p> <p id="billing-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $statusMessage }}</p>
@@ -74,6 +74,7 @@ new class extends Component
['index' => 'invoices', 'label' => __('billing.index.columns.invoices'), 'sortable' => false, 'align' => 'right'], ['index' => 'invoices', 'label' => __('billing.index.columns.invoices'), 'sortable' => false, 'align' => 'right'],
['index' => 'jobs', 'label' => __('billing.index.columns.jobs'), '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' => '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) @interact('column_net', $export)
<span class="whitespace-nowrap">{{ $export->netCents === null ? '' : $this->money($export->netCents) }}</span> <span class="whitespace-nowrap">{{ $export->netCents === null ? '' : $this->money($export->netCents) }}</span>
@endinteract @endinteract
@interact('column_file', $export)
@if ($export->status->value === 'created')
<x-link :href="route('billing.csv', $export->id)" icon="arrow-down-tray" :aria-label="__('billing.csv.download_named', ['number' => $export->id])">{{ __('billing.csv.download_short') }}</x-link>
@endif
@endinteract
</x-table> </x-table>
@endif @endif
</div> </div>
@@ -1,5 +1,6 @@
<?php <?php
use App\Modules\Billing\Presentation\Http\Controllers\DownloadBillingCsv;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth', 'can:billing.manage']) Route::middleware(['web', 'auth', 'can:billing.manage'])
@@ -8,4 +9,5 @@ Route::middleware(['web', 'auth', 'can:billing.manage'])
->group(function () { ->group(function () {
Route::livewire('/', 'billing::index')->name('index'); Route::livewire('/', 'billing::index')->name('index');
Route::livewire('/{export}', 'billing::export')->whereNumber('export')->name('export'); Route::livewire('/{export}', 'billing::export')->whereNumber('export')->name('export');
Route::get('/{export}/csv', DownloadBillingCsv::class)->whereNumber('export')->name('csv');
}); });
+3 -2
View File
@@ -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)*. - 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)*. - **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)*. - 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)*. - 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)* ## 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ä. - 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ä. - 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. - 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. - 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. - "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). - 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 ## 18. Avoimet kysymykset
+21
View File
@@ -3,6 +3,26 @@
return [ return [
'expense_line' => ':category :day: :what', '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' => [ 'statuses' => [
'draft' => 'Luonnos', 'draft' => 'Luonnos',
'created' => 'Muodostettu', 'created' => 'Muodostettu',
@@ -54,6 +74,7 @@ return [
'invoices' => 'Laskuja', 'invoices' => 'Laskuja',
'jobs' => 'Töitä', 'jobs' => 'Töitä',
'net' => 'Veroton summa', 'net' => 'Veroton summa',
'file' => 'Tiedosto',
], ],
'export_label' => 'Aineisto :number', 'export_label' => 'Aineisto :number',
], ],
@@ -83,6 +83,7 @@ it('adds and combines jobs and creates the material', function () {
->click('#finalize-dialog button:last-child') ->click('#finalize-dialog button:last-child')
->assertSee('Laskuaineisto muodostettu: 2 laskua.') ->assertSee('Laskuaineisto muodostettu: 2 laskua.')
->assertSee('Laskutetut h') ->assertSee('Laskutetut h')
->assertSee('Lataa CSV')
->assertNoAccessibilityIssues(level: 2); ->assertNoAccessibilityIssues(level: 2);
expect($first->refresh()->status)->toBe(JobStatus::Invoiced); expect($first->refresh()->status)->toBe(JobStatus::Invoiced);
@@ -0,0 +1,152 @@
<?php
use App\Models\User;
use App\Modules\Billing\Application\UseCases\AddJobToDraft;
use App\Modules\Billing\Application\UseCases\FinalizeBillingExport;
use App\Modules\Billing\Application\UseCases\OpenBillingDraft;
use App\Modules\Billing\Presentation\Http\Controllers\DownloadBillingCsv;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\BillingUnitModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->manager = User::factory()->management()->create();
$this->actingAs($this->manager);
$this->layout = WorkTypeModel::factory()->create(['name' => 'Taitto', 'hourly_rate_cents' => 8050]);
});
/**
* @param array<string, mixed> $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<CustomerJobModel> $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<list<string>>
*/
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'],
]);