You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BillResource.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. namespace App\Filament\Company\Resources\Purchases;
  3. use App\Filament\Company\Resources\Purchases\BillResource\Pages;
  4. use App\Models\Accounting\Adjustment;
  5. use App\Models\Accounting\Bill;
  6. use App\Models\Accounting\DocumentLineItem;
  7. use App\Models\Common\Offering;
  8. use App\Utilities\Currency\CurrencyAccessor;
  9. use Awcodes\TableRepeater\Components\TableRepeater;
  10. use Awcodes\TableRepeater\Header;
  11. use Carbon\CarbonInterface;
  12. use Filament\Forms;
  13. use Filament\Forms\Form;
  14. use Filament\Resources\Resource;
  15. use Filament\Tables;
  16. use Filament\Tables\Table;
  17. use Illuminate\Database\Eloquent\Model;
  18. use Illuminate\Support\Carbon;
  19. use Illuminate\Support\Facades\Auth;
  20. class BillResource extends Resource
  21. {
  22. protected static ?string $model = Bill::class;
  23. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  24. public static function form(Form $form): Form
  25. {
  26. $company = Auth::user()->currentCompany;
  27. return $form
  28. ->schema([
  29. Forms\Components\Section::make('Bill Details')
  30. ->schema([
  31. Forms\Components\Split::make([
  32. Forms\Components\Group::make([
  33. Forms\Components\Select::make('vendor_id')
  34. ->relationship('vendor', 'name')
  35. ->preload()
  36. ->searchable()
  37. ->required(),
  38. ]),
  39. Forms\Components\Group::make([
  40. Forms\Components\TextInput::make('bill_number')
  41. ->label('Bill Number')
  42. ->default(fn () => Bill::getNextDocumentNumber()),
  43. Forms\Components\TextInput::make('order_number')
  44. ->label('P.O/S.O Number'),
  45. Forms\Components\DatePicker::make('date')
  46. ->label('Bill Date')
  47. ->default(now()),
  48. Forms\Components\DatePicker::make('due_date')
  49. ->label('Due Date')
  50. ->default(function () use ($company) {
  51. return now()->addDays($company->defaultBill->payment_terms->getDays());
  52. }),
  53. ])->grow(true),
  54. ])->from('md'),
  55. TableRepeater::make('lineItems')
  56. ->relationship()
  57. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  58. if (! is_array($state)) {
  59. $state = [];
  60. }
  61. $relationship = $component->getRelationship();
  62. $existingRecords = $component->getCachedExistingRecords();
  63. $recordsToDelete = [];
  64. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  65. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  66. continue;
  67. }
  68. $recordsToDelete[] = $keyToCheckForDeletion;
  69. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  70. }
  71. $relationship
  72. ->whereKey($recordsToDelete)
  73. ->get()
  74. ->each(static fn (Model $record) => $record->delete());
  75. $childComponentContainers = $component->getChildComponentContainers(
  76. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  77. );
  78. $itemOrder = 1;
  79. $orderColumn = $component->getOrderColumn();
  80. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  81. foreach ($childComponentContainers as $itemKey => $item) {
  82. $itemData = $item->getState(shouldCallHooksBefore: false);
  83. if ($orderColumn) {
  84. $itemData[$orderColumn] = $itemOrder;
  85. $itemOrder++;
  86. }
  87. if ($record = ($existingRecords[$itemKey] ?? null)) {
  88. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  89. if ($itemData === null) {
  90. continue;
  91. }
  92. $translatableContentDriver ?
  93. $translatableContentDriver->updateRecord($record, $itemData) :
  94. $record->fill($itemData)->save();
  95. continue;
  96. }
  97. $relatedModel = $component->getRelatedModel();
  98. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  99. if ($itemData === null) {
  100. continue;
  101. }
  102. if ($translatableContentDriver) {
  103. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  104. } else {
  105. $record = new $relatedModel;
  106. $record->fill($itemData);
  107. }
  108. $record = $relationship->save($record);
  109. $item->model($record)->saveRelationships();
  110. $existingRecords->push($record);
  111. }
  112. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  113. /** @var Bill $bill */
  114. $bill = $component->getRecord();
  115. // Recalculate totals for line items
  116. $bill->lineItems()->each(function (DocumentLineItem $lineItem) {
  117. $lineItem->updateQuietly([
  118. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  119. 'discount_total' => $lineItem->calculateDiscountTotal()->getAmount(),
  120. ]);
  121. });
  122. $subtotal = $bill->lineItems()->sum('subtotal') / 100;
  123. $taxTotal = $bill->lineItems()->sum('tax_total') / 100;
  124. $discountTotal = $bill->lineItems()->sum('discount_total') / 100;
  125. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  126. $bill->updateQuietly([
  127. 'subtotal' => $subtotal,
  128. 'tax_total' => $taxTotal,
  129. 'discount_total' => $discountTotal,
  130. 'total' => $grandTotal,
  131. ]);
  132. })
  133. ->headers([
  134. Header::make('Items')->width('15%'),
  135. Header::make('Description')->width('25%'),
  136. Header::make('Quantity')->width('10%'),
  137. Header::make('Price')->width('10%'),
  138. Header::make('Taxes')->width('15%'),
  139. Header::make('Discounts')->width('15%'),
  140. Header::make('Amount')->width('10%')->align('right'),
  141. ])
  142. ->schema([
  143. Forms\Components\Select::make('offering_id')
  144. ->relationship('purchasableOffering', 'name')
  145. ->preload()
  146. ->searchable()
  147. ->required()
  148. ->live()
  149. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  150. $offeringId = $state;
  151. $offeringRecord = Offering::with('purchaseTaxes')->find($offeringId);
  152. if ($offeringRecord) {
  153. $set('description', $offeringRecord->description);
  154. $set('unit_price', $offeringRecord->price);
  155. $set('purchaseTaxes', $offeringRecord->purchaseTaxes->pluck('id')->toArray());
  156. $set('purchaseDiscounts', $offeringRecord->purchaseDiscounts->pluck('id')->toArray());
  157. }
  158. }),
  159. Forms\Components\TextInput::make('description'),
  160. Forms\Components\TextInput::make('quantity')
  161. ->required()
  162. ->numeric()
  163. ->live()
  164. ->default(1),
  165. Forms\Components\TextInput::make('unit_price')
  166. ->hiddenLabel()
  167. ->numeric()
  168. ->live()
  169. ->default(0),
  170. Forms\Components\Select::make('purchaseTaxes')
  171. ->relationship('purchaseTaxes', 'name')
  172. ->preload()
  173. ->multiple()
  174. ->live()
  175. ->searchable(),
  176. Forms\Components\Select::make('purchaseDiscounts')
  177. ->relationship('purchaseDiscounts', 'name')
  178. ->preload()
  179. ->multiple()
  180. ->live()
  181. ->searchable(),
  182. Forms\Components\Placeholder::make('total')
  183. ->hiddenLabel()
  184. ->content(function (Forms\Get $get) {
  185. $quantity = max((float) ($get('quantity') ?? 0), 0);
  186. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  187. $purchaseTaxes = $get('purchaseTaxes') ?? [];
  188. $purchaseDiscounts = $get('purchaseDiscounts') ?? [];
  189. $subtotal = $quantity * $unitPrice;
  190. // Calculate tax amount based on subtotal
  191. $taxAmount = 0;
  192. if (! empty($purchaseTaxes)) {
  193. $taxRates = Adjustment::whereIn('id', $purchaseTaxes)->pluck('rate');
  194. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  195. }
  196. // Calculate discount amount based on subtotal
  197. $discountAmount = 0;
  198. if (! empty($purchaseDiscounts)) {
  199. $discountRates = Adjustment::whereIn('id', $purchaseDiscounts)->pluck('rate');
  200. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  201. }
  202. // Final total
  203. $total = $subtotal + ($taxAmount - $discountAmount);
  204. return money($total, CurrencyAccessor::getDefaultCurrency(), true)->format();
  205. }),
  206. ]),
  207. Forms\Components\Grid::make(6)
  208. ->schema([
  209. Forms\Components\ViewField::make('totals')
  210. ->columnStart(5)
  211. ->columnSpan(2)
  212. ->view('filament.forms.components.bill-totals'),
  213. ]),
  214. ]),
  215. ]);
  216. }
  217. public static function table(Table $table): Table
  218. {
  219. return $table
  220. ->columns([
  221. Tables\Columns\TextColumn::make('status')
  222. ->badge()
  223. ->searchable(),
  224. Tables\Columns\TextColumn::make('due_date')
  225. ->label('Due')
  226. ->formatStateUsing(function (Tables\Columns\TextColumn $column, mixed $state) {
  227. if (blank($state)) {
  228. return null;
  229. }
  230. $date = Carbon::parse($state)
  231. ->setTimezone($timezone ?? $column->getTimezone());
  232. if ($date->isToday()) {
  233. return 'Today';
  234. }
  235. return $date->diffForHumans([
  236. 'options' => CarbonInterface::ONE_DAY_WORDS,
  237. ]);
  238. })
  239. ->sortable(),
  240. Tables\Columns\TextColumn::make('date')
  241. ->date()
  242. ->sortable(),
  243. Tables\Columns\TextColumn::make('bill_number')
  244. ->label('Number')
  245. ->searchable(),
  246. Tables\Columns\TextColumn::make('vendor.name')
  247. ->sortable(),
  248. Tables\Columns\TextColumn::make('total')
  249. ->currency(),
  250. Tables\Columns\TextColumn::make('amount_paid')
  251. ->label('Amount Paid')
  252. ->currency(),
  253. Tables\Columns\TextColumn::make('amount_due')
  254. ->label('Amount Due')
  255. ->currency(),
  256. ]);
  257. }
  258. public static function getRelations(): array
  259. {
  260. return [
  261. //
  262. ];
  263. }
  264. public static function getPages(): array
  265. {
  266. return [
  267. 'index' => Pages\ListBills::route('/'),
  268. 'create' => Pages\CreateBill::route('/create'),
  269. 'edit' => Pages\EditBill::route('/{record}/edit'),
  270. ];
  271. }
  272. }