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.

Budget.php 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Concerns\Blamable;
  4. use App\Concerns\CompanyOwned;
  5. use App\Enums\Accounting\BudgetIntervalType;
  6. use App\Enums\Accounting\BudgetStatus;
  7. use App\Filament\Company\Resources\Accounting\BudgetResource;
  8. use Filament\Actions\Action;
  9. use Filament\Actions\MountableAction;
  10. use Filament\Actions\ReplicateAction;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Database\Eloquent\Casts\Attribute;
  13. use Illuminate\Database\Eloquent\Factories\HasFactory;
  14. use Illuminate\Database\Eloquent\Model;
  15. use Illuminate\Database\Eloquent\Relations\HasMany;
  16. use Illuminate\Database\Eloquent\Relations\HasManyThrough;
  17. use Illuminate\Support\Carbon;
  18. class Budget extends Model
  19. {
  20. use Blamable;
  21. use CompanyOwned;
  22. use HasFactory;
  23. protected $fillable = [
  24. 'company_id',
  25. 'name',
  26. 'start_date',
  27. 'end_date',
  28. 'status', // draft, active, closed
  29. 'interval_type', // day, week, month, quarter, year
  30. 'notes',
  31. 'approved_at',
  32. 'closed_at',
  33. 'created_by',
  34. 'updated_by',
  35. ];
  36. protected $casts = [
  37. 'start_date' => 'date',
  38. 'end_date' => 'date',
  39. 'status' => BudgetStatus::class,
  40. 'interval_type' => BudgetIntervalType::class,
  41. 'approved_at' => 'datetime',
  42. 'closed_at' => 'datetime',
  43. ];
  44. public function budgetItems(): HasMany
  45. {
  46. return $this->hasMany(BudgetItem::class);
  47. }
  48. public function allocations(): HasManyThrough
  49. {
  50. return $this->hasManyThrough(BudgetAllocation::class, BudgetItem::class);
  51. }
  52. public function isDraft(): bool
  53. {
  54. return $this->status === BudgetStatus::Draft;
  55. }
  56. public function isActive(): bool
  57. {
  58. return $this->status === BudgetStatus::Active;
  59. }
  60. public function isClosed(): bool
  61. {
  62. return $this->status === BudgetStatus::Closed;
  63. }
  64. public function wasApproved(): bool
  65. {
  66. return $this->approved_at !== null;
  67. }
  68. public function wasClosed(): bool
  69. {
  70. return $this->closed_at !== null;
  71. }
  72. public function canBeApproved(): bool
  73. {
  74. return $this->isDraft() && ! $this->wasApproved();
  75. }
  76. public function canBeClosed(): bool
  77. {
  78. return $this->isActive() && ! $this->wasClosed();
  79. }
  80. public function hasItems(): bool
  81. {
  82. return $this->budgetItems()->exists();
  83. }
  84. public function hasAllocations(): bool
  85. {
  86. return $this->allocations()->exists();
  87. }
  88. public function scopeDraft(Builder $query): Builder
  89. {
  90. return $query->where('status', BudgetStatus::Draft);
  91. }
  92. public function scopeActive(Builder $query): Builder
  93. {
  94. return $query->where('status', BudgetStatus::Active);
  95. }
  96. public function scopeClosed(Builder $query): Builder
  97. {
  98. return $query->where('status', BudgetStatus::Closed);
  99. }
  100. public function scopeCurrentlyActive(Builder $query): Builder
  101. {
  102. return $query->active()
  103. ->where('start_date', '<=', now())
  104. ->where('end_date', '>=', now());
  105. }
  106. protected function isCurrentlyInPeriod(): Attribute
  107. {
  108. return Attribute::get(function () {
  109. return now()->between($this->start_date, $this->end_date);
  110. });
  111. }
  112. /**
  113. * Approve a draft budget
  114. */
  115. public function approveDraft(?Carbon $approvedAt = null): void
  116. {
  117. if (! $this->canBeApproved()) {
  118. throw new \RuntimeException('Budget cannot be approved.');
  119. }
  120. $approvedAt ??= now();
  121. $this->update([
  122. 'status' => BudgetStatus::Active,
  123. 'approved_at' => $approvedAt,
  124. ]);
  125. }
  126. /**
  127. * Close an active budget
  128. */
  129. public function close(?Carbon $closedAt = null): void
  130. {
  131. if (! $this->canBeClosed()) {
  132. throw new \RuntimeException('Budget cannot be closed.');
  133. }
  134. $closedAt ??= now();
  135. $this->update([
  136. 'status' => BudgetStatus::Closed,
  137. 'closed_at' => $closedAt,
  138. ]);
  139. }
  140. /**
  141. * Reopen a closed budget
  142. */
  143. public function reopen(): void
  144. {
  145. if (! $this->isClosed()) {
  146. throw new \RuntimeException('Only closed budgets can be reopened.');
  147. }
  148. $this->update([
  149. 'status' => BudgetStatus::Active,
  150. 'closed_at' => null,
  151. ]);
  152. }
  153. /**
  154. * Get Action for approving a draft budget
  155. */
  156. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  157. {
  158. return $action::make('approveDraft')
  159. ->label('Approve')
  160. ->icon('heroicon-m-check-circle')
  161. ->visible(function (self $record) {
  162. return $record->canBeApproved();
  163. })
  164. ->databaseTransaction()
  165. ->successNotificationTitle('Budget approved')
  166. ->action(function (self $record, MountableAction $action) {
  167. $record->approveDraft();
  168. $action->success();
  169. });
  170. }
  171. /**
  172. * Get Action for closing an active budget
  173. */
  174. public static function getCloseAction(string $action = Action::class): MountableAction
  175. {
  176. return $action::make('close')
  177. ->label('Close')
  178. ->icon('heroicon-m-lock-closed')
  179. ->color('warning')
  180. ->visible(function (self $record) {
  181. return $record->canBeClosed();
  182. })
  183. ->requiresConfirmation()
  184. ->databaseTransaction()
  185. ->successNotificationTitle('Budget closed')
  186. ->action(function (self $record, MountableAction $action) {
  187. $record->close();
  188. $action->success();
  189. });
  190. }
  191. /**
  192. * Get Action for reopening a closed budget
  193. */
  194. public static function getReopenAction(string $action = Action::class): MountableAction
  195. {
  196. return $action::make('reopen')
  197. ->label('Reopen')
  198. ->icon('heroicon-m-lock-open')
  199. ->visible(function (self $record) {
  200. return $record->isClosed();
  201. })
  202. ->requiresConfirmation()
  203. ->databaseTransaction()
  204. ->successNotificationTitle('Budget reopened')
  205. ->action(function (self $record, MountableAction $action) {
  206. $record->reopen();
  207. $action->success();
  208. });
  209. }
  210. /**
  211. * Get Action for duplicating a budget
  212. */
  213. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  214. {
  215. return $action::make()
  216. ->excludeAttributes([
  217. 'status',
  218. 'approved_at',
  219. 'closed_at',
  220. 'created_by',
  221. 'updated_by',
  222. 'created_at',
  223. 'updated_at',
  224. ])
  225. ->modal(false)
  226. ->beforeReplicaSaved(function (self $original, self $replica) {
  227. $replica->status = BudgetStatus::Draft;
  228. $replica->name = $replica->name . ' (Copy)';
  229. })
  230. ->databaseTransaction()
  231. ->after(function (self $original, self $replica) {
  232. // Clone budget items and their allocations
  233. $original->budgetItems->each(function (BudgetItem $item) use ($replica) {
  234. $newItem = $item->replicate([
  235. 'budget_id',
  236. 'created_by',
  237. 'updated_by',
  238. 'created_at',
  239. 'updated_at',
  240. ]);
  241. $newItem->budget_id = $replica->id;
  242. $newItem->save();
  243. // Clone the allocations for this budget item
  244. $item->allocations->each(function (BudgetAllocation $allocation) use ($newItem) {
  245. $newAllocation = $allocation->replicate([
  246. 'budget_item_id',
  247. 'created_at',
  248. 'updated_at',
  249. ]);
  250. $newAllocation->budget_item_id = $newItem->id;
  251. $newAllocation->save();
  252. });
  253. });
  254. })
  255. ->successRedirectUrl(static function (self $replica) {
  256. return BudgetResource::getUrl('edit', ['record' => $replica]);
  257. });
  258. }
  259. }