Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Budget.php 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. /**
  53. * Get all periods for this budget in chronological order.
  54. *
  55. * @return array
  56. */
  57. public function getPeriods(): array
  58. {
  59. return $this->budgetItems()
  60. ->with('allocations')
  61. ->get()
  62. ->flatMap(fn ($item) => $item->allocations)
  63. ->sortBy('start_date')
  64. ->pluck('period')
  65. ->unique()
  66. ->values()
  67. ->toArray();
  68. }
  69. public function isDraft(): bool
  70. {
  71. return $this->status === BudgetStatus::Draft;
  72. }
  73. public function isActive(): bool
  74. {
  75. return $this->status === BudgetStatus::Active;
  76. }
  77. public function isClosed(): bool
  78. {
  79. return $this->status === BudgetStatus::Closed;
  80. }
  81. public function wasApproved(): bool
  82. {
  83. return $this->approved_at !== null;
  84. }
  85. public function wasClosed(): bool
  86. {
  87. return $this->closed_at !== null;
  88. }
  89. public function canBeApproved(): bool
  90. {
  91. return $this->isDraft() && ! $this->wasApproved();
  92. }
  93. public function canBeClosed(): bool
  94. {
  95. return $this->isActive() && ! $this->wasClosed();
  96. }
  97. public function hasItems(): bool
  98. {
  99. return $this->budgetItems()->exists();
  100. }
  101. public function hasAllocations(): bool
  102. {
  103. return $this->allocations()->exists();
  104. }
  105. public function scopeDraft(Builder $query): Builder
  106. {
  107. return $query->where('status', BudgetStatus::Draft);
  108. }
  109. public function scopeActive(Builder $query): Builder
  110. {
  111. return $query->where('status', BudgetStatus::Active);
  112. }
  113. public function scopeClosed(Builder $query): Builder
  114. {
  115. return $query->where('status', BudgetStatus::Closed);
  116. }
  117. public function scopeCurrentlyActive(Builder $query): Builder
  118. {
  119. return $query->active()
  120. ->where('start_date', '<=', now())
  121. ->where('end_date', '>=', now());
  122. }
  123. protected function isCurrentlyInPeriod(): Attribute
  124. {
  125. return Attribute::get(function () {
  126. return now()->between($this->start_date, $this->end_date);
  127. });
  128. }
  129. /**
  130. * Approve a draft budget
  131. */
  132. public function approveDraft(?Carbon $approvedAt = null): void
  133. {
  134. if (! $this->canBeApproved()) {
  135. throw new \RuntimeException('Budget cannot be approved.');
  136. }
  137. $approvedAt ??= now();
  138. $this->update([
  139. 'status' => BudgetStatus::Active,
  140. 'approved_at' => $approvedAt,
  141. ]);
  142. }
  143. /**
  144. * Close an active budget
  145. */
  146. public function close(?Carbon $closedAt = null): void
  147. {
  148. if (! $this->canBeClosed()) {
  149. throw new \RuntimeException('Budget cannot be closed.');
  150. }
  151. $closedAt ??= now();
  152. $this->update([
  153. 'status' => BudgetStatus::Closed,
  154. 'closed_at' => $closedAt,
  155. ]);
  156. }
  157. /**
  158. * Reopen a closed budget
  159. */
  160. public function reopen(): void
  161. {
  162. if (! $this->isClosed()) {
  163. throw new \RuntimeException('Only closed budgets can be reopened.');
  164. }
  165. $this->update([
  166. 'status' => BudgetStatus::Active,
  167. 'closed_at' => null,
  168. ]);
  169. }
  170. /**
  171. * Get Action for approving a draft budget
  172. */
  173. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  174. {
  175. return $action::make('approveDraft')
  176. ->label('Approve')
  177. ->icon('heroicon-m-check-circle')
  178. ->visible(function (self $record) {
  179. return $record->canBeApproved();
  180. })
  181. ->databaseTransaction()
  182. ->successNotificationTitle('Budget approved')
  183. ->action(function (self $record, MountableAction $action) {
  184. $record->approveDraft();
  185. $action->success();
  186. });
  187. }
  188. /**
  189. * Get Action for closing an active budget
  190. */
  191. public static function getCloseAction(string $action = Action::class): MountableAction
  192. {
  193. return $action::make('close')
  194. ->label('Close')
  195. ->icon('heroicon-m-lock-closed')
  196. ->color('warning')
  197. ->visible(function (self $record) {
  198. return $record->canBeClosed();
  199. })
  200. ->requiresConfirmation()
  201. ->databaseTransaction()
  202. ->successNotificationTitle('Budget closed')
  203. ->action(function (self $record, MountableAction $action) {
  204. $record->close();
  205. $action->success();
  206. });
  207. }
  208. /**
  209. * Get Action for reopening a closed budget
  210. */
  211. public static function getReopenAction(string $action = Action::class): MountableAction
  212. {
  213. return $action::make('reopen')
  214. ->label('Reopen')
  215. ->icon('heroicon-m-lock-open')
  216. ->visible(function (self $record) {
  217. return $record->isClosed();
  218. })
  219. ->requiresConfirmation()
  220. ->databaseTransaction()
  221. ->successNotificationTitle('Budget reopened')
  222. ->action(function (self $record, MountableAction $action) {
  223. $record->reopen();
  224. $action->success();
  225. });
  226. }
  227. /**
  228. * Get Action for duplicating a budget
  229. */
  230. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  231. {
  232. return $action::make()
  233. ->excludeAttributes([
  234. 'status',
  235. 'approved_at',
  236. 'closed_at',
  237. 'created_by',
  238. 'updated_by',
  239. 'created_at',
  240. 'updated_at',
  241. ])
  242. ->modal(false)
  243. ->beforeReplicaSaved(function (self $original, self $replica) {
  244. $replica->status = BudgetStatus::Draft;
  245. $replica->name = $replica->name . ' (Copy)';
  246. })
  247. ->databaseTransaction()
  248. ->after(function (self $original, self $replica) {
  249. // Clone budget items and their allocations
  250. $original->budgetItems->each(function (BudgetItem $item) use ($replica) {
  251. $newItem = $item->replicate([
  252. 'budget_id',
  253. 'created_by',
  254. 'updated_by',
  255. 'created_at',
  256. 'updated_at',
  257. ]);
  258. $newItem->budget_id = $replica->id;
  259. $newItem->save();
  260. // Clone the allocations for this budget item
  261. $item->allocations->each(function (BudgetAllocation $allocation) use ($newItem) {
  262. $newAllocation = $allocation->replicate([
  263. 'budget_item_id',
  264. 'created_at',
  265. 'updated_at',
  266. ]);
  267. $newAllocation->budget_item_id = $newItem->id;
  268. $newAllocation->save();
  269. });
  270. });
  271. })
  272. ->successRedirectUrl(static function (self $replica) {
  273. return BudgetResource::getUrl('edit', ['record' => $replica]);
  274. });
  275. }
  276. }