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.

MacroServiceProvider.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. <?php
  2. namespace App\Providers;
  3. use Akaunting\Money\Currency;
  4. use Akaunting\Money\Money;
  5. use App\Enums\Accounting\AdjustmentComputation;
  6. use App\Enums\Setting\DateFormat;
  7. use App\Models\Accounting\AccountSubtype;
  8. use App\Models\Setting\Localization;
  9. use App\Services\CompanySettingsService;
  10. use App\Utilities\Accounting\AccountCode;
  11. use App\Utilities\Currency\CurrencyAccessor;
  12. use App\Utilities\Currency\CurrencyConverter;
  13. use BackedEnum;
  14. use Carbon\CarbonInterface;
  15. use Closure;
  16. use Filament\Forms\Components\DatePicker;
  17. use Filament\Forms\Components\Field;
  18. use Filament\Forms\Components\TextInput;
  19. use Filament\Infolists\Components\TextEntry;
  20. use Filament\Support\Enums\IconPosition;
  21. use Filament\Support\RawJs;
  22. use Filament\Tables\Columns\TextColumn;
  23. use Filament\Tables\Contracts\HasTable;
  24. use Illuminate\Contracts\Support\Htmlable;
  25. use Illuminate\Support\Carbon;
  26. use Illuminate\Support\Collection;
  27. use Illuminate\Support\HtmlString;
  28. use Illuminate\Support\ServiceProvider;
  29. class MacroServiceProvider extends ServiceProvider
  30. {
  31. /**
  32. * Register services.
  33. */
  34. public function register(): void
  35. {
  36. //
  37. }
  38. /**
  39. * Bootstrap services.
  40. */
  41. public function boot(): void
  42. {
  43. Collection::macro('whereNot', function (callable | string $key, mixed $value = null): Collection {
  44. return $this->where($key, '!=', $value);
  45. });
  46. TextInput::macro('money', function (string | Closure | null $currency = null, bool $useAffix = true): static {
  47. $currency ??= CurrencyAccessor::getDefaultCurrency();
  48. if ($useAffix) {
  49. $this
  50. ->prefix(static function (TextInput $component) use ($currency) {
  51. $currency = $component->evaluate($currency);
  52. return currency($currency)->getPrefix();
  53. })
  54. ->suffix(static function (TextInput $component) use ($currency) {
  55. $currency = $component->evaluate($currency);
  56. return currency($currency)->getSuffix();
  57. });
  58. }
  59. $this->mask(RawJs::make('$money($input)'))
  60. ->dehydrateStateUsing(function (?string $state): ?int {
  61. if (blank($state)) {
  62. return null;
  63. }
  64. // Remove thousand separators
  65. $cleaned = str_replace(',', '', $state);
  66. // If no decimal point, assume it's whole dollars (add .00)
  67. if (! str_contains($cleaned, '.')) {
  68. $cleaned .= '.00';
  69. }
  70. // Convert to float then to cents (integer)
  71. return (int) round((float) $cleaned * 100);
  72. });
  73. return $this;
  74. });
  75. TextInput::macro('rate', function (string | Closure | null $computation = null, string | Closure | null $currency = null, bool $showAffix = true): static {
  76. return $this
  77. ->when(
  78. $showAffix,
  79. fn (TextInput $component) => $component
  80. ->prefix(function (TextInput $component) use ($computation, $currency) {
  81. $evaluatedComputation = $component->evaluate($computation);
  82. $evaluatedCurrency = $component->evaluate($currency);
  83. return ratePrefix($evaluatedComputation, $evaluatedCurrency);
  84. })
  85. ->suffix(function (TextInput $component) use ($computation, $currency) {
  86. $evaluatedComputation = $component->evaluate($computation);
  87. $evaluatedCurrency = $component->evaluate($currency);
  88. return rateSuffix($evaluatedComputation, $evaluatedCurrency);
  89. })
  90. )
  91. ->mask(static function (TextInput $component) use ($computation, $currency) {
  92. $computation = $component->evaluate($computation);
  93. $currency = $component->evaluate($currency);
  94. $computationEnum = AdjustmentComputation::parse($computation);
  95. if ($computationEnum->isPercentage()) {
  96. return rateMask(computation: $computation);
  97. }
  98. return moneyMask($currency);
  99. })
  100. ->rule(static function (TextInput $component) use ($computation) {
  101. return static function (string $attribute, $value, Closure $fail) use ($computation, $component) {
  102. $computation = $component->evaluate($computation);
  103. $numericValue = (float) $value;
  104. if ($computation instanceof BackedEnum) {
  105. $computation = $computation->value;
  106. }
  107. if ($computation === 'percentage' || $computation === 'compound') {
  108. if ($numericValue < 0 || $numericValue > 100) {
  109. $fail(translate('The rate must be between 0 and 100.'));
  110. }
  111. } elseif ($computation === 'fixed' && $numericValue < 0) {
  112. $fail(translate('The rate must be greater than 0.'));
  113. }
  114. };
  115. });
  116. });
  117. TextColumn::macro('coloredDescription', function (string | Htmlable | Closure | null $description, string $color = 'danger') {
  118. $this->description(static function (TextColumn $column) use ($description, $color): Htmlable {
  119. $description = $column->evaluate($description);
  120. return new HtmlString("<span class='text-{$color}-700 dark:text-{$color}-400'>{$description}</span>");
  121. });
  122. return $this;
  123. });
  124. TextColumn::macro('hideOnTabs', function (array $tabs): static {
  125. $this->toggleable(isToggledHiddenByDefault: function (HasTable $livewire) use ($tabs) {
  126. return in_array($livewire->activeTab, $tabs);
  127. });
  128. return $this;
  129. });
  130. TextColumn::macro('showOnTabs', function (array $tabs): static {
  131. $this->toggleable(isToggledHiddenByDefault: function (HasTable $livewire) use ($tabs) {
  132. return ! in_array($livewire->activeTab, $tabs);
  133. });
  134. return $this;
  135. });
  136. TextColumn::macro('defaultDateFormat', function (): static {
  137. $localization = Localization::firstOrFail();
  138. $dateFormat = $localization->date_format->value ?? DateFormat::DEFAULT;
  139. $timezone = $localization->timezone ?? Carbon::now()->timezoneName;
  140. $this->date($dateFormat, $timezone);
  141. return $this;
  142. });
  143. DatePicker::macro('defaultDateFormat', function (): static {
  144. $localization = Localization::firstOrFail();
  145. $dateFormat = $localization->date_format->value ?? DateFormat::DEFAULT;
  146. $timezone = $localization->timezone ?? Carbon::now()->timezoneName;
  147. $this->displayFormat($dateFormat)
  148. ->timezone($timezone);
  149. return $this;
  150. });
  151. TextColumn::macro('currency', function (string | Closure | null $currency = null, ?bool $convert = null): static {
  152. $currency ??= CurrencyAccessor::getDefaultCurrency();
  153. $convert ??= true;
  154. $this->formatStateUsing(static function (TextColumn $column, $state) use ($currency, $convert): ?string {
  155. if (blank($state)) {
  156. return null;
  157. }
  158. $currency = $column->evaluate($currency);
  159. $convert = $column->evaluate($convert);
  160. return money($state, $currency, $convert)->format();
  161. });
  162. return $this;
  163. });
  164. TextEntry::macro('currency', function (string | Closure | null $currency = null, ?bool $convert = null): static {
  165. $currency ??= CurrencyAccessor::getDefaultCurrency();
  166. $convert ??= true;
  167. $this->formatStateUsing(static function (TextEntry $entry, $state) use ($currency, $convert): ?string {
  168. if (blank($state)) {
  169. return null;
  170. }
  171. $currency = $entry->evaluate($currency);
  172. $convert = $entry->evaluate($convert);
  173. return money($state, $currency, $convert)->format();
  174. });
  175. return $this;
  176. });
  177. TextColumn::macro('currencyWithConversion', function (string | Closure | null $currency = null, ?bool $convertFromCents = null): static {
  178. $currency ??= CurrencyAccessor::getDefaultCurrency();
  179. $convertFromCents ??= false;
  180. $this->formatStateUsing(static function (TextColumn $column, $state) use ($currency, $convertFromCents): ?string {
  181. if (blank($state)) {
  182. return null;
  183. }
  184. $currency = $column->evaluate($currency);
  185. $showCurrency = $currency !== CurrencyAccessor::getDefaultCurrency();
  186. if ($convertFromCents) {
  187. $balanceInCents = $state;
  188. } else {
  189. $balanceInCents = CurrencyConverter::convertToCents($state, $currency);
  190. }
  191. if ($balanceInCents < 0) {
  192. return '(' . CurrencyConverter::formatCentsToMoney(abs($balanceInCents), $currency, $showCurrency) . ')';
  193. }
  194. return CurrencyConverter::formatCentsToMoney($balanceInCents, $currency, $showCurrency);
  195. });
  196. $this->description(static function (TextColumn $column, $state) use ($currency, $convertFromCents): ?string {
  197. if (blank($state)) {
  198. return null;
  199. }
  200. $oldCurrency = $column->evaluate($currency);
  201. $newCurrency = CurrencyAccessor::getDefaultCurrency();
  202. if ($oldCurrency === $newCurrency) {
  203. return null;
  204. }
  205. if ($convertFromCents) {
  206. $balanceInCents = $state;
  207. } else {
  208. $balanceInCents = CurrencyConverter::convertToCents($state, $oldCurrency);
  209. }
  210. $convertedBalanceInCents = CurrencyConverter::convertBalance($balanceInCents, $oldCurrency, $newCurrency);
  211. if ($convertedBalanceInCents < 0) {
  212. return '(' . CurrencyConverter::formatCentsToMoney(abs($convertedBalanceInCents), $newCurrency, true) . ')';
  213. }
  214. return CurrencyConverter::formatCentsToMoney($convertedBalanceInCents, $newCurrency, true);
  215. });
  216. return $this;
  217. });
  218. TextEntry::macro('currencyWithConversion', function (string | Closure | null $currency = null): static {
  219. $currency ??= CurrencyAccessor::getDefaultCurrency();
  220. $this->formatStateUsing(static function (TextEntry $entry, $state) use ($currency): ?string {
  221. if (blank($state)) {
  222. return null;
  223. }
  224. $currency = $entry->evaluate($currency);
  225. return CurrencyConverter::formatToMoney($state, $currency);
  226. });
  227. $this->helperText(static function (TextEntry $entry, $state) use ($currency): ?string {
  228. if (blank($state)) {
  229. return null;
  230. }
  231. $oldCurrency = $entry->evaluate($currency);
  232. $newCurrency = CurrencyAccessor::getDefaultCurrency();
  233. if ($oldCurrency === $newCurrency) {
  234. return null;
  235. }
  236. $balanceInCents = CurrencyConverter::convertToCents($state, $oldCurrency);
  237. $convertedBalanceInCents = CurrencyConverter::convertBalance($balanceInCents, $oldCurrency, $newCurrency);
  238. return CurrencyConverter::formatCentsToMoney($convertedBalanceInCents, $newCurrency, true);
  239. });
  240. return $this;
  241. });
  242. Field::macro('validateAccountCode', function (string | Closure | null $subtype = null): static {
  243. $this
  244. ->rules([
  245. fn (Field $component): Closure => static function (string $attribute, $value, Closure $fail) use ($subtype, $component) {
  246. $subtype = $component->evaluate($subtype);
  247. $chartSubtype = AccountSubtype::find($subtype);
  248. $type = $chartSubtype->type;
  249. if (! AccountCode::isValidCode($value, $type)) {
  250. $message = AccountCode::getMessage($type);
  251. $fail($message);
  252. }
  253. },
  254. ]);
  255. return $this;
  256. });
  257. TextColumn::macro('rate', function (string | Closure | null $computation = null): static {
  258. $this->formatStateUsing(static function (TextColumn $column, $state) use ($computation): ?string {
  259. $computation = $column->evaluate($computation);
  260. return rateFormat(state: $state, computation: $computation);
  261. });
  262. return $this;
  263. });
  264. Field::macro('softRequired', function (): static {
  265. $this
  266. ->required()
  267. ->markAsRequired(false);
  268. return $this;
  269. });
  270. TextColumn::macro('asRelativeDay', function (?string $timezone = null): static {
  271. $this->formatStateUsing(function (TextColumn $column, mixed $state) use ($timezone) {
  272. if (blank($state)) {
  273. return null;
  274. }
  275. $date = Carbon::parse($state)
  276. ->setTimezone($timezone ?? $column->getTimezone());
  277. if ($date->isToday()) {
  278. return 'Today';
  279. }
  280. return $date->diffForHumans([
  281. 'options' => CarbonInterface::ONE_DAY_WORDS,
  282. ]);
  283. });
  284. return $this;
  285. });
  286. TextEntry::macro('asRelativeDay', function (?string $timezone = null): static {
  287. $this->formatStateUsing(function (TextEntry $entry, mixed $state) use ($timezone) {
  288. if (blank($state)) {
  289. return null;
  290. }
  291. $date = Carbon::parse($state)
  292. ->setTimezone($timezone ?? $entry->getTimezone());
  293. if ($date->isToday()) {
  294. return 'Today';
  295. }
  296. return $date->diffForHumans([
  297. 'options' => CarbonInterface::ONE_DAY_WORDS,
  298. ]);
  299. });
  300. return $this;
  301. });
  302. TextEntry::macro('link', function (bool $condition = true): static {
  303. if ($condition) {
  304. $this
  305. ->limit(50)
  306. ->openUrlInNewTab()
  307. ->icon('heroicon-o-arrow-top-right-on-square')
  308. ->iconColor('primary')
  309. ->iconPosition(IconPosition::After);
  310. }
  311. return $this;
  312. });
  313. Money::macro('swapAmountFor', function ($newCurrency) {
  314. $oldCurrency = $this->currency->getCurrency();
  315. $balanceInSubunits = $this->getAmount();
  316. $oldCurrencySubunit = currency($oldCurrency)->getSubunit();
  317. $newCurrencySubunit = currency($newCurrency)->getSubunit();
  318. $balanceInMajorUnits = $balanceInSubunits / $oldCurrencySubunit;
  319. $oldRate = currency($oldCurrency)->getRate();
  320. $newRate = currency($newCurrency)->getRate();
  321. $ratio = $newRate / $oldRate;
  322. $convertedBalanceInMajorUnits = $balanceInMajorUnits * $ratio;
  323. $roundedConvertedBalanceInMajorUnits = round($convertedBalanceInMajorUnits, currency($newCurrency)->getPrecision());
  324. $convertedBalanceInSubunits = $roundedConvertedBalanceInMajorUnits * $newCurrencySubunit;
  325. return (int) round($convertedBalanceInSubunits);
  326. });
  327. Money::macro('formatWithCode', function (bool $codeBefore = false) {
  328. $formatted = $this->format();
  329. $currencyCode = $this->currency->getCurrency();
  330. if ($codeBefore) {
  331. return $currencyCode . ' ' . $formatted;
  332. }
  333. return $formatted . ' ' . $currencyCode;
  334. });
  335. Currency::macro('getEntity', function () {
  336. $currencyCode = $this->getCurrency();
  337. $entity = config("money.currencies.{$currencyCode}.entity");
  338. return $entity ?? $currencyCode;
  339. });
  340. Currency::macro('getCodePrefix', function () {
  341. if ($this->isSymbolFirst()) {
  342. return '';
  343. }
  344. return ' ' . $this->getCurrency();
  345. });
  346. Currency::macro('getCodeSuffix', function () {
  347. if ($this->isSymbolFirst()) {
  348. return ' ' . $this->getCurrency();
  349. }
  350. return '';
  351. });
  352. Carbon::macro('toDefaultDateFormat', function () {
  353. $companyId = auth()->user()?->current_company_id;
  354. $dateFormat = CompanySettingsService::getDefaultDateFormat($companyId);
  355. $timezone = CompanySettingsService::getDefaultTimezone($companyId);
  356. return $this->setTimezone($timezone)->format($dateFormat);
  357. });
  358. }
  359. }