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

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