diff --git a/app/Modules/Jobs/Application/Contracts/TaskQueries.php b/app/Modules/Jobs/Application/Contracts/TaskQueries.php index b3fad7c..1eb85b8 100644 --- a/app/Modules/Jobs/Application/Contracts/TaskQueries.php +++ b/app/Modules/Jobs/Application/Contracts/TaskQueries.php @@ -23,6 +23,16 @@ interface TaskQueries */ public function pinnedTaskIds(int $jobId): array; + /** + * Tasks scheduled for the user between the dates (Y-m-d): booked on + * their task calendar row, or open tasks they are the assignee or a + * member of whose planned period overlaps the dates or that have no + * planned period at all (so unscheduled own work is never hidden). + * + * @return list + */ + public function scheduledTaskIdsFor(int $userId, string $from, string $to): array; + /** * Null when the task does not exist or belongs to another job. */ diff --git a/app/Modules/Jobs/Application/DTOs/BookableTask.php b/app/Modules/Jobs/Application/DTOs/BookableTask.php index 3a81b62..cb8d6b3 100644 --- a/app/Modules/Jobs/Application/DTOs/BookableTask.php +++ b/app/Modules/Jobs/Application/DTOs/BookableTask.php @@ -8,8 +8,9 @@ use App\Modules\Jobs\Domain\Enums\JobStatus; use App\Modules\Jobs\Domain\Enums\TaskStatus; /** - * A task as time is recorded on it: which job and work type it belongs to, - * and whether the job is locked for time entries. + * A task as time is recorded on it: which job, customer and work type it + * belongs to, the job's payment basis (a PaymentBasis value) and whether + * the job is locked for time entries. */ final readonly class BookableTask { @@ -23,6 +24,10 @@ final readonly class BookableTask public string $workTypeName, public JobStatus $jobStatus, public TaskStatus $taskStatus, + public int $customerId = 0, + public string $customerName = '', + public ?string $customerHeaderColor = null, + public ?string $paymentBasis = null, ) {} public function isLocked(): bool diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php index 92ccc3a..2be494e 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php @@ -3,6 +3,7 @@ namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories; use App\Modules\Catalog\Application\Contracts\CatalogQueries; +use App\Modules\Customers\Application\Contracts\CustomerQueries; use App\Modules\Jobs\Application\Contracts\TaskQueries; use App\Modules\Jobs\Application\DTOs\BookableTask; use App\Modules\Jobs\Application\DTOs\NamedId; @@ -21,8 +22,31 @@ class EloquentTaskQueries implements TaskQueries public function __construct( private CatalogQueries $catalog, private UserAccountQueries $users, + private CustomerQueries $customers, ) {} + public function scheduledTaskIdsFor(int $userId, string $from, string $to): array + { + $booked = DB::table('task_bookings') + ->where('user_id', $userId) + ->whereBetween('day', [$from, $to]) + ->pluck('task_id'); + + $planned = DB::table('tasks') + ->where('status', '!=', TaskStatus::Done->value) + ->where(fn ($query) => $query + ->whereNull('planned_from') + ->orWhere(fn ($query) => $query + ->where('planned_from', '<=', $to) + ->where(fn ($query) => $query->whereNull('planned_to')->orWhere('planned_to', '>=', $from)))) + ->where(fn ($query) => $query + ->where('assignee_user_id', $userId) + ->orWhereIn('id', DB::table('task_members')->select('task_id')->where('user_id', $userId))) + ->pluck('id'); + + return $booked->merge($planned)->map(fn ($id): int => (int) $id)->unique()->values()->all(); + } + public function tasksOf(int $jobId): array { $models = TaskModel::query() @@ -116,7 +140,11 @@ class EloquentTaskQueries implements TaskQueries ->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id') ->orderBy('customer_jobs.number') ->orderBy('tasks.id') - ->get(['tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.work_type_id', 'tasks.status', 'customer_jobs.number', 'customer_jobs.name', 'customer_jobs.status as job_status']); + ->get(['tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.work_type_id', 'tasks.status', 'customer_jobs.number', 'customer_jobs.name', 'customer_jobs.status as job_status', 'customer_jobs.customer_id', 'customer_jobs.payment_basis']); + + $customerIds = $rows->pluck('customer_id')->map(fn ($id): int => (int) $id)->unique()->values()->all(); + $customerNames = $this->customers->namesByIds($customerIds); + $customerColors = $this->customers->headerColorsByIds($customerIds); $workTypeNames = []; foreach ($rows->pluck('work_type_id')->unique() as $workTypeId) { @@ -133,6 +161,10 @@ class EloquentTaskQueries implements TaskQueries $workTypeNames[(int) $row->work_type_id] ?? '', JobStatus::from((string) $row->job_status), TaskStatus::from((string) $row->status), + (int) $row->customer_id, + $customerNames[(int) $row->customer_id] ?? '', + $customerColors[(int) $row->customer_id] ?? null, + $row->payment_basis === null ? null : (string) $row->payment_basis, ))->values()->all(); } diff --git a/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php b/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php index 2ab7680..41e6a5a 100644 --- a/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php +++ b/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php @@ -6,7 +6,9 @@ namespace App\Modules\TimeTracking\Application\Contracts; use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek; use App\Modules\TimeTracking\Application\DTOs\JobBillingHours; +use App\Modules\TimeTracking\Application\DTOs\MonthSummary; use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary; +use App\Modules\TimeTracking\Application\DTOs\TimesheetWeek; use App\Modules\TimeTracking\Application\DTOs\WeekSheet; interface TimeEntryQueries @@ -19,6 +21,19 @@ interface TimeEntryQueries */ public function week(int $userId, string $monday, array $extraTaskIds = []): WeekSheet; + /** + * The time sheet of a week: scheduled and pinned tasks with their + * entries, grouped by customer and job (docs/ui-timesheet.md 4). + * + * @param string $monday Y-m-d + */ + public function timesheet(int $userId, string $monday): TimesheetWeek; + + /** + * The user's hours in a month (Y-m), billable against internal. + */ + public function monthSummary(int $userId, string $month): MonthSummary; + /** * The user's entries on a task, newest day first. * diff --git a/app/Modules/TimeTracking/Application/DTOs/MissingBillingNote.php b/app/Modules/TimeTracking/Application/DTOs/MissingBillingNote.php new file mode 100644 index 0000000..c551119 --- /dev/null +++ b/app/Modules/TimeTracking/Application/DTOs/MissingBillingNote.php @@ -0,0 +1,20 @@ +billingNote !== null && trim($this->billingNote) !== ''; + } +} diff --git a/app/Modules/TimeTracking/Application/DTOs/TimesheetCustomerGroup.php b/app/Modules/TimeTracking/Application/DTOs/TimesheetCustomerGroup.php new file mode 100644 index 0000000..23f7b03 --- /dev/null +++ b/app/Modules/TimeTracking/Application/DTOs/TimesheetCustomerGroup.php @@ -0,0 +1,26 @@ + $jobs + */ + public function __construct( + public int $customerId, + public string $name, + public ?string $headerColor, + public array $jobs, + ) {} + + public function taskCount(): int + { + return array_sum(array_map(fn (TimesheetJobGroup $job): int => count($job->rows), $this->jobs)); + } +} diff --git a/app/Modules/TimeTracking/Application/DTOs/TimesheetJobGroup.php b/app/Modules/TimeTracking/Application/DTOs/TimesheetJobGroup.php new file mode 100644 index 0000000..8b08917 --- /dev/null +++ b/app/Modules/TimeTracking/Application/DTOs/TimesheetJobGroup.php @@ -0,0 +1,37 @@ + $rows + */ + public function __construct( + public int $jobId, + public string $number, + public string $name, + public JobStatus $status, + public ?string $paymentBasis, + public int $accumulatedQuarters, + public array $rows, + ) {} + + public function billingModel(): EntryBillingModel + { + return EntryBillingModel::forPaymentBasis($this->paymentBasis); + } + + public function isContinuing(): bool + { + return $this->status === JobStatus::Ongoing; + } +} diff --git a/app/Modules/TimeTracking/Application/DTOs/TimesheetTaskRow.php b/app/Modules/TimeTracking/Application/DTOs/TimesheetTaskRow.php new file mode 100644 index 0000000..8e23722 --- /dev/null +++ b/app/Modules/TimeTracking/Application/DTOs/TimesheetTaskRow.php @@ -0,0 +1,37 @@ + $cells by Y-m-d + */ + public function __construct( + public BookableTask $task, + public array $cells, + public int $totalQuarters, + public bool $pinned, + ) {} + + public function cell(string $day): ?TimesheetCell + { + return $this->cells[$day] ?? null; + } + + /** + * The laskutusperuste new entries get: from the job's payment basis. + */ + public function defaultBillingModel(): EntryBillingModel + { + return EntryBillingModel::forPaymentBasis($this->task->paymentBasis); + } +} diff --git a/app/Modules/TimeTracking/Application/DTOs/TimesheetWeek.php b/app/Modules/TimeTracking/Application/DTOs/TimesheetWeek.php new file mode 100644 index 0000000..ae67c13 --- /dev/null +++ b/app/Modules/TimeTracking/Application/DTOs/TimesheetWeek.php @@ -0,0 +1,77 @@ + $days Y-m-d, Monday to Sunday + * @param list $scheduled + * @param list $pinned + * @param array $dayTotals + * @param list $missingNotes + */ + public function __construct( + public array $days, + public array $scheduled, + public array $pinned, + public array $dayTotals, + public int $totalQuarters, + public int $unapprovedQuarters, + public ?WeekApproval $lastApproval, + public array $missingNotes, + ) {} + + public function isApproved(): bool + { + return $this->totalQuarters > 0 && $this->unapprovedQuarters === 0; + } + + /** + * @return list + */ + public function rows(): array + { + $rows = []; + + foreach ([...$this->scheduled, ...$this->pinned] as $customer) { + foreach ($customer->jobs as $job) { + foreach ($job->rows as $row) { + $rows[] = $row; + } + } + } + + return $rows; + } + + public function row(int $taskId): ?TimesheetTaskRow + { + foreach ($this->rows() as $row) { + if ($row->task->taskId === $taskId) { + return $row; + } + } + + return null; + } + + public function scheduledTaskCount(): int + { + return array_sum(array_map(fn (TimesheetCustomerGroup $customer): int => $customer->taskCount(), $this->scheduled)); + } + + public function pinnedTaskCount(): int + { + return array_sum(array_map(fn (TimesheetCustomerGroup $customer): int => $customer->taskCount(), $this->pinned)); + } +} diff --git a/app/Modules/TimeTracking/Application/Services/TimesheetLayout.php b/app/Modules/TimeTracking/Application/Services/TimesheetLayout.php new file mode 100644 index 0000000..e0e6f21 --- /dev/null +++ b/app/Modules/TimeTracking/Application/Services/TimesheetLayout.php @@ -0,0 +1,91 @@ + $rows every candidate row, pinned or not + * @param list $scheduledTaskIds + * @param array $accumulatedQuarters by job id + * @return array{scheduled: list, pinned: list} + */ + public function arrange(array $rows, array $scheduledTaskIds, array $accumulatedQuarters): array + { + $scheduled = []; + $pinned = []; + + foreach ($rows as $row) { + $open = ! $row->task->isLocked() && $row->task->taskStatus->value !== 'done'; + + if ($row->pinned && ($open || $row->totalQuarters > 0)) { + $pinned[] = $row; + } elseif ($row->totalQuarters > 0 || ($open && in_array($row->task->taskId, $scheduledTaskIds, true))) { + $scheduled[] = $row; + } + } + + return [ + 'scheduled' => $this->grouped($scheduled, $accumulatedQuarters), + 'pinned' => $this->grouped($pinned, $accumulatedQuarters), + ]; + } + + /** + * @param list $rows + * @param array $accumulatedQuarters + * @return list + */ + private function grouped(array $rows, array $accumulatedQuarters): array + { + $collator = class_exists(Collator::class) ? new Collator('fi_FI') : null; + $compare = fn (string $a, string $b): int => $collator?->compare($a, $b) ?: strcmp(mb_strtolower($a), mb_strtolower($b)); + + usort($rows, fn (TimesheetTaskRow $a, TimesheetTaskRow $b): int => $compare($a->task->customerName, $b->task->customerName) + ?: ($a->task->customerId <=> $b->task->customerId) + ?: strnatcmp($a->task->jobNumber, $b->task->jobNumber) + ?: $compare($a->task->taskTitle, $b->task->taskTitle) + ?: ($a->task->taskId <=> $b->task->taskId)); + + $customers = []; + + foreach ($rows as $row) { + $customers[$row->task->customerId]['name'] = $row->task->customerName; + $customers[$row->task->customerId]['color'] = $row->task->customerHeaderColor; + $customers[$row->task->customerId]['jobs'][$row->task->jobId][] = $row; + } + + $groups = []; + + foreach ($customers as $customerId => $customer) { + $jobs = []; + + foreach ($customer['jobs'] as $jobId => $jobRows) { + $task = $jobRows[0]->task; + $jobs[] = new TimesheetJobGroup($jobId, $task->jobNumber, $task->jobName, $task->jobStatus, $task->paymentBasis, $accumulatedQuarters[$jobId] ?? 0, $jobRows); + } + + $groups[] = new TimesheetCustomerGroup($customerId, $customer['name'], $customer['color'], $jobs); + } + + return $groups; + } +} diff --git a/app/Modules/TimeTracking/Application/UseCases/ApproveWeek.php b/app/Modules/TimeTracking/Application/UseCases/ApproveWeek.php index a0f7887..f095bfc 100644 --- a/app/Modules/TimeTracking/Application/UseCases/ApproveWeek.php +++ b/app/Modules/TimeTracking/Application/UseCases/ApproveWeek.php @@ -7,6 +7,7 @@ namespace App\Modules\TimeTracking\Application\UseCases; use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\TimeTracking\Application\Services\TimeBooking; use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository; +use App\Modules\TimeTracking\Domain\Exceptions\BillingNotesMissing; use App\Modules\Users\Application\Contracts\Clock; /** @@ -24,6 +25,8 @@ final class ApproveWeek /** * @param string $monday Y-m-d of the week's Monday. * @return int How many entries were approved now. + * + * @throws BillingNotesMissing when an unapproved entry has no billing note */ public function execute(int $userId, string $monday, int $approverId): int { @@ -32,8 +35,20 @@ final class ApproveWeek return $this->transactions->run(function () use ($userId, $start, $approverId, $now): int { $approved = 0; + $entries = $this->entries->forUserBetween($userId, $start, $start->modify('+6 days')); + $missing = []; - foreach ($this->entries->forUserBetween($userId, $start, $start->modify('+6 days')) as $entry) { + foreach ($entries as $entry) { + if (! $entry->isApproved() && ! $entry->hasBillingNote()) { + $missing[] = (int) $entry->id(); + } + } + + if ($missing !== []) { + throw new BillingNotesMissing($missing); + } + + foreach ($entries as $entry) { if ($entry->isApproved()) { continue; } diff --git a/app/Modules/TimeTracking/Application/UseCases/DescribeTimeEntry.php b/app/Modules/TimeTracking/Application/UseCases/DescribeTimeEntry.php new file mode 100644 index 0000000..a362214 --- /dev/null +++ b/app/Modules/TimeTracking/Application/UseCases/DescribeTimeEntry.php @@ -0,0 +1,40 @@ +transactions->run(function () use ($userId, $taskId, $date, $billingModel, $billingNote, $internalComment): void { + $entry = $this->entries->findForDay($userId, $taskId, $date) ?? throw new TimeEntryNotFound(0); + + $entry->describe($billingModel, $billingNote, $internalComment); + $this->entries->save($entry); + }); + } +} diff --git a/app/Modules/TimeTracking/Application/UseCases/PinTimesheetTasks.php b/app/Modules/TimeTracking/Application/UseCases/PinTimesheetTasks.php new file mode 100644 index 0000000..6480fd2 --- /dev/null +++ b/app/Modules/TimeTracking/Application/UseCases/PinTimesheetTasks.php @@ -0,0 +1,63 @@ + $taskIds + * + * @throws TaskNotBookable + * @throws TimeLocked + */ + public function pin(int $userId, array $taskIds): void + { + $now = $this->clock->now(); + + $this->transactions->run(function () use ($userId, $taskIds, $now): void { + foreach ($taskIds as $taskId) { + $task = $this->tasks->bookableTask($taskId) ?? throw new TaskNotBookable($taskId); + + if ($task->isLocked()) { + throw new TimeLocked; + } + + $this->pins->pin($userId, $taskId, $now); + } + }); + } + + public function unpin(int $userId, int $taskId): void + { + $this->transactions->run(fn () => $this->pins->unpin($userId, $taskId)); + } + + /** + * "Poista kaikki kiinnitykset". + */ + public function unpinAll(int $userId): int + { + return $this->transactions->run(fn (): int => $this->pins->unpinAll($userId)); + } +} diff --git a/app/Modules/TimeTracking/Domain/Contracts/PinnedTaskRepository.php b/app/Modules/TimeTracking/Domain/Contracts/PinnedTaskRepository.php new file mode 100644 index 0000000..3496a1e --- /dev/null +++ b/app/Modules/TimeTracking/Domain/Contracts/PinnedTaskRepository.php @@ -0,0 +1,27 @@ + + */ + public function pinnedTaskIds(int $userId): array; +} diff --git a/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php b/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php index a7a185a..a9b3416 100644 --- a/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php +++ b/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Modules\TimeTracking\Domain\Entities; +use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel; use App\Modules\TimeTracking\Domain\Exceptions\TimeApproved; use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours; use DateTimeImmutable; @@ -28,6 +29,8 @@ final class TimeEntry private ?int $approvedBy = null, private ?DateTimeImmutable $approvedAt = null, private ?int $billingExportId = null, + private ?EntryBillingModel $billingModel = null, + private ?string $internalComment = null, ) {} public static function create(int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note = null): self @@ -35,9 +38,39 @@ final class TimeEntry return new self(null, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, self::text($note)); } - public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null, ?int $billingExportId = null): self + public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null, ?int $billingExportId = null, ?EntryBillingModel $billingModel = null, ?string $internalComment = null): self { - return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt, $billingExportId); + return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt, $billingExportId, $billingModel, $internalComment); + } + + /** + * The entry's laskutusperuste, billing note (shown to the customer or in + * fixed-price follow-up, required before the week is approved) and + * internal comment. A null billing model follows the job. + * + * @throws TimeApproved + */ + public function describe(?EntryBillingModel $billingModel, ?string $billingNote, ?string $internalComment): void + { + $this->ensureNotApproved(); + $this->billingModel = $billingModel; + $this->note = self::text($billingNote); + $this->internalComment = self::text($internalComment); + } + + public function hasBillingNote(): bool + { + return $this->note !== null; + } + + public function billingModel(): ?EntryBillingModel + { + return $this->billingModel; + } + + public function internalComment(): ?string + { + return $this->internalComment; } /** diff --git a/app/Modules/TimeTracking/Domain/Enums/EntryBillingModel.php b/app/Modules/TimeTracking/Domain/Enums/EntryBillingModel.php new file mode 100644 index 0000000..8bfb3b8 --- /dev/null +++ b/app/Modules/TimeTracking/Domain/Enums/EntryBillingModel.php @@ -0,0 +1,47 @@ + self::Fixed, + 'not_billable' => self::NonBillable, + default => self::Hourly, + }; + } + + public function symbol(): string + { + return match ($this) { + self::Fixed => 'K', + self::Hourly => '€', + self::NonBillable => '•', + }; + } + + /** + * Billed or within a fixed price, against internal work. + */ + public function isBillable(): bool + { + return $this !== self::NonBillable; + } +} diff --git a/app/Modules/TimeTracking/Domain/Exceptions/BillingNotesMissing.php b/app/Modules/TimeTracking/Domain/Exceptions/BillingNotesMissing.php new file mode 100644 index 0000000..193de35 --- /dev/null +++ b/app/Modules/TimeTracking/Domain/Exceptions/BillingNotesMissing.php @@ -0,0 +1,22 @@ + $entryIds + */ + public function __construct(public readonly array $entryIds) + { + parent::__construct(count($entryIds).' time entries have no billing note.'); + } +} diff --git a/app/Modules/TimeTracking/Domain/ValueObjects/WorkedHours.php b/app/Modules/TimeTracking/Domain/ValueObjects/WorkedHours.php index 538aeb1..2171348 100644 --- a/app/Modules/TimeTracking/Domain/ValueObjects/WorkedHours.php +++ b/app/Modules/TimeTracking/Domain/ValueObjects/WorkedHours.php @@ -51,6 +51,47 @@ final readonly class WorkedHours return new self((int) round($quarters)); } + /** + * Parses what the time sheet's cell accepts (docs/ui-timesheet.md 5.1): + * "1:30" (hours and minutes), "1,5" or "1.5" (hours), a whole number up + * to 24 as hours ("2") and above it as minutes ("90"). Null for an empty + * value or zero. Always whole quarter hours. + * + * @throws InvalidWorkedHours + */ + public static function parseFlexible(string $value): ?self + { + $value = trim($value); + + if ($value === '' || preg_match('/^0+([:.,]0+)?$/', $value) === 1) { + return null; + } + + if (preg_match('/^(\d{1,2}):([0-5]\d)$/', $value, $matches) === 1) { + $minutes = (int) $matches[1] * 60 + (int) $matches[2]; + } elseif (preg_match('/^\d+$/', $value) === 1 && (int) $value > 24) { + $minutes = (int) $value; + } else { + return self::parse($value); + } + + if ($minutes % 15 !== 0) { + throw new InvalidWorkedHours; + } + + return new self(intdiv($minutes, 15)); + } + + /** + * Hours and minutes, "1:30" or "0:00". + */ + public static function formatClock(int $quarters): string + { + $minutes = $quarters * 15; + + return intdiv($minutes, 60).':'.str_pad((string) ($minutes % 60), 2, '0', STR_PAD_LEFT); + } + public static function fromDecimal(float $hours): self { return new self((int) round($hours * 4)); diff --git a/app/Modules/TimeTracking/Infrastructure/Persistence/Eloquent/TimeEntryModel.php b/app/Modules/TimeTracking/Infrastructure/Persistence/Eloquent/TimeEntryModel.php index 6b83d0b..c430f71 100644 --- a/app/Modules/TimeTracking/Infrastructure/Persistence/Eloquent/TimeEntryModel.php +++ b/app/Modules/TimeTracking/Infrastructure/Persistence/Eloquent/TimeEntryModel.php @@ -22,9 +22,11 @@ use Illuminate\Database\Eloquent\Model; * @property CarbonImmutable|null $approved_at * @property int|null $approved_by * @property int|null $billing_export_id + * @property string|null $billing_model EntryBillingModel value; null follows the job + * @property string|null $internal_comment */ #[Table('time_entries')] -#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by', 'billing_export_id'])] +#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by', 'billing_export_id', 'billing_model', 'internal_comment'])] #[UseFactory(TimeEntryFactory::class)] class TimeEntryModel extends Model { diff --git a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentPinnedTaskRepository.php b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentPinnedTaskRepository.php new file mode 100644 index 0000000..2b15948 --- /dev/null +++ b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentPinnedTaskRepository.php @@ -0,0 +1,39 @@ +insertOrIgnore([ + 'user_id' => $userId, + 'task_id' => $taskId, + 'pinned_at' => $at->format('Y-m-d H:i:s'), + ]); + } + + public function unpin(int $userId, int $taskId): void + { + DB::table('time_pinned_tasks')->where('user_id', $userId)->where('task_id', $taskId)->delete(); + } + + public function unpinAll(int $userId): int + { + return DB::table('time_pinned_tasks')->where('user_id', $userId)->delete(); + } + + public function pinnedTaskIds(int $userId): array + { + return DB::table('time_pinned_tasks') + ->where('user_id', $userId) + ->orderBy('pinned_at') + ->pluck('task_id') + ->map(fn ($id): int => (int) $id) + ->all(); + } +} diff --git a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php index 05d4942..3d3077d 100644 --- a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php +++ b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php @@ -6,10 +6,18 @@ use App\Modules\Jobs\Application\Contracts\TaskQueries; use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries; use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek; use App\Modules\TimeTracking\Application\DTOs\JobBillingHours; +use App\Modules\TimeTracking\Application\DTOs\MissingBillingNote; +use App\Modules\TimeTracking\Application\DTOs\MonthSummary; use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary; +use App\Modules\TimeTracking\Application\DTOs\TimesheetCell; +use App\Modules\TimeTracking\Application\DTOs\TimesheetTaskRow; +use App\Modules\TimeTracking\Application\DTOs\TimesheetWeek; use App\Modules\TimeTracking\Application\DTOs\WeekApproval; use App\Modules\TimeTracking\Application\DTOs\WeekRow; use App\Modules\TimeTracking\Application\DTOs\WeekSheet; +use App\Modules\TimeTracking\Application\Services\TimesheetLayout; +use App\Modules\TimeTracking\Domain\Contracts\PinnedTaskRepository; +use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel; use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel; use App\Modules\Users\Application\Contracts\UserAccountQueries; use Carbon\CarbonImmutable; @@ -20,8 +28,103 @@ class EloquentTimeEntryQueries implements TimeEntryQueries public function __construct( private TaskQueries $tasks, private UserAccountQueries $users, + private PinnedTaskRepository $pins, + private TimesheetLayout $layout, ) {} + public function timesheet(int $userId, string $monday): TimesheetWeek + { + $start = CarbonImmutable::parse($monday)->startOfWeek(); + $days = []; + for ($i = 0; $i < 7; $i++) { + $days[] = $start->addDays($i)->toDateString(); + } + + $entries = TimeEntryModel::query() + ->where('user_id', $userId) + ->whereBetween('worked_on', [$days[0], $days[6]]) + ->get(); + $pinnedIds = $this->pins->pinnedTaskIds($userId); + $scheduledIds = $this->tasks->scheduledTaskIdsFor($userId, $days[0], $days[6]); + $taskIds = array_values(array_unique(array_merge( + $pinnedIds, + $scheduledIds, + $entries->pluck('task_id')->map(fn ($id): int => (int) $id)->all(), + ))); + + $cells = []; + foreach ($entries as $entry) { + $cells[$entry->task_id][$entry->worked_on->toDateString()] = new TimesheetCell( + $entry->quarters(), + $entry->note, + $entry->internal_comment, + $entry->billing_model === null ? null : EntryBillingModel::tryFrom($entry->billing_model), + $entry->approved_at !== null, + ); + } + + $rows = []; + $dayTotals = array_fill_keys($days, 0); + $missing = []; + + foreach ($this->tasks->bookableTasks($taskIds) as $task) { + $taskCells = $cells[$task->taskId] ?? []; + $total = 0; + + foreach ($taskCells as $day => $cell) { + $dayTotals[$day] += $cell->quarters; + $total += $cell->quarters; + + if (! $cell->approved && ! $cell->hasBillingNote()) { + $missing[] = new MissingBillingNote($task->taskId, $day, $cell->quarters, $task->customerName, $task->jobNumber, $task->taskTitle); + } + } + + $rows[] = new TimesheetTaskRow($task, $taskCells, $total, in_array($task->taskId, $pinnedIds, true)); + } + + usort($missing, fn (MissingBillingNote $a, MissingBillingNote $b): int => [$a->day, $a->jobNumber] <=> [$b->day, $b->jobNumber]); + + $sections = $this->layout->arrange( + $rows, + $scheduledIds, + $this->quartersByJobs(array_values(array_unique(array_map(fn (TimesheetTaskRow $row): int => $row->task->jobId, $rows)))), + ); + $unapproved = $entries->whereNull('approved_at')->sum(fn (TimeEntryModel $entry): int => $entry->quarters()); + + return new TimesheetWeek($days, $sections['scheduled'], $sections['pinned'], $dayTotals, array_sum($dayTotals), (int) $unapproved, $this->latestApproval($entries), $missing); + } + + public function monthSummary(int $userId, string $month): MonthSummary + { + $start = CarbonImmutable::createFromFormat('!Y-m', $month) ?: CarbonImmutable::now()->startOfMonth(); + $entries = TimeEntryModel::query() + ->where('user_id', $userId) + ->whereBetween('worked_on', [$start->toDateString(), $start->endOfMonth()->toDateString()]) + ->get(); + $paymentBases = []; + + foreach ($this->tasks->bookableTasks($entries->pluck('task_id')->map(fn ($id): int => (int) $id)->unique()->values()->all()) as $task) { + $paymentBases[$task->taskId] = $task->paymentBasis; + } + + $billable = 0; + $internal = 0; + + foreach ($entries as $entry) { + $model = ($entry->billing_model === null ? null : EntryBillingModel::tryFrom($entry->billing_model)) + ?? EntryBillingModel::forPaymentBasis($paymentBases[$entry->task_id] ?? null); + + if ($model->isBillable()) { + $billable += $entry->quarters(); + } else { + $internal += $entry->quarters(); + } + } + + return new MonthSummary($start->format('Y-m'), $billable + $internal, $billable, $internal); + } + public function week(int $userId, string $monday, array $extraTaskIds = []): WeekSheet { $start = CarbonImmutable::parse($monday)->startOfWeek(); diff --git a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php index e3393e0..a402aac 100644 --- a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php +++ b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php @@ -4,6 +4,7 @@ namespace App\Modules\TimeTracking\Infrastructure\Persistence\Repositories; use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository; use App\Modules\TimeTracking\Domain\Entities\TimeEntry; +use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel; use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours; use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel; use DateTimeImmutable; @@ -40,6 +41,8 @@ class EloquentTimeEntryRepository implements TimeEntryRepository 'worked_on' => $entry->workedOn()->format('Y-m-d'), 'hours' => $entry->hours()->decimal(), 'note' => $entry->note(), + 'billing_model' => $entry->billingModel()?->value, + 'internal_comment' => $entry->internalComment(), 'approved_by' => $entry->approvedBy(), 'approved_at' => $entry->approvedAt()?->format('Y-m-d H:i:s'), 'billing_export_id' => $entry->billingExportId(), @@ -102,6 +105,8 @@ class EloquentTimeEntryRepository implements TimeEntryRepository $model->approved_by, $model->approved_at === null ? null : DateTimeImmutable::createFromInterface($model->approved_at), $model->billing_export_id, + $model->billing_model === null ? null : EntryBillingModel::tryFrom($model->billing_model), + $model->internal_comment, ); } } diff --git a/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php b/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php index bd5de55..eb0a42d 100644 --- a/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php +++ b/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php @@ -8,8 +8,10 @@ use App\Modules\Jobs\Application\Contracts\LoggedJobHours; use App\Modules\Jobs\Application\Contracts\TaskUsage; use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries; use App\Modules\TimeTracking\Application\Contracts\TimeReportQueries; +use App\Modules\TimeTracking\Domain\Contracts\PinnedTaskRepository; use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository; use App\Modules\TimeTracking\Infrastructure\LoggedHoursFromTimeEntries; +use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentPinnedTaskRepository; use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeEntryQueries; use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeEntryRepository; use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeReportQueries; @@ -29,6 +31,7 @@ class TimeTrackingServiceProvider extends ServiceProvider */ public array $bindings = [ TimeEntryRepository::class => EloquentTimeEntryRepository::class, + PinnedTaskRepository::class => EloquentPinnedTaskRepository::class, TimeEntryQueries::class => EloquentTimeEntryQueries::class, TimeReportQueries::class => EloquentTimeReportQueries::class, TaskUsage::class => TaskUsageFromTimeEntries::class, diff --git a/app/Modules/TimeTracking/Presentation/Livewire/⚡approvals.blade.php b/app/Modules/TimeTracking/Presentation/Livewire/⚡approvals.blade.php index 9317d51..f9bb8b9 100644 --- a/app/Modules/TimeTracking/Presentation/Livewire/⚡approvals.blade.php +++ b/app/Modules/TimeTracking/Presentation/Livewire/⚡approvals.blade.php @@ -3,6 +3,7 @@ use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries; use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek; use App\Modules\TimeTracking\Application\UseCases\ApproveWeek; +use App\Modules\TimeTracking\Domain\Exceptions\BillingNotesMissing; use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours; use App\Modules\Users\Application\Contracts\Clock; use App\Modules\Users\Application\Contracts\UserAccountQueries; @@ -68,7 +69,14 @@ new class extends Component return; } - $approveWeek->execute($userId, $monday, (int) auth()->id()); + try { + $approveWeek->execute($userId, $monday, (int) auth()->id()); + } catch (BillingNotesMissing $exception) { + $this->statusMessage = __('time.approvals.notes_missing', ['name' => $week->userName, 'week' => $this->weekLabel($monday), 'count' => count($exception->entryIds)]); + + return; + } + unset($this->pending, $this->approved); $this->statusMessage = __('time.approval.approved_for', ['name' => $week->userName, 'week' => $this->weekLabel($monday)]); diff --git a/app/Modules/TimeTracking/Presentation/Livewire/⚡week.blade.php b/app/Modules/TimeTracking/Presentation/Livewire/⚡week.blade.php index 87fe5da..b15b07f 100644 --- a/app/Modules/TimeTracking/Presentation/Livewire/⚡week.blade.php +++ b/app/Modules/TimeTracking/Presentation/Livewire/⚡week.blade.php @@ -1,13 +1,27 @@ [Y-m-d => "2,5"]]. - * The cells send their value with wire:change; the desktop grid and the - * phone list both have an input for the same cell. + * Stored hours as shown (H:MM), by task id and day. * * @var array> */ #[Locked] public array $cells = []; - /** - * Tasks added to this week by search, besides the user's own. - * - * @var list - */ - #[Locked] - public array $extraTaskIds = []; - /** * Values that were not saved, shown back in their cell with the error. * @@ -79,13 +92,29 @@ new class extends Component public array $rejected = []; /** - * The day shown on phones; changed only by selectDay(), because it is - * written into element ids and wire:change calls. + * The day shown on phones; changed only by selectDay(). */ #[Locked] public string $selectedDay = ''; - public string $taskSearch = ''; + #[Locked] + public string $today = ''; + + public bool $showMonth = false; + + public string $pinSearch = ''; + + #[Locked] + public ?int $entryTaskId = null; + + #[Locked] + public string $entryDay = ''; + + public string $entryBillingModel = ''; + + public string $entryNote = ''; + + public string $entryComment = ''; public string $statusMessage = ''; @@ -109,16 +138,22 @@ new class extends Component $this->user = ''; } - $this->week = $this->mondayOf($this->week !== '' ? $this->week : $clock->today()->format('Y-m-d')); - $today = $clock->today()->format('Y-m-d'); - $this->selectedDay = in_array($today, $this->sheet->days, true) ? $today : $this->week; + $this->today = $clock->today()->format('Y-m-d'); + $this->week = $this->mondayOf($this->week !== '' ? $this->week : $this->today); + $this->selectedDay = in_array($this->today, $this->sheet->days, true) ? $this->today : $this->week; $this->loadCells(); } #[Computed] - public function sheet(): WeekSheet + public function sheet(): TimesheetWeek { - return app(TimeEntryQueries::class)->week($this->viewedUserId, $this->week, $this->extraTaskIds); + return app(TimeEntryQueries::class)->timesheet($this->viewedUserId, $this->week); + } + + #[Computed] + public function month(): MonthSummary + { + return app(TimeEntryQueries::class)->monthSummary($this->viewedUserId, CarbonImmutable::parse($this->week)->addDays(3)->format('Y-m')); } /** @@ -129,16 +164,185 @@ new class extends Component return $this->viewedUserId !== (int) auth()->id(); } + public function isCurrentWeek(): bool + { + return $this->week === $this->mondayOf($this->today); + } + public function canApprove(): bool { return Gate::allows('time.approve', $this->viewedUserId); } + /** + * @return list + */ + #[Computed] + public function pinCandidates(): array + { + $term = trim($this->pinSearch); + + if (mb_strlen($term) < 2) { + return []; + } + + $pinned = array_map(fn (TimesheetTaskRow $row): int => $row->task->taskId, array_filter($this->sheet->rows(), fn (TimesheetTaskRow $row): bool => $row->pinned)); + + return array_values(array_filter( + app(TaskQueries::class)->searchBookableTasks($term, $this->isSubcontractor() ? (int) auth()->id() : null), + fn (BookableTask $task): bool => ! $task->isLocked() && ! in_array($task->taskId, $pinned, true), + )); + } + + /** + * The jobs of the week for "+/- Työmääräykset". + * + * @return list + */ + public function weekJobs(): array + { + $jobs = []; + + foreach ([...$this->sheet->scheduled, ...$this->sheet->pinned] as $customer) { + foreach ($customer->jobs as $job) { + $jobs[$job->jobId] ??= ['job' => $job, 'customer' => $customer->name, 'color' => $customer->headerColor, 'rows' => []]; + $jobs[$job->jobId]['rows'] = [...$jobs[$job->jobId]['rows'], ...$job->rows]; + } + } + + return array_values($jobs); + } + + public function saveCell(int $taskId, string $day, string $value): void + { + try { + $quarters = WorkedHours::parseFlexible($value)?->quarters ?? 0; + } catch (InvalidWorkedHours) { + $this->rejectCell($taskId, $day, $value, __('time.errors.invalid_hours')); + + return; + } + + $this->storeCell($taskId, $day, $quarters, $value); + } + + /** + * The −15 min / +15 min buttons. + */ + public function adjustCell(int $taskId, string $day, int $delta): void + { + $row = $this->sheet->row($taskId); + $current = $row?->cell($day)?->quarters ?? 0; + + $this->storeCell($taskId, $day, max(0, $current + ($delta > 0 ? 1 : -1)), null); + } + + public function openEntry(int $taskId, string $day): void + { + $row = $this->sheet->row($taskId); + $cell = $row?->cell($day); + + if ($row === null || ! in_array($day, $this->sheet->days, true)) { + return; + } + + if ($cell === null) { + $this->statusMessage = __('time.sheet.entry_needs_hours'); + + return; + } + + $this->resetErrorBag('entryNote'); + $this->entryTaskId = $taskId; + $this->entryDay = $day; + $this->entryBillingModel = ($cell->billingModel ?? $row->defaultBillingModel())->value; + $this->entryNote = (string) $cell->billingNote; + $this->entryComment = (string) $cell->internalComment; + + $this->js("document.getElementById('".self::MISSING_DIALOG."').close(); document.getElementById('".self::ENTRY_DIALOG."').showModal()"); + } + + /** + * "Tallenna", Escape or closing the entry dialog. + */ + public function saveEntry(DescribeTimeEntry $describe): void + { + $this->authorize('time.use'); + + $row = $this->entryTaskId === null ? null : $this->sheet->row($this->entryTaskId); + + if ($this->isReadOnly() || $row === null || $row->task->isLocked() || $row->cell($this->entryDay)?->approved !== false) { + $this->js("document.getElementById('".self::ENTRY_DIALOG."').close()"); + + return; + } + + $this->authorize('time.book', $row->task->jobId); + + $model = EntryBillingModel::tryFrom($this->entryBillingModel); + + try { + $describe->execute( + (int) auth()->id(), + $row->task->taskId, + $this->entryDay, + $model === $row->defaultBillingModel() && $row->cell($this->entryDay)?->billingModel === null ? null : $model, + mb_substr($this->entryNote, 0, 2000), + mb_substr($this->entryComment, 0, 2000), + ); + } catch (DomainException) { + $this->errorMessage = __('time.errors.approved'); + + return; + } + + unset($this->sheet); + $this->statusMessage = __('time.sheet.entry_saved', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($this->entryDay)]); + $this->entryTaskId = null; + $this->js("document.getElementById('".self::ENTRY_DIALOG."').close()"); + } + + /** + * "Pysäytä ja tallenna" of the timer: the time rounded to the nearest + * quarter hour, at least 15 minutes, on today's cell. + */ + public function saveTimer(int $taskId, int $seconds, string $note, AddTaskHours $addHours): void + { + $row = $this->sheet->row($taskId); + + if ($this->isReadOnly() || $row === null || ! in_array($this->today, $this->sheet->days, true)) { + return; + } + + $this->authorize('time.book', $row->task->jobId); + + $quarters = max(1, (int) round($seconds / 900)); + + try { + $addHours->execute((int) auth()->id(), $taskId, $this->today, WorkedHours::formatQuarters(min($quarters, WorkedHours::MAX_QUARTERS)), trim($note) === '' ? null : mb_substr(trim($note), 0, 2000)); + } catch (DomainException $exception) { + $this->errorMessage = $row->task->taskTitle.': '.$this->domainMessage($exception); + + return; + } + + unset($this->sheet, $this->month); + $this->loadCells(); + $this->statusMessage = __('time.sheet.timer_saved', ['time' => WorkedHours::formatClock($quarters), 'task' => $row->task->taskTitle]); + } + public function approveWeek(ApproveWeek $approveWeek): void { $this->authorize('time.approve', $this->viewedUserId); - $count = $approveWeek->execute($this->viewedUserId, $this->week, (int) auth()->id()); + try { + $count = $approveWeek->execute($this->viewedUserId, $this->week, (int) auth()->id()); + } catch (BillingNotesMissing) { + unset($this->sheet); + $this->js("document.getElementById('".self::MISSING_DIALOG."').showModal()"); + + return; + } unset($this->sheet); $this->loadCells(); @@ -167,90 +371,134 @@ new class extends Component $this->loadCells(); $this->statusMessage = __('time.approval.cancelled', ['week' => $this->weekHeading()]); - $this->js("document.getElementById('cancel-approval-dialog').close(); document.getElementById('approval-heading').focus()"); + $this->js("document.getElementById('cancel-approval-dialog').close(); document.getElementById('week-heading').focus()"); } /** - * @return list + * @param list $taskIds */ - #[Computed] - public function searchResults(): array - { - $term = trim($this->taskSearch); - - if (mb_strlen($term) < 2) { - return []; - } - - $shown = array_map(fn ($row): int => $row->task->taskId, $this->sheet->rows); - - return array_values(array_filter( - app(TaskQueries::class)->searchBookableTasks($term, $this->isSubcontractor() ? (int) auth()->id() : null), - fn (BookableTask $task): bool => ! in_array($task->taskId, $shown, true), - )); - } - - public function saveCell(int $taskId, string $day, string $value): void + public function pinTasks(array $taskIds, PinTimesheetTasks $pins): void { $this->authorize('time.use'); - $row = collect($this->sheet->rows)->first(fn ($row): bool => $row->task->taskId === $taskId); - - if ($this->isReadOnly() || $row === null || ! in_array($day, $this->sheet->days, true)) { + if ($this->isReadOnly()) { return; } - $this->authorize('time.book', $row->task->jobId); - $this->resetErrorBag("cells.{$taskId}.{$day}"); - unset($this->rejected["{$taskId}.{$day}"]); - $this->errorMessage = ''; + $taskIds = array_values(array_filter(array_map('intval', $taskIds), fn (int $id): bool => $id > 0)); + $tasks = app(TaskQueries::class)->bookableTasks($taskIds); + + foreach ($tasks as $task) { + if (Gate::denies('time.book', $task->jobId)) { + return; + } + } try { - app(SetDayHours::class)->execute((int) auth()->id(), $taskId, $day, $value); - } catch (DomainException $exception) { - $message = __(match (true) { - $exception instanceof InvalidWorkedHours => 'time.errors.invalid_hours', - $exception instanceof DailyHoursExceeded => 'time.errors.day_full', - $exception instanceof TimeLocked => 'time.errors.locked', - $exception instanceof TimeApproved => 'time.errors.approved', - default => 'time.errors.not_found', - }); - $this->addError("cells.{$taskId}.{$day}", $message); - $this->errorMessage = $row->task->taskTitle.', '.$this->dayLabel($day).': '.$message; - $this->rejected["{$taskId}.{$day}"] = $value; + $pins->pin((int) auth()->id(), array_map(fn (BookableTask $task): int => $task->taskId, $tasks)); + } catch (DomainException) { + $this->errorMessage = __('time.sheet.cannot_pin'); return; } - unset($this->sheet); + unset($this->sheet, $this->pinCandidates); $this->loadCells(); - - $hours = $this->cells[$taskId][$day] ?? ''; - $this->statusMessage = $hours === '' - ? __('time.removed', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($day)]) - : __('time.saved', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($day), 'hours' => $hours]); + $this->statusMessage = count($tasks) === 1 + ? __('time.sheet.pinned_task', ['task' => $tasks[0]->taskTitle]) + : __('time.sheet.pinned_job', ['job' => $tasks[0]->jobNumber ?? '']); } - public function addTask(int $taskId): void + /** + * "★ Kiinnitä työ": every open task of the job shown on the sheet. + */ + public function pinJob(int $jobId, PinTimesheetTasks $pins): void + { + $taskIds = []; + + foreach ($this->sheet->rows() as $row) { + if ($row->task->jobId === $jobId && ! $row->task->isLocked() && ! $row->pinned) { + $taskIds[] = $row->task->taskId; + } + } + + if ($taskIds !== []) { + $this->pinTasks($taskIds, $pins); + } + } + + public function unpinTask(int $taskId, PinTimesheetTasks $pins): void { $this->authorize('time.use'); - $task = app(TaskQueries::class)->bookableTask($taskId); - - if ($this->isReadOnly() || $task === null || $task->isLocked() || Gate::denies('time.book', $task->jobId)) { + if ($this->isReadOnly()) { return; } - if (! in_array($taskId, $this->extraTaskIds, true)) { - $this->extraTaskIds[] = $taskId; + $row = $this->sheet->row($taskId); + $pins->unpin((int) auth()->id(), $taskId); + + unset($this->sheet, $this->pinCandidates); + $this->loadCells(); + $this->statusMessage = __('time.sheet.unpinned', ['task' => $row->task->taskTitle ?? '']); + } + + public function clearPins(PinTimesheetTasks $pins): void + { + $this->authorize('time.use'); + + if ($this->isReadOnly()) { + return; } - $this->taskSearch = ''; + $count = $pins->unpinAll((int) auth()->id()); + unset($this->sheet); $this->loadCells(); - $this->statusMessage = __('time.add.added', ['task' => $task->label()]); + $this->statusMessage = trans_choice('time.sheet.pins_cleared', $count, ['count' => $count]); + $this->js("document.getElementById('clear-pins-dialog').close(); document.getElementById('week-heading').focus()"); + } - $this->js("(document.getElementById('cell-{$taskId}-{$this->selectedDay}')?.offsetParent ? document.getElementById('cell-{$taskId}-{$this->selectedDay}') : document.getElementById('mcell-{$taskId}-{$this->selectedDay}'))?.focus()"); + /** + * "Merkitse valmiiksi" in +/- Työmääräykset. + */ + public function markJobDone(int $jobId, ChangeJobStatus $changeStatus): void + { + $this->authorize('jobs.manage'); + + $job = collect($this->weekJobs())->first(fn (array $job): bool => $job['job']->jobId === $jobId); + + if ($job === null || $job['job']->status->locksTime()) { + return; + } + + try { + $changeStatus->execute($jobId, JobStatus::Done, (int) auth()->id()); + } catch (CustomerJobNotFound) { + return; + } + + unset($this->sheet); + $this->loadCells(); + $this->statusMessage = __('time.sheet.marked_done', ['job' => $job['job']->number.' '.$job['job']->name]); + } + + public function setCustomerColor(int $customerId, ?string $color, ChangeCustomerHeaderColor $changeColor): void + { + $this->authorize('customers.use'); + + $name = collect($this->sheet->rows())->first(fn (TimesheetTaskRow $row): bool => $row->task->customerId === $customerId)?->task->customerName ?? ''; + + try { + $changeColor->execute($customerId, $color); + } catch (InvalidHexColor|CustomerNotFound) { + $this->errorMessage = __('time.sheet.invalid_color'); + + return; + } + + unset($this->sheet); + $this->statusMessage = __('time.sheet.color_saved', ['customer' => $name]); } public function selectDay(string $day): void @@ -260,16 +508,16 @@ new class extends Component } } - public function showWeek(string $which, Clock $clock): void + public function showWeek(string $which): void { $this->week = match ($which) { 'previous' => CarbonImmutable::parse($this->week)->subWeek()->toDateString(), 'next' => CarbonImmutable::parse($this->week)->addWeek()->toDateString(), - default => $this->mondayOf($clock->today()->format('Y-m-d')), + default => $this->mondayOf($this->today), }; - unset($this->sheet); - $this->selectedDay = $this->week; + unset($this->sheet, $this->month); + $this->selectedDay = $this->isCurrentWeek() ? $this->today : $this->week; $this->statusMessage = $this->weekHeading(); $this->errorMessage = ''; $this->resetErrorBag(); @@ -295,9 +543,24 @@ new class extends Component return __('time.days')[$date->dayOfWeekIso - 1].' '.$date->format('j.n.'); } - public function hours(int $quarters): string + /** + * @return array + */ + public function dayLabels(): array { - return WorkedHours::formatQuarters($quarters); + return collect($this->sheet->days)->mapWithKeys(fn (string $day): array => [$day => $this->dayLabel($day)])->all(); + } + + public function clock(int $quarters): string + { + return WorkedHours::formatClock($quarters); + } + + public function monthLabel(): string + { + $date = CarbonImmutable::createFromFormat('!Y-m', $this->month->month) ?: CarbonImmutable::now(); + + return ucfirst(__('time.sheet.months')[$date->month - 1]).' '.$date->year; } public function isSubcontractor(): bool @@ -315,14 +578,64 @@ new class extends Component return $this->view()->title($this->heading()); } + private function storeCell(int $taskId, string $day, int $quarters, ?string $typed): void + { + $this->authorize('time.use'); + + $row = $this->sheet->row($taskId); + + if ($this->isReadOnly() || $row === null || ! in_array($day, $this->sheet->days, true)) { + return; + } + + $this->authorize('time.book', $row->task->jobId); + $this->resetErrorBag("cells.{$taskId}.{$day}"); + unset($this->rejected["{$taskId}.{$day}"]); + $this->errorMessage = ''; + + try { + app(SetDayHours::class)->execute((int) auth()->id(), $taskId, $day, $quarters === 0 ? '' : WorkedHours::formatQuarters(min($quarters, WorkedHours::MAX_QUARTERS + 1))); + } catch (DomainException $exception) { + $this->rejectCell($taskId, $day, $typed ?? WorkedHours::formatClock($quarters), $this->domainMessage($exception)); + + return; + } + + unset($this->sheet, $this->month); + $this->loadCells(); + + $this->statusMessage = $quarters === 0 + ? __('time.removed', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($day)]) + : __('time.sheet.saved', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($day), 'hours' => WorkedHours::formatClock($quarters)]); + } + + private function rejectCell(int $taskId, string $day, string $value, string $message): void + { + $title = $this->sheet->row($taskId)->task->taskTitle ?? ''; + + $this->addError("cells.{$taskId}.{$day}", $message); + $this->errorMessage = $title.', '.$this->dayLabel($day).': '.$message; + $this->rejected["{$taskId}.{$day}"] = $value; + } + + private function domainMessage(DomainException $exception): string + { + return __(match (true) { + $exception instanceof InvalidWorkedHours => 'time.errors.invalid_hours', + $exception instanceof DailyHoursExceeded => 'time.errors.day_full', + $exception instanceof TimeLocked => 'time.errors.locked', + $exception instanceof TimeApproved => 'time.errors.approved', + default => 'time.errors.not_found', + }); + } + private function loadCells(): void { $cells = []; - foreach ($this->sheet->rows as $row) { + foreach ($this->sheet->rows() as $row) { foreach ($this->sheet->days as $day) { - $quarters = $row->quartersByDay[$day] ?? 0; - $cells[$row->task->taskId][$day] = $quarters === 0 ? '' : WorkedHours::formatQuarters($quarters); + $cells[$row->task->taskId][$day] = WorkedHours::formatClock($row->cell($day)?->quarters ?? 0); } } @@ -340,246 +653,575 @@ new class extends Component }; ?> -@php($sheet = $this->sheet) +@php + $sheet = $this->sheet; + $readOnly = $this->isReadOnly(); + $current = $this->isCurrentWeek(); + $today = $current ? $today : null; + $labels = $this->dayLabels(); + $approved = $sheet->isApproved(); + $currentMonday = CarbonImmutable::parse($this->today)->startOfWeek(); + $shownMonday = CarbonImmutable::parse($week); + $userKey = (int) auth()->id(); +@endphp -
-
- {{ $this->heading() }} - @if ($this->isReadOnly()) -

{{ __('time.other_intro') }}

- {{ __('time.approval.back_to_list') }} - @else -

{{ __('time.intro') }}

- @endif +
+

{{ $this->heading() }}

+ + @if ($readOnly) +
+

{{ __('time.other_intro') }}

+

{{ __('time.approval.back_to_list') }}

+
+ @endif + + {{-- Banner when another week than the current one is shown --}} +
+ @unless ($current) +
+
+ +
+

{{ __($shownMonday->lt($currentMonday) ? 'time.sheet.off_week_past' : 'time.sheet.off_week_future', ['number' => $shownMonday->isoWeek()]) }}

+

{{ __('time.sheet.off_week_hint', ['number' => $currentMonday->isoWeek(), 'from' => $currentMonday->format('j.n.'), 'to' => $currentMonday->addDays(6)->format('j.n.Y')]) }}

+
+
+ +
+ @endunless
-
-

{{ $this->weekHeading() }}

-
- - - -
-
+ {{-- Toolbar --}} +
$current, + 'border-amber-600 ring-2 ring-amber-500/80' => ! $current, + ])> +
+
+
+
+

