您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

PayBills.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. ->requiresConfirmation()
  58. ->modalHeading('Confirm payments')
  59. ->modalDescription(function () {
  60. $billCount = collect($this->paymentAmounts)->filter(fn ($amount) => $amount > 0)->count();
  61. $totalAmount = array_sum($this->paymentAmounts);
  62. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  63. $totalFormatted = CurrencyConverter::formatCentsToMoney($totalAmount, $currencyCode, true);
  64. return "You are about to pay {$billCount} " . Str::plural('bill', $billCount) . " for a total of {$totalFormatted}. This action cannot be undone.";
  65. })
  66. ->action(function () {
  67. $data = $this->data;
  68. $tableRecords = $this->getTableRecords();
  69. $paidCount = 0;
  70. $totalPaid = 0;
  71. /** @var Bill $bill */
  72. foreach ($tableRecords as $bill) {
  73. if (! $bill->canRecordPayment()) {
  74. continue;
  75. }
  76. // Get the payment amount from our component state
  77. $paymentAmount = $this->getPaymentAmount($bill);
  78. if ($paymentAmount <= 0) {
  79. continue;
  80. }
  81. $paymentData = [
  82. 'posted_at' => $data['posted_at'],
  83. 'payment_method' => $data['payment_method'],
  84. 'bank_account_id' => $data['bank_account_id'],
  85. 'amount' => $paymentAmount,
  86. ];
  87. $bill->recordPayment($paymentData);
  88. $paidCount++;
  89. $totalPaid += $paymentAmount;
  90. }
  91. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  92. $totalFormatted = CurrencyConverter::formatCentsToMoney($totalPaid, $currencyCode, true);
  93. Notification::make()
  94. ->title('Bills paid successfully')
  95. ->body("Paid {$paidCount} " . Str::plural('bill', $paidCount) . " for a total of {$totalFormatted}")
  96. ->success()
  97. ->send();
  98. $this->reset('paymentAmounts');
  99. $this->resetTable();
  100. }),
  101. ];
  102. }
  103. /**
  104. * @return array<int | string, string | Form>
  105. */
  106. protected function getForms(): array
  107. {
  108. return [
  109. 'form',
  110. ];
  111. }
  112. public function form(Form $form): Form
  113. {
  114. return $form
  115. ->live()
  116. ->schema([
  117. Forms\Components\Grid::make(3)
  118. ->schema([
  119. Forms\Components\Select::make('bank_account_id')
  120. ->label('Account')
  121. ->options(static function () {
  122. return Transaction::getBankAccountOptionsFlat();
  123. })
  124. ->default(fn () => BankAccount::where('enabled', true)->first()?->id)
  125. ->selectablePlaceholder(false)
  126. ->searchable()
  127. ->softRequired(),
  128. Forms\Components\DatePicker::make('posted_at')
  129. ->label('Date')
  130. ->default(now())
  131. ->softRequired(),
  132. Forms\Components\Select::make('payment_method')
  133. ->label('Payment method')
  134. ->selectablePlaceholder(false)
  135. ->options(PaymentMethod::class)
  136. ->default(PaymentMethod::BankPayment)
  137. ->softRequired(),
  138. ]),
  139. ])->statePath('data');
  140. }
  141. public function table(Table $table): Table
  142. {
  143. return $table
  144. ->query(
  145. Bill::query()
  146. ->with(['vendor'])
  147. ->unpaid()
  148. )
  149. ->recordClasses(['is-spreadsheet'])
  150. ->defaultSort('due_date')
  151. ->paginated(false)
  152. ->columns([
  153. TextColumn::make('vendor.name')
  154. ->label('Vendor')
  155. ->sortable(),
  156. TextColumn::make('bill_number')
  157. ->label('Bill number')
  158. ->sortable(),
  159. TextColumn::make('due_date')
  160. ->label('Due date')
  161. ->defaultDateFormat()
  162. ->sortable(),
  163. Tables\Columns\TextColumn::make('status')
  164. ->badge()
  165. ->sortable(),
  166. TextColumn::make('amount_due')
  167. ->label('Amount due')
  168. ->currency(static fn (Bill $record) => $record->currency_code)
  169. ->alignEnd()
  170. ->sortable()
  171. ->summarize([
  172. Summarizer::make()
  173. ->using(function (Builder $query) {
  174. $totalAmountDue = $query->sum('amount_due');
  175. $bankAccountCurrency = $this->getSelectedBankAccount()->account->currency_code;
  176. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? $bankAccountCurrency;
  177. if ($activeCurrency !== $bankAccountCurrency) {
  178. $totalAmountDue = CurrencyConverter::convertBalance($totalAmountDue, $activeCurrency, $bankAccountCurrency);
  179. }
  180. return CurrencyConverter::formatCentsToMoney($totalAmountDue, $bankAccountCurrency, true);
  181. }),
  182. Summarizer::make()
  183. ->using(function (Builder $query) {
  184. $totalAmountDue = $query->sum('amount_due');
  185. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  186. return CurrencyConverter::formatCentsToMoney($totalAmountDue, $currencyCode, true);
  187. })
  188. ->visible(function () {
  189. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? null;
  190. $bankAccountCurrency = $this->getSelectedBankAccount()->account->currency_code;
  191. return $activeCurrency && $activeCurrency !== $bankAccountCurrency;
  192. }),
  193. ]),
  194. Tables\Columns\IconColumn::make('applyFullAmountAction')
  195. ->icon('heroicon-m-chevron-double-right')
  196. ->color('primary')
  197. ->label('')
  198. ->default('')
  199. ->alignCenter()
  200. ->width('3rem')
  201. ->tooltip('Apply full amount')
  202. ->action(
  203. Tables\Actions\Action::make('applyFullPayment')
  204. ->action(function (Bill $record) {
  205. $this->paymentAmounts[$record->id] = $record->amount_due;
  206. }),
  207. ),
  208. CustomTextInputColumn::make('payment_amount')
  209. ->label('Payment amount')
  210. ->alignEnd()
  211. ->navigable()
  212. ->mask(RawJs::make('$money($input)'))
  213. ->updateStateUsing(function (Bill $record, $state) {
  214. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  215. $this->paymentAmounts[$record->id] = 0;
  216. return '0.00';
  217. }
  218. $paymentCents = CurrencyConverter::convertToCents($state, 'USD');
  219. if ($paymentCents > $record->amount_due) {
  220. $paymentCents = $record->amount_due;
  221. }
  222. $this->paymentAmounts[$record->id] = $paymentCents;
  223. return $state;
  224. })
  225. ->getStateUsing(function (Bill $record) {
  226. $paymentAmount = $this->paymentAmounts[$record->id] ?? 0;
  227. return CurrencyConverter::convertCentsToFormatSimple($paymentAmount, 'USD');
  228. })
  229. ->summarize([
  230. Summarizer::make()
  231. ->using(function () {
  232. $total = array_sum($this->paymentAmounts);
  233. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  234. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? $defaultCurrency;
  235. if ($activeCurrency !== $defaultCurrency) {
  236. $total = CurrencyConverter::convertBalance($total, $activeCurrency, $defaultCurrency);
  237. }
  238. return CurrencyConverter::formatCentsToMoney($total, $defaultCurrency, true);
  239. }),
  240. Summarizer::make()
  241. ->using(fn () => $this->totalPaymentAmount)
  242. ->visible(function () {
  243. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? null;
  244. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  245. return $activeCurrency && $activeCurrency !== $defaultCurrency;
  246. }),
  247. ]),
  248. ])
  249. ->bulkActions([
  250. Tables\Actions\BulkAction::make('applyFullAmounts')
  251. ->label('Apply full amounts')
  252. ->icon('heroicon-o-banknotes')
  253. ->color('primary')
  254. ->deselectRecordsAfterCompletion()
  255. ->action(function (Collection $records) {
  256. $records->each(function (Bill $bill) {
  257. $this->paymentAmounts[$bill->id] = $bill->amount_due;
  258. });
  259. }),
  260. Tables\Actions\BulkAction::make('clearAmounts')
  261. ->label('Clear amounts')
  262. ->icon('heroicon-o-x-mark')
  263. ->color('gray')
  264. ->deselectRecordsAfterCompletion()
  265. ->action(function (Collection $records) {
  266. $records->each(function (Bill $bill) {
  267. $this->paymentAmounts[$bill->id] = 0;
  268. });
  269. }),
  270. ])
  271. ->filters([
  272. Tables\Filters\SelectFilter::make('currency_code')
  273. ->label('Currency')
  274. ->selectablePlaceholder(false)
  275. ->default(CurrencyAccessor::getDefaultCurrency())
  276. ->options(Currency::query()->pluck('name', 'code')->toArray())
  277. ->searchable()
  278. ->resetState([
  279. 'value' => CurrencyAccessor::getDefaultCurrency(),
  280. ])
  281. ->indicateUsing(function (Tables\Filters\SelectFilter $filter, array $state) {
  282. if (blank($state['value'] ?? null)) {
  283. return [];
  284. }
  285. $label = collect($filter->getOptions())
  286. ->mapWithKeys(fn (string | array $label, string $value): array => is_array($label) ? $label : [$value => $label])
  287. ->get($state['value']);
  288. if (blank($label)) {
  289. return [];
  290. }
  291. $indicator = $filter->getLabel();
  292. return Tables\Filters\Indicator::make("{$indicator}: {$label}")->removable(false);
  293. }),
  294. Tables\Filters\SelectFilter::make('vendor_id')
  295. ->label('Vendor')
  296. ->options(fn () => Vendor::query()->pluck('name', 'id')->toArray())
  297. ->searchable(),
  298. Tables\Filters\SelectFilter::make('status')
  299. ->multiple()
  300. ->options(BillStatus::getUnpaidOptions()),
  301. ]);
  302. }
  303. protected function getPaymentAmount(Bill $record): int
  304. {
  305. return $this->paymentAmounts[$record->id] ?? 0;
  306. }
  307. #[Computed]
  308. public function totalPaymentAmount(): string
  309. {
  310. $total = array_sum($this->paymentAmounts);
  311. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  312. return CurrencyConverter::formatCentsToMoney($total, $currencyCode, true);
  313. }
  314. public function getSelectedBankAccount(): BankAccount
  315. {
  316. $bankAccountId = $this->data['bank_account_id'];
  317. $bankAccount = BankAccount::find($bankAccountId);
  318. return $bankAccount ?: BankAccount::where('enabled', true)->first();
  319. }
  320. protected function handleTableFilterUpdates(): void
  321. {
  322. parent::handleTableFilterUpdates();
  323. $visibleBillIds = $this->getTableRecords()->pluck('id')->toArray();
  324. $visibleBillKeys = array_flip($visibleBillIds);
  325. $this->paymentAmounts = array_intersect_key($this->paymentAmounts, $visibleBillKeys);
  326. }
  327. }