Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

MacroServiceProvider.php 16KB

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