{{ $this->weekHeading() }}

+ $current, + 'border-amber-500/50 bg-amber-100 text-amber-900 dark:bg-amber-500/20 dark:text-amber-100' => ! $current, + ])>{{ $current ? __('time.sheet.current_week') : ($shownMonday->lt($currentMonday) ? __('time.sheet.past_week') : __('time.sheet.future_week')) }} +
+ +
-

{{ $statusMessage }}

- - - @if ($sheet->rows === []) - {{ __('time.no_rows') }} - @else - {{-- Desktop: the whole week as an input grid (a form, so a native table rather than ). --}} - - - {{-- Phone: one day at a time. --}} -
-
- @foreach ($sheet->days as $day) - - @endforeach + + + + +
+ @if ($sheet->totalQuarters > 0 && ! $approved && $this->canApprove()) + + @elseif ($sheet->lastApproval !== null) + @can('time.cancel-approval') + + @endcan + @endif + + @unless ($readOnly) + + + + @endunless +
-
    - @foreach ($sheet->rows as $row) -
  • - {{ $row->task->label() }} - {{ $row->task->workTypeName }} +
    + - @if ($row->isApprovedOn($selectedDay)) -

    -

    - @elseif ($row->task->isLocked() || $this->isReadOnly()) -

    - @if ($row->task->isLocked()) -

    - @else - - task->taskId.'.'.$selectedDay) aria-invalid="true" aria-describedby="mcell-{{ $row->task->taskId }}-{{ $selectedDay }}-error" @enderror - class="mt-1 w-24 rounded-md border border-zinc-400 bg-white px-2 py-2 text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400" + @if (! $approved && $sheet->missingNotes !== []) + + @endif + +

    + {{ $approved ? __('time.sheet.approved_total') : __('time.sheet.unapproved_total') }} + $approved, 'text-sky-800 dark:text-sky-300' => ! $approved])>{{ $this->clock($approved ? $sheet->totalQuarters : $sheet->unapprovedQuarters) }} +

    +
    +
