You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BaseReportPage.php 10KB

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