This commit is contained in:
Adrian Hopek 2022-02-17 11:31:24 +01:00
parent 026dd87a44
commit de05798e06
10 changed files with 1104 additions and 168 deletions

View File

@ -29,7 +29,7 @@ class CalendarGenerator
return $this->generateCalendar($period, $holidays); return $this->generateCalendar($period, $holidays);
} }
protected function monthNameToNumber($name): int protected function monthNameToNumber(string $name): int
{ {
return match ($name) { return match ($name) {
default => CarbonInterface::JANUARY, default => CarbonInterface::JANUARY,

View File

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Toby\Domain;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class TimesheetExport implements WithMultipleSheets
{
protected Collection $users;
protected Carbon $month;
public function sheets(): array
{
$sheets = [];
foreach ($this->users as $user) {
$sheets[] = new TimesheetPerUserSheet($user, $this->month);
}
return $sheets;
}
public function forUsers(Collection $users): static
{
$this->users = $users;
return $this;
}
public function forMonth(Carbon $month): static
{
$this->month = $month;
return $this;
}
}

View File

@ -0,0 +1,216 @@
<?php
declare(strict_types=1);
namespace Toby\Domain;
use Carbon\CarbonInterface;
use Carbon\CarbonPeriod;
use Generator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromGenerator;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Toby\Domain\Enums\VacationRequestState;
use Toby\Domain\Enums\VacationType;
use Toby\Eloquent\Models\Holiday;
use Toby\Eloquent\Models\User;
use Toby\Eloquent\Models\Vacation;
class TimesheetPerUserSheet implements WithTitle, WithHeadings, WithEvents, WithStyles, WithStrictNullComparison, ShouldAutoSize, FromGenerator
{
use RegistersEventListeners;
protected const HOURS_PER_DAY = 8;
public function __construct(
protected User $user,
protected Carbon $month,
) {
}
public function title(): string
{
return $this->user->fullName;
}
public function headings(): array
{
$types = VacationType::cases();
$headings = [
__("Date"),
__("Day of week"),
__("Start date"),
__("End date"),
__("Worked hours"),
];
foreach ($types as $type) {
$headings[] = $type->label();
}
return $headings;
}
public function generator(): Generator
{
$period = CarbonPeriod::create($this->month->copy()->startOfMonth(), $this->month->copy()->endOfMonth());
$vacations = $this->getVacationsForPeriod($this->user, $period);
$holidays = $this->getHolidaysForPeriod($period);
foreach ($period as $day) {
$vacationsForDay = $vacations->get($day->toDateString(), new Collection());
$workedThisDay = $this->checkIfWorkedThisDay($day, $holidays, $vacationsForDay);
$row = [
Date::dateTimeToExcel($day),
$day->translatedFormat("l"),
$workedThisDay ? $this->toExcelTime(Carbon::createFromTime(8)) : null,
$workedThisDay ? $this->toExcelTime(Carbon::createFromTime(16)) : null,
$workedThisDay ? static::HOURS_PER_DAY : null,
];
foreach (VacationType::cases() as $type) {
$row[] = $vacationsForDay->has($type->value) ? static::HOURS_PER_DAY : null;
}
yield $row;
}
}
public function styles(Worksheet $sheet): void
{
$lastRow = $sheet->getHighestRow();
$lastColumn = $sheet->getHighestColumn();
$sheet->getStyle("A1:{$lastColumn}1")
->getFont()->setBold(true);
$sheet->getStyle("A1:{$lastColumn}1")
->getAlignment()
->setVertical(Alignment::VERTICAL_CENTER);
$sheet->getStyle("A1:{$lastColumn}1")
->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()
->setRGB("D9D9D9");
$sheet->getStyle("C1:{$lastColumn}{$lastRow}")
->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getStyle("A2:A{$lastRow}")
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_DATE_DDMMYYYY);
$sheet->getStyle("C1:D{$lastRow}")
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_DATE_TIME3);
$sheet->getStyle("A2:A{$lastRow}")
->getFont()
->setBold(true);
for ($i = 2; $i < $lastRow; $i++) {
$date = Date::excelToDateTimeObject($sheet->getCell("A{$i}")->getValue());
if (Carbon::createFromInterface($date)->isWeekend()) {
$sheet->getStyle("A{$i}:{$lastColumn}{$i}")
->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()
->setRGB("FEE2E2");
}
}
$sheet->getStyle("A1:{$lastColumn}{$lastRow}")
->getBorders()
->getAllBorders()
->setBorderStyle(Border::BORDER_THIN);
}
public static function afterSheet(AfterSheet $event): void
{
$sheet = $event->getSheet();
$lastRow = $sheet->getDelegate()->getHighestRow();
$sheet->append([
__("Sum:"),
null,
null,
null,
"=SUM(E2:E{$lastRow})",
]);
$lastRow++;
$sheet->getDelegate()->getStyle("A{$lastRow}")
->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_RIGHT);
$sheet->getDelegate()->getStyle("A{$lastRow}")
->getFont()
->setBold(true);
$sheet->getDelegate()->getStyle("E{$lastRow}")
->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getDelegate()->mergeCells("A{$lastRow}:D{$lastRow}");
$sheet->getDelegate()->getStyle("A{$lastRow}:E{$lastRow}")
->getBorders()
->getAllBorders()
->setBorderStyle(Border::BORDER_THIN);
}
protected function getVacationsForPeriod(User $user, CarbonPeriod $period): Collection
{
return $user->vacations()
->with("vacationRequest")
->whereBetween("date", [$period->start, $period->end])
->whereRelation("vacationRequest", "state", VacationRequestState::Approved->value)
->get()
->groupBy(
[
fn(Vacation $vacation) => $vacation->date->toDateString(),
fn(Vacation $vacation) => $vacation->vacationRequest->type->value,
],
);
}
protected function getHolidaysForPeriod(CarbonPeriod $period): Collection
{
return Holiday::query()
->whereBetween("date", [$period->start, $period->end])
->pluck("date");
}
protected function toExcelTime(Carbon $time): float
{
$excelTimestamp = Date::dateTimeToExcel($time);
$excelDate = floor($excelTimestamp);
return $excelTimestamp - $excelDate;
}
protected function checkIfWorkedThisDay(CarbonInterface $day, Collection $holidays, Collection $vacations): bool
{
return $day->isWeekday() && $holidays->doesntContain($day) && $vacations->isEmpty();
}
}

View File

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Toby\Infrastructure\Http\Controllers;
use Carbon\CarbonInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Toby\Domain\TimesheetExport;
use Toby\Eloquent\Helpers\YearPeriodRetriever;
use Toby\Eloquent\Models\User;
class TimesheetController extends Controller
{
public function __invoke(Request $request, YearPeriodRetriever $yearPeriodRetriever): BinaryFileResponse
{
$yearPeriod = $yearPeriodRetriever->selected();
$month = Str::lower($request->query("month", Carbon::now()->englishMonth));
$month = Carbon::create($yearPeriod->year, $this->monthNameToNumber($month));
$users = User::query()
->orderBy("last_name")
->orderBy("first_name")
->get();
$filename = "{$month->translatedFormat("F Y")}.xlsx";
$timesheet = (new TimesheetExport())
->forMonth($month)
->forUsers($users);
return Excel::download($timesheet, $filename);
}
protected function monthNameToNumber(string $name): int
{
return match ($name) {
default => CarbonInterface::JANUARY,
"february" => CarbonInterface::FEBRUARY,
"march" => CarbonInterface::MARCH,
"april" => CarbonInterface::APRIL,
"may" => CarbonInterface::MAY,
"june" => CarbonInterface::JUNE,
"july" => CarbonInterface::JULY,
"august" => CarbonInterface::AUGUST,
"september" => CarbonInterface::SEPTEMBER,
"october" => CarbonInterface::OCTOBER,
"november" => CarbonInterface::NOVEMBER,
"december" => CarbonInterface::DECEMBER,
};
}
}

View File

@ -18,6 +18,7 @@
"laravel/telescope": "^4.6", "laravel/telescope": "^4.6",
"laravel/tinker": "^2.5", "laravel/tinker": "^2.5",
"lasserafn/php-initial-avatar-generator": "^4.2", "lasserafn/php-initial-avatar-generator": "^4.2",
"maatwebsite/excel": "^3.1",
"spatie/laravel-google-calendar": "^3.5" "spatie/laravel-google-calendar": "^3.5"
}, },
"require-dev": { "require-dev": {

823
composer.lock generated

File diff suppressed because it is too large Load Diff

103
config/excel.php Normal file
View File

@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
use Maatwebsite\Excel\Excel;
return [
"exports" => [
"chunk_size" => 1000,
"pre_calculate_formulas" => false,
"strict_null_comparison" => false,
"csv" => [
"delimiter" => ",",
"enclosure" => '"',
"line_ending" => PHP_EOL,
"use_bom" => false,
"include_separator_line" => false,
"excel_compatibility" => false,
"output_encoding" => "",
],
"properties" => [
"creator" => "",
"lastModifiedBy" => "",
"title" => "",
"description" => "",
"subject" => "",
"keywords" => "",
"category" => "",
"manager" => "",
"company" => "",
],
],
"imports" => [
"read_only" => true,
"ignore_empty" => false,
"heading_row" => [
"formatter" => "slug",
],
"csv" => [
"delimiter" => ",",
"enclosure" => '"',
"escape_character" => "\\",
"contiguous" => false,
"input_encoding" => "UTF-8",
],
"properties" => [
"creator" => "",
"lastModifiedBy" => "",
"title" => "",
"description" => "",
"subject" => "",
"keywords" => "",
"category" => "",
"manager" => "",
"company" => "",
],
],
"extension_detector" => [
"xlsx" => Excel::XLSX,
"xlsm" => Excel::XLSX,
"xltx" => Excel::XLSX,
"xltm" => Excel::XLSX,
"xls" => Excel::XLS,
"xlt" => Excel::XLS,
"ods" => Excel::ODS,
"ots" => Excel::ODS,
"slk" => Excel::SLK,
"xml" => Excel::XML,
"gnumeric" => Excel::GNUMERIC,
"htm" => Excel::HTML,
"html" => Excel::HTML,
"csv" => Excel::CSV,
"tsv" => Excel::TSV,
"pdf" => Excel::DOMPDF,
],
"value_binder" => [
"default" => Maatwebsite\Excel\DefaultValueBinder::class,
],
"cache" => [
"driver" => "memory",
"batch" => [
"memory_limit" => 60000,
],
"illuminate" => [
"store" => null,
],
],
"transactions" => [
"handler" => "db",
"db" => [
"connection" => null,
],
],
"temporary_files" => [
"local_path" => storage_path("framework/cache/laravel-excel"),
"remote_disk" => null,
"remote_prefix" => null,
"force_resync_remote" => null,
],
];

View File

@ -1,10 +1,20 @@
<template> <template>
<InertiaHead title="Kalendarz urlopów" /> <InertiaHead title="Kalendarz urlopów" />
<div class="bg-white shadow-md"> <div class="bg-white shadow-md">
<div class="p-4 sm:px-6"> <div class="flex justify-between items-center p-4 sm:px-6">
<h2 class="text-lg leading-6 font-medium text-gray-900"> <div>
Kalendarz urlopów <h2 class="text-lg leading-6 font-medium text-gray-900">
</h2> Kalendarz urlopów
</h2>
</div>
<div>
<a
:href="`timesheet?month=${currentMonth}`"
class="inline-flex items-center px-4 py-3 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-blumilk-600 hover:bg-blumilk-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blumilk-500"
>
Pobierz plik excel
</a>
</div>
</div> </div>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="w-full text-center table-fixed text-sm border border-gray-300"> <table class="w-full text-center table-fixed text-sm border border-gray-300">

View File

@ -43,6 +43,11 @@
"Vacation request has been created.": "Wniosek urlopowy został utworzony.", "Vacation request has been created.": "Wniosek urlopowy został utworzony.",
"Vacation request has been accepted.": "Wniosek urlopowy został zaakceptowany.", "Vacation request has been accepted.": "Wniosek urlopowy został zaakceptowany.",
"Vacation request has been rejected.": "Wniosek urlopowy został odrzucony.", "Vacation request has been rejected.": "Wniosek urlopowy został odrzucony.",
"Vacation request has been canceled.": "Wniosek urlopowy został anulowany." "Vacation request has been canceled.": "Wniosek urlopowy został anulowany.",
"Sum:": "Suma:",
"Date": "Data",
"Day of week": "Dzień tygodnia",
"Start date": "Data rozpoczecia",
"End date": "Data zakończenia",
"Worked hours": "Ilość godzin"
} }