+ + @if ($sheet->lastApproval !== null) +

+

+ @endif + @if ($sheet->totalQuarters > 0 && ! $approved && ! $this->canApprove()) +

{{ __('time.approval.management_approves') }}

+ @endif +
+ +

{{ $statusMessage }}

+ + + {{-- Desktop: two cards with an air gap, wide tables that may scroll sideways --}} + + + {{-- Phone: one day at a time --}} +
+
+ @foreach ($sheet->days as $day) + + @endforeach +
+ + @foreach (['scheduled' => $sheet->scheduled, 'pinned' => $sheet->pinned] as $section => $groups) +
+

{{ __('time.sheet.'.$section) }}

+ @if ($groups === []) +

{{ __('time.sheet.'.$section.'_empty') }}

+ @endif + @foreach ($groups as $customer) + @php + $color = new \App\Modules\Shared\Domain\ValueObjects\HexColor($customer->headerColor ?? '#374151'); + @endphp +
+

{{ $customer->name }}

+
    + @foreach ($customer->jobs as $job) + @foreach ($job->rows as $row) + @php + $taskId = $row->task->taskId; + $cell = $row->cell($selectedDay); + $editable = ! $readOnly && ! $row->task->isLocked() && ! ($cell?->approved ?? false); + $fieldId = 'mcell-'.$section.'-'.$taskId.'-'.$selectedDay; + @endphp +
  • +

    #{{ $job->number }} {{ $job->name }}

    + {{ $row->task->taskTitle }} + @if ($editable) + +
    + + + + @if (($cell?->quarters ?? 0) > 0) + + @endif +
    + @error('cells.'.$taskId.'.'.$selectedDay) +

    {{ $message }}

    + @enderror + @else +

    + @if ($row->task->isLocked()) +

    + @endif +
  • + @endforeach + @endforeach +
