Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

AdjustmentResource.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. <?php
  2. namespace App\Filament\Company\Clusters\Settings\Resources;
  3. use App\Enums\Accounting\AdjustmentCategory;
  4. use App\Enums\Accounting\AdjustmentComputation;
  5. use App\Enums\Accounting\AdjustmentScope;
  6. use App\Enums\Accounting\AdjustmentStatus;
  7. use App\Enums\Accounting\AdjustmentType;
  8. use App\Filament\Company\Clusters\Settings;
  9. use App\Filament\Company\Clusters\Settings\Resources\AdjustmentResource\Pages;
  10. use App\Models\Accounting\Adjustment;
  11. use Filament\Forms;
  12. use Filament\Forms\Form;
  13. use Filament\Notifications\Notification;
  14. use Filament\Resources\Resource;
  15. use Filament\Tables;
  16. use Filament\Tables\Filters\Indicator;
  17. use Filament\Tables\Table;
  18. use Illuminate\Database\Eloquent\Builder;
  19. use Illuminate\Database\Eloquent\Collection;
  20. class AdjustmentResource extends Resource
  21. {
  22. protected static ?string $model = Adjustment::class;
  23. protected static ?string $cluster = Settings::class;
  24. public static function form(Form $form): Form
  25. {
  26. return $form
  27. ->schema([
  28. Forms\Components\Section::make('General')
  29. ->schema([
  30. Forms\Components\TextInput::make('name')
  31. ->autofocus()
  32. ->required()
  33. ->maxLength(255),
  34. Forms\Components\Textarea::make('description')
  35. ->label('Description'),
  36. ]),
  37. Forms\Components\Section::make('Configuration')
  38. ->schema([
  39. Forms\Components\Select::make('category')
  40. ->localizeLabel()
  41. ->options(AdjustmentCategory::class)
  42. ->default(AdjustmentCategory::Tax)
  43. ->live()
  44. ->required(),
  45. Forms\Components\Select::make('type')
  46. ->localizeLabel()
  47. ->options(AdjustmentType::class)
  48. ->default(AdjustmentType::Sales)
  49. ->live()
  50. ->required(),
  51. Forms\Components\Checkbox::make('recoverable')
  52. ->label('Recoverable')
  53. ->default(false)
  54. ->helperText('When enabled, tax is tracked separately as claimable from the government. Non-recoverable taxes are treated as part of the expense.')
  55. ->visible(fn (Forms\Get $get) => AdjustmentCategory::parse($get('category'))->isTax() && AdjustmentType::parse($get('type'))->isPurchase()),
  56. ])
  57. ->columns()
  58. ->visibleOn('create'),
  59. Forms\Components\Section::make('Adjustment Details')
  60. ->schema([
  61. Forms\Components\Select::make('computation')
  62. ->localizeLabel()
  63. ->options(AdjustmentComputation::class)
  64. ->default(AdjustmentComputation::Percentage)
  65. ->live()
  66. ->required(),
  67. Forms\Components\TextInput::make('rate')
  68. ->localizeLabel()
  69. ->rate(static fn (Forms\Get $get) => $get('computation'))
  70. ->required(),
  71. Forms\Components\Select::make('scope')
  72. ->localizeLabel()
  73. ->options(AdjustmentScope::class),
  74. ])
  75. ->columns(),
  76. Forms\Components\Section::make('Dates')
  77. ->schema([
  78. Forms\Components\DateTimePicker::make('start_date'),
  79. Forms\Components\DateTimePicker::make('end_date')
  80. ->after('start_date'),
  81. ])
  82. ->columns()
  83. ->visible(fn (Forms\Get $get) => AdjustmentCategory::parse($get('category'))->isDiscount()),
  84. ]);
  85. }
  86. public static function table(Table $table): Table
  87. {
  88. return $table
  89. ->columns([
  90. Tables\Columns\TextColumn::make('name')
  91. ->label('Name')
  92. ->sortable(),
  93. Tables\Columns\TextColumn::make('status')
  94. ->badge(),
  95. Tables\Columns\TextColumn::make('category')
  96. ->searchable(),
  97. Tables\Columns\TextColumn::make('type')
  98. ->searchable(),
  99. Tables\Columns\TextColumn::make('rate')
  100. ->localizeLabel()
  101. ->rate(static fn (Adjustment $record) => $record->computation->value)
  102. ->searchable()
  103. ->sortable(),
  104. Tables\Columns\TextColumn::make('paused_until')
  105. ->label('Auto-Resume Date')
  106. ->dateTime()
  107. ->sortable()
  108. ->toggleable(isToggledHiddenByDefault: true),
  109. Tables\Columns\TextColumn::make('start_date')
  110. ->dateTime()
  111. ->sortable()
  112. ->toggleable(isToggledHiddenByDefault: true),
  113. Tables\Columns\TextColumn::make('end_date')
  114. ->dateTime()
  115. ->sortable()
  116. ->toggleable(isToggledHiddenByDefault: true),
  117. ])
  118. ->filters([
  119. Tables\Filters\SelectFilter::make('status')
  120. ->label('Status')
  121. ->native(false)
  122. ->default('unarchived')
  123. ->options(
  124. collect(AdjustmentStatus::cases())
  125. ->mapWithKeys(fn (AdjustmentStatus $status) => [$status->value => $status->getLabel()])
  126. ->merge([
  127. 'unarchived' => 'Unarchived',
  128. ])
  129. ->toArray()
  130. )
  131. ->indicateUsing(function (Tables\Filters\SelectFilter $filter, array $state) {
  132. if (blank($state['value'] ?? null)) {
  133. return [];
  134. }
  135. $label = collect($filter->getOptions())
  136. ->mapWithKeys(fn (string | array $label, string $value): array => is_array($label) ? $label : [$value => $label])
  137. ->get($state['value']);
  138. if (blank($label)) {
  139. return [];
  140. }
  141. $indicator = $filter->getIndicator();
  142. if (! $indicator instanceof Indicator) {
  143. if ($state['value'] === 'unarchived') {
  144. $indicator = $label;
  145. } else {
  146. $indicator = Indicator::make("{$indicator}: {$label}");
  147. }
  148. }
  149. return [$indicator];
  150. })
  151. ->query(function (Builder $query, array $data): Builder {
  152. if (blank($data['value'] ?? null)) {
  153. return $query;
  154. }
  155. if ($data['value'] !== 'unarchived') {
  156. return $query->where('status', $data['value']);
  157. } else {
  158. return $query->where('status', '!=', AdjustmentStatus::Archived->value);
  159. }
  160. }),
  161. Tables\Filters\SelectFilter::make('category')
  162. ->label('Category')
  163. ->native(false)
  164. ->options(AdjustmentCategory::class),
  165. Tables\Filters\SelectFilter::make('type')
  166. ->label('Type')
  167. ->native(false)
  168. ->options(AdjustmentType::class),
  169. Tables\Filters\SelectFilter::make('computation')
  170. ->label('Computation')
  171. ->native(false)
  172. ->options(AdjustmentComputation::class),
  173. ])
  174. ->actions([
  175. Tables\Actions\ActionGroup::make([
  176. Tables\Actions\EditAction::make(),
  177. Tables\Actions\Action::make('pause')
  178. ->label('Pause')
  179. ->icon('heroicon-m-pause')
  180. ->form([
  181. Forms\Components\DateTimePicker::make('paused_until')
  182. ->label('Auto-resume date')
  183. ->helperText('When should this adjustment automatically resume? Leave empty to keep paused indefinitely.')
  184. ->after('now'),
  185. Forms\Components\Textarea::make('status_reason')
  186. ->label('Reason for pausing')
  187. ->maxLength(255),
  188. ])
  189. ->databaseTransaction()
  190. ->successNotificationTitle('Adjustment paused')
  191. ->failureNotificationTitle('Failed to pause adjustment')
  192. ->visible(fn (Adjustment $record) => $record->canBePaused())
  193. ->action(function (Adjustment $record, array $data, Tables\Actions\Action $action) {
  194. $pausedUntil = $data['paused_until'] ?? null;
  195. $reason = $data['status_reason'] ?? null;
  196. $record->pause($reason, $pausedUntil);
  197. $action->success();
  198. }),
  199. Tables\Actions\Action::make('resume')
  200. ->label('Resume')
  201. ->icon('heroicon-m-play')
  202. ->requiresConfirmation()
  203. ->databaseTransaction()
  204. ->successNotificationTitle('Adjustment resumed')
  205. ->failureNotificationTitle('Failed to resume adjustment')
  206. ->visible(fn (Adjustment $record) => $record->canBeResumed())
  207. ->action(function (Adjustment $record, Tables\Actions\Action $action) {
  208. $record->resume();
  209. $action->success();
  210. }),
  211. Tables\Actions\Action::make('archive')
  212. ->label('Archive')
  213. ->icon('heroicon-m-archive-box')
  214. ->color('danger')
  215. ->form([
  216. Forms\Components\Textarea::make('status_reason')
  217. ->label('Reason for archiving')
  218. ->maxLength(255),
  219. ])
  220. ->databaseTransaction()
  221. ->successNotificationTitle('Adjustment archived')
  222. ->failureNotificationTitle('Failed to archive adjustment')
  223. ->visible(fn (Adjustment $record) => $record->canBeArchived())
  224. ->action(function (Adjustment $record, array $data, Tables\Actions\Action $action) {
  225. $reason = $data['status_reason'] ?? null;
  226. $record->archive($reason);
  227. $action->success();
  228. }),
  229. ]),
  230. ])
  231. ->bulkActions([
  232. Tables\Actions\BulkActionGroup::make([
  233. Tables\Actions\BulkAction::make('pause')
  234. ->label('Pause')
  235. ->icon('heroicon-m-pause')
  236. ->form([
  237. Forms\Components\DateTimePicker::make('paused_until')
  238. ->label('Auto-resume date')
  239. ->helperText('When should these adjustments automatically resume? Leave empty to keep paused indefinitely.')
  240. ->after('now'),
  241. Forms\Components\Textarea::make('status_reason')
  242. ->label('Reason for pausing')
  243. ->maxLength(255),
  244. ])
  245. ->databaseTransaction()
  246. ->successNotificationTitle('Adjustments paused')
  247. ->failureNotificationTitle('Failed to pause adjustments')
  248. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  249. $isInvalid = $records->contains(fn (Adjustment $record) => ! $record->canBePaused());
  250. if ($isInvalid) {
  251. Notification::make()
  252. ->title('Pause failed')
  253. ->body('Only adjustments that are currently active can be paused. Please adjust your selection and try again.')
  254. ->persistent()
  255. ->danger()
  256. ->send();
  257. $action->cancel(true);
  258. }
  259. })
  260. ->deselectRecordsAfterCompletion()
  261. ->action(function (Collection $records, array $data, Tables\Actions\BulkAction $action) {
  262. $pausedUntil = $data['paused_until'] ?? null;
  263. $reason = $data['status_reason'] ?? null;
  264. $records->each(function (Adjustment $record) use ($reason, $pausedUntil) {
  265. $record->pause($reason, $pausedUntil);
  266. });
  267. $action->success();
  268. }),
  269. Tables\Actions\BulkAction::make('resume')
  270. ->label('Resume')
  271. ->icon('heroicon-m-play')
  272. ->databaseTransaction()
  273. ->requiresConfirmation()
  274. ->successNotificationTitle('Adjustments resumed')
  275. ->failureNotificationTitle('Failed to resume adjustments')
  276. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  277. $isInvalid = $records->contains(fn (Adjustment $record) => ! $record->canBeResumed());
  278. if ($isInvalid) {
  279. Notification::make()
  280. ->title('Resume failed')
  281. ->body('Only adjustments that are currently paused can be resumed. Please adjust your selection and try again.')
  282. ->persistent()
  283. ->danger()
  284. ->send();
  285. $action->cancel(true);
  286. }
  287. })
  288. ->deselectRecordsAfterCompletion()
  289. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  290. $records->each(function (Adjustment $record) {
  291. $record->resume();
  292. });
  293. $action->success();
  294. }),
  295. Tables\Actions\BulkAction::make('archive')
  296. ->label('Archive')
  297. ->icon('heroicon-m-archive-box')
  298. ->color('danger')
  299. ->form([
  300. Forms\Components\Textarea::make('status_reason')
  301. ->label('Reason for archiving')
  302. ->maxLength(255),
  303. ])
  304. ->databaseTransaction()
  305. ->successNotificationTitle('Adjustments archived')
  306. ->failureNotificationTitle('Failed to archive adjustments')
  307. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  308. $isInvalid = $records->contains(fn (Adjustment $record) => ! $record->canBeArchived());
  309. if ($isInvalid) {
  310. Notification::make()
  311. ->title('Archive failed')
  312. ->body('Only adjustments that are currently active or paused can be archived. Please adjust your selection and try again.')
  313. ->persistent()
  314. ->danger()
  315. ->send();
  316. $action->cancel(true);
  317. }
  318. })
  319. ->deselectRecordsAfterCompletion()
  320. ->action(function (Collection $records, array $data, Tables\Actions\BulkAction $action) {
  321. $reason = $data['status_reason'] ?? null;
  322. $records->each(function (Adjustment $record) use ($reason) {
  323. $record->archive($reason);
  324. });
  325. $action->success();
  326. }),
  327. ]),
  328. ]);
  329. }
  330. public static function getRelations(): array
  331. {
  332. return [
  333. //
  334. ];
  335. }
  336. public static function getPages(): array
  337. {
  338. return [
  339. 'index' => Pages\ListAdjustments::route('/'),
  340. 'create' => Pages\CreateAdjustment::route('/create'),
  341. 'edit' => Pages\EditAdjustment::route('/{record}/edit'),
  342. ];
  343. }
  344. }