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.

PayBills.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <?php
  2. namespace App\Filament\Company\Resources\Purchases\BillResource\Pages;
  3. use App\Enums\Accounting\BillStatus;
  4. use App\Enums\Accounting\PaymentMethod;
  5. use App\Filament\Company\Resources\Purchases\BillResource;
  6. use App\Filament\Tables\Columns\CustomTextInputColumn;
  7. use App\Models\Accounting\Bill;
  8. use App\Models\Accounting\Transaction;
  9. use App\Models\Banking\BankAccount;
  10. use App\Models\Common\Vendor;
  11. use App\Models\Setting\Currency;
  12. use App\Utilities\Currency\CurrencyAccessor;
  13. use App\Utilities\Currency\CurrencyConverter;
  14. use Filament\Actions;
  15. use Filament\Forms;
  16. use Filament\Forms\Form;
  17. use Filament\Notifications\Notification;
  18. use Filament\Resources\Pages\ListRecords;
  19. use Filament\Support\RawJs;
  20. use Filament\Tables;
  21. use Filament\Tables\Columns\Summarizers\Summarizer;
  22. use Filament\Tables\Columns\TextColumn;
  23. use Filament\Tables\Table;
  24. use Illuminate\Contracts\Support\Htmlable;
  25. use Illuminate\Database\Eloquent\Collection;
  26. use Illuminate\Database\Query\Builder;
  27. use Illuminate\Support\Str;
  28. use Livewire\Attributes\Computed;
  29. /**
  30. * @property Form $form
  31. */
  32. class PayBills extends ListRecords
  33. {
  34. protected static string $resource = BillResource::class;
  35. protected static string $view = 'filament.company.resources.purchases.bill-resource.pages.pay-bills';
  36. public array $paymentAmounts = [];
  37. public ?array $data = [];
  38. public function getBreadcrumb(): ?string
  39. {
  40. return 'Pay';
  41. }
  42. public function getTitle(): string | Htmlable
  43. {
  44. return 'Pay Bills';
  45. }
  46. public function mount(): void
  47. {
  48. parent::mount();
  49. $this->form->fill();
  50. $this->reset('tableFilters');
  51. }
  52. protected function getHeaderActions(): array
  53. {
  54. return [
  55. Actions\Action::make('processPayments')
  56. ->color('primary')
  57. ->action(function () {
  58. $data = $this->data;
  59. $tableRecords = $this->getTableRecords();
  60. $paidCount = 0;
  61. $totalPaid = 0;
  62. /** @var Bill $bill */
  63. foreach ($tableRecords as $bill) {
  64. if (! $bill->canRecordPayment()) {
  65. continue;
  66. }
  67. // Get the payment amount from our component state
  68. $paymentAmount = $this->getPaymentAmount($bill);
  69. if ($paymentAmount <= 0) {
  70. continue;
  71. }
  72. $paymentData = [
  73. 'posted_at' => $data['posted_at'],
  74. 'payment_method' => $data['payment_method'],
  75. 'bank_account_id' => $data['bank_account_id'],
  76. 'amount' => $paymentAmount,
  77. ];
  78. $bill->recordPayment($paymentData);
  79. $paidCount++;
  80. $totalPaid += $paymentAmount;
  81. }
  82. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  83. $totalFormatted = CurrencyConverter::formatCentsToMoney($totalPaid, $currencyCode, true);
  84. Notification::make()
  85. ->title('Bills paid successfully')
  86. ->body("Paid {$paidCount} " . Str::plural('bill', $paidCount) . " for a total of {$totalFormatted}")
  87. ->success()
  88. ->send();
  89. $this->reset('paymentAmounts');
  90. $this->resetTable();
  91. }),
  92. ];
  93. }
  94. /**
  95. * @return array<int | string, string | Form>
  96. */
  97. protected function getForms(): array
  98. {
  99. return [
  100. 'form',
  101. ];
  102. }
  103. public function form(Form $form): Form
  104. {
  105. return $form
  106. ->live()
  107. ->schema([
  108. Forms\Components\Grid::make(3)
  109. ->schema([
  110. Forms\Components\Select::make('bank_account_id')
  111. ->label('Account')
  112. ->options(static function () {
  113. return Transaction::getBankAccountOptionsFlat();
  114. })
  115. ->default(fn () => BankAccount::where('enabled', true)->first()?->id)
  116. ->selectablePlaceholder(false)
  117. ->searchable()
  118. ->softRequired(),
  119. Forms\Components\DatePicker::make('posted_at')
  120. ->label('Date')
  121. ->default(now())
  122. ->softRequired(),
  123. Forms\Components\Select::make('payment_method')
  124. ->label('Payment method')
  125. ->selectablePlaceholder(false)
  126. ->options(PaymentMethod::class)
  127. ->default(PaymentMethod::BankPayment)
  128. ->softRequired(),
  129. ]),
  130. ])->statePath('data');
  131. }
  132. public function table(Table $table): Table
  133. {
  134. return $table
  135. ->query(
  136. Bill::query()
  137. ->with(['vendor'])
  138. ->unpaid()
  139. )
  140. ->recordClasses(['is-spreadsheet'])
  141. ->defaultSort('due_date')
  142. ->paginated(false)
  143. ->columns([
  144. TextColumn::make('vendor.name')
  145. ->label('Vendor')
  146. ->sortable(),
  147. TextColumn::make('bill_number')
  148. ->label('Bill number')
  149. ->sortable(),
  150. TextColumn::make('due_date')
  151. ->label('Due date')
  152. ->defaultDateFormat()
  153. ->sortable(),
  154. Tables\Columns\TextColumn::make('status')
  155. ->badge()
  156. ->sortable(),
  157. TextColumn::make('amount_due')
  158. ->label('Amount due')
  159. ->currency(static fn (Bill $record) => $record->currency_code)
  160. ->alignEnd()
  161. ->sortable()
  162. ->summarize([
  163. Summarizer::make()
  164. ->using(function (Builder $query) {
  165. $totalAmountDue = $query->sum('amount_due');
  166. $bankAccountCurrency = $this->getSelectedBankAccount()->account->currency_code;
  167. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? $bankAccountCurrency;
  168. if ($activeCurrency !== $bankAccountCurrency) {
  169. $totalAmountDue = CurrencyConverter::convertBalance($totalAmountDue, $activeCurrency, $bankAccountCurrency);
  170. }
  171. return CurrencyConverter::formatCentsToMoney($totalAmountDue, $bankAccountCurrency, true);
  172. }),
  173. Summarizer::make()
  174. ->using(function (Builder $query) {
  175. $totalAmountDue = $query->sum('amount_due');
  176. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  177. return CurrencyConverter::formatCentsToMoney($totalAmountDue, $currencyCode, true);
  178. })
  179. ->visible(function () {
  180. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? null;
  181. $bankAccountCurrency = $this->getSelectedBankAccount()->account->currency_code;
  182. return $activeCurrency && $activeCurrency !== $bankAccountCurrency;
  183. }),
  184. ]),
  185. CustomTextInputColumn::make('payment_amount')
  186. ->label('Payment amount')
  187. ->alignEnd()
  188. ->navigable()
  189. ->mask(RawJs::make('$money($input)'))
  190. ->updateStateUsing(function (Bill $record, $state) {
  191. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  192. $this->paymentAmounts[$record->id] = 0;
  193. return '0.00';
  194. }
  195. $paymentCents = CurrencyConverter::convertToCents($state, 'USD');
  196. if ($paymentCents > $record->amount_due) {
  197. $paymentCents = $record->amount_due;
  198. }
  199. $this->paymentAmounts[$record->id] = $paymentCents;
  200. return $state;
  201. })
  202. ->getStateUsing(function (Bill $record) {
  203. $paymentAmount = $this->paymentAmounts[$record->id] ?? 0;
  204. return CurrencyConverter::convertCentsToFormatSimple($paymentAmount, 'USD');
  205. })
  206. ->summarize([
  207. Summarizer::make()
  208. ->using(function () {
  209. $total = array_sum($this->paymentAmounts);
  210. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  211. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? $defaultCurrency;
  212. if ($activeCurrency !== $defaultCurrency) {
  213. $total = CurrencyConverter::convertBalance($total, $activeCurrency, $defaultCurrency);
  214. }
  215. return CurrencyConverter::formatCentsToMoney($total, $defaultCurrency, true);
  216. }),
  217. Summarizer::make()
  218. ->using(fn () => $this->totalPaymentAmount)
  219. ->visible(function () {
  220. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? null;
  221. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  222. return $activeCurrency && $activeCurrency !== $defaultCurrency;
  223. }),
  224. ]),
  225. ])
  226. ->bulkActions([
  227. Tables\Actions\BulkAction::make('setFullAmounts')
  228. ->label('Set full amounts')
  229. ->icon('heroicon-o-banknotes')
  230. ->color('primary')
  231. ->deselectRecordsAfterCompletion()
  232. ->action(function (Collection $records) {
  233. $records->each(function (Bill $bill) {
  234. $this->paymentAmounts[$bill->id] = $bill->amount_due;
  235. });
  236. }),
  237. Tables\Actions\BulkAction::make('clearAmounts')
  238. ->label('Clear amounts')
  239. ->icon('heroicon-o-x-mark')
  240. ->color('gray')
  241. ->deselectRecordsAfterCompletion()
  242. ->action(function (Collection $records) {
  243. $records->each(function (Bill $bill) {
  244. $this->paymentAmounts[$bill->id] = 0;
  245. });
  246. }),
  247. ])
  248. ->filters([
  249. Tables\Filters\SelectFilter::make('currency_code')
  250. ->label('Currency')
  251. ->selectablePlaceholder(false)
  252. ->default(CurrencyAccessor::getDefaultCurrency())
  253. ->options(Currency::query()->pluck('name', 'code')->toArray())
  254. ->searchable()
  255. ->resetState([
  256. 'value' => CurrencyAccessor::getDefaultCurrency(),
  257. ])
  258. ->indicateUsing(function (Tables\Filters\SelectFilter $filter, array $state) {
  259. if (blank($state['value'] ?? null)) {
  260. return [];
  261. }
  262. $label = collect($filter->getOptions())
  263. ->mapWithKeys(fn (string | array $label, string $value): array => is_array($label) ? $label : [$value => $label])
  264. ->get($state['value']);
  265. if (blank($label)) {
  266. return [];
  267. }
  268. $indicator = $filter->getLabel();
  269. return Tables\Filters\Indicator::make("{$indicator}: {$label}")->removable(false);
  270. }),
  271. Tables\Filters\SelectFilter::make('vendor_id')
  272. ->label('Vendor')
  273. ->options(fn () => Vendor::query()->pluck('name', 'id')->toArray())
  274. ->searchable(),
  275. Tables\Filters\SelectFilter::make('status')
  276. ->multiple()
  277. ->options(BillStatus::getUnpaidOptions()),
  278. ]);
  279. }
  280. protected function getPaymentAmount(Bill $record): int
  281. {
  282. return $this->paymentAmounts[$record->id] ?? 0;
  283. }
  284. #[Computed]
  285. public function totalPaymentAmount(): string
  286. {
  287. $total = array_sum($this->paymentAmounts);
  288. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  289. return CurrencyConverter::formatCentsToMoney($total, $currencyCode, true);
  290. }
  291. public function getSelectedBankAccount(): BankAccount
  292. {
  293. $bankAccountId = $this->data['bank_account_id'];
  294. $bankAccount = BankAccount::find($bankAccountId);
  295. return $bankAccount ?: BankAccount::where('enabled', true)->first();
  296. }
  297. protected function handleTableFilterUpdates(): void
  298. {
  299. parent::handleTableFilterUpdates();
  300. $visibleBillIds = $this->getTableRecords()->pluck('id')->toArray();
  301. $visibleBillKeys = array_flip($visibleBillIds);
  302. $this->paymentAmounts = array_intersect_key($this->paymentAmounts, $visibleBillKeys);
  303. }
  304. }