Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

PaymentsRelationManager.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales\InvoiceResource\RelationManagers;
  3. use App\Enums\Accounting\InvoiceStatus;
  4. use App\Enums\Accounting\PaymentMethod;
  5. use App\Enums\Accounting\TransactionType;
  6. use App\Models\Accounting\Invoice;
  7. use App\Models\Accounting\Transaction;
  8. use App\Models\Banking\BankAccount;
  9. use App\Utilities\Currency\CurrencyAccessor;
  10. use App\Utilities\Currency\CurrencyConverter;
  11. use Closure;
  12. use Filament\Forms;
  13. use Filament\Forms\Form;
  14. use Filament\Resources\RelationManagers\RelationManager;
  15. use Filament\Support\Colors\Color;
  16. use Filament\Support\Enums\FontWeight;
  17. use Filament\Support\Enums\MaxWidth;
  18. use Filament\Tables;
  19. use Filament\Tables\Table;
  20. use Illuminate\Database\Eloquent\Model;
  21. class PaymentsRelationManager extends RelationManager
  22. {
  23. protected static string $relationship = 'payments';
  24. protected static ?string $modelLabel = 'Payment';
  25. protected static bool $isLazy = false;
  26. protected $listeners = [
  27. 'refresh' => '$refresh',
  28. ];
  29. public function isReadOnly(): bool
  30. {
  31. return false;
  32. }
  33. public static function canViewForRecord(Model $ownerRecord, string $pageClass): bool
  34. {
  35. return $ownerRecord->status !== InvoiceStatus::Draft;
  36. }
  37. public function form(Form $form): Form
  38. {
  39. return $form
  40. ->columns(1)
  41. ->schema([
  42. Forms\Components\DatePicker::make('posted_at')
  43. ->label('Date'),
  44. Forms\Components\Grid::make()
  45. ->schema([
  46. Forms\Components\Select::make('bank_account_id')
  47. ->label('Account')
  48. ->required()
  49. ->live()
  50. ->options(function () {
  51. return BankAccount::query()
  52. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  53. ->select(['bank_accounts.id', 'accounts.name', 'accounts.currency_code'])
  54. ->get()
  55. ->mapWithKeys(function ($account) {
  56. $label = $account->name;
  57. if ($account->currency_code) {
  58. $label .= " ({$account->currency_code})";
  59. }
  60. return [$account->id => $label];
  61. })
  62. ->toArray();
  63. })
  64. ->searchable(),
  65. Forms\Components\TextInput::make('amount')
  66. ->label('Amount')
  67. ->required()
  68. ->money(function (RelationManager $livewire) {
  69. /** @var Invoice $invoice */
  70. $invoice = $livewire->getOwnerRecord();
  71. return $invoice->currency_code;
  72. })
  73. ->live(onBlur: true)
  74. ->helperText(function (RelationManager $livewire, $state, ?Transaction $record) {
  75. /** @var Invoice $ownerRecord */
  76. $ownerRecord = $livewire->getOwnerRecord();
  77. $invoiceCurrency = $ownerRecord->currency_code;
  78. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  79. return null;
  80. }
  81. $amountDue = $ownerRecord->amount_due;
  82. $amount = CurrencyConverter::convertToCents($state, 'USD');
  83. if ($amount <= 0) {
  84. return 'Please enter a valid positive amount';
  85. }
  86. $currentPaymentAmount = $record?->amount ?? 0;
  87. if ($ownerRecord->status === InvoiceStatus::Overpaid) {
  88. $newAmountDue = $amountDue + $amount - $currentPaymentAmount;
  89. } else {
  90. $newAmountDue = $amountDue - $amount + $currentPaymentAmount;
  91. }
  92. return match (true) {
  93. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  94. $newAmountDue === 0 => 'Invoice will be fully paid',
  95. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  96. };
  97. })
  98. ->rules([
  99. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  100. if (! CurrencyConverter::isValidAmount($value, 'USD')) {
  101. $fail('Please enter a valid amount');
  102. }
  103. },
  104. ]),
  105. ])->columns(2),
  106. Forms\Components\Placeholder::make('currency_conversion')
  107. ->label('Currency Conversion')
  108. ->content(function (Forms\Get $get, RelationManager $livewire) {
  109. $amount = $get('amount');
  110. $bankAccountId = $get('bank_account_id');
  111. /** @var Invoice $invoice */
  112. $invoice = $livewire->getOwnerRecord();
  113. $invoiceCurrency = $invoice->currency_code;
  114. if (empty($amount) || empty($bankAccountId) || ! CurrencyConverter::isValidAmount($amount, 'USD')) {
  115. return null;
  116. }
  117. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  118. if (! $bankAccount) {
  119. return null;
  120. }
  121. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  122. // If currencies are the same, no conversion needed
  123. if ($invoiceCurrency === $bankCurrency) {
  124. return null;
  125. }
  126. // Convert amount from invoice currency to bank currency
  127. $amountInInvoiceCurrencyCents = CurrencyConverter::convertToCents($amount, 'USD');
  128. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  129. $amountInInvoiceCurrencyCents,
  130. $invoiceCurrency,
  131. $bankCurrency
  132. );
  133. $formattedBankAmount = CurrencyConverter::formatCentsToMoney($amountInBankCurrencyCents, $bankCurrency);
  134. return "Payment will be recorded as {$formattedBankAmount} in the bank account's currency ({$bankCurrency}).";
  135. })
  136. ->hidden(function (Forms\Get $get, RelationManager $livewire) {
  137. $bankAccountId = $get('bank_account_id');
  138. if (empty($bankAccountId)) {
  139. return true;
  140. }
  141. /** @var Invoice $invoice */
  142. $invoice = $livewire->getOwnerRecord();
  143. $invoiceCurrency = $invoice->currency_code;
  144. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  145. if (! $bankAccount) {
  146. return true;
  147. }
  148. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  149. // Hide if currencies are the same
  150. return $invoiceCurrency === $bankCurrency;
  151. }),
  152. Forms\Components\Select::make('payment_method')
  153. ->label('Payment method')
  154. ->required()
  155. ->options(PaymentMethod::class),
  156. Forms\Components\Textarea::make('notes')
  157. ->label('Notes'),
  158. ]);
  159. }
  160. public function table(Table $table): Table
  161. {
  162. return $table
  163. ->recordTitleAttribute('description')
  164. ->columns([
  165. Tables\Columns\TextColumn::make('posted_at')
  166. ->label('Date')
  167. ->sortable()
  168. ->defaultDateFormat(),
  169. Tables\Columns\TextColumn::make('type')
  170. ->label('Type')
  171. ->sortable()
  172. ->toggleable(isToggledHiddenByDefault: true),
  173. Tables\Columns\TextColumn::make('description')
  174. ->label('Description')
  175. ->limit(30)
  176. ->toggleable(),
  177. Tables\Columns\TextColumn::make('bankAccount.account.name')
  178. ->label('Account')
  179. ->toggleable(),
  180. Tables\Columns\TextColumn::make('amount')
  181. ->label('Amount')
  182. ->weight(static fn (Transaction $transaction) => $transaction->reviewed ? null : FontWeight::SemiBold)
  183. ->color(
  184. static fn (Transaction $transaction) => match ($transaction->type) {
  185. TransactionType::Deposit => Color::rgb('rgb(' . Color::Green[700] . ')'),
  186. TransactionType::Journal => 'primary',
  187. default => null,
  188. }
  189. )
  190. ->sortable()
  191. ->currency(static fn (Transaction $transaction) => $transaction->bankAccount?->account->currency_code ?? CurrencyAccessor::getDefaultCurrency()),
  192. ])
  193. ->filters([
  194. //
  195. ])
  196. ->headerActions([
  197. Tables\Actions\CreateAction::make()
  198. ->label(fn () => $this->getOwnerRecord()->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  199. ->modalHeading(fn (Tables\Actions\CreateAction $action) => $action->getLabel())
  200. ->slideOver()
  201. ->modalWidth(MaxWidth::TwoExtraLarge)
  202. ->visible(function () {
  203. return $this->getOwnerRecord()->canRecordPayment();
  204. })
  205. ->mountUsing(function (Form $form) {
  206. $record = $this->getOwnerRecord();
  207. $form->fill([
  208. 'posted_at' => company_today()->toDateString(),
  209. 'amount' => abs($record->amount_due),
  210. ]);
  211. })
  212. ->databaseTransaction()
  213. ->successNotificationTitle('Payment recorded')
  214. ->action(function (Tables\Actions\CreateAction $action, array $data) {
  215. /** @var Invoice $record */
  216. $record = $this->getOwnerRecord();
  217. $record->recordPayment($data);
  218. $action->success();
  219. $this->dispatch('refresh');
  220. }),
  221. ])
  222. ->actions([
  223. Tables\Actions\DeleteAction::make()
  224. ->after(fn () => $this->dispatch('refresh')),
  225. ])
  226. ->bulkActions([
  227. Tables\Actions\BulkActionGroup::make([
  228. Tables\Actions\DeleteBulkAction::make(),
  229. ]),
  230. ]);
  231. }
  232. }