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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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(keep: true)]
  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. }
  77. protected function convertDatesToDateTimeString(array $filters): array
  78. {
  79. if (isset($filters['startDate'])) {
  80. $filters['startDate'] = Carbon::parse($filters['startDate'])->startOfDay()->toDateTimeString();
  81. }
  82. if (isset($filters['endDate'])) {
  83. $filters['endDate'] = Carbon::parse($filters['endDate'])->endOfDay()->toDateTimeString();
  84. }
  85. return $filters;
  86. }
  87. protected function getForms(): array
  88. {
  89. return [
  90. 'toggleTableColumnForm',
  91. 'filtersForm' => $this->getFiltersForm(),
  92. ];
  93. }
  94. public function filtersForm(Form $form): Form
  95. {
  96. return $form;
  97. }
  98. public function getFiltersForm(): Form
  99. {
  100. return $this->filtersForm($this->makeForm()
  101. ->statePath('deferredFilters'));
  102. }
  103. public function updatedFilters(): void
  104. {
  105. $this->deferredFilters = $this->filters;
  106. $this->handleFilterUpdates();
  107. }
  108. protected function isValidDate($date): bool
  109. {
  110. return strtotime($date) !== false;
  111. }
  112. protected function handleFilterUpdates(): void
  113. {
  114. //
  115. }
  116. public function applyFilters(): void
  117. {
  118. $this->filters = $this->normalizeFilters($this->deferredFilters);
  119. $this->handleFilterUpdates();
  120. $this->loadReportData();
  121. }
  122. protected function normalizeFilters(array $filters): array
  123. {
  124. foreach ($filters as $name => &$value) {
  125. if ($name === 'dateRange') {
  126. unset($filters[$name]);
  127. } elseif ($this->isValidDate($value)) {
  128. $value = Carbon::parse($value)->toDateString();
  129. }
  130. }
  131. return $filters;
  132. }
  133. public function getFiltersApplyAction(): Action
  134. {
  135. return Action::make('applyFilters')
  136. ->label('Update Report')
  137. ->action('applyFilters')
  138. ->keyBindings(['mod+s'])
  139. ->button();
  140. }
  141. public function getFilterState(string $name): mixed
  142. {
  143. return Arr::get($this->filters, $name);
  144. }
  145. public function setFilterState(string $name, mixed $value): void
  146. {
  147. Arr::set($this->filters, $name, $value);
  148. }
  149. public function getDeferredFilterState(string $name): mixed
  150. {
  151. return Arr::get($this->deferredFilters, $name);
  152. }
  153. public function setDeferredFilterState(string $name, mixed $value): void
  154. {
  155. Arr::set($this->deferredFilters, $name, $value);
  156. }
  157. protected function initializeProperties(): void
  158. {
  159. $this->company = auth()->user()->currentCompany;
  160. $this->fiscalYearStartDate = $this->company->locale->fiscalYearStartDate();
  161. $this->fiscalYearEndDate = $this->company->locale->fiscalYearEndDate();
  162. }
  163. protected function loadDefaultDateRange(): void
  164. {
  165. $startDate = $this->getFilterState('startDate');
  166. $endDate = $this->getFilterState('endDate');
  167. if ($this->isValidDate($startDate) && $this->isValidDate($endDate)) {
  168. $matchingDateRange = app(DateRangeService::class)->getMatchingDateRangeOption(Carbon::parse($startDate), Carbon::parse($endDate));
  169. $this->setFilterState('dateRange', $matchingDateRange);
  170. } else {
  171. $this->setFilterState('dateRange', $this->getDefaultDateRange());
  172. $this->setDateRange(Carbon::parse($this->fiscalYearStartDate), Carbon::parse($this->fiscalYearEndDate));
  173. }
  174. }
  175. public function loadReportData(): void
  176. {
  177. unset($this->report);
  178. $this->reportLoaded = true;
  179. }
  180. protected function loadDefaultTableColumnToggleState(): void
  181. {
  182. $tableColumns = $this->getTable();
  183. foreach ($tableColumns as $column) {
  184. $columnName = $column->getName();
  185. if (empty($this->toggledTableColumns)) {
  186. if ($column->isToggleable()) {
  187. $this->toggledTableColumns[$columnName] = ! $column->isToggledHiddenByDefault();
  188. } else {
  189. $this->toggledTableColumns[$columnName] = true;
  190. }
  191. }
  192. // Handle cases where the toggle state needs to be reset
  193. if (! $column->isToggleable()) {
  194. $this->toggledTableColumns[$columnName] = true;
  195. } elseif ($column->isToggleable() && $column->isToggledHiddenByDefault() && isset($this->toggledTableColumns[$columnName]) && $this->toggledTableColumns[$columnName]) {
  196. $this->toggledTableColumns[$columnName] = false;
  197. }
  198. }
  199. }
  200. public function getDefaultDateRange(): string
  201. {
  202. return 'FY-' . now()->year;
  203. }
  204. protected function getToggledColumns(): array
  205. {
  206. return array_values(
  207. array_filter(
  208. $this->getTable(),
  209. fn (Column $column) => $this->toggledTableColumns[$column->getName()] ?? false,
  210. )
  211. );
  212. }
  213. #[Computed(persist: true)]
  214. public function report(): ?ExportableReport
  215. {
  216. if ($this->reportLoaded === false) {
  217. return null;
  218. }
  219. $columns = $this->getToggledColumns();
  220. $reportDTO = $this->buildReport($columns);
  221. return $this->getTransformer($reportDTO);
  222. }
  223. public function setDateRange(Carbon $start, Carbon $end): void
  224. {
  225. $this->setFilterState('startDate', $start->startOfDay()->toDateTimeString());
  226. $this->setFilterState('endDate', $end->isFuture() ? now()->endOfDay()->toDateTimeString() : $end->endOfDay()->toDateTimeString());
  227. }
  228. public function getFormattedStartDate(): string
  229. {
  230. return Carbon::parse($this->getFilterState('startDate'))->startOfDay()->toDateTimeString();
  231. }
  232. public function getFormattedEndDate(): string
  233. {
  234. return Carbon::parse($this->getFilterState('endDate'))->endOfDay()->toDateTimeString();
  235. }
  236. public function toggleColumnsAction(): Action
  237. {
  238. return Action::make('toggleColumns')
  239. ->label(__('filament-tables::table.actions.toggle_columns.label'))
  240. ->iconButton()
  241. ->size(ActionSize::Large)
  242. ->icon(FilamentIcon::resolve('tables::actions.toggle-columns') ?? 'heroicon-m-view-columns')
  243. ->color('gray');
  244. }
  245. public function toggleTableColumnForm(Form $form): Form
  246. {
  247. return $form
  248. ->schema($this->getTableColumnToggleFormSchema())
  249. ->statePath('toggledTableColumns');
  250. }
  251. protected function hasToggleableColumns(): bool
  252. {
  253. return ! empty($this->getTableColumnToggleFormSchema());
  254. }
  255. /**
  256. * @return array<Checkbox>
  257. */
  258. protected function getTableColumnToggleFormSchema(): array
  259. {
  260. $schema = [];
  261. foreach ($this->getTable() as $column) {
  262. if ($column->isToggleable()) {
  263. $schema[] = Checkbox::make($column->getName())
  264. ->label($column->getLabel());
  265. }
  266. }
  267. return $schema;
  268. }
  269. protected function getHeaderActions(): array
  270. {
  271. return [
  272. ActionGroup::make([
  273. Action::make('exportCSV')
  274. ->label('CSV')
  275. ->action(fn () => $this->exportCSV()),
  276. Action::make('exportPDF')
  277. ->label('PDF')
  278. ->action(fn () => $this->exportPDF()),
  279. ])
  280. ->label('Export')
  281. ->button()
  282. ->outlined()
  283. ->dropdownWidth('max-w-[7rem]')
  284. ->dropdownPlacement('bottom-end')
  285. ->icon('heroicon-c-chevron-down')
  286. ->iconSize(IconSize::Small)
  287. ->iconPosition(IconPosition::After),
  288. ];
  289. }
  290. protected function getDateRangeFormComponent(): Component
  291. {
  292. return DateRangeSelect::make('dateRange')
  293. ->label('Date Range')
  294. ->selectablePlaceholder(false)
  295. ->startDateField('startDate')
  296. ->endDateField('endDate');
  297. }
  298. protected function getStartDateFormComponent(): Component
  299. {
  300. return DatePicker::make('startDate')
  301. ->label('Start Date')
  302. ->live()
  303. ->afterStateUpdated(static function ($state, Set $set) {
  304. $set('dateRange', 'Custom');
  305. });
  306. }
  307. protected function getEndDateFormComponent(): Component
  308. {
  309. return DatePicker::make('endDate')
  310. ->label('End Date')
  311. ->live()
  312. ->afterStateUpdated(static function (Set $set) {
  313. $set('dateRange', 'Custom');
  314. });
  315. }
  316. }