+
+ @endforeach + @if ($section === 'pinned' && ! $readOnly) + + @endif +
+ @endforeach +
+ +

+ + @if ($showMonth) +
+
+ {{ $this->monthLabel() }} + {{ __('time.sheet.month_summary', ['total' => $this->clock($this->month->totalQuarters), 'billable' => $this->clock($this->month->billableQuarters), 'internal' => $this->clock($this->month->internalQuarters)]) }} +
+ +
+ @endif + + {{-- Entry dialog: Escape and closing save --}} + + @php + $entryRow = $entryTaskId === null ? null : $sheet->row($entryTaskId); + @endphp +
+
+
+

{{ __('time.sheet.entry_title') }}

+ @if ($entryRow !== null) +

+ {{ $entryRow->task->customerName }} • + {{ $entryRow->task->taskTitle }} • + {{ $this->dayLabel($entryDay) }} + ({{ $this->clock($entryRow->cell($entryDay)?->quarters ?? 0) }}) +

+ @endif +
+ +
+ +
+ {{ __('time.sheet.billing_model') }} +
+ @foreach (EntryBillingModel::cases() as $model) + + @endforeach +
+
+ +
+ + +

{{ __('time.sheet.billing_note_hint') }}

+
+ +
+ + +

{{ __('time.sheet.internal_comment_hint') }}

