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.

PaymentsRelationManager.php 11KB

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