View File

@ -7,6 +7,7 @@ use Toby\Infrastructure\Http\Controllers\GoogleController;
use Toby\Infrastructure\Http\Controllers\HolidayController; use Toby\Infrastructure\Http\Controllers\HolidayController;
use Toby\Infrastructure\Http\Controllers\LogoutController; use Toby\Infrastructure\Http\Controllers\LogoutController;
use Toby\Infrastructure\Http\Controllers\SelectYearPeriodController; use Toby\Infrastructure\Http\Controllers\SelectYearPeriodController;
use Toby\Infrastructure\Http\Controllers\TimesheetController;
use Toby\Infrastructure\Http\Controllers\UserController; use Toby\Infrastructure\Http\Controllers\UserController;
use Toby\Infrastructure\Http\Controllers\VacationCalendarController; use Toby\Infrastructure\Http\Controllers\VacationCalendarController;
use Toby\Infrastructure\Http\Controllers\VacationLimitController; use Toby\Infrastructure\Http\Controllers\VacationLimitController;
@ -26,6 +27,8 @@ Route::middleware("auth")->group(function (): void {
->name("vacation.limits"); ->name("vacation.limits");
Route::get("/vacation-calendar", [VacationCalendarController::class, "index"]) Route::get("/vacation-calendar", [VacationCalendarController::class, "index"])
->name("vacation.calendar"); ->name("vacation.calendar");
Route::get("/timesheet", TimesheetController::class)
->name("timesheet");
Route::get("/vacation-limits", [VacationLimitController::class, "edit"])->name("vacation.limits"); Route::get("/vacation-limits", [VacationLimitController::class, "edit"])->name("vacation.limits");
Route::put("/vacation-limits", [VacationLimitController::class, "update"]); Route::put("/vacation-limits", [VacationLimitController::class, "update"]);