+
+ +
+
+ @if ($entryRow !== null && Gate::allows('expenses.record')) + {{ __('time.sheet.add_product') }} + @endif + {{ __('time.sheet.esc_saves') }} +
+ +
+
+
+ + {{-- Missing billing notes --}} + +
+

{{ __('time.sheet.missing_intro') }}

+
    + @foreach ($sheet->missingNotes as $missing) +
  • + + {{ $missing->customerName }} • #{{ $missing->jobNumber }} {{ $missing->taskTitle }} • + {{ $this->dayLabel($missing->day) }} ({{ $this->clock($missing->quarters) }}) + + @unless ($readOnly) + - @error('cells.'.$row->task->taskId.'.'.$selectedDay) -

    {{ $message }}

    - @enderror - @endif + @endunless
  • @endforeach
+ + + + +
-

- @endif - -
-

{{ __('time.approval.title') }}

- - @if ($sheet->hasUnapprovedHours()) -

{{ __('time.approval.unapproved', ['hours' => $this->hours($sheet->unapprovedQuarters)]) }}

- @elseif ($sheet->totalQuarters === 0) -

{{ __('time.approval.no_hours') }}

- @endif - - @if ($sheet->lastApproval !== null) -

-

+

+

- @endif +
+

+

+

+
-
- @if ($sheet->hasUnapprovedHours()) - @if ($this->canApprove()) - - @else -

{{ __('time.approval.management_approves') }}

- @endif - @endif +

+
+ @foreach (['h' => 'timer_hours', 'm' => 'timer_minutes', 's' => 'timer_seconds'] as $part => $label) +
+ + +
+ @endforeach + +
+ - @if ($sheet->hasApprovedHours()) - @can('time.cancel-approval') - - @endcan - @endif +

+ +
+ + +
+ +
+ + + + +
-
+ + + @unless ($readOnly) + {{-- +/- Työmääräykset --}} + +
+

{{ __('time.sheet.manage_intro') }}

+ @if ($this->weekJobs() === []) +

{{ __('time.sheet.manage_empty') }}

+ @endif + @foreach ($this->weekJobs() as $item) + @php + $job = $item['job']; + @endphp +
+
+

+ + {{ $item['customer'] }} • + #{{ $job->number }} + {{ $job->name }} +

+ @if ($job->status->locksTime()) + ✓ {{ __('time.sheet.already_done') }} + @elseif (Gate::allows('jobs.manage')) + + @endif +
+
    + @foreach ($item['rows'] as $row) +
  • + {{ $row->task->taskTitle }} + @if ($row->pinned) + + @elseif (! $row->task->isLocked()) + + @endif +
  • + @endforeach +
+
+ @endforeach +
+ + + + +
+ + {{-- + Lisää työ listalle --}} + +
+ + @if (mb_strlen(trim($pinSearch)) >= 2) +

{{ trans_choice('time.sheet.add_count', count($this->pinCandidates), ['count' => count($this->pinCandidates)]) }}

+
    + @foreach ($this->pinCandidates as $task) +
  • + {{ $task->customerName }} • #{{ $task->jobNumber }} {{ $task->jobName }} – {{ $task->taskTitle }} + +
  • + @endforeach +
+ @endif +
+ + + + +
+ + +

{{ __('time.sheet.clear_pins_question') }}

+ + + +
+ @endunless @can('time.cancel-approval')

{{ __('time.approval.cancel_question', ['week' => $this->weekHeading()]) }}

-
@endcan - @unless ($this->isReadOnly()) -
-

{{ __('time.add.search') }}

- - - @if (mb_strlen(trim($taskSearch)) >= 2) -

- {{ trans_choice('time.add.results', count($this->searchResults), ['count' => count($this->searchResults)]) }} -

-
    - @foreach ($this->searchResults as $task) -
  • - -
  • - @endforeach -
