Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

BaseReportPage.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. namespace App\Filament\Company\Pages\Reports;
  3. use App\Contracts\ExportableReport;
  4. use App\DTO\ReportDTO;
  5. use App\Filament\Forms\Components\DateRangeSelect;
  6. use App\Models\Company;
  7. use App\Services\DateRangeService;
  8. use App\Support\Column;
  9. use Filament\Actions\Action;
  10. use Filament\Actions\ActionGroup;
  11. use Filament\Forms\Components\Checkbox;
  12. use Filament\Forms\Components\Component;
  13. use Filament\Forms\Components\DatePicker;
  14. use Filament\Forms\Form;
  15. use Filament\Forms\Set;
  16. use Filament\Pages\Page;
  17. use Filament\Support\Enums\ActionSize;
  18. use Filament\Support\Enums\IconPosition;
  19. use Filament\Support\Enums\IconSize;
  20. use Filament\Support\Facades\FilamentIcon;
  21. use Illuminate\Support\Arr;
  22. use Illuminate\Support\Carbon;
  23. use Livewire\Attributes\Computed;
  24. use Livewire\Attributes\Session;
  25. use Livewire\Attributes\Url;
  26. use Symfony\Component\HttpFoundation\StreamedResponse;
  27. abstract class BaseReportPage extends Page
  28. {
  29. /**
  30. * @var array<string, mixed> | null
  31. */
  32. #[Url]
  33. public ?array $filters = null;
  34. /**
  35. * @var array<string, mixed> | null
  36. */
  37. public ?array $deferredFilters = null;
  38. public string $fiscalYearStartDate;
  39. public string $fiscalYearEndDate;
  40. public Company $company;
  41. public bool $reportLoaded = false;
  42. #[Session]
  43. public array $toggledTableColumns = [];
  44. abstract protected function buildReport(array $columns): ReportDTO;
  45. abstract public function exportCSV(): StreamedResponse;
  46. abstract public function exportPDF(): StreamedResponse;
  47. abstract protected function getTransformer(ReportDTO $reportDTO): ExportableReport;
  48. /**
  49. * @return array<Column>
  50. */
  51. abstract public function getTable(): array;
  52. public function mount(): void
  53. {
  54. $this->initializeProperties();
  55. $this->loadDefaultDateRange();
  56. $this->initializeDefaultFilters();
  57. $this->initializeFilters();
  58. $this->loadDefaultTableColumnToggleState();
  59. }
  60. protected function initializeDefaultFilters(): void
  61. {
  62. //
  63. }
  64. public function initializeFilters(): void
  65. {
  66. if (! count($this->filters ?? [])) {
  67. $this->filters = null;
  68. }
  69. $filtersForForm = $this->filters !== null
  70. ? $this->convertDatesToDateTimeString($this->filters)
  71. : [];
  72. $this->getFiltersForm()->fill($filtersForForm);
  73. if ($this->filters !== null) {
  74. $this->filters = $this->normalizeFilters($this->filters);
  75. }
  76. ray($this->filters);
  77. }
  78. protected function convertDatesToDateTimeString(array $filters): array
  79. {
  80. if (isset($filters['startDate'])) {
  81. $filters['startDate'] = Carbon::parse($filters['startDate'])->startOfDay()->toDateTimeString();
  82. }
  83. if (isset($filters['endDate'])) {
  84. $filters['endDate'] = Carbon::parse($filters['endDate'])->endOfDay()->toDateTimeString();
  85. }
  86. return $filters;
  87. }
  88. protected function getForms(): array
  89. {
  90. return [
  91. 'toggleTableColumnForm',
  92. 'filtersForm' => $this->getFiltersForm(),
  93. ];
  94. }
  95. public function filtersForm(Form $form): Form
  96. {
  97. return $form;
  98. }
  99. public function getFiltersForm(): Form
  100. {
  101. return $this->filtersForm($this->makeForm()
  102. ->statePath('deferredFilters'));
  103. }
  104. public function updatedFilters(): void
  105. {
  106. $this->deferredFilters = $this->filters;
  107. $this->handleFilterUpdates();
  108. }
  109. protected function isValidDate($date): bool
  110. {
  111. return strtotime($date) !== false;
  112. }
  113. protected function handleFilterUpdates(): void
  114. {
  115. //
  116. }
  117. public function applyFilters(): void
  118. {
  119. $this->filters = $this->normalizeFilters($this->deferredFilters);
  120. $this->handleFilterUpdates();
  121. $this->loadReportData();
  122. }
  123. protected function normalizeFilters(array $filters): array
  124. {
  125. foreach ($filters as $name => &$value) {
  126. if ($name === 'dateRange') {
  127. unset($filters[$name]);
  128. } elseif ($this->isValidDate($value)) {
  129. $value = Carbon::parse($value)->toDateString();
  130. }
  131. }
  132. return $filters;
  133. }
  134. public function getFiltersApplyAction(): Action
  135. {
  136. return Action::make('applyFilters')
  137. ->label('Update Report')
  138. ->action('applyFilters')
  139. ->keyBindings(['mod+s'])
  140. ->button();
  141. }
  142. public function getFilterState(string $name): mixed
  143. {
  144. return Arr::get($this->filters, $name);
  145. }
  146. public function setFilterState(string $name, mixed $value): void
  147. {
  148. Arr::set($this->filters, $name, $value);
  149. }
  150. public function getDeferredFilterState(string $name): mixed
  151. {
  152. return Arr::get($this->deferredFilters, $name);
  153. }
  154. public function setDeferredFilterState(string $name, mixed $value): void
  155. {
  156. Arr::set($this->deferredFilters, $name, $value);
  157. }
  158. protected function initializeProperties(): void
  159. {
  160. $this->company = auth()->user()->currentCompany;
  161. $this->fiscalYearStartDate = $this->company->locale->fiscalYearStartDate();
  162. $this->fiscalYearEndDate = $this->company->locale->fiscalYearEndDate();
  163. }
  164. protected function loadDefaultDateRange(): void
  165. {
  166. $startDate = $this->getFilterState('startDate');
  167. $endDate = $this->getFilterState('endDate');
  168. if ($this->isValidDate($startDate) && $this->isValidDate($endDate)) {
  169. $matchingDateRange = app(DateRangeService::class)->getMatchingDateRangeOption(Carbon::parse($startDate), Carbon::parse($endDate));
  170. $this->setFilterState('dateRange', $matchingDateRange);
  171. } else {
  172. $this->setFilterState('dateRange', $this->getDefaultDateRange());
  173. $this->setDateRange(Carbon::parse($this->fiscalYearStartDate), Carbon::parse($this->fiscalYearEndDate));
  174. }
  175. }
  176. public function loadReportData(): void
  177. {
  178. unset($this->report);
  179. $this->reportLoaded = true;
  180. }
  181. protected function loadDefaultTableColumnToggleState(): void
  182. {
  183. $tableColumns = $this->getTable();
  184. foreach ($tableColumns as $column) {
  185. $columnName = $column->getName();
  186. if (empty($this->toggledTableColumns)) {
  187. if ($column->isToggleable()) {
  188. $this->toggledTableColumns[$columnName] = ! $column->isToggledHiddenByDefault();
  189. } else {
  190. $this->toggledTableColumns[$columnName] = true;
  191. }
  192. }
  193. // Handle cases where the toggle state needs to be reset
  194. if (! $column->isToggleable()) {
  195. $this->toggledTableColumns[$columnName] = true;
  196. } elseif ($column->isToggleable() && $column->isToggledHiddenByDefault() && isset($this->toggledTableColumns[$columnName]) && $this->toggledTableColumns[$columnName]) {
  197. $this->toggledTableColumns[$columnName] = false;
  198. }
  199. }
  200. }
  201. public function getDefaultDateRange(): string
  202. {
  203. return 'FY-' . now()->year;
  204. }
  205. protected function getToggledColumns(): array
  206. {
  207. return array_values(
  208. array_filter(
  209. $this->getTable(),
  210. fn (Column $column) => $this->toggledTableColumns[$column->getName()] ?? false,
  211. )
  212. );
  213. }
  214. #[Computed(persist: true)]
  215. public function report(): ?ExportableReport
  216. {
  217. if ($this->reportLoaded === false) {
  218. return null;
  219. }
  220. $columns = $this->getToggledColumns();
  221. $reportDTO = $this->buildReport($columns);
  222. return $this->getTransformer($reportDTO);
  223. }
  224. public function setDateRange(Carbon $start, Carbon $end): void
  225. {
  226. $this->setFilterState('startDate', $start->startOfDay()->toDateTimeString());
  227. $this->setFilterState('endDate', $end->isFuture() ? now()->endOfDay()->toDateTimeString() : $end->endOfDay()->toDateTimeString());
  228. }
  229. public function getFormattedStartDate(): string
  230. {
  231. return Carbon::parse($this->getFilterState('startDate'))->startOfDay()->toDateTimeString();
  232. }
  233. public function getFormattedEndDate(): string
  234. {
  235. return Carbon::parse($this->getFilterState('endDate'))->endOfDay()->toDateTimeString();
  236. }
  237. public function toggleColumnsAction(): Action
  238. {
  239. return Action::make('toggleColumns')
  240. ->label(__('filament-tables::table.actions.toggle_columns.label'))
  241. ->iconButton()
  242. ->size(ActionSize::Large)
  243. ->icon(FilamentIcon::resolve('tables::actions.toggle-columns') ?? 'heroicon-m-view-columns')
  244. ->color('gray');
  245. }
  246. public function toggleTableColumnForm(Form $form): Form
  247. {
  248. return $form
  249. ->schema($this->getTableColumnToggleFormSchema())
  250. ->statePath('toggledTableColumns');
  251. }
  252. protected function hasToggleableColumns(): bool
  253. {
  254. return ! empty($this->getTableColumnToggleFormSchema());
  255. }
  256. /**
  257. * @return array<Checkbox>
  258. */
  259. protected function getTableColumnToggleFormSchema(): array
  260. {
  261. $schema = [];
  262. foreach ($this->getTable() as $column) {
  263. if ($column->isToggleable()) {
  264. $schema[] = Checkbox::make($column->getName())
  265. ->label($column->getLabel());
  266. }
  267. }
  268. return $schema;
  269. }
  270. protected function getHeaderActions(): array
  271. {
  272. return [
  273. ActionGroup::make([
  274. Action::make('exportCSV')
  275. ->label('CSV')
  276. ->action(fn () => $this->exportCSV()),
  277. Action::make('exportPDF')
  278. ->label('PDF')
  279. ->action(fn () => $this->exportPDF()),
  280. ])
  281. ->label('Export')
  282. ->button()
  283. ->outlined()
  284. ->dropdownWidth('max-w-[7rem]')
  285. ->dropdownPlacement('bottom-end')
  286. ->icon('heroicon-c-chevron-down')
  287. ->iconSize(IconSize::Small)
  288. ->iconPosition(IconPosition::After),
  289. ];
  290. }
  291. protected function getDateRangeFormComponent(): Component
  292. {
  293. return DateRangeSelect::make('dateRange')
  294. ->label('Date Range')
  295. ->selectablePlaceholder(false)
  296. ->startDateField('startDate')
  297. ->endDateField('endDate');
  298. }
  299. protected function getStartDateFormComponent(): Component
  300. {
  301. return DatePicker::make('startDate')
  302. ->label('Start Date')
  303. ->live()
  304. ->afterStateUpdated(static function ($state, Set $set) {
  305. $set('dateRange', 'Custom');
  306. });
  307. }
  308. protected function getEndDateFormComponent(): Component
  309. {
  310. return DatePicker::make('endDate')
  311. ->label('End Date')
  312. ->live()
  313. ->afterStateUpdated(static function (Set $set) {
  314. $set('dateRange', 'Custom');
  315. });
  316. }
  317. }