- @endif -
- @endunless +
diff --git a/database/factories/TimeEntryFactory.php b/database/factories/TimeEntryFactory.php index 8663365..c1690c6 100644 --- a/database/factories/TimeEntryFactory.php +++ b/database/factories/TimeEntryFactory.php @@ -26,9 +26,18 @@ class TimeEntryFactory extends Factory 'work_type_id' => fn (array $attributes) => TaskModel::query()->findOrFail($attributes['task_id'])->work_type_id, 'worked_on' => now()->toDateString(), 'hours' => 2, + 'note' => fake()->sentence(3), ]; } + /** + * An entry without a billing note, which keeps its week from being approved. + */ + public function withoutNote(): static + { + return $this->state(['note' => null]); + } + public function approved(?User $by = null): static { return $this->state(fn (array $attributes): array => [ diff --git a/database/migrations/2026_11_30_043508_add_billing_details_to_time_entries_table.php b/database/migrations/2026_11_30_043508_add_billing_details_to_time_entries_table.php new file mode 100644 index 0000000..2736d43 --- /dev/null +++ b/database/migrations/2026_11_30_043508_add_billing_details_to_time_entries_table.php @@ -0,0 +1,27 @@ +string('billing_model', 20)->nullable()->after('note'); + $table->text('internal_comment')->nullable()->after('billing_model'); + }); + } + + public function down(): void + { + Schema::table('time_entries', function (Blueprint $table) { + $table->dropColumn(['billing_model', 'internal_comment']); + }); + } +}; diff --git a/database/migrations/2026_11_30_043509_create_time_pinned_tasks_table.php b/database/migrations/2026_11_30_043509_create_time_pinned_tasks_table.php new file mode 100644 index 0000000..aa119a9 --- /dev/null +++ b/database/migrations/2026_11_30_043509_create_time_pinned_tasks_table.php @@ -0,0 +1,28 @@ +id(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->foreignId('task_id')->constrained()->cascadeOnDelete(); + $table->timestamp('pinned_at'); + $table->unique(['user_id', 'task_id']); + }); + } + + public function down(): void + { + Schema::dropIfExists('time_pinned_tasks'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 7dba32e..786d1e7 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -97,6 +97,7 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli - **Laskutusyksiköt**: useita; nimi (pakollinen, oletuksena asiakkaan nimi), laskutusosoite (vapaa teksti: postiosoite tai laskutussähköposti), verkkolaskuosoite (12–35 kirjainta tai numeroa), välittäjätunnus (pakollinen, jos verkkolaskuosoite on annettu) ja viite. Saman asiakkaan eri laskutusyksiköt laskutetaan omilla laskuillaan. - Asiakkaalla on oma sivu, jolla näkyvät perustiedot, yhteyshenkilöt ja laskutusyksiköt. Uuden asiakkaan tallennus vie asiakkaan sivulle. - Asiakastyön vastaanotossa riittää asiakkaan nimi (ja tyyppi); muut tiedot täydennetään myöhemmin. +- **Tunnusväri** (`customers.header_color`, #rrggbb, valinnainen): asiakkaan Kanban-korttien otsikkopalkin ja tuntikirjauksen asiakasrivin väri. Väriä voi vaihtaa asiakkaan sivulta, Kanban-kortilta ja tuntikirjauksesta (pikavärit, värivalitsin ja R/G/B 0–255). Ilman väriä käytetään oletussävyä. Tekstin väri (valkoinen tai musta) valitaan sen mukaan, kummalla kontrasti on suurempi, joten teksti on aina vähintään 4,5:1 *(valmis)*. - Yrityksen oma sisäinen asiakas, jonka asiakastöihin kirjataan sisäinen työ (hallinto, myynti, koulutus) *(K39)*. Migraatio luo yhden sisäisen asiakkaan "Oma yritys (sisäinen)"; nimen voi muuttaa, mutta se on aina yritys, eikä uusia sisäisiä asiakkaita luoda käyttöliittymästä *(valmis)*. ## 5. Asiakastyö @@ -213,7 +214,9 @@ Asiakastyön kenttien muutokset tallennetaan: kuka, milloin, mikä kenttä, vanh - Toimii puhelimella ja tietokoneella; puhelimella yksi kapea lomake. - Pakolliset: asiakas (haku tai pikalisäys), nimi, lyhyt kuvaus, palveluyksikkö, vastuuhenkilö. Muut kentät täydennetään myöhemmin. -- Uusi työ alkaa tilasta *Prospekti* tai *Alustava* (valittavissa, oletus Alustava). Laji on Kertaluonteinen ja prioriteetti Normaali; vastuuhenkilönä on oletuksena kirjaaja. +- Asiakkaan kontaktihenkilö valitaan asiakkaan yhteyshenkilöistä, ja uuden voi pikalisätä samalla lomakkeella (nimi ja puhelin). +- Alkutila on valittavissa: *Prospekti*, *Alustava* (oletus), *Tarjouspyyntö*, *Tilaus* tai *Tuotannossa*. Prioriteetti on valittavissa (oletus Normaali). Laji on Kertaluonteinen; vastuuhenkilönä on oletuksena kirjaaja. +- Sama lomake aukeaa Kanbanilta dialogina ("Uusi työ / Pikavastaanotto"); tallennus sulkee dialogin, ja alkutilan Alustava tai Tarjouspyyntö kanssa taulu siirtyy Myynti & Tarjoukset -näkymään *(valmis)*. - Tallennuksen jälkeen sivu jää auki seuraavaa työtä varten: lomake tyhjenee (vastuuhenkilö ja tila säilyvät), ja ilmoituksessa on työn numero sekä linkit "Avaa työ" ja "Täydennä tietoja". - Pikavastaanotto löytyy valikosta ja asiakastyölistalta (`/jobs/quick`). - Ei automaattista luontia sähköpostista tai verkkolomakkeesta toistaiseksi. @@ -235,12 +238,18 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä ### 8.1 Asiakastöiden Kanban *(K33)* -- Sarakkeet ovat asiakastyön tilat (5.3), arkistoitu pois lukien. Jatkuvat / Kausi on oma sarakkeensa jatkuville ja kausitöille. Kortti on asiakastyö. -- Oletuksena näytetään käyttäjän omat työt (5.6); suodattimella kaikki (alihankkijalle vain liitetyt). -- Kortilla: numero, nimi, asiakas, prioriteetti (teksti + väri), määräaika ja myöhässä-ilmaisin (teksti + kuvake). -- Kortin siirto toiseen sarakkeeseen vaihtaa tilan ja kirjataan muutoshistoriaan. Kortin voi vetää hiirellä tai kosketuksella, tai valita tilan kortin Tila-valinnasta (näppäimistö, ruudunlukija). -- Laskutustiloihin (Lasku luotu, Laskutettu) voi siirtää vain johto tai työn laskuttaja; arkistointi tehdään työn muokkaussivulla. -- Sivun alussa on linkit jokaiseen sarakkeeseen korttimäärineen. Sarakkeet rivittyvät näytön leveyden mukaan, joten sivulla ei ole vaakavieritystä. +Käyttöliittymän tarkka kuvaus on `docs/ui-kanban-board.md` ja visuaalinen referenssi `docs/prototypes/kanban-prototyyppi.html`. + +- **Taulu**: Oma taulu (oletus: työt, joissa käyttäjä on vastuu-, kontakti- tai laskuttajahenkilö, jäsen tai tehtävän tekijä), toisen henkilön taulu, palvelulinjan taulu tai kaikki työt. Alihankkija näkee vain liitetyt työnsä. Yrityksen vuosittainen pikamyyntityö ei näy taululla. +- **Näkymäputket**: *Päivittäinen työputki* (Tarjoukset = Prospekti + Alustava + Tarjouspyyntö, Jonossa, Työn alla, Työn alla • Kiire, Odottaa asiakasta, Valmis • Laskuta, Jatkuvat & Kausi), *Myynti & Tarjoukset* (kolme myyntitilaa erikseen) ja *Täysi tilaputki* (kaikki tilat Prospektista Laskutettuun sekä Jatkuvat & Kausi). Pikasuodattimet: vain kiireelliset (Kiire, Heti) ja myöhässä. Näytettyjen korttien määrä luetaan ruudunlukijalle. +- **Työn alla • Kiire** on virtuaalinen sarake: Tuotannossa-tilan työt, joiden prioriteetti on käyttäjän valitsemalla kynnyksellä tai yli (Vain Heti / Kiire & Heti (oletus) / Ensin, Kiire & Heti). Kortin pudotus Kiire-sarakkeeseen nostaa prioriteetin kynnykseen; pudotus tavalliseen Työn alla -sarakkeeseen laskee kiireellisen työn prioriteetiksi Normaali. +- **Jatkuvat & Kausi** -sarakkeessa ovat vain tilan *Jatkuvat / Kausi* työt, eikä niitä voi raahata muihin sarakkeisiin (tila vaihdetaan työn tiedoista). Kortilla näkyy seuraava avoin jakso tai tehtävä ("Kuittaa valmiiksi"), kaikki jaksot ja tehtävien pikalisäys. +- **Putkeen nostetut tehtävät (PIN)**: jatkuvan työn tehtävän voi nostaa taululle omaksi kortikseen (`tasks.is_pinned_to_board`). Kortti on sarakkeessa Jonossa, Työn alla tai Valmis tehtävän tilan mukaan, ja siirto vaihtaa tehtävän tilan. "Vapauta" palauttaa sen pelkäksi tehtäväksi. +- **Kortti**: asiakkaan tunnusvärinen otsikkopalkki (asiakas, numero, väri), nimi (koko nimi vihjeenä ja ruudunlukijalle), vastuuhenkilö, palveluyksikkö, prioriteetti (teksti + väri), määräaika tai myöhässä-ilmaisin (teksti + kuvake), kirjatut / arvioidut tunnit ja tehtävät, jotka avautuvat kortin sisään ja kuitataan valmiiksi valintaruudulla. Tiivis näkymä näyttää kortin kolmella rivillä. Kortilla ei ole tilavalintaa. +- **Siirto ja järjestys**: kortin otsikkopalkista raahaus siirtää kortin toiseen sarakkeeseen (tila vaihtuu ja kirjataan muutoshistoriaan) tai saman sarakkeen sisällä (järjestys `customer_jobs.board_position`, ei muutoshistoriaa). Näppäimistöllä ja ruudunlukijalla kortti avataan nimestä, ja tila vaihdetaan muokkausnäkymän tilavalinnasta. Laskutustiloihin voi siirtää vain johto tai työn laskuttaja, ja valmiin työn lukituksen avaa vain johto. +- **Käyttäjäkohtaiset asetukset** (`job_board_preferences`): korttien tiheys (Normaali / Tiivis), Kiire-kynnys sekä jokaisen sarakkeen oma otsikkoväri (oletuksena suunnitelman väri, palautettavissa) ja järjestys (oma järjestys tai eräpäivän mukaan; raahaus eräpäiväjärjestyksessä vaihtaa sarakkeen omaan järjestykseen). Asetukset eivät vaikuta muiden käyttäjien tauluun. +- **Muokkausnäkymä**: kortin avaus näyttää koko asiakastyön dialogissa (työpöydällä kaksi palstaa): tila ja prioriteetti (tallentuvat heti), lukitusilmoitus, nimi, kuvaus, työohjeistus, linkit, tehtävät (tila, tekijä, määräpäivä, tarkistuslista, työnkulkupohjat, uusi tehtävä), tuntien ja kulujen pikakirjaus, muutoshistoria sekä asiakas, yhteyshenkilö, laskutusyksikkö, tiimi, palveluyksiköt, tagit, laji, aikataulu, arvio ja raha (rahaoikeuksien mukaan). +- Työpöydällä sarakkeet ovat rinnakkain yhdellä rivillä ja taulua vieritetään vaakasuunnassa; puhelimella sarakkeet ovat allekkain *(valmis)*. ### 8.2 Tehtävät @@ -259,7 +268,7 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä - Tunnit kirjataan **tehtävälle** (ja sitä kautta asiakastyölle). Tehtävä kuuluu työtehtävään (esim. editointi), jonka tuntihinnalla tunnit hinnoitellaan. - Kaksi tapaa: - - **Viikkonäkymä**: rivit ovat käyttäjän tehtävät, sarakkeet viikonpäivät, soluun kesto tunteina (esim. 1,5). Rivin voi lisätä hakemalla tehtävän. + - **Viikkonäkymä** (tarkka kuvaus `docs/ui-timesheet.md`): kaksi osiota, *Aikataulutettu* (viikolle aikataulutetut tehtävät, aikatauluttamattomat omat avoimet tehtävät ja viikon kirjausten tehtävät) ja *Lukitut työt* (käyttäjän itse kiinnittämät tehtävät, `time_pinned_tasks`, jotka pysyvät viikolta toiselle). Rivit ryhmitellään asiakas A–Ö → asiakastyö → tehtävä. Soluun kirjoitetaan aika muodossa 1:30, 1,5 tai minuutteina (90), ja ±15 min -painikkeet muuttavat sitä. Kiinnitys raukeaa, kun työ tai tehtävä on valmis tai laskutettu, mutta rivi näkyy viikoilla, joilla sille on tunteja. Kuluvalle päivälle on työajastin, joka kirjaa ajan vartin tarkkuudella (vähintään 15 min). - **Tehtävältä**: päivämäärä, kesto ja vapaaehtoinen selite. - Kesto kirjataan tunteina; tarkkuus 0,25 h. Käyttäjällä on tehtävällä enintään yksi kirjaus päivää kohden (tunnit ja selite): viikkonäkymän solu muuttaa sitä, tyhjä solu poistaa sen, ja tehtävän sivulta samalle päivälle kirjatut tunnit lisätään päivän kirjaukseen. - Käyttäjän kirjausten summa voi olla enintään 24 h päivässä. @@ -268,7 +277,8 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä - Sisäinen työ kirjataan sisäisen asiakkaan asiakastöille. - Työajanseuranta (esim. tehdyt tunnit vs. työaika) on asetuksen takana, oletuksena pois. - Tunnit eivät suoraan ole laskutusperuste: laskutettavuus määräytyy työn maksuperusteesta, ja laskutettava tuntimäärä päätetään laskutusvaiheessa (luku 12) *(K40, K41)*. -- **Hyväksyntä**: työntekijä ja harjoittelija hyväksyvät omat tuntinsa itse (esim. viikkonäkymästä "Hyväksy viikko"). Johto voi hyväksyä kenen tahansa tunnit ja hyväksyy alihankkijoiden tunnit. Hyväksyjä ja aika tallennetaan. +- Kirjauksella on **laskutusperuste** (Kiinteä hinta / Tuntityö / Ei laskutettava; oletus työn maksuperusteesta, `time_entries.billing_model`), **laskutusselite** (`note`) ja **sisäinen kommentti** (`internal_comment`). Laskutusperuste on seurantatieto (kuukausiyhteenveto: laskutettava ja kiinteä vs. sisäinen); laskutus toimii edelleen työn maksuperusteen mukaan *(valmis)*. +- **Hyväksyntä**: työntekijä ja harjoittelija hyväksyvät omat tuntinsa itse (viikkonäkymästä "Hyväksy viikko", koko viikko kerralla). Johto voi hyväksyä kenen tahansa tunnit ja hyväksyy alihankkijoiden tunnit. Hyväksyjä ja aika tallennetaan. Viikkoa ei voi hyväksyä, ennen kuin jokaisella hyväksymättömällä kirjauksella on laskutusselite; puuttuvat selitteet listataan, ja jokaiselle on suora "Täytä selite" -painike. - **Johdon tarkistus**: johto tarkistaa hyväksytyt tunnit laskutuksen yhteydessä ja kirjaa niiden perusteella laskulle laskutettavan kokonaistuntimäärän (luku 12). Kirjattuja tunteja ei muuteta. - Hyväksytyt tunnit ja valmiin työn tunnit ovat lukittuja. Hyväksytyn viikon päiville voi kirjata uusia tunteja muille tehtäville; ne on hyväksyttävä erikseen. - Hyväksynnän voi perua vain johto (esim. virheen korjaamiseksi); sen jälkeen tunteja voi muuttaa ja ne hyväksytään uudelleen. diff --git a/docs/prototypes/kanban-prototyyppi.html b/docs/prototypes/kanban-prototyyppi.html new file mode 100644 index 0000000..2da07da --- /dev/null +++ b/docs/prototypes/kanban-prototyyppi.html @@ -0,0 +1,2754 @@ + + + + + + Toiminnanohjaus – Asiakastyöt & Tehtävät (Kanban) + + + + + + + + + + + +
+
+
+
+ + + + Toiminnanohjaus +
+ + +
+ +
+ + + + + +
+
+
+ + +
+
+ +
+ +
+ + +
+ + +
+ + + +
+ + + + + + + +
+ + +
+
+ + +
+ + +
+
+
+ + +
+

Asiakastyöt ja tehtävät – Kanban-työtaulu

+ +
+ +
+
+ + + + + + + + + + + + + + +
+
+

Uusi työ / Pikavastaanotto

+ +
+ +
+
+ + +
+ +
+
+ + +
+ +
+ +
+
+ +
+ + +
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+
+ +
+ + +
+
+
+ + +
+ + + + \ No newline at end of file diff --git a/docs/prototypes/timesheet-prototyyppi.html b/docs/prototypes/timesheet-prototyyppi.html new file mode 100644 index 0000000..c5d7692 --- /dev/null +++ b/docs/prototypes/timesheet-prototyyppi.html @@ -0,0 +1,2288 @@ + + + + + + Työajankirjaus / Timesheet – Prototyyppi + + + + + + + + + +
+
+ + +
+ + + + + + +
+ JM + +
+
+
+
+ + +
+ + +
+
+ + + + + +
+

+ + () +

+

+ Nykyinen kuluva viikko on Viikko 48 (23.11. – 29.11.2026). Varmista ennen kirjausta, että olet oikealla viikolla. +

+
+
+ +
+ + +
+
+ +
+
+
+

+ + Kuluva viikko + + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ + + + + +
+
+ + +
+ + +
+ + +
+
+
+
+ + +
+
+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ Asiakas / Asiakastyö / Tehtävä + A–Ö +
+
Yht.Toim.
+
+ + +
+
+ Ei vapaita aikataulutettuja tehtäviä tälle viikolle (kaikki aikataulutetut työt on kiinnitetty alaosioon). +
+
+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + ★ + + Lukitut työt + +
+ + + +
+ + +
+
+

Ei vielä lukittuja töitä.

+ +
+
+ + + + +
+ + + + + + + + + + + + + + + +
+
+ Päivä- ja viikkoyhteenveto + Tavoite 37:30 / vko +
+
+ + + +
+
+ +
+
+ + +
+
+ Marraskuu 2026 + Kuukauden kokonaiskertymä: 142:15 h (Laskutettava & kiinteä: 108:30 h • Sisäinen: 33:45 h) +
+ +
+ +
+ + + + +
+
+
+
+ + Työajastin +
+
+ + Pysäytä ennen sulkemista + + +
+
+ +
+
+
+
+
+
+ + +
+ + + + +

+
+ +
+ + +
+ + +
+ + + + +
+
+
+
+ + + + +
+
+
+
+

Muokkaa kirjausta

+

+ • + • + + () +

+
+
+ + +
+
+ +
+ +
+ +
+ + + + + +
+
+ + +
+
+ + Vaaditaan viikon hyväksyntää varten +
+ +
+ + +
+
+ + Näkyy vain omalle tiimille ja laskuttajalle +
+ +
+ + +
+
+ + +
+ + +
+
+
+
+ + + + +
+
+
+
+

+/- Työmääräykset ja työn tila

+

Kiinnitä tehtäviä Lukitut-osioon tai testaa työn merkitsemistä Valmiiksi / Laskutetuksi

+
+ +
+ +
+ +
+ +
+ +
+
+
+ + + + +
+
+
+
+

Lisää työ listalle (Lukitut työt)

+

Kaikki henkilön avoimet työt ja tehtävät, joita ei ole vielä kiinnitetty listalle

+
+ +
+ + +
+ +
+ +
+ + +
+ Kaikki hakua vastaavat henkilön avoimet työt on jo kiinnitetty listalle. +
+
+ +
+ +
+
+
+ + + + +
+
+
+
+
+ + + +
+
+

Oletko varma?

+

Poistetaanko kaikki kiinnitykset Lukitut työt -osiosta?

+
+
+ +

+ Toiminto vapauttaa kaikki kiinnitettyä tehtävää Lukitut työt -listalta. Jo kirjatut tunnit säilyvät tallessa, ja aikataulutetut työt palautuvat takaisin yläosan Aikataulutettu-osioon. +

+ +
+ + +
+
+
+
+ + + + +
+
+
+
+ + + + + +
+

Viikkoa ei voi vielä hyväksyä – laskutusselite puuttuu

+

+ Jokaiselle kirjatulle tuntimerkinnälle tulee antaa laskutusselite ennen viikon hyväksyntää ( puuttuvaa). +

+
+
+ +
+ +
+ +
+ +
+ Puuttuvat kohdat on myös korostettu keltaisella merkinnällä ruudukossa. + +
+
+
+ + +
+ + + + \ No newline at end of file diff --git a/docs/ui-kanban-board.md b/docs/ui-kanban-board.md new file mode 100644 index 0000000..64cf283 --- /dev/null +++ b/docs/ui-kanban-board.md @@ -0,0 +1,148 @@ +# UI-määrittely: Asiakastyöt & Tehtävät -työtaulu (`jobs::board`) + +Tämä dokumentti määrittelee toiminnanohjausjärjestelmän Kanban-työtaulun (`jobs::board`), pikavastaanoton (`/jobs/quick`) sekä avatun asiakastyökortin täyden muokkausmodaalin käyttöliittymän ja toiminnot. Dokumentti on laadittu suoraan projektin `CLAUDE.md`- ja `docs/architecture.md`-sääntöjen mukaiseksi (Laravel 13, Livewire 4, TallStackUI 4, Tailwind 4, WCAG 2.2 AA). + +**Visuaalinen referenssi:** `docs/prototypes/kanban-prototyyppi.html` + +--- + +## 1. Yleisasettelu, tiheys ja väripaletti + +### 1.1 Näkymän tiheys ja sarakeleveydet +Työkalupalkissa on käyttäjäkohtainen tiheysvalitsin (**Normaali** / **Tiivis**): +* **Normaali näkymä:** + * Tavallinen sarakeleveys: `252 px` (`w-[252px]`), sisämarginaali `p-2` (`8 px`), korttien väli `gap-2` (`8 px`). + * *Jatkuvat & Kausituotannot* -sarake: `268 px` (`w-[268px]`). + * Kortilla näkyvät: asiakaspalkki + työnumero + väripaletti, katkeava työn nimiotsikko (hover-tooltip koko nimelle), vastuuhenkilö (nimikirjaimet + etunimi), palveluyksikkö, prioriteetti (teksti + väri), määräaika/myöhässä-ilmaisin, toteutuneet/arvioidut tunnit, nopea tilavalitsin sekä laajennettava tehtävälista. +* **Tiivis näkymä (Compact):** + * Tavallinen sarakeleveys: `234 px` (`w-[234px]`), sisämarginaali `p-1.5` (`6 px`), korttien väli `gap-1.5` (`6 px`). + * *Jatkuvat & Kausituotannot* -sarake: `250 px` (`w-[250px]`). + * Kortti kutistuu **kolmiriviseksi**: + 1. Rivi 1: Asiakaspalkki + työnumero + väripaletti. + 2. Rivi 2: Katkeava työn nimiotsikko (hoverilla koko nimi, klikkaamalla täysi muokkausmodaali). + 3. Rivi 3: Vastuuhenkilö (`JM Jussi`) + prioriteettibadge + oikeassa reunassa kompakti tehtävälaskuri (`1/2 ▾`), josta tehtävälista laajenee suoraan kortin sisälle. + +### 1.2 Värijärjestelmä (Tumma ja vaalea tila) +* **Työtilan tausta (`
`):** + * Tumma tila: Keskiharmaa `#5a5e60` (matala silmäkontrasti, ei sinertävää taittoa). + * Vaalea tila: Pehmeä vaaleanharmaa `#e5e7eb`. +* **Kortin runko:** + * Tumma tila: Neutraali tumma liuskekivenharmaa `#282a2e`, reunus `#36393f`. + * Vaalea tila: Puhdas valkoinen `#ffffff`, reunus `#d1d5db`. +* **Listan (sarakkeen) otsikkopalkki ja runko:** + * Jokaisella sarakkeella on yhtenäinen yhden rivin (`h-10`) otsikkopalkki, jossa on ikoni, sarakkeen nimi, toimintokuvakkeet sekä korttimäärälaskuri. + * Käyttäjä voi muokata minkä tahansa listan otsikon taustaväriä paletti-ikonista (**pikavärit + natiivi Color Picker + R/G/B-numerokentät 0–255**). + * **Sarakkeen rungon sävytys:** Sarakkeen tausta lasketaan automaattisesti otsikkovärin johdannaisena: + * Tumma tila: Syvä tumma `#16160e` sekoitettuna 11 % valitusta otsikkoväristä (reunus `#2a2b23` + 15 % otsikkoväristä). + * Vaalea tila: Vaalea `#f6f7f9` sekoitettuna 8 % valitusta otsikkoväristä. + * **WCAG 2.2 AA -kontrasti:** Otsikkopalkin tekstin ja kuvakkeiden väri (`#ffffff` tai `#111827`) lasketaan automaattisesti taustavärin suhteellisen luminanssin perusteella (raja-arvo `0.36`). + +--- + +## 2. Työkalupalkin suodattimet ja näkymätilat + +1. **Tauluvalitsin (`Taulu`):** + * *Oma taulu* (oletus: työt, joissa käyttäjä on vastuuhenkilö, jäsen tai tehtävän tekijä) + * *Henkilön taulu* (valittavissa kuka tahansa aktiivinen työntekijä) + * *Palvelulinjan taulu* (suodattaa palveluyksikön mukaan, esim. *Painotuotanto*, *Mediatuotanto*, *Markkinointi*, *Verkkosivut*) + * *Kaikki työt (Yritys)* (roolioikeuksien mukaisesti; alihankkijalle vain liitetyt) +2. **Näkymäputki (`pipelineView`):** + * **Päivittäinen työputki (Oletus):** `Tarjoukset` (kokoaa tilat *Prospekti*, *Alustava* ja *Tarjouspyyntö*) → `Jonossa` (`Order`) → `Työn alla` (`InProduction`, normaali) → `Työn alla • Kiire` (`InProduction`, priorisoitu) → `Odottaa asiakasta` (`OnHold`) → `Valmis • Laskuta` (`Done`) → `Jatkuvat & Kausi` (`Ongoing`). + * **Myynti & Tarjoukset:** `Prospekti` → `Alustava` → `Tarjouspyyntö` (eriteltynä). + * **Täysi tilaputki:** Kaikki aktiiviset tilat `Prospekti` → `Laskutettu` sekä `Jatkuvat & Kausi` rinnakkain. +3. **Pikasuodattimet:** + * `Vain kiireelliset` (näyttää vain prioriteetit *Kiire* ja *Heti*). + * `Myöhässä` (näyttää työt, joiden määräaika `due_on` on ohitettu). + * Saavutettava `role="status"`-laskuri näyttää suodatettujen korttien määrän reaaliaikaisesti. + +--- + +## 3. Sarakkeiden logiikka, raahaus ja järjestys + +### 3.1 Jaettu *Työn alla* -sarake ja prioriteettikynnyksen valitsin +* *Tuotannossa* (`InProduction`) -tilassa olevat työt jakautuvat kahteen rinnakkaiseen sarakkeeseen: vasemmalla **Työn alla** (normaali työjono) ja sen oikealla puolella **Työn alla • Kiire**. +* Molemmilla sarakkeilla on sama oletusotsikkoväri (`#1d4ed8`), ja käyttäjä voi muokata niitä vapaasti. +* **Työn alla • Kiire** -sarakkeen otsikkopalkin oikeassa reunassa (järjestys- ja värikuvakkeiden vieressä) on kompakti pudotusvalikko (`▾`), josta käyttäjä valitsee kynnyksen: + * *Vain Heti* (`Immediate`) + * *Kiire & Heti* (`Urgent`, `Immediate`) – oletus + * *Ensin, Kiire & Heti* (`First`, `Urgent`, `Immediate`) +* Kortin siirtäminen normaalin ja kiireellisen *Työn alla* -listan välillä päivittää automaattisesti kortin prioriteetin vastaamaan valittua kynnystä. + +### 3.2 Korttien raahaaminen otsikosta ja sarakkeen sisäinen järjestys +* **Vetokahva (`wire:sort:handle`):** Kortin värillinen yläotsikkopalkki toimii vetokahvana (`cursor-grab`). + * **Klikkaus** otsikkopalkkiin tai kortin työnimeen avaa täyden asiakastyön muokkausmodaalin. + * **Raahaus** otsikkopalkista siirtää kortin sekä **sarakkeesta toiseen** (päivittäen tilan/prioriteetin) että **saman sarakkeen sisällä ylös tai alas** (päivittäen järjestyksen `board_position`). Pudotuskohtaan piirtyy selkeä korostusviiva. + * **Näppäimistövaihtoehto (WCAG 2.2 AA):** Jokaisella kortilla on myös tilanvaihtovalikko (` $quarters > 0, + 'border-slate-400 bg-slate-50 text-slate-700 dark:border-[#5a5e66] dark:bg-[#1b1d20] dark:text-zinc-200' => $quarters === 0, + ]) + /> + + @else + {{ WorkedHours::formatClock($quarters) }} + @if ($cell?->approved) +
+ @error($errorKey) +

{{ $message }}

+ @enderror + + @endforeach + + {{ WorkedHours::formatClock($row->totalQuarters) }} + + @unless ($readOnly) + @if ($pinned) + + @elseif (! $locked) + + @endif + @endunless + + + @endforeach + @endforeach + @endforeach + + + diff --git a/tests/Browser/TimeTrackingAccessibilityTest.php b/tests/Browser/TimeTrackingAccessibilityTest.php index 3084fe1..1780104 100644 --- a/tests/Browser/TimeTrackingAccessibilityTest.php +++ b/tests/Browser/TimeTrackingAccessibilityTest.php @@ -35,14 +35,15 @@ it('has no accessibility issues on the time pages and no sideways scrolling', fu it('records hours in the weekly view with the keyboard', function () { $tuesday = now()->startOfWeek()->addDay()->toDateString(); - $cell = '#cell-'.$this->task->id.'-'.$tuesday; + $cell = '#cell-scheduled-'.$this->task->id.'-'.$tuesday; visit(route('time.week')) ->on()->desktop() - ->type($cell, '2,5') + ->clear($cell) + ->type($cell, '2:30') ->keys($cell, 'Tab') ->assertSee('Tallennettu: Mainoskuvat') - ->assertSee('Viikko yhteensä: 4 h') + ->assertSee('Viikko yhteensä: 4:00 h') ->assertNoAccessibilityIssues(level: 2); expect((float) TimeEntryModel::query()->whereDate('worked_on', $tuesday)->sole()->hours)->toBe(2.5); @@ -50,8 +51,8 @@ it('records hours in the weekly view with the keyboard', function () { it('shows an invalid value as an error at the field', function (string $device) { $selector = $device === 'mobile' - ? '#mcell-'.$this->task->id.'-'.$this->monday - : '#cell-'.$this->task->id.'-'.$this->monday; + ? '#mcell-scheduled-'.$this->task->id.'-'.$this->monday + : '#cell-scheduled-'.$this->task->id.'-'.$this->monday; $visit = visit(route('time.week')); $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); @@ -90,7 +91,7 @@ it('has no accessibility issues on the approval pages', function (string $page, $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); - $visit->assertSee($page === 'approvals' ? 'Kaisa Kollega' : 'hyväksytty') + $visit->assertSee($page === 'approvals' ? 'Kaisa Kollega' : 'Hyväksytty:') ->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true) ->assertNoJavaScriptErrors() ->assertNoAccessibilityIssues(level: 2); @@ -103,11 +104,51 @@ it('has no accessibility issues on the approval pages', function (string $page, it('approves the own week with the keyboard and shows the cells as approved', function () { visit(route('time.week')) - ->assertSee('Hyväksymättä 1,5 h.') - ->keys('#approval-heading + p + div button', 'Enter') + ->assertSee('Hyväksymättä:') + ->assertSee('1:30') + ->click('Hyväksy viikko') ->assertSee('Hyväksytyt tunnit on lukittu.') - ->assertSee('hyväksytty') + ->assertSee('Hyväksytty:') ->assertNoAccessibilityIssues(level: 2); expect(TimeEntryModel::query()->sole()->approved_at)->not->toBeNull(); }); + +it('asks for the missing billing notes before approving, and fills one in the entry dialog', function () { + TimeEntryModel::query()->update(['note' => null]); + + visit(route('time.week')) + ->on()->desktop() + ->assertSee('1 selite puuttuu') + ->click('Hyväksy viikko') + ->assertScript('document.getElementById("missing-notes-dialog").open', true) + ->assertNoAccessibilityIssues(level: 2) + ->click('#missing-notes-dialog button[wire\\:click^="openEntry"]') + ->assertScript('document.getElementById("entry-dialog").open', true) + ->assertNoAccessibilityIssues(level: 2) + ->type('#entry-note', 'Mainoskuvien luonnokset') + ->keys('#entry-note', 'Escape') + ->assertSee('Kirjaus tallennettu') + ->assertScript('document.getElementById("entry-dialog").open', false); + + expect(TimeEntryModel::query()->sole()->note)->toBe('Mainoskuvien luonnokset'); +}); + +it('has no accessibility issues in the timer, work orders and add to list dialogs', function (string $colorScheme) { + $visit = visit(route('time.week'))->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->click('[aria-label^="Työajastin: Mainoskuvat"]') + ->assertScript('document.getElementById("timer-dialog").open', true) + ->assertNoAccessibilityIssues(level: 2) + ->keys('#timer-note', 'Escape') + ->click('#open-manage') + ->assertScript('document.getElementById("manage-dialog").open', true) + ->assertNoAccessibilityIssues(level: 2) + ->keys('#manage-dialog', 'Escape') + ->click('#open-add-to-list') + ->assertScript('document.getElementById("add-to-list-dialog").open', true) + ->type('#pin-search', 'Mainos') + ->assertSee('1 osuma') + ->assertNoAccessibilityIssues(level: 2); +})->with(['light', 'dark']); diff --git a/tests/Fakes/FakeTaskQueries.php b/tests/Fakes/FakeTaskQueries.php index 2a2408f..0257673 100644 --- a/tests/Fakes/FakeTaskQueries.php +++ b/tests/Fakes/FakeTaskQueries.php @@ -21,6 +21,11 @@ class FakeTaskQueries implements TaskQueries $this->tasks[$taskId] = new BookableTask($taskId, $jobId, '2026-0001', 'Kampanja', 'Tehtävä '.$taskId, $workTypeId, 'graafinen työ', $jobStatus, TaskStatus::Waiting); } + public function scheduledTaskIdsFor(int $userId, string $from, string $to): array + { + return []; + } + public function pinnedTaskIds(int $jobId): array { return []; diff --git a/tests/Fakes/InMemoryPinnedTaskRepository.php b/tests/Fakes/InMemoryPinnedTaskRepository.php new file mode 100644 index 0000000..8d57ce1 --- /dev/null +++ b/tests/Fakes/InMemoryPinnedTaskRepository.php @@ -0,0 +1,37 @@ +> task ids by user id */ + public array $pins = []; + + public function pin(int $userId, int $taskId, DateTimeImmutable $at): void + { + if (! in_array($taskId, $this->pins[$userId] ?? [], true)) { + $this->pins[$userId][] = $taskId; + } + } + + public function unpin(int $userId, int $taskId): void + { + $this->pins[$userId] = array_values(array_diff($this->pins[$userId] ?? [], [$taskId])); + } + + public function unpinAll(int $userId): int + { + $count = count($this->pins[$userId] ?? []); + $this->pins[$userId] = []; + + return $count; + } + + public function pinnedTaskIds(int $userId): array + { + return $this->pins[$userId] ?? []; + } +} diff --git a/tests/Fakes/InMemoryTimeEntryRepository.php b/tests/Fakes/InMemoryTimeEntryRepository.php index 94b4259..2beb09f 100644 --- a/tests/Fakes/InMemoryTimeEntryRepository.php +++ b/tests/Fakes/InMemoryTimeEntryRepository.php @@ -34,7 +34,7 @@ class InMemoryTimeEntryRepository implements TimeEntryRepository public function save(TimeEntry $entry): TimeEntry { $id = $entry->id() ?? $this->nextId++; - $this->entries[$id] = TimeEntry::reconstitute($id, $entry->userId(), $entry->taskId(), $entry->jobId(), $entry->workTypeId(), $entry->workedOn(), $entry->hours(), $entry->note(), $entry->approvedBy(), $entry->approvedAt(), $entry->billingExportId()); + $this->entries[$id] = TimeEntry::reconstitute($id, $entry->userId(), $entry->taskId(), $entry->jobId(), $entry->workTypeId(), $entry->workedOn(), $entry->hours(), $entry->note(), $entry->approvedBy(), $entry->approvedAt(), $entry->billingExportId(), $entry->billingModel(), $entry->internalComment()); return clone $this->entries[$id]; } diff --git a/tests/Feature/Modules/TimeTracking/ApprovalTest.php b/tests/Feature/Modules/TimeTracking/ApprovalTest.php index 8692cdc..1f68c06 100644 --- a/tests/Feature/Modules/TimeTracking/ApprovalTest.php +++ b/tests/Feature/Modules/TimeTracking/ApprovalTest.php @@ -33,7 +33,7 @@ it('approves the own week in the weekly view, which locks its cells', function ( $this->actingAs($this->employee); Livewire::test('time::week') - ->assertSee('Hyväksymättä 3 h.') + ->assertSee('Hyväksymättä:')->assertSee('3:00') ->call('approveWeek') ->assertSet('statusMessage', fn (string $message) => str_contains($message, 'hyväksytty. Hyväksytyt tunnit on lukittu.')) ->assertDontSee('id="cell-'.$this->task->id.'-'.$this->monday.'"', false) diff --git a/tests/Feature/Modules/TimeTracking/TimeEntriesTest.php b/tests/Feature/Modules/TimeTracking/TimeEntriesTest.php index 3dbaf7f..bfb174e 100644 --- a/tests/Feature/Modules/TimeTracking/TimeEntriesTest.php +++ b/tests/Feature/Modules/TimeTracking/TimeEntriesTest.php @@ -6,6 +6,7 @@ use App\Modules\Jobs\Domain\Exceptions\TaskHasTimeEntries; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel; use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\DB; use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException; use Livewire\Livewire; @@ -23,7 +24,7 @@ it('saves and clears a cell of the weekly view', function () { Livewire::test('time::week') ->call('saveCell', $this->task->id, $this->monday, '2,5') - ->assertSee('2,5 h.') + ->assertSee('2:30.') ->call('saveCell', $this->task->id, $this->monday, '1,1') ->assertHasErrors(["cells.{$this->task->id}.{$this->monday}"]); @@ -34,6 +35,100 @@ it('saves and clears a cell of the weekly view', function () { expect(TimeEntryModel::query()->count())->toBe(0); }); +it('takes hours and minutes, minutes and 15 minute steps in a cell', function () { + $week = Livewire::test('time::week') + ->call('saveCell', $this->task->id, $this->monday, '1:30') + ->call('adjustCell', $this->task->id, $this->monday, 1); + + expect((float) TimeEntryModel::query()->sole()->hours)->toBe(1.75); + + $week->call('saveCell', $this->task->id, $this->monday, '90'); + expect((float) TimeEntryModel::query()->sole()->hours)->toBe(1.5); + + $week->call('saveCell', $this->task->id, $this->monday, '1:10') + ->assertHasErrors(["cells.{$this->task->id}.{$this->monday}"]); + + foreach (range(1, 6) as $step) { + $week->call('adjustCell', $this->task->id, $this->monday, -1); + } + + expect(TimeEntryModel::query()->count())->toBe(0); +}); + +it('stores the billing basis, billing note and internal comment of an entry', function () { + Livewire::test('time::week') + ->call('saveCell', $this->task->id, $this->monday, '2') + ->call('openEntry', $this->task->id, $this->monday) + ->assertSet('entryBillingModel', 'hourly') + ->set('entryBillingModel', 'non_billable') + ->set('entryNote', 'Kuvien rajaus') + ->set('entryComment', 'Asiakas toivoi kiirettä') + ->call('saveEntry') + ->assertSee('Kirjaus tallennettu'); + + $entry = TimeEntryModel::query()->sole(); + + expect($entry->note)->toBe('Kuvien rajaus') + ->and($entry->internal_comment)->toBe('Asiakas toivoi kiirettä') + ->and($entry->billing_model)->toBe('non_billable'); +}); + +it('blocks approving a week without billing notes and lists the entries', function () { + Livewire::test('time::week') + ->call('saveCell', $this->task->id, $this->monday, '2') + ->assertSee('1 selite puuttuu') + ->call('approveWeek') + ->assertSee('Viikkoa ei voi vielä hyväksyä'); + + expect(TimeEntryModel::query()->sole()->approved_at)->toBeNull(); +}); + +it('pins tasks to the pinned part, keeps them on later weeks and unpins them', function () { + $other = TaskModel::factory()->create(['title' => 'Kehitystyöt']); + + $week = Livewire::test('time::week') + ->call('pinTasks', [$other->id]) + ->assertSee('Tehtävä Kehitystyöt kiinnitetty'); + + expect($week->instance()->sheet->row($other->id)?->pinned)->toBeTrue() + ->and($week->instance()->sheet->pinnedTaskCount())->toBe(1); + + $week->call('showWeek', 'next'); + expect($week->instance()->sheet->pinnedTaskCount())->toBe(1); + + $week->call('unpinTask', $other->id); + expect($week->instance()->sheet->pinnedTaskCount())->toBe(0); + + $week->call('pinTasks', [$other->id])->call('clearPins')->assertSee('1 kiinnitys poistettu.'); +}); + +it('lets a pin lapse after the job is done, except on weeks with hours', function () { + $week = Livewire::test('time::week') + ->call('pinTasks', [$this->task->id]) + ->call('saveCell', $this->task->id, $this->monday, '1'); + + DB::table('customer_jobs')->where('id', $this->task->customer_job_id)->update(['status' => 'done']); + + $week->call('showWeek', 'this'); + expect($week->instance()->sheet->pinnedTaskCount())->toBe(1); + + $week->call('showWeek', 'next'); + expect($week->instance()->sheet->pinnedTaskCount())->toBe(0) + ->and($week->instance()->sheet->scheduledTaskCount())->toBe(0); +}); + +it('saves the timer time rounded to quarter hours on today', function () { + Livewire::test('time::week') + ->call('saveTimer', $this->task->id, 50 * 60, 'Ottelun striimaus') + ->assertSee('0:45 kirjattu tehtävälle Mainoskuvat'); + + $entry = TimeEntryModel::query()->sole(); + + expect((float) $entry->hours)->toBe(0.75) + ->and($entry->worked_on->toDateString())->toBe(now()->toDateString()) + ->and($entry->note)->toBe('Ottelun striimaus'); +}); + it('takes the week only from the URL and the week buttons', function () { $this->get(route('time.week', ['viikko' => "abc'); alert(1); ('"]))->assertOk()->assertSee('Mainoskuvat'); diff --git a/tests/Unit/Modules/TimeTracking/ApprovalTest.php b/tests/Unit/Modules/TimeTracking/ApprovalTest.php index 88b34ef..ff39a78 100644 --- a/tests/Unit/Modules/TimeTracking/ApprovalTest.php +++ b/tests/Unit/Modules/TimeTracking/ApprovalTest.php @@ -7,6 +7,7 @@ use App\Modules\TimeTracking\Application\UseCases\CancelWeekApproval; use App\Modules\TimeTracking\Application\UseCases\RemoveTimeEntry; use App\Modules\TimeTracking\Application\UseCases\SetDayHours; use App\Modules\TimeTracking\Application\UseCases\UpdateTimeEntry; +use App\Modules\TimeTracking\Domain\Exceptions\BillingNotesMissing; use App\Modules\TimeTracking\Domain\Exceptions\TimeApproved; use Tests\Fakes\FakeClock; use Tests\Fakes\FakeTaskQueries; @@ -34,6 +35,12 @@ beforeEach(function () { $this->setDayHours->execute(10, 1, '2026-11-29', '2'); $this->setDayHours->execute(10, 1, '2026-11-30', '3'); $this->setDayHours->execute(11, 1, '2026-11-23', '5'); + + // Every entry has its billing note, which the approval requires. + foreach ($this->entries->entries as $entry) { + $entry->describe(null, 'Suunnittelu', null); + $this->entries->save($entry); + } }); it('approves the user\'s unapproved hours of the week only', function () { @@ -76,3 +83,10 @@ it('cancels the approval of a week so the hours can be changed again', function expect($this->entries->findForDay(10, 1, new DateTimeImmutable('2026-11-23'))?->hours()->format())->toBe('5'); }); + +it('refuses to approve a week while an entry has no billing note', function () { + $this->setDayHours->execute(10, 2, '2026-11-24', '1'); + + expect(fn () => $this->approveWeek->execute(10, '2026-11-23', approverId: 99))->toThrow(BillingNotesMissing::class); + expect(array_filter($this->entries->entries, fn ($entry) => $entry->isApproved()))->toBeEmpty(); +}); diff --git a/tests/Unit/Modules/TimeTracking/TimesheetTest.php b/tests/Unit/Modules/TimeTracking/TimesheetTest.php new file mode 100644 index 0000000..c819be9 --- /dev/null +++ b/tests/Unit/Modules/TimeTracking/TimesheetTest.php @@ -0,0 +1,84 @@ + 0 ? ['2026-11-30' => new TimesheetCell($quarters, null, null, null, false)] : []; + + return new TimesheetTaskRow($task, $cells, $quarters, $pinned); +} + +it('reads hours and minutes, decimal hours and minutes from a cell', function (string $value, ?int $quarters) { + expect(WorkedHours::parseFlexible($value)?->quarters)->toBe($quarters); +})->with([ + 'h:mm' => ['1:30', 6], + 'decimal comma' => ['1,5', 6], + 'decimal point' => ['2.25', 9], + 'whole hours' => ['2', 8], + 'minutes over 24' => ['90', 6], + 'zero' => ['0:00', null], + 'empty' => ['', null], +]); + +it('refuses times that are not whole quarter hours', function (string $value) { + WorkedHours::parseFlexible($value); +})->throws(InvalidWorkedHours::class)->with(['1:10', '50', '1,1', 'abc', '25:00']); + +it('formats quarters as hours and minutes', function () { + expect(WorkedHours::formatClock(0))->toBe('0:00') + ->and(WorkedHours::formatClock(6))->toBe('1:30') + ->and(WorkedHours::formatClock(41))->toBe('10:15'); +}); + +it('takes the default billing basis from the job\'s payment basis', function (?string $basis, EntryBillingModel $model) { + expect(EntryBillingModel::forPaymentBasis($basis))->toBe($model); +})->with([ + ['fixed_quote', EntryBillingModel::Fixed], + ['price_list', EntryBillingModel::Fixed], + ['monthly_fee', EntryBillingModel::Fixed], + ['hourly', EntryBillingModel::Hourly], + [null, EntryBillingModel::Hourly], + ['not_billable', EntryBillingModel::NonBillable], +]); + +it('groups rows customer A–Ö, then job, then task, in Finnish order', function () { + $rows = [ + sheetRow(1, 'Ässä KP Oy', '798', 'Markkinointi'), + sheetRow(2, 'Agrikumppanit Oy', '5', 'Myyntityö'), + sheetRow(3, 'Loimaan kaupunki', '778', 'Videokuvaus'), + sheetRow(4, 'Loimaan kaupunki', '778', 'Käsikirjoitus'), + sheetRow(5, 'Ravintola ATA ky', '470', 'Lounaslista'), + ]; + + $sections = (new TimesheetLayout)->arrange($rows, [1, 2, 3, 4, 5], []); + + expect(array_map(fn ($customer) => $customer->name, $sections['scheduled']))->toBe(['Agrikumppanit Oy', 'Loimaan kaupunki', 'Ravintola ATA ky', 'Ässä KP Oy']) + ->and(array_map(fn ($row) => $row->task->taskTitle, $sections['scheduled'][1]->jobs[0]->rows))->toBe(['Käsikirjoitus', 'Videokuvaus']); +}); + +it('moves pinned rows out of the scheduled part and keeps lapsed pins only with hours', function () { + $rows = [ + sheetRow(1, 'A Oy', '1', 'Pinned open', pinned: true), + sheetRow(2, 'A Oy', '1', 'Pinned done with hours', pinned: true, quarters: 4, jobStatus: JobStatus::Done), + sheetRow(3, 'A Oy', '1', 'Pinned done without hours', pinned: true, jobStatus: JobStatus::Done), + sheetRow(4, 'B Oy', '2', 'Scheduled'), + sheetRow(5, 'B Oy', '2', 'Not scheduled, no hours'), + sheetRow(6, 'B Oy', '2', 'Hours only', quarters: 2), + ]; + + $sections = (new TimesheetLayout)->arrange($rows, [1, 4], []); + $titles = fn (array $groups): array => array_merge(...array_map(fn ($customer) => array_merge(...array_map(fn ($job) => array_map(fn ($row) => $row->task->taskTitle, $job->rows), $customer->jobs)), $groups)); + + expect($titles($sections['pinned']))->toBe(['Pinned done with hours', 'Pinned open']) + ->and($titles($sections['scheduled']))->toBe(['Hours only', 'Scheduled']); +});