From 9222c82af082b3b770a986798c9aec1463fc6ed1 Mon Sep 17 00:00:00 2001 From: James Cole Date: Sun, 25 Feb 2024 18:09:52 +0100 Subject: [PATCH] Expand frontend, first attempt at sorting. --- .../List/TransactionController.php | 13 +- ...untRequest.php => InfiniteListRequest.php} | 27 +- .../Extensions/CollectorProperties.php | 2 + app/Helpers/Collector/GroupCollector.php | 119 ++++--- .../Collector/GroupCollectorInterface.php | 19 ++ app/Http/Controllers/DebugController.php | 28 +- config/firefly.php | 7 + public/build/assets/create-6dc4ec8c.js | 1 + ...6a0d.js => create-empty-split-c1e678fd.js} | 2 +- public/build/assets/create-f971d025.js | 1 - ...oard-52719b55.js => dashboard-ff9938f0.js} | 2 +- .../{edit-203e67aa.js => edit-0910e359.js} | 2 +- ...y-276370ed.js => format-money-2cbd3c32.js} | 2 +- .../{get-5385bfb8.js => get-4f3e9dd6.js} | 2 +- public/build/assets/get-9c5eaf42.js | 1 - public/build/assets/get-f02d6b9c.js | 1 + public/build/assets/index-5175d98b.js | 1 - public/build/assets/index-b671e1f6.js | 1 + ...js => parse-downloaded-splits-a5d66b5f.js} | 2 +- .../{put-016ad2aa.js => put-375c2f08.js} | 2 +- .../{show-02715d84.js => show-56332d03.js} | 2 +- ...lice-errors-into-transactions-8731db70.js} | 2 +- public/build/assets/vendor-47e474ee.js | 314 +++++++++++++++++ public/build/assets/vendor-5c5099b4.css | 1 + public/build/assets/vendor-6fbf50c2.css | 1 - public/build/assets/vendor-7d6e65fe.js | 315 ------------------ public/build/manifest.json | 146 ++++---- public/v2/i18n/bg.json | 43 +++ public/v2/i18n/ca.json | 43 +++ public/v2/i18n/cs.json | 43 +++ public/v2/i18n/da.json | 43 +++ public/v2/i18n/de.json | 43 +++ public/v2/i18n/el.json | 43 +++ public/v2/i18n/en-gb.json | 43 +++ public/v2/i18n/es.json | 43 +++ public/v2/i18n/fi.json | 43 +++ public/v2/i18n/fr.json | 43 +++ public/v2/i18n/hu.json | 43 +++ public/v2/i18n/id.json | 43 +++ public/v2/i18n/it.json | 43 +++ public/v2/i18n/ja.json | 43 +++ public/v2/i18n/ko.json | 43 +++ public/v2/i18n/nb.json | 43 +++ public/v2/i18n/nl.json | 43 +++ public/v2/i18n/nn.json | 43 +++ public/v2/i18n/pl.json | 43 +++ public/v2/i18n/pt-br.json | 43 +++ public/v2/i18n/pt.json | 43 +++ public/v2/i18n/pt_PT.json | 38 +-- public/v2/i18n/ro.json | 43 +++ public/v2/i18n/ru.json | 43 +++ public/v2/i18n/sk.json | 43 +++ public/v2/i18n/sl.json | 43 +++ public/v2/i18n/sv.json | 43 +++ public/v2/i18n/tr.json | 43 +++ public/v2/i18n/uk.json | 43 +++ public/v2/i18n/vi.json | 43 +++ public/v2/i18n/zh-cn.json | 43 +++ public/v2/i18n/zh-tw.json | 43 +++ resources/assets/js/locales/cs.json | 60 ++-- resources/assets/js/locales/pt.json | 4 +- .../assets/v2/api/v2/model/transaction/get.js | 4 +- .../assets/v2/pages/transactions/create.js | 5 + .../assets/v2/pages/transactions/index.js | 63 ++-- .../support/ag-grid/TransactionDataSource.js | 13 +- routes/api.php | 7 +- 66 files changed, 1989 insertions(+), 554 deletions(-) rename app/Api/V2/Request/Model/Transaction/{ListByCountRequest.php => InfiniteListRequest.php} (77%) create mode 100644 public/build/assets/create-6dc4ec8c.js rename public/build/assets/{create-empty-split-d23e6a0d.js => create-empty-split-c1e678fd.js} (93%) delete mode 100644 public/build/assets/create-f971d025.js rename public/build/assets/{dashboard-52719b55.js => dashboard-ff9938f0.js} (98%) rename public/build/assets/{edit-203e67aa.js => edit-0910e359.js} (94%) rename public/build/assets/{format-money-276370ed.js => format-money-2cbd3c32.js} (99%) rename public/build/assets/{get-5385bfb8.js => get-4f3e9dd6.js} (81%) delete mode 100644 public/build/assets/get-9c5eaf42.js create mode 100644 public/build/assets/get-f02d6b9c.js delete mode 100644 public/build/assets/index-5175d98b.js create mode 100644 public/build/assets/index-b671e1f6.js rename public/build/assets/{parse-downloaded-splits-7301d402.js => parse-downloaded-splits-a5d66b5f.js} (91%) rename public/build/assets/{put-016ad2aa.js => put-375c2f08.js} (55%) rename public/build/assets/{show-02715d84.js => show-56332d03.js} (98%) rename public/build/assets/{splice-errors-into-transactions-5f35da56.js => splice-errors-into-transactions-8731db70.js} (98%) create mode 100644 public/build/assets/vendor-47e474ee.js create mode 100644 public/build/assets/vendor-5c5099b4.css delete mode 100644 public/build/assets/vendor-6fbf50c2.css delete mode 100644 public/build/assets/vendor-7d6e65fe.js create mode 100644 public/v2/i18n/bg.json create mode 100644 public/v2/i18n/ca.json create mode 100644 public/v2/i18n/cs.json create mode 100644 public/v2/i18n/da.json create mode 100644 public/v2/i18n/de.json create mode 100644 public/v2/i18n/el.json create mode 100644 public/v2/i18n/en-gb.json create mode 100644 public/v2/i18n/es.json create mode 100644 public/v2/i18n/fi.json create mode 100644 public/v2/i18n/fr.json create mode 100644 public/v2/i18n/hu.json create mode 100644 public/v2/i18n/id.json create mode 100644 public/v2/i18n/it.json create mode 100644 public/v2/i18n/ja.json create mode 100644 public/v2/i18n/ko.json create mode 100644 public/v2/i18n/nb.json create mode 100644 public/v2/i18n/nl.json create mode 100644 public/v2/i18n/nn.json create mode 100644 public/v2/i18n/pl.json create mode 100644 public/v2/i18n/pt-br.json create mode 100644 public/v2/i18n/pt.json create mode 100644 public/v2/i18n/ro.json create mode 100644 public/v2/i18n/ru.json create mode 100644 public/v2/i18n/sk.json create mode 100644 public/v2/i18n/sl.json create mode 100644 public/v2/i18n/sv.json create mode 100644 public/v2/i18n/tr.json create mode 100644 public/v2/i18n/uk.json create mode 100644 public/v2/i18n/vi.json create mode 100644 public/v2/i18n/zh-cn.json create mode 100644 public/v2/i18n/zh-tw.json diff --git a/app/Api/V2/Controllers/Transaction/List/TransactionController.php b/app/Api/V2/Controllers/Transaction/List/TransactionController.php index 31c4924fc6..326c4cb907 100644 --- a/app/Api/V2/Controllers/Transaction/List/TransactionController.php +++ b/app/Api/V2/Controllers/Transaction/List/TransactionController.php @@ -24,7 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Api\V2\Controllers\Transaction\List; use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Model\Transaction\ListByCountRequest; +use FireflyIII\Api\V2\Request\Model\Transaction\InfiniteListRequest; use FireflyIII\Api\V2\Request\Model\Transaction\ListRequest; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Transformers\V2\TransactionGroupTransformer; @@ -60,9 +60,6 @@ class TransactionController extends Controller $collector->setEnd($end); } - // $collector->dumpQuery(); - // exit; - $paginator = $collector->getPaginatedGroups(); $params = $request->buildParams($pageSize); $paginator->setPath( @@ -79,8 +76,11 @@ class TransactionController extends Controller ; } - public function listByCount(ListByCountRequest $request): JsonResponse + public function infiniteList(InfiniteListRequest $request): JsonResponse { + // get sort instructions + $instructions = $request->getSortInstructions(); + // collect transactions: /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -89,6 +89,7 @@ class TransactionController extends Controller ->setStartRow($request->getStartRow()) ->setEndRow($request->getEndRow()) ->setTypes($request->getTransactionTypes()) + ->setSorting($instructions) ; $start = $this->parameters->get('start'); @@ -105,7 +106,7 @@ class TransactionController extends Controller $paginator->setPath( sprintf( '%s?%s', - route('api.v2.transactions.list'), + route('api.v2.infinite.transactions.list'), $params ) ); diff --git a/app/Api/V2/Request/Model/Transaction/ListByCountRequest.php b/app/Api/V2/Request/Model/Transaction/InfiniteListRequest.php similarity index 77% rename from app/Api/V2/Request/Model/Transaction/ListByCountRequest.php rename to app/Api/V2/Request/Model/Transaction/InfiniteListRequest.php index dbd9083667..c341890e1a 100644 --- a/app/Api/V2/Request/Model/Transaction/ListByCountRequest.php +++ b/app/Api/V2/Request/Model/Transaction/InfiniteListRequest.php @@ -31,10 +31,10 @@ use FireflyIII\Support\Request\ConvertsDataTypes; use Illuminate\Foundation\Http\FormRequest; /** - * Class ListRequest + * Class InfiniteListRequest * Used specifically to list transactions. */ -class ListByCountRequest extends FormRequest +class InfiniteListRequest extends FormRequest { use ChecksLogin; use ConvertsDataTypes; @@ -88,6 +88,29 @@ class ListByCountRequest extends FormRequest return 0 === $page || $page > 65536 ? 1 : $page; } + public function getSortInstructions(): array { + $allowed = config('firefly.sorting.allowed.transactions'); + $set = $this->get('sorting', []); + $result= []; + if(0 === count($set)) { + return []; + } + foreach($set as $info) { + $column = $info['column'] ?? 'NOPE'; + $direction = $info['direction'] ?? 'NOPE'; + if('asc' !== $direction && 'desc' !== $direction) { + // skip invalid direction + continue; + } + if(in_array($column, $allowed, true) === false) { + // skip invalid column + continue; + } + $result[$column] = $direction; + } + return $result; + } + public function getTransactionTypes(): array { $type = (string)$this->get('type', 'default'); diff --git a/app/Helpers/Collector/Extensions/CollectorProperties.php b/app/Helpers/Collector/Extensions/CollectorProperties.php index a9a71a9e43..aa8a3c58dc 100644 --- a/app/Helpers/Collector/Extensions/CollectorProperties.php +++ b/app/Helpers/Collector/Extensions/CollectorProperties.php @@ -33,6 +33,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany; */ trait CollectorProperties { + + public array $sorting; public const string TEST = 'Test'; private ?int $endRow; private bool $expandGroupSearch; diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php index fbeaef9a84..da37788608 100644 --- a/app/Helpers/Collector/GroupCollector.php +++ b/app/Helpers/Collector/GroupCollector.php @@ -25,7 +25,6 @@ namespace FireflyIII\Helpers\Collector; use Carbon\Carbon; use Carbon\Exceptions\InvalidFormatException; -use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Collector\Extensions\AccountCollection; use FireflyIII\Helpers\Collector\Extensions\AmountCollection; @@ -62,14 +61,15 @@ class GroupCollector implements GroupCollectorInterface */ public function __construct() { - $this->postFilters = []; - $this->tags = []; - $this->user = null; - $this->userGroup = null; - $this->limit = null; - $this->page = null; - $this->startRow = null; - $this->endRow = null; + $this->sorting = []; + $this->postFilters = []; + $this->tags = []; + $this->user = null; + $this->userGroup = null; + $this->limit = null; + $this->page = null; + $this->startRow = null; + $this->endRow = null; $this->hasAccountInfo = false; $this->hasCatInformation = false; @@ -291,7 +291,7 @@ class GroupCollector implements GroupCollectorInterface if (is_int($param)) { $replace = (string)$param; } - $pos = strpos($query, '?'); + $pos = strpos($query, '?'); if (false !== $pos) { $query = substr_replace($query, $replace, $pos, 1); } @@ -459,13 +459,16 @@ class GroupCollector implements GroupCollectorInterface // add to query: $this->query->orWhereIn('transaction_journals.transaction_group_id', $groupIds); } - $result = $this->query->get($this->fields); + $result = $this->query->get($this->fields); // now to parse this into an array. - $collection = $this->parseArray($result); + $collection = $this->parseArray($result); // filter the array using all available post filters: - $collection = $this->postFilterCollection($collection); + $collection = $this->postFilterCollection($collection); + + // sort the collection, if sort instructions are present. + $collection = $this->sortCollection($collection); // count it and continue: $this->total = $collection->count(); @@ -498,12 +501,12 @@ class GroupCollector implements GroupCollectorInterface /** @var TransactionJournal $augumentedJournal */ foreach ($collection as $augumentedJournal) { - $groupId = (int)$augumentedJournal->transaction_group_id; + $groupId = (int)$augumentedJournal->transaction_group_id; if (!array_key_exists($groupId, $groups)) { // make new array - $parsedGroup = $this->parseAugmentedJournal($augumentedJournal); - $groupArray = [ + $parsedGroup = $this->parseAugmentedJournal($augumentedJournal); + $groupArray = [ 'id' => (int)$augumentedJournal->transaction_group_id, 'user_id' => $augumentedJournal->user_id, 'user_group_id' => $augumentedJournal->user_group_id, @@ -575,7 +578,7 @@ class GroupCollector implements GroupCollectorInterface } // try to process meta date value (if present) - $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date']; + $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date']; if (array_key_exists('meta_name', $result) && in_array($result['meta_name'], $dates, true)) { $name = $result['meta_name']; if (array_key_exists('meta_data', $result) && '' !== (string)$result['meta_data']) { @@ -584,15 +587,15 @@ class GroupCollector implements GroupCollectorInterface } // convert values to integers: - $result = $this->convertToInteger($result); + $result = $this->convertToInteger($result); // convert back to strings because SQLite is dumb like that. - $result = $this->convertToStrings($result); + $result = $this->convertToStrings($result); - $result['reconciled'] = 1 === (int)$result['reconciled']; + $result['reconciled'] = 1 === (int)$result['reconciled']; if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well. - $tagId = (int)$augumentedJournal['tag_id']; - $tagDate = null; + $tagId = (int)$augumentedJournal['tag_id']; + $tagDate = null; try { $tagDate = Carbon::parse($augumentedJournal['tag_date']); @@ -656,9 +659,9 @@ class GroupCollector implements GroupCollectorInterface { $newArray = $newJournal->toArray(); if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well. - $tagId = (int)$newJournal['tag_id']; + $tagId = (int)$newJournal['tag_id']; - $tagDate = null; + $tagDate = null; try { $tagDate = Carbon::parse($newArray['tag_date']); @@ -681,7 +684,7 @@ class GroupCollector implements GroupCollectorInterface { $newArray = $newJournal->toArray(); if (array_key_exists('attachment_id', $newArray)) { - $attachmentId = (int)$newJournal['attachment_id']; + $attachmentId = (int)$newJournal['attachment_id']; $existingJournal['attachments'][$attachmentId] = [ 'id' => $attachmentId, @@ -700,7 +703,7 @@ class GroupCollector implements GroupCollectorInterface foreach ($groups as $groudId => $group) { /** @var array $transaction */ foreach ($group['transactions'] as $transaction) { - $currencyId = (int)$transaction['currency_id']; + $currencyId = (int)$transaction['currency_id']; if (null === $transaction['amount']) { throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId)); } @@ -716,7 +719,7 @@ class GroupCollector implements GroupCollectorInterface $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']); if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) { - $currencyId = (int)$transaction['foreign_currency_id']; + $currencyId = (int)$transaction['foreign_currency_id']; // set default: if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { @@ -749,7 +752,7 @@ class GroupCollector implements GroupCollectorInterface */ foreach ($this->postFilters as $function) { app('log')->debug('Applying filter...'); - $nextCollection = new Collection(); + $nextCollection = new Collection(); // loop everything in the current collection // and save it (or not) in the new collection. @@ -985,8 +988,7 @@ class GroupCollector implements GroupCollectorInterface 'transactions as source', static function (JoinClause $join): void { $join->on('source.transaction_journal_id', '=', 'transaction_journals.id') - ->where('source.amount', '<', 0) - ; + ->where('source.amount', '<', 0); } ) // join destination transaction @@ -994,8 +996,7 @@ class GroupCollector implements GroupCollectorInterface 'transactions as destination', static function (JoinClause $join): void { $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id') - ->where('destination.amount', '>', 0) - ; + ->where('destination.amount', '>', 0); } ) // left join transaction type. @@ -1010,8 +1011,7 @@ class GroupCollector implements GroupCollectorInterface ->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') - ->orderBy('source.amount', 'DESC') - ; + ->orderBy('source.amount', 'DESC'); } /** @@ -1042,8 +1042,7 @@ class GroupCollector implements GroupCollectorInterface 'transactions as source', static function (JoinClause $join): void { $join->on('source.transaction_journal_id', '=', 'transaction_journals.id') - ->where('source.amount', '<', 0) - ; + ->where('source.amount', '<', 0); } ) // join destination transaction @@ -1051,8 +1050,7 @@ class GroupCollector implements GroupCollectorInterface 'transactions as destination', static function (JoinClause $join): void { $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id') - ->where('destination.amount', '>', 0) - ; + ->where('destination.amount', '>', 0); } ) // left join transaction type. @@ -1067,8 +1065,7 @@ class GroupCollector implements GroupCollectorInterface ->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') - ->orderBy('source.amount', 'DESC') - ; + ->orderBy('source.amount', 'DESC'); } /** @@ -1079,13 +1076,47 @@ class GroupCollector implements GroupCollectorInterface // include source + destination account name and type. $this->withAccountInformation() // include category ID + name (if any) - ->withCategoryInformation() + ->withCategoryInformation() // include budget ID + name (if any) - ->withBudgetInformation() + ->withBudgetInformation() // include bill ID + name (if any) - ->withBillInformation() - ; + ->withBillInformation(); return $this; } + + /** + * @inheritDoc + */ + #[\Override] public function sortCollection(Collection $collection): Collection + { + foreach ($this->sorting as $field => $direction) { + $func = $direction === 'ASC' ? 'sortBy' : 'sortByDesc'; + $collection = $collection->$func(function (array $product, int $key) use ($field, $direction) { + // depends on $field: + if ('description' === $field) { + if (1 === count($product['transactions'])) { + return array_values($product['transactions'])[0][$field]; + } + if (count($product['transactions']) > 1) { + return $product['title']; + } + return 'zzz'; + } + die('here we are'); + }); + } + + + return $collection; + } + + /** + * @inheritDoc + */ + #[\Override] public function setSorting(array $instructions): GroupCollectorInterface + { + $this->sorting = $instructions; + return $this; + } } diff --git a/app/Helpers/Collector/GroupCollectorInterface.php b/app/Helpers/Collector/GroupCollectorInterface.php index d80ee79f2c..d2d26b70b1 100644 --- a/app/Helpers/Collector/GroupCollectorInterface.php +++ b/app/Helpers/Collector/GroupCollectorInterface.php @@ -285,6 +285,25 @@ interface GroupCollectorInterface */ public function getPaginatedGroups(): LengthAwarePaginator; + /** + * + * + * @param array $instructions + * + * @return self + */ + public function setSorting(array $instructions): self; + + + /** + * Sort the collection on a column. + * + * @param Collection $collection + * + * @return Collection + */ + public function sortCollection(Collection $collection): Collection; + public function hasAnyTag(): self; /** diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php index 745e4d8cf4..a1b96fe76e 100644 --- a/app/Http/Controllers/DebugController.php +++ b/app/Http/Controllers/DebugController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; use Carbon\Carbon; -use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Middleware\IsDemoUser; use FireflyIII\Models\AccountType; @@ -116,12 +115,12 @@ class DebugController extends Controller */ public function index() { - $table = $this->generateTable(); - $table = str_replace(["\n", "\t", ' '], '', $table); - $now = now(config('app.timezone'))->format('Y-m-d H:i:s'); + $table = $this->generateTable(); + $table = str_replace(["\n", "\t", ' '], '', $table); + $now = now(config('app.timezone'))->format('Y-m-d H:i:s'); // get latest log file: - $logger = Log::driver(); + $logger = Log::driver(); // PHPstan doesn't recognize the method because of its polymorphic nature. $handlers = $logger->getHandlers(); // @phpstan-ignore-line $logContent = ''; @@ -135,7 +134,7 @@ class DebugController extends Controller } if ('' !== $logContent) { // last few lines - $logContent = 'Truncated from this point <----|'.substr((string)$logContent, -16384); + $logContent = 'Truncated from this point <----|' . substr((string)$logContent, -16384); } return view('debug', compact('table', 'now', 'logContent')); @@ -188,6 +187,7 @@ class DebugController extends Controller try { if (file_exists('/var/www/counter-main.txt')) { $return['build'] = trim((string)file_get_contents('/var/www/counter-main.txt')); + app('log')->debug(sprintf('build is now "%s"', $return['build'])); } } catch (\Exception $e) { // @phpstan-ignore-line app('log')->debug('Could not check build counter, but thats ok.'); @@ -214,7 +214,7 @@ class DebugController extends Controller private function getAppInfo(): array { - $userGuard = config('auth.defaults.guard'); + $userGuard = config('auth.defaults.guard'); $config = app('fireflyconfig')->get('last_rt_job', 0); $lastTime = (int)$config->data; @@ -239,24 +239,24 @@ class DebugController extends Controller // any of the cron jobs will do, they always run at the same time. // but this job is the oldest, so the biggest chance it ran once - 'last_cronjob' => $lastCronjob, - 'last_cronjob_ago' => $lastCronjobAgo, + 'last_cronjob' => $lastCronjob, + 'last_cronjob_ago' => $lastCronjobAgo, ]; } private function getuserInfo(): array { - $userFlags = $this->getUserFlags(); + $userFlags = $this->getUserFlags(); // user info - $userAgent = request()->header('user-agent'); + $userAgent = request()->header('user-agent'); // set languages, see what happens: $original = setlocale(LC_ALL, '0'); $localeAttempts = []; $parts = app('steam')->getLocaleArray(app('steam')->getLocale()); foreach ($parts as $code) { - $code = trim($code); + $code = trim($code); app('log')->debug(sprintf('Trying to set %s', $code)); $result = setlocale(LC_ALL, $code); $localeAttempts[$code] = $result === $code; @@ -280,7 +280,7 @@ class DebugController extends Controller $flags = []; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); // has liabilities if ($user->accounts()->accountTypeIn([AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE])->count() > 0) { @@ -293,7 +293,7 @@ class DebugController extends Controller } // has stored reconciliations - $type = TransactionType::whereType(TransactionType::RECONCILIATION)->first(); + $type = TransactionType::whereType(TransactionType::RECONCILIATION)->first(); if ($user->transactionJournals()->where('transaction_type_id', $type->id)->count() > 0) { $flags[] = ':ledger:'; } diff --git a/config/firefly.php b/config/firefly.php index 9ae1514036..76c440fec8 100644 --- a/config/firefly.php +++ b/config/firefly.php @@ -912,4 +912,11 @@ return [ // preselected account lists possibilities: 'preselected_accounts' => ['all', 'assets', 'liabilities'], + + // allowed sort columns for API's + 'sorting' => [ + 'allowed' => [ + 'transactions' => ['description','amount'], + ], + ], ]; diff --git a/public/build/assets/create-6dc4ec8c.js b/public/build/assets/create-6dc4ec8c.js new file mode 100644 index 0000000000..b9c41a4df9 --- /dev/null +++ b/public/build/assets/create-6dc4ec8c.js @@ -0,0 +1 @@ +import{a as m,d as y,f as d}from"./format-money-2cbd3c32.js";import{d as w,c as b}from"./create-empty-split-c1e678fd.js";import{l as v,a as T,b as C,c as P,p as _,d as E,s as L,e as c,f as S,g as D,h as A,i as k,j as x,k as h,m as p}from"./splice-errors-into-transactions-8731db70.js";import{l,i as r,m as B}from"./vendor-47e474ee.js";import"./get-4f3e9dd6.js";class M{post(t){let s="/api/v2/transactions";return m.post(s,t)}}let n=[],u=[];document.addEventListener("location-remove",e=>{u[e.detail.index].remove()});function O(e){let t=0;if(document.querySelector("#form")._x_dataStack[0].$data.entries[t].hasLocation===!1){u[t]=new l.marker(e.latlng,{draggable:!0}),u[t].on("dragend",U),u[t].addTo(n[t]);const o=new CustomEvent("location-set",{detail:{latitude:e.latlng.lat,longitude:e.latlng.lng,index:t,zoomLevel:n[t].getZoom()}});document.dispatchEvent(o)}}function F(e){let t=0;const s=new CustomEvent("location-zoom",{detail:{index:t,zoomLevel:n[t].getZoom()}});document.dispatchEvent(s)}function U(e){let t=e.target,s=t.getLatLng();t.setLatLng(new l.LatLng(s.lat,s.lng),{draggable:"true"});const o=new CustomEvent("location-move",{detail:{latitude:s.lat,longitude:s.lng,index:0}});document.dispatchEvent(o)}function z(e){if(e>0){console.warn("Corwardly refuse to add a map on split #"+(e+1));return}if(typeof n[e]>"u"){let t=document.getElementById("location_map");t&&(n[e]=l.map(t).setView([t.dataset.latitude,t.dataset.longitude],t.dataset.zoomLevel),l.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{maxZoom:19,attribution:'© OpenStreetMap'}).addTo(n[e]),n[e].on("click",O),n[e].on("zoomend",F))}}const a=x();let I=function(){return{entries:[],formStates:{loadingCurrencies:!0,loadingBudgets:!0,loadingPiggyBanks:!0,loadingSubscriptions:!0,isSubmitting:!1,returnHereButton:!1,saveAsNewButton:!1,resetButton:!0,rulesButton:!0,webhooksButton:!0},formBehaviour:{formType:"create",foreignCurrencyEnabled:!0},formData:{defaultCurrency:null,enabledCurrencies:[],nativeCurrencies:[],foreignCurrencies:[],budgets:[],piggyBanks:[],subscriptions:[]},groupProperties:{transactionType:"unknown",title:null,id:null,totalAmount:0},notifications:{error:{show:!1,text:"",url:""},success:{show:!1,text:"",url:""},wait:{show:!1,text:""}},filters:{source:[],destination:[]},changedDateTime(e){console.warn("changedDateTime, event is not used")},changedDescription(e){console.warn("changedDescription, event is not used")},changedDestinationAccount(e){this.detectTransactionType()},changedSourceAccount(e){this.detectTransactionType()},detectTransactionType(){const e=this.entries[0].source_account.type??"unknown",t=this.entries[0].destination_account.type??"unknown";if(e==="unknown"&&t==="unknown"){this.groupProperties.transactionType="unknown",console.warn("Cannot infer transaction type from two unknown accounts.");return}if(e===t&&["Asset account","Loan","Debt","Mortgage"].includes(e)){this.groupProperties.transactionType="transfer",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),console.log("filter down currencies for transfer."),this.filterNativeCurrencies(this.entries[0].source_account.currency_code),this.filterForeignCurrencies(this.entries[0].destination_account.currency_code);return}if(e==="Asset account"&&["Expense account","Debt","Loan","Mortgage"].includes(t)){this.groupProperties.transactionType="withdrawal",console.log('[a] Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(e==="Asset account"&&t==="unknown"){this.groupProperties.transactionType="withdrawal",console.log('[b] Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),console.log(this.entries[0].source_account),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(["Debt","Loan","Mortgage"].includes(e)&&t==="Expense account"){this.groupProperties.transactionType="withdrawal",console.log('[c] Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(e==="Revenue account"&&["Asset account","Debt","Loan","Mortgage"].includes(t)){this.groupProperties.transactionType="deposit",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".');return}if(e==="unknown"&&["Asset account","Debt","Loan","Mortgage"].includes(t)){this.groupProperties.transactionType="deposit",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".');return}if(["Debt","Loan","Mortgage"].includes(e)&&t==="Asset account"){this.groupProperties.transactionType="deposit",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".');return}console.warn('Unknown account combination between "'+e+'" and "'+t+'".')},formattedTotalAmount(){return this.entries.length===0?d(this.groupProperties.totalAmount,"EUR"):d(this.groupProperties.totalAmount,this.entries[0].currency_code??"EUR")},filterForeignCurrencies(e){let t=[],s;for(let o in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(o)){let i=this.formData.enabledCurrencies[o];i.code===e&&(s=i)}t.push(s),this.formData.foreignCurrencies=t,t.length===1&&t[0].code===this.entries[0].source_account.currency_code&&(console.log("Foreign currency is same as source currency. Disable foreign amount."),this.formBehaviour.foreignCurrencyEnabled=!1),t.length===1&&t[0].code!==this.entries[0].source_account.currency_code&&(console.log("Foreign currency is NOT same as source currency. Enable foreign amount."),this.formBehaviour.foreignCurrencyEnabled=!0);for(let o in this.entries)this.entries.hasOwnProperty(o)&&(this.entries[o].foreign_currency_code=e)},filterNativeCurrencies(e){let t=[],s;for(let o in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(o)){let i=this.formData.enabledCurrencies[o];i.code===e&&(s=i)}t.push(s),this.formData.nativeCurrencies=t;for(let o in this.entries)this.entries.hasOwnProperty(o)&&(this.entries[o].currency_code=e)},changedAmount(e){const t=parseInt(e.target.dataset.index);this.entries[t].amount=parseFloat(e.target.value),this.groupProperties.totalAmount=0;for(let s in this.entries)this.entries.hasOwnProperty(s)&&(this.groupProperties.totalAmount=this.groupProperties.totalAmount+parseFloat(this.entries[s].amount))},addedSplit(){},processUpload(e){this.showMessageOrRedirectUser()},processUploadError(e){this.notifications.success.show=!1,this.notifications.wait.show=!1,this.notifications.error.show=!0,this.formStates.isSubmitting=!1,this.notifications.error.text=r.t("firefly.errors_upload"),console.error(e)},init(){this.addSplit(),v().then(e=>{this.formStates.loadingCurrencies=!1,this.formData.defaultCurrency=e.defaultCurrency,this.formData.enabledCurrencies=e.enabledCurrencies,this.formData.nativeCurrencies=e.nativeCurrencies,this.formData.foreignCurrencies=e.foreignCurrencies}),T().then(e=>{this.formData.budgets=e,this.formStates.loadingBudgets=!1}),C().then(e=>{this.formData.piggyBanks=e,this.formStates.loadingPiggyBanks=!1}),P().then(e=>{this.formData.subscriptions=e,this.formStates.loadingSubscriptions=!1}),document.addEventListener("upload-success",e=>{this.processUpload(e),document.querySelectorAll("input[type=file]").value=""}),document.addEventListener("upload-error",e=>{this.processUploadError(e)}),document.addEventListener("location-move",e=>{this.entries[e.detail.index].latitude=e.detail.latitude,this.entries[e.detail.index].longitude=e.detail.longitude}),document.addEventListener("location-set",e=>{this.entries[e.detail.index].hasLocation=!0,this.entries[e.detail.index].latitude=e.detail.latitude,this.entries[e.detail.index].longitude=e.detail.longitude,this.entries[e.detail.index].zoomLevel=e.detail.zoomLevel}),document.addEventListener("location-zoom",e=>{this.entries[e.detail.index].hasLocation=!0,this.entries[e.detail.index].zoomLevel=e.detail.zoomLevel}),this.filters.source=["Asset account","Loan","Debt","Mortgage","Revenue account"],this.filters.destination=["Expense account","Loan","Debt","Mortgage","Asset account"]},submitTransaction(){this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1;for(let o in this.entries)this.entries.hasOwnProperty(o)&&(this.entries[o].errors=w());this.formStates.isSubmitting=!0,this.detectTransactionType();let e=_(this.entries,null,this.groupProperties.transactionType),t={group_title:this.groupProperties.title,fire_webhooks:this.formStates.webhooksButton,apply_rules:this.formStates.rulesButton,transactions:e};this.groupProperties.title===null&&e.length>1&&(t.group_title=e[0].description);let s=new M;console.log(t),s.post(t).then(o=>{const i=o.data.data;if(this.groupProperties.id=parseInt(i.id),this.groupProperties.title=i.attributes.group_title??i.attributes.transactions[0].description,E(this.groupProperties.id,i.attributes.transactions)>0){this.notifications.wait.show=!0,this.notifications.wait.text=r.t("firefly.wait_attachments");return}this.showMessageOrRedirectUser()}).catch(o=>{this.submitting=!1,console.log(o),typeof o.response<"u"&&this.parseErrors(o.response.data)})},showMessageOrRedirectUser(){if(this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.returnHereButton){this.notifications.success.show=!0,this.notifications.success.url="transactions/show/"+this.groupProperties.id,this.notifications.success.text=r.t("firefly.stored_journal_js",{description:this.groupProperties.title}),this.formStates.resetButton&&(this.entries=[],this.addSplit(),this.groupProperties.totalAmount=0);return}window.location="transactions/show/"+this.groupProperties.id+"?transaction_group_id="+this.groupProperties.id+"&message=created"},parseErrors(e){this.notifications.error.show=!0,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.isSubmitting=!1,this.notifications.error.text=r.t("firefly.errors_submission_v2",{errorMessage:e.message}),e.hasOwnProperty("errors")&&(this.entries=L(e.errors,this.entries))},addSplit(){this.entries.push(b()),setTimeout(()=>{B.init("select.ac-tags",{allowClear:!0,server:a.tag,liveServer:!0,clearEnd:!0,allowNew:!0,notFoundMessage:r.t("firefly.nothing_found"),noCache:!0,fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}}});const e=this.entries.length-1;z(e);const t=function(s,o,i){return s.name_with_balance+'
'+r.t("firefly.account_type_"+s.type)+""};c({selector:"input.ac-source",serverUrl:a.account,onChange:S,onSelectItem:D,hiddenValue:this.entries[e].source_account.alpine_name}),c({selector:"input.ac-dest",serverUrl:a.account,filters:this.filters.destination,onRenderItem:t,onChange:A,onSelectItem:k}),c({selector:"input.ac-category",serverUrl:a.category,valueField:"id",labelField:"name",onChange:h,onSelectItem:h}),c({selector:"input.ac-description",serverUrl:a.description,valueField:"id",labelField:"description",onChange:p,onSelectItem:p})},150)},removeSplit(e){this.entries.splice(e,1),document.querySelector("#split-0-tab").click()},clearLocation(e){e.preventDefault();const t=e.currentTarget,s=parseInt(t.attributes["data-index"].value);this.entries[s].hasLocation=!1,this.entries[s].latitude=null,this.entries[s].longitude=null,this.entries[s].zoomLevel=null;const o=new CustomEvent("location-remove",{detail:{index:s}});return document.dispatchEvent(o),!1}}},g={transactions:I,dates:y};function f(){Object.keys(g).forEach(e=>{console.log(`Loading page component "${e}"`);let t=g[e]();Alpine.data(e,()=>t)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),f()});window.bootstrapped&&(console.log("Loaded through window variable."),f()); diff --git a/public/build/assets/create-empty-split-d23e6a0d.js b/public/build/assets/create-empty-split-c1e678fd.js similarity index 93% rename from public/build/assets/create-empty-split-d23e6a0d.js rename to public/build/assets/create-empty-split-c1e678fd.js index c70bfda67b..dcdb0d29fc 100644 --- a/public/build/assets/create-empty-split-d23e6a0d.js +++ b/public/build/assets/create-empty-split-c1e678fd.js @@ -1 +1 @@ -import{f as n}from"./vendor-7d6e65fe.js";function e(){return{id:"",name:"",alpine_name:""}}function o(){return{description:[],amount:[],currency_code:[],foreign_amount:[],foreign_currency_code:[],source_account:[],destination_account:[],budget_id:[],category_name:[],piggy_bank_id:[],bill_id:[],tags:[],notes:[],internal_reference:[],external_url:[],latitude:[],longitude:[],zoom_level:[],date:[],interest_date:[],book_date:[],process_date:[],due_date:[],payment_date:[],invoice_date:[]}}function d(){let t=n(new Date,"yyyy-MM-dd HH:mm");return{description:"",amount:"",currency_code:"EUR",foreign_amount:"",foreign_currency_code:"",source_account:e(),destination_account:e(),budget_id:null,category_name:"",piggy_bank_id:null,bill_id:null,tags:[],notes:"",internal_reference:"",external_url:"",hasLocation:!1,latitude:null,longitude:null,zoomLevel:null,date:t,interest_date:"",book_date:"",process_date:"",due_date:"",payment_date:"",invoice_date:"",errors:o()}}export{d as c,o as d}; +import{f as n}from"./vendor-47e474ee.js";function e(){return{id:"",name:"",alpine_name:""}}function o(){return{description:[],amount:[],currency_code:[],foreign_amount:[],foreign_currency_code:[],source_account:[],destination_account:[],budget_id:[],category_name:[],piggy_bank_id:[],bill_id:[],tags:[],notes:[],internal_reference:[],external_url:[],latitude:[],longitude:[],zoom_level:[],date:[],interest_date:[],book_date:[],process_date:[],due_date:[],payment_date:[],invoice_date:[]}}function d(){let t=n(new Date,"yyyy-MM-dd HH:mm");return{description:"",amount:"",currency_code:"EUR",foreign_amount:"",foreign_currency_code:"",source_account:e(),destination_account:e(),budget_id:null,category_name:"",piggy_bank_id:null,bill_id:null,tags:[],notes:"",internal_reference:"",external_url:"",hasLocation:!1,latitude:null,longitude:null,zoomLevel:null,date:t,interest_date:"",book_date:"",process_date:"",due_date:"",payment_date:"",invoice_date:"",errors:o()}}export{d as c,o as d}; diff --git a/public/build/assets/create-f971d025.js b/public/build/assets/create-f971d025.js deleted file mode 100644 index 2e9c7ee9a1..0000000000 --- a/public/build/assets/create-f971d025.js +++ /dev/null @@ -1 +0,0 @@ -import{a as m,d as y,f as d}from"./format-money-276370ed.js";import{d as w,c as b}from"./create-empty-split-d23e6a0d.js";import{l as v,a as C,b as T,c as _,p as E,d as P,s as L,e as c,f as S,g as D,h as A,i as x,j as k,k as h,m as p}from"./splice-errors-into-transactions-5f35da56.js";import{l,i as r,m as B}from"./vendor-7d6e65fe.js";import"./get-5385bfb8.js";class M{post(t){let s="/api/v2/transactions";return m.post(s,t)}}let n=[],u=[];document.addEventListener("location-remove",e=>{u[e.detail.index].remove()});function O(e){let t=0;if(document.querySelector("#form")._x_dataStack[0].$data.entries[t].hasLocation===!1){u[t]=new l.marker(e.latlng,{draggable:!0}),u[t].on("dragend",U),u[t].addTo(n[t]);const i=new CustomEvent("location-set",{detail:{latitude:e.latlng.lat,longitude:e.latlng.lng,index:t,zoomLevel:n[t].getZoom()}});document.dispatchEvent(i)}}function F(e){let t=0;const s=new CustomEvent("location-zoom",{detail:{index:t,zoomLevel:n[t].getZoom()}});document.dispatchEvent(s)}function U(e){let t=e.target,s=t.getLatLng();t.setLatLng(new l.LatLng(s.lat,s.lng),{draggable:"true"});const i=new CustomEvent("location-move",{detail:{latitude:s.lat,longitude:s.lng,index:0}});document.dispatchEvent(i)}function z(e){if(e>0){console.warn("Corwardly refuse to add a map on split #"+(e+1));return}if(typeof n[e]>"u"){let t=document.getElementById("location_map");t&&(n[e]=l.map(t).setView([t.dataset.latitude,t.dataset.longitude],t.dataset.zoomLevel),l.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{maxZoom:19,attribution:'© OpenStreetMap'}).addTo(n[e]),n[e].on("click",O),n[e].on("zoomend",F))}}const a=k();let I=function(){return{entries:[],formStates:{loadingCurrencies:!0,loadingBudgets:!0,loadingPiggyBanks:!0,loadingSubscriptions:!0,isSubmitting:!1,returnHereButton:!1,saveAsNewButton:!1,resetButton:!0,rulesButton:!0,webhooksButton:!0},formBehaviour:{formType:"create",foreignCurrencyEnabled:!0},formData:{defaultCurrency:null,enabledCurrencies:[],nativeCurrencies:[],foreignCurrencies:[],budgets:[],piggyBanks:[],subscriptions:[]},groupProperties:{transactionType:"unknown",title:null,id:null,totalAmount:0},notifications:{error:{show:!1,text:"",url:""},success:{show:!1,text:"",url:""},wait:{show:!1,text:""}},filters:{source:[],destination:[]},changedDateTime(e){console.warn("changedDateTime, event is not used")},changedDescription(e){console.warn("changedDescription, event is not used")},changedDestinationAccount(e){this.detectTransactionType()},changedSourceAccount(e){this.detectTransactionType()},detectTransactionType(){const e=this.entries[0].source_account.type??"unknown",t=this.entries[0].destination_account.type??"unknown";if(e==="unknown"&&t==="unknown"){this.groupProperties.transactionType="unknown",console.warn("Cannot infer transaction type from two unknown accounts.");return}if(e===t&&["Asset account","Loan","Debt","Mortgage"].includes(e)){this.groupProperties.transactionType="transfer",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),console.log("filter down currencies for transfer."),this.filterNativeCurrencies(this.entries[0].source_account.currency_code),this.filterForeignCurrencies(this.entries[0].destination_account.currency_code);return}if(e==="Asset account"&&["Expense account","Debt","Loan","Mortgage"].includes(t)){this.groupProperties.transactionType="withdrawal",console.log('[a] Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(e==="Asset account"&&t==="unknown"){this.groupProperties.transactionType="withdrawal",console.log('[b] Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),console.log(this.entries[0].source_account),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(["Debt","Loan","Mortgage"].includes(e)&&t==="Expense account"){this.groupProperties.transactionType="withdrawal",console.log('[c] Transaction type is detected to be "'+this.groupProperties.transactionType+'".'),this.filterNativeCurrencies(this.entries[0].source_account.currency_code);return}if(e==="Revenue account"&&["Asset account","Debt","Loan","Mortgage"].includes(t)){this.groupProperties.transactionType="deposit",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".');return}if(["Debt","Loan","Mortgage"].includes(e)&&t==="Asset account"){this.groupProperties.transactionType="deposit",console.log('Transaction type is detected to be "'+this.groupProperties.transactionType+'".');return}console.warn('Unknown account combination between "'+e+'" and "'+t+'".')},formattedTotalAmount(){return this.entries.length===0?d(this.groupProperties.totalAmount,"EUR"):d(this.groupProperties.totalAmount,this.entries[0].currency_code??"EUR")},filterForeignCurrencies(e){let t=[],s;for(let i in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(i)){let o=this.formData.enabledCurrencies[i];o.code===e&&(s=o)}t.push(s),this.formData.foreignCurrencies=t,t.length===1&&t[0].code===this.entries[0].source_account.currency_code&&(console.log("Foreign currency is same as source currency. Disable foreign amount."),this.formBehaviour.foreignCurrencyEnabled=!1),t.length===1&&t[0].code!==this.entries[0].source_account.currency_code&&(console.log("Foreign currency is NOT same as source currency. Enable foreign amount."),this.formBehaviour.foreignCurrencyEnabled=!0);for(let i in this.entries)this.entries.hasOwnProperty(i)&&(this.entries[i].foreign_currency_code=e)},filterNativeCurrencies(e){let t=[],s;for(let i in this.formData.enabledCurrencies)if(this.formData.enabledCurrencies.hasOwnProperty(i)){let o=this.formData.enabledCurrencies[i];o.code===e&&(s=o)}t.push(s),this.formData.nativeCurrencies=t;for(let i in this.entries)this.entries.hasOwnProperty(i)&&(this.entries[i].currency_code=e)},changedAmount(e){const t=parseInt(e.target.dataset.index);this.entries[t].amount=parseFloat(e.target.value),this.groupProperties.totalAmount=0;for(let s in this.entries)this.entries.hasOwnProperty(s)&&(this.groupProperties.totalAmount=this.groupProperties.totalAmount+parseFloat(this.entries[s].amount))},addedSplit(){},processUpload(e){this.showMessageOrRedirectUser()},processUploadError(e){this.notifications.success.show=!1,this.notifications.wait.show=!1,this.notifications.error.show=!0,this.formStates.isSubmitting=!1,this.notifications.error.text=r.t("firefly.errors_upload"),console.error(e)},init(){this.addSplit(),v().then(e=>{this.formStates.loadingCurrencies=!1,this.formData.defaultCurrency=e.defaultCurrency,this.formData.enabledCurrencies=e.enabledCurrencies,this.formData.nativeCurrencies=e.nativeCurrencies,this.formData.foreignCurrencies=e.foreignCurrencies}),C().then(e=>{this.formData.budgets=e,this.formStates.loadingBudgets=!1}),T().then(e=>{this.formData.piggyBanks=e,this.formStates.loadingPiggyBanks=!1}),_().then(e=>{this.formData.subscriptions=e,this.formStates.loadingSubscriptions=!1}),document.addEventListener("upload-success",e=>{this.processUpload(e),document.querySelectorAll("input[type=file]").value=""}),document.addEventListener("upload-error",e=>{this.processUploadError(e)}),document.addEventListener("location-move",e=>{this.entries[e.detail.index].latitude=e.detail.latitude,this.entries[e.detail.index].longitude=e.detail.longitude}),document.addEventListener("location-set",e=>{this.entries[e.detail.index].hasLocation=!0,this.entries[e.detail.index].latitude=e.detail.latitude,this.entries[e.detail.index].longitude=e.detail.longitude,this.entries[e.detail.index].zoomLevel=e.detail.zoomLevel}),document.addEventListener("location-zoom",e=>{this.entries[e.detail.index].hasLocation=!0,this.entries[e.detail.index].zoomLevel=e.detail.zoomLevel}),this.filters.source=["Asset account","Loan","Debt","Mortgage","Revenue account"],this.filters.destination=["Expense account","Loan","Debt","Mortgage","Asset account"]},submitTransaction(){this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1;for(let i in this.entries)this.entries.hasOwnProperty(i)&&(this.entries[i].errors=w());this.formStates.isSubmitting=!0,this.detectTransactionType();let e=E(this.entries,null,this.groupProperties.transactionType),t={group_title:this.groupProperties.title,fire_webhooks:this.formStates.webhooksButton,apply_rules:this.formStates.rulesButton,transactions:e};this.groupProperties.title===null&&e.length>1&&(t.group_title=e[0].description);let s=new M;console.log(t),s.post(t).then(i=>{const o=i.data.data;if(this.groupProperties.id=parseInt(o.id),this.groupProperties.title=o.attributes.group_title??o.attributes.transactions[0].description,P(this.groupProperties.id,o.attributes.transactions)>0){this.notifications.wait.show=!0,this.notifications.wait.text=r.t("firefly.wait_attachments");return}this.showMessageOrRedirectUser()}).catch(i=>{this.submitting=!1,console.log(i),typeof i.response<"u"&&this.parseErrors(i.response.data)})},showMessageOrRedirectUser(){if(this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.returnHereButton){this.notifications.success.show=!0,this.notifications.success.url="transactions/show/"+this.groupProperties.id,this.notifications.success.text=r.t("firefly.stored_journal_js",{description:this.groupProperties.title}),this.formStates.resetButton&&(this.entries=[],this.addSplit(),this.groupProperties.totalAmount=0);return}window.location="transactions/show/"+this.groupProperties.id+"?transaction_group_id="+this.groupProperties.id+"&message=created"},parseErrors(e){this.notifications.error.show=!0,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.isSubmitting=!1,this.notifications.error.text=r.t("firefly.errors_submission_v2",{errorMessage:e.message}),e.hasOwnProperty("errors")&&(this.entries=L(e.errors,this.entries))},addSplit(){this.entries.push(b()),setTimeout(()=>{B.init("select.ac-tags",{allowClear:!0,server:a.tag,liveServer:!0,clearEnd:!0,allowNew:!0,notFoundMessage:r.t("firefly.nothing_found"),noCache:!0,fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}}});const e=this.entries.length-1;z(e);const t=function(s,i,o){return s.name_with_balance+'
'+r.t("firefly.account_type_"+s.type)+""};c({selector:"input.ac-source",serverUrl:a.account,onChange:S,onSelectItem:D,hiddenValue:this.entries[e].source_account.alpine_name}),c({selector:"input.ac-dest",serverUrl:a.account,filters:this.filters.destination,onRenderItem:t,onChange:A,onSelectItem:x}),c({selector:"input.ac-category",serverUrl:a.category,valueField:"id",labelField:"name",onChange:h,onSelectItem:h}),c({selector:"input.ac-description",serverUrl:a.description,valueField:"id",labelField:"description",onChange:p,onSelectItem:p})},150)},removeSplit(e){this.entries.splice(e,1),document.querySelector("#split-0-tab").click()},clearLocation(e){e.preventDefault();const t=e.currentTarget,s=parseInt(t.attributes["data-index"].value);this.entries[s].hasLocation=!1,this.entries[s].latitude=null,this.entries[s].longitude=null,this.entries[s].zoomLevel=null;const i=new CustomEvent("location-remove",{detail:{index:s}});return document.dispatchEvent(i),!1}}},f={transactions:I,dates:y};function g(){Object.keys(f).forEach(e=>{console.log(`Loading page component "${e}"`);let t=f[e]();Alpine.data(e,()=>t)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),g()});window.bootstrapped&&(console.log("Loaded through window variable."),g()); diff --git a/public/build/assets/dashboard-52719b55.js b/public/build/assets/dashboard-ff9938f0.js similarity index 98% rename from public/build/assets/dashboard-52719b55.js rename to public/build/assets/dashboard-ff9938f0.js index 5fb5a5e575..3b30672d4c 100644 --- a/public/build/assets/dashboard-52719b55.js +++ b/public/build/assets/dashboard-ff9938f0.js @@ -1 +1 @@ -import{a as O,f,g as v,P as bt,d as wt}from"./format-money-276370ed.js";import{f as g,C as m,a as S,i as p,S as vt,F as mt,L as Ct,b as kt,A as Pt,B as Dt,T as xt,P as Ot,c as Mt,d as Ft,p as St,e as At,g as Bt,h as jt,j as Wt,k as It}from"./vendor-7d6e65fe.js";import{G as $t}from"./get-9c5eaf42.js";import{G as Vt,a as Kt}from"./get-5385bfb8.js";class Lt{get(e,n,a){return O.get("/api/v2/summary/basic",{params:{start:e,end:n,code:a}})}}function P(t,e,n){const a=g(e,"y-MM-dd")+"_"+g(n,"y-MM-dd")+"_"+t;return console.log("getCacheKey: "+a),String(a)}let U=!1;const Et=()=>({balanceBox:{amounts:[],subtitles:[]},billBox:{paid:[],unpaid:[]},leftBox:{left:[],perDay:[]},netBox:{net:[]},autoConversion:!1,loading:!1,boxData:null,boxOptions:null,getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-boxes-data",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){this.boxData=r,this.generateOptions(this.boxData);return}new Lt().get(g(t,"yyyy-MM-dd"),g(e,"yyyy-MM-dd"),null).then(i=>{this.boxData=i.data,window.store.set(n,i.data),this.generateOptions(this.boxData)})},generateOptions(t){this.balanceBox={amounts:[],subtitles:[]},this.billBox={paid:[],unpaid:[]},this.leftBox={left:[],perDay:[]},this.netBox={net:[]};let e={};for(const n in t)if(t.hasOwnProperty(n)){const a=t[n];if(!a.hasOwnProperty("key"))continue;let r=a.key;if(this.autoConversion){if(r.startsWith("balance-in-native")){this.balanceBox.amounts.push(f(a.value,a.currency_code)),e.hasOwnProperty(a.currency_code)||(e[a.currency_code]="");continue}if(r.startsWith("spent-in-native")){e.hasOwnProperty(a.currency_code)||(e[a.currency_code]=""),e[a.currency_code]=e[a.currency_code]+f(a.value,a.currency_code);continue}if(r.startsWith("earned-in-native")){e.hasOwnProperty(a.currency_code)||(e[a.currency_code]=""),e[a.currency_code]=f(a.value,a.currency_code)+" + "+e[a.currency_code];continue}if(r.startsWith("bills-unpaid-in-native")){this.billBox.unpaid.push(f(a.value,a.currency_code));continue}if(r.startsWith("bills-paid-in-native")){this.billBox.paid.push(f(a.value,a.currency_code));continue}if(r.startsWith("left-to-spend-in-native")){this.leftBox.left.push(f(a.value,a.currency_code));continue}if(r.startsWith("left-per-day-to-spend-in-native")){this.leftBox.perDay.push(f(a.value,a.currency_code));continue}if(r.startsWith("net-worth-in-native")){this.netBox.net.push(f(a.value,a.currency_code));continue}}if(!this.autoConversion&&!r.endsWith("native")){if(r.startsWith("balance-in-")){this.balanceBox.amounts.push(f(a.value,a.currency_code));continue}if(r.startsWith("spent-in-")){e.hasOwnProperty(a.currency_code)||(e[a.currency_code]=""),e[a.currency_code]=e[a.currency_code]+f(a.value,a.currency_code);continue}if(r.startsWith("earned-in-")){e.hasOwnProperty(a.currency_code)||(e[a.currency_code]=""),e[a.currency_code]=f(a.value,a.currency_code)+" + "+e[a.currency_code];continue}if(r.startsWith("bills-unpaid-in-")){this.billBox.unpaid.push(f(a.value,a.currency_code));continue}if(r.startsWith("bills-paid-in-")){this.billBox.paid.push(f(a.value,a.currency_code));continue}if(r.startsWith("left-to-spend-in-")){this.leftBox.left.push(f(a.value,a.currency_code));continue}if(r.startsWith("left-per-day-to-spend-in-")){this.leftBox.perDay.push(f(a.value,a.currency_code));continue}r.startsWith("net-worth-in-")&&this.netBox.net.push(f(a.value,a.currency_code))}}for(let n in e)e.hasOwnProperty(n)&&this.balanceBox.subtitles.push(e[n]);this.loading=!1},loadBoxes(){if(this.loading!==!0){if(this.loading=!0,this.boxData===null){this.getFreshData();return}this.generateOptions(this.boxData),this.loading=!1}},init(){Promise.all([v("viewRange"),v("autoConversion",!1)]).then(t=>{U=!0,this.autoConversion=t[1],this.loadBoxes()}),window.store.observe("end",()=>{U&&(this.boxData=null,this.loadBoxes())}),window.store.observe("autoConversion",t=>{U&&(this.autoConversion=t,this.loadBoxes())})}});class Gt{put(e,n){let a="/api/v1/preferences/"+e;return O.put(a,{data:n})}}function Tt(t,e=null){window.store.set(t,e),new Gt().put(t,e).then(a=>{}).catch(()=>{new bt().post(t,e).then(r=>{})})}let Rt=class{dashboard(e,n){let a=g(e,"y-MM-dd"),r=g(n,"y-MM-dd");return O.get("/api/v2/chart/account/dashboard",{params:{start:a,end:r}})}expense(e,n){let a=g(e,"y-MM-dd"),r=g(n,"y-MM-dd");return O.get("/api/v2/chart/account/expense-dashboard",{params:{start:a,end:r}})}};class st{get(e,n){let a={date:g(n,"y-MM-dd").slice(0,10)};return n?O.get("/api/v2/accounts/"+e,{params:a}):O.get("/api/v2/accounts/"+e)}transactions(e,n){const a={page:n.page??1};return n.hasOwnProperty("start")&&(a.start=g(n.start,"y-MM-dd")),n.hasOwnProperty("end")&&(a.end=g(n.end,"y-MM-dd")),O.get("/api/v2/accounts/"+e+"/transactions",{params:a})}}function N(t){return t==="sankey"?{type:"sankey",data:{datasets:[]},options:{animations:!1}}:t==="pie"?{type:"pie",data:{datasets:[]}}:t==="column"?{type:"bar",data:{labels:[],datasets:[]},options:{plugins:{tooltip:{callbacks:{label:function(e){let n=e.dataset.currency_code;return f(e.raw,n)}}}},maintainAspectRatio:!1,scales:{}}}:t==="line"?{options:{plugins:{tooltip:{callbacks:{label:function(e){let n=e.dataset.currency_code;return f(e.raw,n)}}}},maintainAspectRatio:!1,scales:{x:{type:"time",time:{tooltipFormat:"PP"}}}},type:"line",data:{labels:[],datasets:[]}}:{}}let q=new m("#36a2eb"),I=new m("#ff6384"),G=new m("#4bc0c0"),ft=new m("#ff9f40"),qt=new m("#9966ff"),Nt=new m("#ffcd56"),Yt=new m("#c9cbcf"),lt=0;window.theme==="dark"&&(I.darken(.3).desaturate(.3),G.darken(.3).desaturate(.3),q.darken(.3).desaturate(.3),ft.darken(.3).desaturate(.3));let z=[I,ft,q,G,qt,Nt,Yt,G];function j(t,e){let n={borderColor:I.rgbString(),backgroundColor:I.rgbString()},a;switch(t){default:let o=Math.floor(lt/2)%z.length;a=new m(z[o].rgbString()),a.lighten(.38),n={borderColor:z[o].hexString(),backgroundColor:a.hexString()};break;case"spent":a=new m(q.rgbString()),a.lighten(.38),n={borderColor:q.rgbString(),backgroundColor:a.rgbString()};break;case"left":a=new m(G.rgbString()),a.lighten(.38),n={borderColor:G.rgbString(),backgroundColor:a.rgbString()};break;case"overspent":a=new m(I.rgbString()),a.lighten(.22),n={borderColor:I.rgbString(),backgroundColor:a.rgbString()};break}return lt++,e==="border"?n.borderColor:e==="background"?n.backgroundColor:"#FF0000"}let A=[],$=null,H=null,J=!1;const Ut=()=>({loading:!1,loadingAccounts:!1,accountList:[],autoConversion:!1,chartOptions:null,switchAutoConversion(){this.autoConversion=!this.autoConversion,Tt("autoConversion",this.autoConversion)},getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-accounts-chart",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){console.log(r),this.drawChart(this.generateOptions(r)),this.loading=!1;return}new Rt().dashboard(t,e,null).then(i=>{this.chartData=i.data,window.store.set(n,i.data),console.log(i.data),this.drawChart(this.generateOptions(this.chartData)),this.loading=!1})},generateOptions(t){A=[];let e=N("line");for(let n=0;n0){this.loadingAccounts=!1;return}const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-accounts-data",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){this.accountList=r,this.loadingAccounts=!1;return}const o=10;let i=0,l=0,u=[];Promise.all([v("frontpageAccounts")]).then(d=>{i=d[0].length;for(let h in d[0]){let c=d[0];if(c.hasOwnProperty(h)){let _=c[h];new st().get(_,new Date(window.store.get("end"))).then(w=>{let C=w.data.data;const yt={page:1,start:new Date(window.store.get("start")),end:new Date(window.store.get("end"))};new st().transactions(C.id,yt).then(at=>{let nt=[];for(let B=0;B=o);B++){let M=at.data.data[B],rt={title:M.attributes.group_title===null?"":M.attributes.group_title,id:M.id,transactions:[]};for(let Y=0;YB.order-M.order),this.accountList=u,this.loadingAccounts=!1,window.store.set(n,u))})})}}})},init(){Promise.all([v("viewRange","1M"),v("autoConversion",!1),v("language","en_US")]).then(t=>{this.autoConversion=t[1],J=!0,this.loadChart(),this.loadAccounts()}),window.store.observe("end",()=>{J&&(H=null,this.accountList=[],this.loadChart(),this.loadAccounts())}),window.store.observe("autoConversion",()=>{J&&(this.loadChart(),this.loadAccounts())})}});let zt=class{dashboard(e,n){let a=g(e,"y-MM-dd"),r=g(n,"y-MM-dd");return O.get("/api/v2/chart/budget/dashboard",{params:{start:a,end:r}})}},V=[],T=null,F=null,Z=!1;const Ht=()=>({loading:!1,autoConversion:!1,loadChart(){if(this.loading!==!0){if(this.loading=!0,F!==null){this.drawChart(this.generateOptions(F)),this.loading=!1;return}this.getFreshData()}},drawChart(t){if(T!==null){T.data.datasets=t.data.datasets,T.update();return}T=new S(document.querySelector("#budget-chart"),t)},getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-budgets-chart",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){F=r,this.drawChart(this.generateOptions(F)),this.loading=!1;return}new zt().dashboard(t,e,null).then(i=>{F=i.data,this.drawChart(this.generateOptions(F)),window.store.set(n,F),this.loading=!1})},generateOptions(t){V=[];let e=N("column");e.options.locale=window.store.get("locale").replace("_","-"),e.options.plugins={tooltip:{callbacks:{title:function(n){return n.label},label:function(n){let a=n.dataset.label||"";return a&&(a+=": "),a+" "+f(n.parsed.y,V[n.parsed.x]??"EUR")}}}},e.data={labels:[],datasets:[{label:p.t("firefly.spent"),data:[],borderWidth:1,stack:1,backgroundColor:j("spent","background"),borderColor:j("spent","border")},{label:p.t("firefly.left"),data:[],borderWidth:1,stack:1,backgroundColor:j("left","background"),borderColor:j("left","border")},{label:p.t("firefly.overspent"),data:[],borderWidth:1,stack:1,backgroundColor:j("overspent","background"),borderColor:j("overspent","border")}]};for(const n in t)if(t.hasOwnProperty(n)){let a=t[n],r=a.label+" ("+a.currency_code+")";e.data.labels.push(r),this.autoConversion&&(V.push(a.native_currency_code),e.data.datasets[0].data.push(parseFloat(a.native_entries.spent)*-1),e.data.datasets[1].data.push(parseFloat(a.native_entries.left)),e.data.datasets[2].data.push(parseFloat(a.native_entries.overspent))),this.autoConversion||(V.push(a.currency_code),e.data.datasets[0].data.push(parseFloat(a.entries.spent)*-1),e.data.datasets[1].data.push(parseFloat(a.entries.left)),e.data.datasets[2].data.push(parseFloat(a.entries.overspent)))}return e.options.scales={y:{ticks:{callback:function(n){return f(n,V[0]??"EUR")}}}},e},init(){Promise.all([v("autoConversion",!1)]).then(t=>{this.autoConversion=t[0],Z=!0,this.loading===!1&&this.loadChart()}),window.store.observe("end",()=>{Z&&this.loading===!1&&(F=null,this.loadChart())}),window.store.observe("autoConversion",t=>{Z&&(this.autoConversion=t,this.loading===!1&&this.loadChart())})}});class Jt{dashboard(e,n){let a=g(e,"y-MM-dd"),r=g(n,"y-MM-dd");return O.get("/api/v2/chart/category/dashboard",{params:{start:a,end:r}})}}let ut=[],K=null,W=null,Q=!1;const Zt=()=>({loading:!1,autoConversion:!1,generateOptions(t){ut=[];let e=N("column"),n={};for(const r in t)if(t.hasOwnProperty(r)){let o=t[r],i=o.currency_code;this.autoConversion&&(i=o.native_currency_code),n.hasOwnProperty(i)||(n[i]={name:i,yAxisID:"",data:{}},ut.push(i))}for(const r in t)if(t.hasOwnProperty(r)){let o=t[r],i=o.currency_code;this.autoConversion&&(i=o.native_currency_code);for(const l in n)if(n.hasOwnProperty(l)){let u=0;i===l&&(u=parseFloat(o.amount),""+o.currency_code,this.autoConversion&&(u=parseFloat(o.native_amount),""+o.native_currency_code)),n[l].data.hasOwnProperty(o.label)&&(n[l].data[o.label]=n[l].data[o.label]+u),n[l].data.hasOwnProperty(o.label)||(n[l].data[o.label]=u)}e.data.labels.includes(o.label)||e.data.labels.push(o.label)}let a=0;for(const r in n){let o="y"+r,i={label:r,currency_code:r,yAxisID:o,data:[]};for(const l in n[r].data)i.data.push(n[r].data[l]);e.data.datasets.push(i),e.options.scales.hasOwnProperty(o)||(e.options.scales[o]={beginAtZero:!0,type:"linear",position:a===1?"right":"left",ticks:{callback:function(l,u,d){return f(l,r)}}},a++)}return e},drawChart(t){if(K!==null){K.options=t.options,K.data=t.data,K.update();return}K=new S(document.querySelector("#category-chart"),t)},getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-categories-chart",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){W=r,this.drawChart(this.generateOptions(W)),this.loading=!1;return}new Jt().dashboard(t,e,null).then(i=>{W=i.data,this.drawChart(this.generateOptions(i.data)),window.store.set(n,W),this.loading=!1})},loadChart(){if(this.loading!==!0){if(this.loading=!0,W!==null){this.drawChart(this.generateOptions(W)),this.loading=!1;return}this.getFreshData()}},init(){Promise.all([v("autoConversion",!1)]).then(t=>{this.autoConversion=t[0],Q=!0,this.loadChart()}),window.store.observe("end",()=>{Q&&(this.chartData=null,this.loadChart())}),window.store.observe("autoConversion",t=>{Q&&(this.autoConversion=t,this.loadChart())})}});S.register({SankeyController:vt,Flow:mt});const ct="dashboard-sankey-data";let X=!1,R=null,D=[],y=!1,s={category:null,unknown_category:null,in:null,out:null,unknown_source:null,unknown_dest:null,unknown_account:null,expense_account:null,revenue_account:null,budget:null,unknown_budget:null,all_money:null};const dt=function(t){return t.includes(s.revenue_account)?"forestgreen":t.includes("("+s.in+",")?"green":t.includes(s.budget)||t.includes(s.unknown_budget)?"Orchid":t.includes("("+s.out+",")?"MediumOrchid":t.includes(s.all_money)?"blue":"red"};function L(t,e,n,a){if(t==="category"&&e!==null&&n==="in")return s.category+' "'+e+'" ('+s.in+(y?", "+a+")":")");if(t==="category"&&e===null&&n==="in")return s.unknown_category+" ("+s.in+(y?", "+a+")":")");if(t==="category"&&e!==null&&n==="out")return s.category+' "'+e+'" ('+s.out+(y?", "+a+")":")");if(t==="category"&&e===null&&n==="out")return s.unknown_category+" ("+s.out+(y?", "+a+")":")");if(t==="account"&&e===null&&n==="in")return s.unknown_source+(y?" ("+a+")":"");if(t==="account"&&e!==null&&n==="in")return s.revenue_account+'"'+e+'"'+(y?" ("+a+")":"");if(t==="account"&&e===null&&n==="out")return s.unknown_dest+(y?" ("+a+")":"");if(t==="account"&&e!==null&&n==="out")return s.expense_account+' "'+e+'"'+(y?" ("+a+")":"");if(t==="budget"&&e!==null)return s.budget+' "'+e+'"'+(y?" ("+a+")":"");if(t==="budget"&&e===null)return s.unknown_budget+(y?" ("+a+")":"");console.error('Cannot handle: type:"'+t+'", dir: "'+n+'"')}function E(t,e,n){if(t==="category"&&e!==null)return s.category+' "'+e+'"'+(y?" ("+n+")":"");if(t==="category"&&e===null)return s.unknown_category+(y?" ("+n+")":"");if(t==="account"&&e===null)return s.unknown_account+(y?" ("+n+")":"");if(t==="account"&&e!==null)return e+(y?" ("+n+")":"");if(t==="budget"&&e!==null)return s.budget+' "'+e+'"'+(y?" ("+n+")":"");if(t==="budget"&&e===null)return s.unknown_budget+(y?" ("+n+")":"");console.error('Cannot handle: type:"'+t+'"')}const Qt=()=>({loading:!1,autoConversion:!1,generateOptions(){let t=N("sankey"),e={},n={};for(let r in D)if(D.hasOwnProperty(r)){let o=D[r];for(let i in o.attributes.transactions)if(o.attributes.transactions.hasOwnProperty(i)){let l=o.attributes.transactions[i],u=this.autoConversion?l.native_currency_code:l.currency_code,d=this.autoConversion?parseFloat(l.native_amount):parseFloat(l.amount),h;if(l.type==="deposit"){let c=L("category",l.category_name,"in",u),_=L("account",l.source_name,"in",u);n[c]=E("category",l.category_name,u),n[_]=E("account",l.source_name,u),h=_+"-"+c+"-"+u,e.hasOwnProperty(h)||(e[h]={from:_,to:c,amount:0}),e[h].amount+=d,h=c+"-"+s.all_money+"-"+u,e.hasOwnProperty(h)||(e[h]={from:c,to:s.all_money+(this.autoConversion?" ("+u+")":""),amount:0}),e[h].amount+=d}if(l.type==="withdrawal"){let c=L("budget",l.budget_name,"out",u);n[c]=E("budget",l.budget_name,u),h=s.all_money+"-"+c+"-"+u,e.hasOwnProperty(h)||(e[h]={from:s.all_money+(this.autoConversion?" ("+u+")":""),to:c,amount:0}),e[h].amount+=d;let _=L("category",l.category_name,"out",u);n[_]=E("category",l.category_name,u),h=c+"-"+_+"-"+u,e.hasOwnProperty(h)||(e[h]={from:c,to:_,amount:0}),e[h].amount+=d;let w=L("account",l.destination_name,"out",u);n[w]=E("account",l.destination_name,u),h=_+"-"+w+"-"+u,e.hasOwnProperty(h)||(e[h]={from:_,to:w,amount:0}),e[h].amount+=d}}}let a={label:"Firefly III dashboard sankey chart",data:[],colorFrom:r=>dt(r.dataset.data[r.dataIndex]?r.dataset.data[r.dataIndex].from:""),colorTo:r=>dt(r.dataset.data[r.dataIndex]?r.dataset.data[r.dataIndex].to:""),colorMode:"gradient",labels:n,size:"min"};for(let r in e)if(e.hasOwnProperty(r)){let o=e[r];a.data.push({from:o.from,to:o.to,flow:o.amount})}return t.data.datasets.push(a),t},drawChart(t){if(R!==null){R.data.datasets=t.data.datasets,R.update();return}R=new S(document.querySelector("#sankey-chart"),t)},getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P(ct,t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){D=r,this.drawChart(this.generateOptions()),this.loading=!1;return}let o={start:g(t,"y-MM-dd"),end:g(e,"y-MM-dd"),type:"withdrawal,deposit",page:1};this.downloadTransactions(o)},downloadTransactions(t){const e=new Date(window.store.get("start")),n=new Date(window.store.get("end")),a=P(ct,e,n);new $t().list(t).then(o=>{if(D=[...D,...o.data.data],parseInt(o.data.meta.pagination.total_pages)>t.page){t.page++,this.downloadTransactions(t);return}window.store.set(a,D),this.drawChart(this.generateOptions()),this.loading=!1})},loadChart(){if(this.loading!==!0){if(this.loading=!0,D.length!==0){this.drawChart(this.generateOptions()),this.loading=!1;return}this.getFreshData()}},init(){D=[],Promise.all([v("autoConversion",!1)]).then(t=>{this.autoConversion=t[0],y=t[0],s.all_money=p.t("firefly.all_money"),s.category=p.t("firefly.category"),s.in=p.t("firefly.money_flowing_in"),s.out=p.t("firefly.money_flowing_out"),s.unknown_category=p.t("firefly.unknown_category_plain"),s.unknown_source=p.t("firefly.unknown_source_plain"),s.unknown_dest=p.t("firefly.unknown_dest_plain"),s.unknown_account=p.t("firefly.unknown_any_plain"),s.unknown_budget=p.t("firefly.unknown_budget_plain"),s.expense_account=p.t("firefly.expense_account"),s.revenue_account=p.t("firefly.revenue_account"),s.budget=p.t("firefly.budget"),X=!0,this.loadChart()}),window.store.observe("end",()=>{X&&(this.transactions=[],this.loadChart())}),window.store.observe("autoConversion",t=>{X&&(this.autoConversion=t,this.loadChart())})}});let tt=!1,b={};function gt(t){return new Vt().list(t).then(n=>{let a=n.data.data;for(let r in a)if(a.hasOwnProperty(r)){let o=a[r];if(o.attributes.active&&o.attributes.pay_dates.length>0){let i=o.attributes.object_group_id===null?0:o.attributes.object_group_id,l=o.attributes.object_group_title===null?p.t("firefly.default_group_title_name_plain"):o.attributes.object_group_title,u=o.attributes.object_group_order===null?0:o.attributes.object_group_order;b.hasOwnProperty(i)||(b[i]={id:i,title:l,order:u,payment_info:{},bills:[]});let d={id:o.id,name:o.attributes.name,amount_min:o.attributes.amount_min,amount_max:o.attributes.amount_max,amount:(parseFloat(o.attributes.amount_max)+parseFloat(o.attributes.amount_min))/2,currency_code:o.attributes.currency_code,native_amount_min:o.attributes.native_amount_min,native_amount_max:o.attributes.native_amount_max,native_amount:(parseFloat(o.attributes.native_amount_max)+parseFloat(o.attributes.native_amount_min))/2,native_currency_code:o.attributes.native_currency_code,transactions:[],pay_dates:o.attributes.pay_dates,paid:o.attributes.paid_dates.length>0};d.expected_amount=t.autoConversion?f(d.native_amount,d.native_currency_code):f(d.amount,d.currency_code),d.expected_times=p.t("firefly.subscr_expected_x_times",{times:o.attributes.pay_dates.length,amount:d.expected_amount});for(let h in o.attributes.paid_dates)if(o.attributes.paid_dates.hasOwnProperty(h)){const c=o.attributes.paid_dates[h];let _=100;t.autoConversion&&(_=Math.round(-100+parseFloat(c.native_amount)*-1/parseFloat(d.native_amount)*100)),t.autoConversion||(_=Math.round(-100+parseFloat(c.amount)*-1/parseFloat(d.amount)*100));let w={amount:t.autoConversion?f(c.native_amount,c.native_currency_code):f(c.amount,c.currency_code),percentage:_,date:g(new Date(c.date),"PP"),foreign_amount:null};c.foreign_currency_code!==null&&(w.foreign_amount=t.autoConversion?c.foreign_native_amount:c.foreign_amount,w.foreign_currency_code=t.autoConversion?c.native_currency_code:c.foreign_currency_code),d.transactions.push(w)}if(b[i].bills.push(d),o.attributes.paid_dates.length===0){const h=o.attributes.pay_dates.length*d.amount,c=o.attributes.pay_dates.length*d.native_amount;b[i].payment_info.hasOwnProperty(d.currency_code)||(b[i].payment_info[d.currency_code]={currency_code:d.currency_code,paid:0,unpaid:0,native_currency_code:d.native_currency_code,native_paid:0,native_unpaid:0}),b[i].payment_info[d.currency_code].unpaid+=h,b[i].payment_info[d.currency_code].native_unpaid+=c}if(o.attributes.paid_dates.length>0){for(let h in o.attributes.paid_dates)if(o.attributes.paid_dates.hasOwnProperty(h)){let c=o.attributes.paid_dates[h];b[i].payment_info.hasOwnProperty(c.currency_code)||(b[i].payment_info[c.currency_code]={currency_code:d.currency_code,paid:0,unpaid:0,native_currency_code:d.native_currency_code,native_paid:0,native_unpaid:0});const _=parseFloat(c.amount)*-1,w=parseFloat(c.native_amount)*-1;b[i].payment_info[c.currency_code].paid+=_,b[i].payment_info[c.currency_code].native_paid+=w}}}}return parseInt(n.data.meta.pagination.total_pages)>t.page?(t.page++,gt(t)):Promise.resolve()})}const Xt=()=>({loading:!1,autoConversion:!1,subscriptions:[],startSubscriptions(){this.loading=!0;let t=new Date(window.store.get("start")),e=new Date(window.store.get("end"));const n=window.store.get("cacheValid");let a=window.store.get(P("subscriptions-data-dashboard",t,e));n&&typeof a<"u",b={},this.subscriptions=[];let r={start:g(t,"y-MM-dd"),end:g(e,"y-MM-dd"),autoConversion:this.autoConversion,page:1};gt(r).then(()=>{let o=Object.values(b);for(let i in o)if(o.hasOwnProperty(i)){let l=o[i];const u=Object.keys(l.payment_info);l.col_size=u.length===1?"col-6 offset-3":"col-6",l.chart_width=u.length===1?"50%":"100%",l.payment_length=u.length,this.subscriptions.push(l)}this.loading=!1})},drawPieChart(t,e,n){let a="#pie_"+t+"_"+n.currency_code;const r=this.autoConversion?n.native_unpaid:n.unpaid,o=this.autoConversion?n.native_paid:n.paid,i=this.autoConversion?n.native_currency_code:n.currency_code,u={type:"doughnut",data:{labels:[p.t("firefly.paid"),p.t("firefly.unpaid")],datasets:[{label:p.t("firefly.subscriptions_in_group",{title:e}),data:[o,r],backgroundColor:["rgb(54, 162, 235)","rgb(255, 99, 132)"],hoverOffset:4}]},options:{plugins:{tooltip:{callbacks:{label:function(h){return h.dataset.label+": "+f(h.raw,i)}}}}}};var d=S.getChart(document.querySelector(a));typeof d<"u"&&d.destroy(),new S(document.querySelector(a),u)},init(){Promise.all([v("autoConversion",!1)]).then(t=>{this.autoConversion=t[0],tt=!0,this.loading===!1&&this.startSubscriptions()}),window.store.observe("end",()=>{tt&&this.loading===!1&&this.startSubscriptions()}),window.store.observe("autoConversion",t=>{tt&&(this.autoConversion=t,this.loading===!1&&this.startSubscriptions())})}});let x={},et=!1;const ht="dashboard-piggies-data",te=()=>({loading:!1,autoConversion:!1,sankeyGrouping:"account",piggies:[],getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P(ht,t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){x=r,this.parsePiggies(),this.loading=!1;return}let o={start:g(t,"y-MM-dd"),end:g(e,"y-MM-dd"),page:1};this.downloadPiggyBanks(o)},downloadPiggyBanks(t){const e=new Date(window.store.get("start")),n=new Date(window.store.get("end")),a=P(ht,e,n);new Kt().list(t).then(o=>{if(x=[...x,...o.data.data],parseInt(o.data.meta.pagination.total_pages)>t.page){t.page++,this.downloadPiggyBanks(t);return}window.store.set(a,x),this.parsePiggies(),this.loading=!1})},parsePiggies(){let t=[];for(let e in x)if(x.hasOwnProperty(e)){let n=x[e];if(n.attributes.percentage>=100||n.attributes.percentage===0)continue;let a=n.object_group_title??p.t("firefly.default_group_title_name_plain");t.hasOwnProperty(a)||(t[a]={id:n.object_group_id??0,title:a,order:n.object_group_order??0,piggies:[]});let r={id:n.id,name:n.attributes.name,percentage:parseInt(n.attributes.percentage),amount:this.autoConversion?n.attributes.native_current_amount:n.attributes.current_amount,left_to_save:this.autoConversion?n.attributes.native_left_to_save:n.attributes.left_to_save,target_amount:this.autoConversion?n.attributes.native_target_amount:n.attributes.target_amount,save_per_month:this.autoConversion?n.attributes.native_save_per_month:n.attributes.save_per_month,currency_code:this.autoConversion?n.attributes.native_currency_code:n.attributes.currency_code};t[a].piggies.push(r)}this.piggies=Object.values(t)},loadPiggyBanks(){if(this.loading!==!0){if(this.loading=!0,this.piggies.length!==0){this.parsePiggies(),this.loading=!1;return}this.getFreshData()}},init(){x=[],Promise.all([v("autoConversion",!1)]).then(t=>{et=!0,this.autoConversion=t[0],this.loadPiggyBanks()}),window.store.observe("end",()=>{et&&(x=[],this.loadPiggyBanks())}),window.store.observe("autoConversion",t=>{et&&(this.autoConversion=t,this.loadPiggyBanks())})}});S.register({LineController:Ct,LineElement:kt,ArcElement:Pt,BarController:Dt,TimeScale:xt,PieController:Ot,BarElement:Mt,Filler:Ft,Colors:St,LinearScale:At,CategoryScale:Bt,PointElement:jt,Tooltip:Wt,Legend:It});const pt={dates:wt,boxes:Et,accounts:Ut,budgets:Ht,categories:Zt,sankey:Qt,subscriptions:Xt,piggies:te};function _t(t){Object.keys(t).forEach(e=>{let n=t[e]();Alpine.data(e,()=>n)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),_t(pt)});window.bootstrapped&&(console.log("Loaded through window variable."),_t(pt)); +import{a as O,f,g as v,P as bt,d as wt}from"./format-money-2cbd3c32.js";import{f as g,C as m,a as S,i as p,S as vt,F as mt,L as Ct,b as kt,A as Pt,B as Dt,T as xt,P as Ot,c as Mt,d as Ft,p as St,e as At,g as Bt,h as jt,j as Wt,k as It}from"./vendor-47e474ee.js";import{G as $t}from"./get-f02d6b9c.js";import{G as Vt,a as Kt}from"./get-4f3e9dd6.js";class Lt{get(e,n,a){return O.get("/api/v2/summary/basic",{params:{start:e,end:n,code:a}})}}function P(t,e,n){const a=g(e,"y-MM-dd")+"_"+g(n,"y-MM-dd")+"_"+t;return console.log("getCacheKey: "+a),String(a)}let U=!1;const Et=()=>({balanceBox:{amounts:[],subtitles:[]},billBox:{paid:[],unpaid:[]},leftBox:{left:[],perDay:[]},netBox:{net:[]},autoConversion:!1,loading:!1,boxData:null,boxOptions:null,getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-boxes-data",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){this.boxData=r,this.generateOptions(this.boxData);return}new Lt().get(g(t,"yyyy-MM-dd"),g(e,"yyyy-MM-dd"),null).then(i=>{this.boxData=i.data,window.store.set(n,i.data),this.generateOptions(this.boxData)})},generateOptions(t){this.balanceBox={amounts:[],subtitles:[]},this.billBox={paid:[],unpaid:[]},this.leftBox={left:[],perDay:[]},this.netBox={net:[]};let e={};for(const n in t)if(t.hasOwnProperty(n)){const a=t[n];if(!a.hasOwnProperty("key"))continue;let r=a.key;if(this.autoConversion){if(r.startsWith("balance-in-native")){this.balanceBox.amounts.push(f(a.value,a.currency_code)),e.hasOwnProperty(a.currency_code)||(e[a.currency_code]="");continue}if(r.startsWith("spent-in-native")){e.hasOwnProperty(a.currency_code)||(e[a.currency_code]=""),e[a.currency_code]=e[a.currency_code]+f(a.value,a.currency_code);continue}if(r.startsWith("earned-in-native")){e.hasOwnProperty(a.currency_code)||(e[a.currency_code]=""),e[a.currency_code]=f(a.value,a.currency_code)+" + "+e[a.currency_code];continue}if(r.startsWith("bills-unpaid-in-native")){this.billBox.unpaid.push(f(a.value,a.currency_code));continue}if(r.startsWith("bills-paid-in-native")){this.billBox.paid.push(f(a.value,a.currency_code));continue}if(r.startsWith("left-to-spend-in-native")){this.leftBox.left.push(f(a.value,a.currency_code));continue}if(r.startsWith("left-per-day-to-spend-in-native")){this.leftBox.perDay.push(f(a.value,a.currency_code));continue}if(r.startsWith("net-worth-in-native")){this.netBox.net.push(f(a.value,a.currency_code));continue}}if(!this.autoConversion&&!r.endsWith("native")){if(r.startsWith("balance-in-")){this.balanceBox.amounts.push(f(a.value,a.currency_code));continue}if(r.startsWith("spent-in-")){e.hasOwnProperty(a.currency_code)||(e[a.currency_code]=""),e[a.currency_code]=e[a.currency_code]+f(a.value,a.currency_code);continue}if(r.startsWith("earned-in-")){e.hasOwnProperty(a.currency_code)||(e[a.currency_code]=""),e[a.currency_code]=f(a.value,a.currency_code)+" + "+e[a.currency_code];continue}if(r.startsWith("bills-unpaid-in-")){this.billBox.unpaid.push(f(a.value,a.currency_code));continue}if(r.startsWith("bills-paid-in-")){this.billBox.paid.push(f(a.value,a.currency_code));continue}if(r.startsWith("left-to-spend-in-")){this.leftBox.left.push(f(a.value,a.currency_code));continue}if(r.startsWith("left-per-day-to-spend-in-")){this.leftBox.perDay.push(f(a.value,a.currency_code));continue}r.startsWith("net-worth-in-")&&this.netBox.net.push(f(a.value,a.currency_code))}}for(let n in e)e.hasOwnProperty(n)&&this.balanceBox.subtitles.push(e[n]);this.loading=!1},loadBoxes(){if(this.loading!==!0){if(this.loading=!0,this.boxData===null){this.getFreshData();return}this.generateOptions(this.boxData),this.loading=!1}},init(){Promise.all([v("viewRange"),v("autoConversion",!1)]).then(t=>{U=!0,this.autoConversion=t[1],this.loadBoxes()}),window.store.observe("end",()=>{U&&(this.boxData=null,this.loadBoxes())}),window.store.observe("autoConversion",t=>{U&&(this.autoConversion=t,this.loadBoxes())})}});class Gt{put(e,n){let a="/api/v1/preferences/"+e;return O.put(a,{data:n})}}function Tt(t,e=null){window.store.set(t,e),new Gt().put(t,e).then(a=>{}).catch(()=>{new bt().post(t,e).then(r=>{})})}let Rt=class{dashboard(e,n){let a=g(e,"y-MM-dd"),r=g(n,"y-MM-dd");return O.get("/api/v2/chart/account/dashboard",{params:{start:a,end:r}})}expense(e,n){let a=g(e,"y-MM-dd"),r=g(n,"y-MM-dd");return O.get("/api/v2/chart/account/expense-dashboard",{params:{start:a,end:r}})}};class st{get(e,n){let a={date:g(n,"y-MM-dd").slice(0,10)};return n?O.get("/api/v2/accounts/"+e,{params:a}):O.get("/api/v2/accounts/"+e)}transactions(e,n){const a={page:n.page??1};return n.hasOwnProperty("start")&&(a.start=g(n.start,"y-MM-dd")),n.hasOwnProperty("end")&&(a.end=g(n.end,"y-MM-dd")),O.get("/api/v2/accounts/"+e+"/transactions",{params:a})}}function N(t){return t==="sankey"?{type:"sankey",data:{datasets:[]},options:{animations:!1}}:t==="pie"?{type:"pie",data:{datasets:[]}}:t==="column"?{type:"bar",data:{labels:[],datasets:[]},options:{plugins:{tooltip:{callbacks:{label:function(e){let n=e.dataset.currency_code;return f(e.raw,n)}}}},maintainAspectRatio:!1,scales:{}}}:t==="line"?{options:{plugins:{tooltip:{callbacks:{label:function(e){let n=e.dataset.currency_code;return f(e.raw,n)}}}},maintainAspectRatio:!1,scales:{x:{type:"time",time:{tooltipFormat:"PP"}}}},type:"line",data:{labels:[],datasets:[]}}:{}}let q=new m("#36a2eb"),I=new m("#ff6384"),G=new m("#4bc0c0"),ft=new m("#ff9f40"),qt=new m("#9966ff"),Nt=new m("#ffcd56"),Yt=new m("#c9cbcf"),lt=0;window.theme==="dark"&&(I.darken(.3).desaturate(.3),G.darken(.3).desaturate(.3),q.darken(.3).desaturate(.3),ft.darken(.3).desaturate(.3));let z=[I,ft,q,G,qt,Nt,Yt,G];function j(t,e){let n={borderColor:I.rgbString(),backgroundColor:I.rgbString()},a;switch(t){default:let o=Math.floor(lt/2)%z.length;a=new m(z[o].rgbString()),a.lighten(.38),n={borderColor:z[o].hexString(),backgroundColor:a.hexString()};break;case"spent":a=new m(q.rgbString()),a.lighten(.38),n={borderColor:q.rgbString(),backgroundColor:a.rgbString()};break;case"left":a=new m(G.rgbString()),a.lighten(.38),n={borderColor:G.rgbString(),backgroundColor:a.rgbString()};break;case"overspent":a=new m(I.rgbString()),a.lighten(.22),n={borderColor:I.rgbString(),backgroundColor:a.rgbString()};break}return lt++,e==="border"?n.borderColor:e==="background"?n.backgroundColor:"#FF0000"}let A=[],$=null,H=null,J=!1;const Ut=()=>({loading:!1,loadingAccounts:!1,accountList:[],autoConversion:!1,chartOptions:null,switchAutoConversion(){this.autoConversion=!this.autoConversion,Tt("autoConversion",this.autoConversion)},getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-accounts-chart",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){console.log(r),this.drawChart(this.generateOptions(r)),this.loading=!1;return}new Rt().dashboard(t,e,null).then(i=>{this.chartData=i.data,window.store.set(n,i.data),console.log(i.data),this.drawChart(this.generateOptions(this.chartData)),this.loading=!1})},generateOptions(t){A=[];let e=N("line");for(let n=0;n0){this.loadingAccounts=!1;return}const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-accounts-data",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){this.accountList=r,this.loadingAccounts=!1;return}const o=10;let i=0,l=0,u=[];Promise.all([v("frontpageAccounts")]).then(d=>{i=d[0].length;for(let h in d[0]){let c=d[0];if(c.hasOwnProperty(h)){let _=c[h];new st().get(_,new Date(window.store.get("end"))).then(w=>{let C=w.data.data;const yt={page:1,start:new Date(window.store.get("start")),end:new Date(window.store.get("end"))};new st().transactions(C.id,yt).then(at=>{let nt=[];for(let B=0;B=o);B++){let M=at.data.data[B],rt={title:M.attributes.group_title===null?"":M.attributes.group_title,id:M.id,transactions:[]};for(let Y=0;YB.order-M.order),this.accountList=u,this.loadingAccounts=!1,window.store.set(n,u))})})}}})},init(){Promise.all([v("viewRange","1M"),v("autoConversion",!1),v("language","en_US")]).then(t=>{this.autoConversion=t[1],J=!0,this.loadChart(),this.loadAccounts()}),window.store.observe("end",()=>{J&&(H=null,this.accountList=[],this.loadChart(),this.loadAccounts())}),window.store.observe("autoConversion",()=>{J&&(this.loadChart(),this.loadAccounts())})}});let zt=class{dashboard(e,n){let a=g(e,"y-MM-dd"),r=g(n,"y-MM-dd");return O.get("/api/v2/chart/budget/dashboard",{params:{start:a,end:r}})}},V=[],T=null,F=null,Z=!1;const Ht=()=>({loading:!1,autoConversion:!1,loadChart(){if(this.loading!==!0){if(this.loading=!0,F!==null){this.drawChart(this.generateOptions(F)),this.loading=!1;return}this.getFreshData()}},drawChart(t){if(T!==null){T.data.datasets=t.data.datasets,T.update();return}T=new S(document.querySelector("#budget-chart"),t)},getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-budgets-chart",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){F=r,this.drawChart(this.generateOptions(F)),this.loading=!1;return}new zt().dashboard(t,e,null).then(i=>{F=i.data,this.drawChart(this.generateOptions(F)),window.store.set(n,F),this.loading=!1})},generateOptions(t){V=[];let e=N("column");e.options.locale=window.store.get("locale").replace("_","-"),e.options.plugins={tooltip:{callbacks:{title:function(n){return n.label},label:function(n){let a=n.dataset.label||"";return a&&(a+=": "),a+" "+f(n.parsed.y,V[n.parsed.x]??"EUR")}}}},e.data={labels:[],datasets:[{label:p.t("firefly.spent"),data:[],borderWidth:1,stack:1,backgroundColor:j("spent","background"),borderColor:j("spent","border")},{label:p.t("firefly.left"),data:[],borderWidth:1,stack:1,backgroundColor:j("left","background"),borderColor:j("left","border")},{label:p.t("firefly.overspent"),data:[],borderWidth:1,stack:1,backgroundColor:j("overspent","background"),borderColor:j("overspent","border")}]};for(const n in t)if(t.hasOwnProperty(n)){let a=t[n],r=a.label+" ("+a.currency_code+")";e.data.labels.push(r),this.autoConversion&&(V.push(a.native_currency_code),e.data.datasets[0].data.push(parseFloat(a.native_entries.spent)*-1),e.data.datasets[1].data.push(parseFloat(a.native_entries.left)),e.data.datasets[2].data.push(parseFloat(a.native_entries.overspent))),this.autoConversion||(V.push(a.currency_code),e.data.datasets[0].data.push(parseFloat(a.entries.spent)*-1),e.data.datasets[1].data.push(parseFloat(a.entries.left)),e.data.datasets[2].data.push(parseFloat(a.entries.overspent)))}return e.options.scales={y:{ticks:{callback:function(n){return f(n,V[0]??"EUR")}}}},e},init(){Promise.all([v("autoConversion",!1)]).then(t=>{this.autoConversion=t[0],Z=!0,this.loading===!1&&this.loadChart()}),window.store.observe("end",()=>{Z&&this.loading===!1&&(F=null,this.loadChart())}),window.store.observe("autoConversion",t=>{Z&&(this.autoConversion=t,this.loading===!1&&this.loadChart())})}});class Jt{dashboard(e,n){let a=g(e,"y-MM-dd"),r=g(n,"y-MM-dd");return O.get("/api/v2/chart/category/dashboard",{params:{start:a,end:r}})}}let ut=[],K=null,W=null,Q=!1;const Zt=()=>({loading:!1,autoConversion:!1,generateOptions(t){ut=[];let e=N("column"),n={};for(const r in t)if(t.hasOwnProperty(r)){let o=t[r],i=o.currency_code;this.autoConversion&&(i=o.native_currency_code),n.hasOwnProperty(i)||(n[i]={name:i,yAxisID:"",data:{}},ut.push(i))}for(const r in t)if(t.hasOwnProperty(r)){let o=t[r],i=o.currency_code;this.autoConversion&&(i=o.native_currency_code);for(const l in n)if(n.hasOwnProperty(l)){let u=0;i===l&&(u=parseFloat(o.amount),""+o.currency_code,this.autoConversion&&(u=parseFloat(o.native_amount),""+o.native_currency_code)),n[l].data.hasOwnProperty(o.label)&&(n[l].data[o.label]=n[l].data[o.label]+u),n[l].data.hasOwnProperty(o.label)||(n[l].data[o.label]=u)}e.data.labels.includes(o.label)||e.data.labels.push(o.label)}let a=0;for(const r in n){let o="y"+r,i={label:r,currency_code:r,yAxisID:o,data:[]};for(const l in n[r].data)i.data.push(n[r].data[l]);e.data.datasets.push(i),e.options.scales.hasOwnProperty(o)||(e.options.scales[o]={beginAtZero:!0,type:"linear",position:a===1?"right":"left",ticks:{callback:function(l,u,d){return f(l,r)}}},a++)}return e},drawChart(t){if(K!==null){K.options=t.options,K.data=t.data,K.update();return}K=new S(document.querySelector("#category-chart"),t)},getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P("dashboard-categories-chart",t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){W=r,this.drawChart(this.generateOptions(W)),this.loading=!1;return}new Jt().dashboard(t,e,null).then(i=>{W=i.data,this.drawChart(this.generateOptions(i.data)),window.store.set(n,W),this.loading=!1})},loadChart(){if(this.loading!==!0){if(this.loading=!0,W!==null){this.drawChart(this.generateOptions(W)),this.loading=!1;return}this.getFreshData()}},init(){Promise.all([v("autoConversion",!1)]).then(t=>{this.autoConversion=t[0],Q=!0,this.loadChart()}),window.store.observe("end",()=>{Q&&(this.chartData=null,this.loadChart())}),window.store.observe("autoConversion",t=>{Q&&(this.autoConversion=t,this.loadChart())})}});S.register({SankeyController:vt,Flow:mt});const ct="dashboard-sankey-data";let X=!1,R=null,D=[],y=!1,s={category:null,unknown_category:null,in:null,out:null,unknown_source:null,unknown_dest:null,unknown_account:null,expense_account:null,revenue_account:null,budget:null,unknown_budget:null,all_money:null};const dt=function(t){return t.includes(s.revenue_account)?"forestgreen":t.includes("("+s.in+",")?"green":t.includes(s.budget)||t.includes(s.unknown_budget)?"Orchid":t.includes("("+s.out+",")?"MediumOrchid":t.includes(s.all_money)?"blue":"red"};function L(t,e,n,a){if(t==="category"&&e!==null&&n==="in")return s.category+' "'+e+'" ('+s.in+(y?", "+a+")":")");if(t==="category"&&e===null&&n==="in")return s.unknown_category+" ("+s.in+(y?", "+a+")":")");if(t==="category"&&e!==null&&n==="out")return s.category+' "'+e+'" ('+s.out+(y?", "+a+")":")");if(t==="category"&&e===null&&n==="out")return s.unknown_category+" ("+s.out+(y?", "+a+")":")");if(t==="account"&&e===null&&n==="in")return s.unknown_source+(y?" ("+a+")":"");if(t==="account"&&e!==null&&n==="in")return s.revenue_account+'"'+e+'"'+(y?" ("+a+")":"");if(t==="account"&&e===null&&n==="out")return s.unknown_dest+(y?" ("+a+")":"");if(t==="account"&&e!==null&&n==="out")return s.expense_account+' "'+e+'"'+(y?" ("+a+")":"");if(t==="budget"&&e!==null)return s.budget+' "'+e+'"'+(y?" ("+a+")":"");if(t==="budget"&&e===null)return s.unknown_budget+(y?" ("+a+")":"");console.error('Cannot handle: type:"'+t+'", dir: "'+n+'"')}function E(t,e,n){if(t==="category"&&e!==null)return s.category+' "'+e+'"'+(y?" ("+n+")":"");if(t==="category"&&e===null)return s.unknown_category+(y?" ("+n+")":"");if(t==="account"&&e===null)return s.unknown_account+(y?" ("+n+")":"");if(t==="account"&&e!==null)return e+(y?" ("+n+")":"");if(t==="budget"&&e!==null)return s.budget+' "'+e+'"'+(y?" ("+n+")":"");if(t==="budget"&&e===null)return s.unknown_budget+(y?" ("+n+")":"");console.error('Cannot handle: type:"'+t+'"')}const Qt=()=>({loading:!1,autoConversion:!1,generateOptions(){let t=N("sankey"),e={},n={};for(let r in D)if(D.hasOwnProperty(r)){let o=D[r];for(let i in o.attributes.transactions)if(o.attributes.transactions.hasOwnProperty(i)){let l=o.attributes.transactions[i],u=this.autoConversion?l.native_currency_code:l.currency_code,d=this.autoConversion?parseFloat(l.native_amount):parseFloat(l.amount),h;if(l.type==="deposit"){let c=L("category",l.category_name,"in",u),_=L("account",l.source_name,"in",u);n[c]=E("category",l.category_name,u),n[_]=E("account",l.source_name,u),h=_+"-"+c+"-"+u,e.hasOwnProperty(h)||(e[h]={from:_,to:c,amount:0}),e[h].amount+=d,h=c+"-"+s.all_money+"-"+u,e.hasOwnProperty(h)||(e[h]={from:c,to:s.all_money+(this.autoConversion?" ("+u+")":""),amount:0}),e[h].amount+=d}if(l.type==="withdrawal"){let c=L("budget",l.budget_name,"out",u);n[c]=E("budget",l.budget_name,u),h=s.all_money+"-"+c+"-"+u,e.hasOwnProperty(h)||(e[h]={from:s.all_money+(this.autoConversion?" ("+u+")":""),to:c,amount:0}),e[h].amount+=d;let _=L("category",l.category_name,"out",u);n[_]=E("category",l.category_name,u),h=c+"-"+_+"-"+u,e.hasOwnProperty(h)||(e[h]={from:c,to:_,amount:0}),e[h].amount+=d;let w=L("account",l.destination_name,"out",u);n[w]=E("account",l.destination_name,u),h=_+"-"+w+"-"+u,e.hasOwnProperty(h)||(e[h]={from:_,to:w,amount:0}),e[h].amount+=d}}}let a={label:"Firefly III dashboard sankey chart",data:[],colorFrom:r=>dt(r.dataset.data[r.dataIndex]?r.dataset.data[r.dataIndex].from:""),colorTo:r=>dt(r.dataset.data[r.dataIndex]?r.dataset.data[r.dataIndex].to:""),colorMode:"gradient",labels:n,size:"min"};for(let r in e)if(e.hasOwnProperty(r)){let o=e[r];a.data.push({from:o.from,to:o.to,flow:o.amount})}return t.data.datasets.push(a),t},drawChart(t){if(R!==null){R.data.datasets=t.data.datasets,R.update();return}R=new S(document.querySelector("#sankey-chart"),t)},getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P(ct,t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){D=r,this.drawChart(this.generateOptions()),this.loading=!1;return}let o={start:g(t,"y-MM-dd"),end:g(e,"y-MM-dd"),type:"withdrawal,deposit",page:1};this.downloadTransactions(o)},downloadTransactions(t){const e=new Date(window.store.get("start")),n=new Date(window.store.get("end")),a=P(ct,e,n);new $t().list(t).then(o=>{if(D=[...D,...o.data.data],parseInt(o.data.meta.pagination.total_pages)>t.page){t.page++,this.downloadTransactions(t);return}window.store.set(a,D),this.drawChart(this.generateOptions()),this.loading=!1})},loadChart(){if(this.loading!==!0){if(this.loading=!0,D.length!==0){this.drawChart(this.generateOptions()),this.loading=!1;return}this.getFreshData()}},init(){D=[],Promise.all([v("autoConversion",!1)]).then(t=>{this.autoConversion=t[0],y=t[0],s.all_money=p.t("firefly.all_money"),s.category=p.t("firefly.category"),s.in=p.t("firefly.money_flowing_in"),s.out=p.t("firefly.money_flowing_out"),s.unknown_category=p.t("firefly.unknown_category_plain"),s.unknown_source=p.t("firefly.unknown_source_plain"),s.unknown_dest=p.t("firefly.unknown_dest_plain"),s.unknown_account=p.t("firefly.unknown_any_plain"),s.unknown_budget=p.t("firefly.unknown_budget_plain"),s.expense_account=p.t("firefly.expense_account"),s.revenue_account=p.t("firefly.revenue_account"),s.budget=p.t("firefly.budget"),X=!0,this.loadChart()}),window.store.observe("end",()=>{X&&(this.transactions=[],this.loadChart())}),window.store.observe("autoConversion",t=>{X&&(this.autoConversion=t,this.loadChart())})}});let tt=!1,b={};function gt(t){return new Vt().list(t).then(n=>{let a=n.data.data;for(let r in a)if(a.hasOwnProperty(r)){let o=a[r];if(o.attributes.active&&o.attributes.pay_dates.length>0){let i=o.attributes.object_group_id===null?0:o.attributes.object_group_id,l=o.attributes.object_group_title===null?p.t("firefly.default_group_title_name_plain"):o.attributes.object_group_title,u=o.attributes.object_group_order===null?0:o.attributes.object_group_order;b.hasOwnProperty(i)||(b[i]={id:i,title:l,order:u,payment_info:{},bills:[]});let d={id:o.id,name:o.attributes.name,amount_min:o.attributes.amount_min,amount_max:o.attributes.amount_max,amount:(parseFloat(o.attributes.amount_max)+parseFloat(o.attributes.amount_min))/2,currency_code:o.attributes.currency_code,native_amount_min:o.attributes.native_amount_min,native_amount_max:o.attributes.native_amount_max,native_amount:(parseFloat(o.attributes.native_amount_max)+parseFloat(o.attributes.native_amount_min))/2,native_currency_code:o.attributes.native_currency_code,transactions:[],pay_dates:o.attributes.pay_dates,paid:o.attributes.paid_dates.length>0};d.expected_amount=t.autoConversion?f(d.native_amount,d.native_currency_code):f(d.amount,d.currency_code),d.expected_times=p.t("firefly.subscr_expected_x_times",{times:o.attributes.pay_dates.length,amount:d.expected_amount});for(let h in o.attributes.paid_dates)if(o.attributes.paid_dates.hasOwnProperty(h)){const c=o.attributes.paid_dates[h];let _=100;t.autoConversion&&(_=Math.round(-100+parseFloat(c.native_amount)*-1/parseFloat(d.native_amount)*100)),t.autoConversion||(_=Math.round(-100+parseFloat(c.amount)*-1/parseFloat(d.amount)*100));let w={amount:t.autoConversion?f(c.native_amount,c.native_currency_code):f(c.amount,c.currency_code),percentage:_,date:g(new Date(c.date),"PP"),foreign_amount:null};c.foreign_currency_code!==null&&(w.foreign_amount=t.autoConversion?c.foreign_native_amount:c.foreign_amount,w.foreign_currency_code=t.autoConversion?c.native_currency_code:c.foreign_currency_code),d.transactions.push(w)}if(b[i].bills.push(d),o.attributes.paid_dates.length===0){const h=o.attributes.pay_dates.length*d.amount,c=o.attributes.pay_dates.length*d.native_amount;b[i].payment_info.hasOwnProperty(d.currency_code)||(b[i].payment_info[d.currency_code]={currency_code:d.currency_code,paid:0,unpaid:0,native_currency_code:d.native_currency_code,native_paid:0,native_unpaid:0}),b[i].payment_info[d.currency_code].unpaid+=h,b[i].payment_info[d.currency_code].native_unpaid+=c}if(o.attributes.paid_dates.length>0){for(let h in o.attributes.paid_dates)if(o.attributes.paid_dates.hasOwnProperty(h)){let c=o.attributes.paid_dates[h];b[i].payment_info.hasOwnProperty(c.currency_code)||(b[i].payment_info[c.currency_code]={currency_code:d.currency_code,paid:0,unpaid:0,native_currency_code:d.native_currency_code,native_paid:0,native_unpaid:0});const _=parseFloat(c.amount)*-1,w=parseFloat(c.native_amount)*-1;b[i].payment_info[c.currency_code].paid+=_,b[i].payment_info[c.currency_code].native_paid+=w}}}}return parseInt(n.data.meta.pagination.total_pages)>t.page?(t.page++,gt(t)):Promise.resolve()})}const Xt=()=>({loading:!1,autoConversion:!1,subscriptions:[],startSubscriptions(){this.loading=!0;let t=new Date(window.store.get("start")),e=new Date(window.store.get("end"));const n=window.store.get("cacheValid");let a=window.store.get(P("subscriptions-data-dashboard",t,e));n&&typeof a<"u",b={},this.subscriptions=[];let r={start:g(t,"y-MM-dd"),end:g(e,"y-MM-dd"),autoConversion:this.autoConversion,page:1};gt(r).then(()=>{let o=Object.values(b);for(let i in o)if(o.hasOwnProperty(i)){let l=o[i];const u=Object.keys(l.payment_info);l.col_size=u.length===1?"col-6 offset-3":"col-6",l.chart_width=u.length===1?"50%":"100%",l.payment_length=u.length,this.subscriptions.push(l)}this.loading=!1})},drawPieChart(t,e,n){let a="#pie_"+t+"_"+n.currency_code;const r=this.autoConversion?n.native_unpaid:n.unpaid,o=this.autoConversion?n.native_paid:n.paid,i=this.autoConversion?n.native_currency_code:n.currency_code,u={type:"doughnut",data:{labels:[p.t("firefly.paid"),p.t("firefly.unpaid")],datasets:[{label:p.t("firefly.subscriptions_in_group",{title:e}),data:[o,r],backgroundColor:["rgb(54, 162, 235)","rgb(255, 99, 132)"],hoverOffset:4}]},options:{plugins:{tooltip:{callbacks:{label:function(h){return h.dataset.label+": "+f(h.raw,i)}}}}}};var d=S.getChart(document.querySelector(a));typeof d<"u"&&d.destroy(),new S(document.querySelector(a),u)},init(){Promise.all([v("autoConversion",!1)]).then(t=>{this.autoConversion=t[0],tt=!0,this.loading===!1&&this.startSubscriptions()}),window.store.observe("end",()=>{tt&&this.loading===!1&&this.startSubscriptions()}),window.store.observe("autoConversion",t=>{tt&&(this.autoConversion=t,this.loading===!1&&this.startSubscriptions())})}});let x={},et=!1;const ht="dashboard-piggies-data",te=()=>({loading:!1,autoConversion:!1,sankeyGrouping:"account",piggies:[],getFreshData(){const t=new Date(window.store.get("start")),e=new Date(window.store.get("end")),n=P(ht,t,e),a=window.store.get("cacheValid");let r=window.store.get(n);if(a&&typeof r<"u"){x=r,this.parsePiggies(),this.loading=!1;return}let o={start:g(t,"y-MM-dd"),end:g(e,"y-MM-dd"),page:1};this.downloadPiggyBanks(o)},downloadPiggyBanks(t){const e=new Date(window.store.get("start")),n=new Date(window.store.get("end")),a=P(ht,e,n);new Kt().list(t).then(o=>{if(x=[...x,...o.data.data],parseInt(o.data.meta.pagination.total_pages)>t.page){t.page++,this.downloadPiggyBanks(t);return}window.store.set(a,x),this.parsePiggies(),this.loading=!1})},parsePiggies(){let t=[];for(let e in x)if(x.hasOwnProperty(e)){let n=x[e];if(n.attributes.percentage>=100||n.attributes.percentage===0)continue;let a=n.object_group_title??p.t("firefly.default_group_title_name_plain");t.hasOwnProperty(a)||(t[a]={id:n.object_group_id??0,title:a,order:n.object_group_order??0,piggies:[]});let r={id:n.id,name:n.attributes.name,percentage:parseInt(n.attributes.percentage),amount:this.autoConversion?n.attributes.native_current_amount:n.attributes.current_amount,left_to_save:this.autoConversion?n.attributes.native_left_to_save:n.attributes.left_to_save,target_amount:this.autoConversion?n.attributes.native_target_amount:n.attributes.target_amount,save_per_month:this.autoConversion?n.attributes.native_save_per_month:n.attributes.save_per_month,currency_code:this.autoConversion?n.attributes.native_currency_code:n.attributes.currency_code};t[a].piggies.push(r)}this.piggies=Object.values(t)},loadPiggyBanks(){if(this.loading!==!0){if(this.loading=!0,this.piggies.length!==0){this.parsePiggies(),this.loading=!1;return}this.getFreshData()}},init(){x=[],Promise.all([v("autoConversion",!1)]).then(t=>{et=!0,this.autoConversion=t[0],this.loadPiggyBanks()}),window.store.observe("end",()=>{et&&(x=[],this.loadPiggyBanks())}),window.store.observe("autoConversion",t=>{et&&(this.autoConversion=t,this.loadPiggyBanks())})}});S.register({LineController:Ct,LineElement:kt,ArcElement:Pt,BarController:Dt,TimeScale:xt,PieController:Ot,BarElement:Mt,Filler:Ft,Colors:St,LinearScale:At,CategoryScale:Bt,PointElement:jt,Tooltip:Wt,Legend:It});const pt={dates:wt,boxes:Et,accounts:Ut,budgets:Ht,categories:Zt,sankey:Qt,subscriptions:Xt,piggies:te};function _t(t){Object.keys(t).forEach(e=>{let n=t[e]();Alpine.data(e,()=>n)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),_t(pt)});window.bootstrapped&&(console.log("Loaded through window variable."),_t(pt)); diff --git a/public/build/assets/edit-203e67aa.js b/public/build/assets/edit-0910e359.js similarity index 94% rename from public/build/assets/edit-203e67aa.js rename to public/build/assets/edit-0910e359.js index 3dc8c629c4..4d040f6c54 100644 --- a/public/build/assets/edit-203e67aa.js +++ b/public/build/assets/edit-0910e359.js @@ -1 +1 @@ -import{d as p,f as l}from"./format-money-276370ed.js";import{G as f}from"./get-9c5eaf42.js";import{p as g}from"./parse-downloaded-splits-7301d402.js";import{p as m,d as w,e as a,f as y,g as b,h as P,i as S,l as v,a as C,b as A,c as _,s as E,j as D,k as c,m as u}from"./splice-errors-into-transactions-5f35da56.js";import{i as o,m as T}from"./vendor-7d6e65fe.js";import{d as x}from"./create-empty-split-d23e6a0d.js";import{P as B}from"./put-016ad2aa.js";import"./get-5385bfb8.js";const n=D();let L=function(){return{entries:[],originals:[],formStates:{loadingCurrencies:!0,loadingBudgets:!0,loadingPiggyBanks:!0,loadingSubscriptions:!0,isSubmitting:!1,returnHereButton:!1,saveAsNewButton:!1,resetButton:!0,rulesButton:!0,webhooksButton:!0},formBehaviour:{formType:"edit",foreignCurrencyEnabled:!0},formData:{defaultCurrency:null,enabledCurrencies:[],nativeCurrencies:[],foreignCurrencies:[],budgets:[],piggyBanks:[],subscriptions:[]},groupProperties:{transactionType:"unknown",title:null,editTitle:null,id:null,totalAmount:0},notifications:{error:{show:!1,text:"",url:""},success:{show:!1,text:"",url:""},wait:{show:!1,text:""}},submitTransaction(){this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1;for(let e in this.entries)this.entries.hasOwnProperty(e)&&(this.entries[e].errors=x());this.formStates.isSubmitting=!0;let t=m(this.entries,this.originals,this.groupProperties.transactionType),s={group_title:this.groupProperties.editTitle,fire_webhooks:this.formStates.webhooksButton,apply_rules:this.formStates.rulesButton,transactions:t};this.groupProperties.title===null&&t.length>1&&(s.group_title=t[0].description);let r=new B;console.log(s),r.put(s,{id:this.groupProperties.id}).then(e=>{const i=e.data.data;if(this.groupProperties.id=parseInt(i.id),this.groupProperties.title=i.attributes.group_title??i.attributes.transactions[0].description,w(this.groupProperties.id,i.attributes.transactions)>0){this.notifications.wait.show=!0,this.notifications.wait.text=o.t("firefly.wait_attachments");return}this.showMessageOrRedirectUser()}).catch(e=>{this.submitting=!1,console.log(e),typeof e.response<"u"&&this.parseErrors(e.response.data)})},filters:{source:[],destination:[]},addedSplit(){setTimeout(()=>{const t=function(s,r,e){return s.name_with_balance+'
'+o.t("firefly.account_type_"+s.type)+""};a({selector:"input.ac-source",serverUrl:n.account,filters:this.filters.source,onRenderItem:t,onChange:y,onSelectItem:b}),a({selector:"input.ac-dest",serverUrl:n.account,filters:this.filters.destination,onRenderItem:t,onChange:P,onSelectItem:S}),a({selector:"input.ac-category",serverUrl:n.category,valueField:"id",labelField:"name",onChange:c,onSelectItem:c}),a({selector:"input.ac-description",serverUrl:n.description,valueField:"id",labelField:"description",onChange:u,onSelectItem:u})},250)},changedDateTime(t){console.warn("changedDateTime, event is not used")},changedDescription(t){console.warn("changedDescription, event is not used")},changedDestinationAccount(t){console.warn("changedDestinationAccount, event is not used")},changedSourceAccount(t){console.warn("changedSourceAccount, event is not used")},formattedTotalAmount(){return this.entries.length===0?l(this.groupProperties.totalAmount,"EUR"):l(this.groupProperties.totalAmount,this.entries[0].currency_code??"EUR")},getTags(t){return console.log("at get tags "+t),console.log(this.entries[t].tags),this.entries[t].tags??[]},getTransactionGroup(){this.entries=[];const t=window.location.href.split("/"),s=parseInt(t[t.length-1]);new f().show(s,{}).then(e=>{const i=e.data.data;this.groupProperties.id=parseInt(i.id),this.groupProperties.transactionType=i.attributes.transactions[0].type.toLowerCase(),this.groupProperties.title=i.attributes.title??i.attributes.transactions[0].description,this.entries=g(i.attributes.transactions,parseInt(i.id)),this.notifications.wait.show=!1}).then(()=>{this.groupProperties.totalAmount=0;for(let e in this.entries)this.entries.hasOwnProperty(e)&&(this.groupProperties.totalAmount=this.groupProperties.totalAmount+parseFloat(this.entries[e].amount),this.filters.source.push(this.entries[e].source_account.type),this.filters.destination.push(this.entries[e].destination_account.type));console.log(this.filters),setTimeout(()=>{T.init("select.ac-tags",{allowClear:!0,server:n.tag,liveServer:!0,clearEnd:!0,allowNew:!0,notFoundMessage:o.t("firefly.nothing_found"),noCache:!0,fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}}})},150)})},init(){this.notifications.wait.show=!0,this.notifications.wait.text=o.t("firefly.wait_loading_transaction"),this.getTransactionGroup(),v().then(t=>{this.formStates.loadingCurrencies=!1,this.formData.defaultCurrency=t.defaultCurrency,this.formData.enabledCurrencies=t.enabledCurrencies,this.formData.nativeCurrencies=t.nativeCurrencies,this.formData.foreignCurrencies=t.foreignCurrencies}),C().then(t=>{this.formData.budgets=t,this.formStates.loadingBudgets=!1}),A().then(t=>{this.formData.piggyBanks=t,this.formStates.loadingPiggyBanks=!1}),_().then(t=>{this.formData.subscriptions=t,this.formStates.loadingSubscriptions=!1}),document.addEventListener("upload-success",t=>{this.processUpload(t),document.querySelectorAll("input[type=file]").value=""}),document.addEventListener("upload-error",t=>{this.processUploadError(t)}),document.addEventListener("location-move",t=>{this.entries[t.detail.index].latitude=t.detail.latitude,this.entries[t.detail.index].longitude=t.detail.longitude}),document.addEventListener("location-set",t=>{this.entries[t.detail.index].hasLocation=!0,this.entries[t.detail.index].latitude=t.detail.latitude,this.entries[t.detail.index].longitude=t.detail.longitude,this.entries[t.detail.index].zoomLevel=t.detail.zoomLevel}),document.addEventListener("location-zoom",t=>{this.entries[t.detail.index].hasLocation=!0,this.entries[t.detail.index].zoomLevel=t.detail.zoomLevel})},changedAmount(t){const s=parseInt(t.target.dataset.index);this.entries[s].amount=parseFloat(t.target.value),this.groupProperties.totalAmount=0;for(let r in this.entries)this.entries.hasOwnProperty(r)&&(this.groupProperties.totalAmount=this.groupProperties.totalAmount+parseFloat(this.entries[r].amount))},showMessageOrRedirectUser(){if(this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.returnHereButton){this.notifications.success.show=!0,this.notifications.success.url="transactions/show/"+this.groupProperties.id,this.notifications.success.text=o.t("firefly.updated_journal_js",{description:this.groupProperties.title});return}window.location="transactions/show/"+this.groupProperties.id+"?transaction_group_id="+this.groupProperties.id+"&message=updated"},parseErrors(t){this.notifications.error.show=!0,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.isSubmitting=!1,this.notifications.error.text=o.t("firefly.errors_submission_v2",{errorMessage:t.message}),t.hasOwnProperty("errors")&&(this.entries=E(t.errors,this.entries))},processUpload(t){this.showMessageOrRedirectUser()},processUploadError(t){this.notifications.success.show=!1,this.notifications.wait.show=!1,this.notifications.error.show=!0,this.formStates.isSubmitting=!1,this.notifications.error.text=o.t("firefly.errors_upload"),console.error(t)}}},h={transactions:L,dates:p};function d(){Object.keys(h).forEach(t=>{console.log(`Loading page component "${t}"`);let s=h[t]();Alpine.data(t,()=>s)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),d()});window.bootstrapped&&(console.log("Loaded through window variable."),d()); +import{d as p,f as l}from"./format-money-2cbd3c32.js";import{G as f}from"./get-f02d6b9c.js";import{p as g}from"./parse-downloaded-splits-a5d66b5f.js";import{p as m,d as w,e as a,f as y,g as b,h as P,i as S,l as v,a as C,b as A,c as _,s as E,j as D,k as c,m as u}from"./splice-errors-into-transactions-8731db70.js";import{i as o,m as T}from"./vendor-47e474ee.js";import{d as x}from"./create-empty-split-c1e678fd.js";import{P as B}from"./put-375c2f08.js";import"./get-4f3e9dd6.js";const n=D();let L=function(){return{entries:[],originals:[],formStates:{loadingCurrencies:!0,loadingBudgets:!0,loadingPiggyBanks:!0,loadingSubscriptions:!0,isSubmitting:!1,returnHereButton:!1,saveAsNewButton:!1,resetButton:!0,rulesButton:!0,webhooksButton:!0},formBehaviour:{formType:"edit",foreignCurrencyEnabled:!0},formData:{defaultCurrency:null,enabledCurrencies:[],nativeCurrencies:[],foreignCurrencies:[],budgets:[],piggyBanks:[],subscriptions:[]},groupProperties:{transactionType:"unknown",title:null,editTitle:null,id:null,totalAmount:0},notifications:{error:{show:!1,text:"",url:""},success:{show:!1,text:"",url:""},wait:{show:!1,text:""}},submitTransaction(){this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1;for(let e in this.entries)this.entries.hasOwnProperty(e)&&(this.entries[e].errors=x());this.formStates.isSubmitting=!0;let t=m(this.entries,this.originals,this.groupProperties.transactionType),s={group_title:this.groupProperties.editTitle,fire_webhooks:this.formStates.webhooksButton,apply_rules:this.formStates.rulesButton,transactions:t};this.groupProperties.title===null&&t.length>1&&(s.group_title=t[0].description);let r=new B;console.log(s),r.put(s,{id:this.groupProperties.id}).then(e=>{const i=e.data.data;if(this.groupProperties.id=parseInt(i.id),this.groupProperties.title=i.attributes.group_title??i.attributes.transactions[0].description,w(this.groupProperties.id,i.attributes.transactions)>0){this.notifications.wait.show=!0,this.notifications.wait.text=o.t("firefly.wait_attachments");return}this.showMessageOrRedirectUser()}).catch(e=>{this.submitting=!1,console.log(e),typeof e.response<"u"&&this.parseErrors(e.response.data)})},filters:{source:[],destination:[]},addedSplit(){setTimeout(()=>{const t=function(s,r,e){return s.name_with_balance+'
'+o.t("firefly.account_type_"+s.type)+""};a({selector:"input.ac-source",serverUrl:n.account,filters:this.filters.source,onRenderItem:t,onChange:y,onSelectItem:b}),a({selector:"input.ac-dest",serverUrl:n.account,filters:this.filters.destination,onRenderItem:t,onChange:P,onSelectItem:S}),a({selector:"input.ac-category",serverUrl:n.category,valueField:"id",labelField:"name",onChange:c,onSelectItem:c}),a({selector:"input.ac-description",serverUrl:n.description,valueField:"id",labelField:"description",onChange:u,onSelectItem:u})},250)},changedDateTime(t){console.warn("changedDateTime, event is not used")},changedDescription(t){console.warn("changedDescription, event is not used")},changedDestinationAccount(t){console.warn("changedDestinationAccount, event is not used")},changedSourceAccount(t){console.warn("changedSourceAccount, event is not used")},formattedTotalAmount(){return this.entries.length===0?l(this.groupProperties.totalAmount,"EUR"):l(this.groupProperties.totalAmount,this.entries[0].currency_code??"EUR")},getTags(t){return console.log("at get tags "+t),console.log(this.entries[t].tags),this.entries[t].tags??[]},getTransactionGroup(){this.entries=[];const t=window.location.href.split("/"),s=parseInt(t[t.length-1]);new f().show(s,{}).then(e=>{const i=e.data.data;this.groupProperties.id=parseInt(i.id),this.groupProperties.transactionType=i.attributes.transactions[0].type.toLowerCase(),this.groupProperties.title=i.attributes.title??i.attributes.transactions[0].description,this.entries=g(i.attributes.transactions,parseInt(i.id)),this.notifications.wait.show=!1}).then(()=>{this.groupProperties.totalAmount=0;for(let e in this.entries)this.entries.hasOwnProperty(e)&&(this.groupProperties.totalAmount=this.groupProperties.totalAmount+parseFloat(this.entries[e].amount),this.filters.source.push(this.entries[e].source_account.type),this.filters.destination.push(this.entries[e].destination_account.type));console.log(this.filters),setTimeout(()=>{T.init("select.ac-tags",{allowClear:!0,server:n.tag,liveServer:!0,clearEnd:!0,allowNew:!0,notFoundMessage:o.t("firefly.nothing_found"),noCache:!0,fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}}})},150)})},init(){this.notifications.wait.show=!0,this.notifications.wait.text=o.t("firefly.wait_loading_transaction"),this.getTransactionGroup(),v().then(t=>{this.formStates.loadingCurrencies=!1,this.formData.defaultCurrency=t.defaultCurrency,this.formData.enabledCurrencies=t.enabledCurrencies,this.formData.nativeCurrencies=t.nativeCurrencies,this.formData.foreignCurrencies=t.foreignCurrencies}),C().then(t=>{this.formData.budgets=t,this.formStates.loadingBudgets=!1}),A().then(t=>{this.formData.piggyBanks=t,this.formStates.loadingPiggyBanks=!1}),_().then(t=>{this.formData.subscriptions=t,this.formStates.loadingSubscriptions=!1}),document.addEventListener("upload-success",t=>{this.processUpload(t),document.querySelectorAll("input[type=file]").value=""}),document.addEventListener("upload-error",t=>{this.processUploadError(t)}),document.addEventListener("location-move",t=>{this.entries[t.detail.index].latitude=t.detail.latitude,this.entries[t.detail.index].longitude=t.detail.longitude}),document.addEventListener("location-set",t=>{this.entries[t.detail.index].hasLocation=!0,this.entries[t.detail.index].latitude=t.detail.latitude,this.entries[t.detail.index].longitude=t.detail.longitude,this.entries[t.detail.index].zoomLevel=t.detail.zoomLevel}),document.addEventListener("location-zoom",t=>{this.entries[t.detail.index].hasLocation=!0,this.entries[t.detail.index].zoomLevel=t.detail.zoomLevel})},changedAmount(t){const s=parseInt(t.target.dataset.index);this.entries[s].amount=parseFloat(t.target.value),this.groupProperties.totalAmount=0;for(let r in this.entries)this.entries.hasOwnProperty(r)&&(this.groupProperties.totalAmount=this.groupProperties.totalAmount+parseFloat(this.entries[r].amount))},showMessageOrRedirectUser(){if(this.notifications.error.show=!1,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.returnHereButton){this.notifications.success.show=!0,this.notifications.success.url="transactions/show/"+this.groupProperties.id,this.notifications.success.text=o.t("firefly.updated_journal_js",{description:this.groupProperties.title});return}window.location="transactions/show/"+this.groupProperties.id+"?transaction_group_id="+this.groupProperties.id+"&message=updated"},parseErrors(t){this.notifications.error.show=!0,this.notifications.success.show=!1,this.notifications.wait.show=!1,this.formStates.isSubmitting=!1,this.notifications.error.text=o.t("firefly.errors_submission_v2",{errorMessage:t.message}),t.hasOwnProperty("errors")&&(this.entries=E(t.errors,this.entries))},processUpload(t){this.showMessageOrRedirectUser()},processUploadError(t){this.notifications.success.show=!1,this.notifications.wait.show=!1,this.notifications.error.show=!0,this.formStates.isSubmitting=!1,this.notifications.error.text=o.t("firefly.errors_upload"),console.error(t)}}},h={transactions:L,dates:p};function d(){Object.keys(h).forEach(t=>{console.log(`Loading page component "${t}"`);let s=h[t]();Alpine.data(t,()=>s)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),d()});window.bootstrapped&&(console.log("Loaded through window variable."),d()); diff --git a/public/build/assets/format-money-276370ed.js b/public/build/assets/format-money-2cbd3c32.js similarity index 99% rename from public/build/assets/format-money-276370ed.js rename to public/build/assets/format-money-2cbd3c32.js index f6c928aa28..285a24a3ce 100644 --- a/public/build/assets/format-money-276370ed.js +++ b/public/build/assets/format-money-2cbd3c32.js @@ -1 +1 @@ -import{q as y,s as d,r as l,t as p,u as _,v as c,w as b,x as N,y as P,z as v,D as g,i as C,E as B,G as x,H as O,J as o,K as E,N as T,f as L,O as S,Q as W,R as U,U as I,V as q,W as Q,X as V,Y,Z as $,_ as j,$ as z,a0 as X,a1 as F,a2 as G,a3 as H,a4 as J,a5 as K,a6 as Z,a7 as ee,a8 as te,a9 as ae,aa as se,ab as ne,ac as re,ad as le,ae as de,af as oe,ag as ie,ah as ue,ai as ge,aj as ce,ak as we,al as he,am as ye}from"./vendor-7d6e65fe.js";const k="/",h=y.create({baseURL:k,withCredentials:!0});y.defaults.withCredentials=!0;y.defaults.baseURL=k;class R{getByName(e){return h.get("/api/v1/preferences/"+e)}getByNameNow(e){return h.get("/api/v1/preferences/"+e)}postByName(e,a){return h.post("/api/v1/preferences",{name:e,data:a})}}class A{post(e,a){let s="/api/v1/preferences";return h.post(s,{name:e,data:a})}}function fe(t,e=null){return new R().getByName(t).then(s=>Promise.resolve(m(t,s))).catch(()=>{new A().post(t,e).then(i=>Promise.resolve(m(t,i)))})}function m(t,e){return e.data.data.attributes.data}function w(t,e=null){const a=window.store.get("cacheValid");if(a&&window.hasOwnProperty(t))return Promise.resolve(window[t]);const s=window.store.get(t);return a&&typeof s<"u"?Promise.resolve(s):new R().getByName(t).then(u=>Promise.resolve(M(t,u))).catch(()=>{new A().post(t,e).then(n=>Promise.resolve(M(t,n)))})}function M(t,e){let a=e.data.data.attributes.data;return window.store.set(t,a),a}function be(t,e){let a,s;switch(t){case"last365":a=d(g(e,365)),s=l(e);break;case"last90":a=d(g(e,90)),s=l(e);break;case"last30":a=d(g(e,30)),s=l(e);break;case"last7":a=d(g(e,7)),s=l(e);break;case"YTD":a=v(e),s=l(e);break;case"QTD":a=p(e),s=l(e);break;case"MTD":a=c(e),s=l(e);break;case"1D":a=d(e),s=l(e);break;case"1W":a=d(N(e,{weekStartsOn:1})),s=l(P(e,{weekStartsOn:1}));break;case"1M":a=d(c(e)),s=l(b(e));break;case"3M":a=d(p(e)),s=l(_(e));break;case"6M":e.getMonth()<=5&&(a=new Date(e),a.setMonth(0),a.setDate(1),a=d(a),s=new Date(e),s.setMonth(5),s.setDate(30),s=l(a)),e.getMonth()>5&&(a=new Date(e),a.setMonth(6),a.setDate(1),a=d(a),s=new Date(e),s.setMonth(11),s.setDate(31),s=l(a));break;case"1Y":a=new Date(e),a.setMonth(0),a.setDate(1),a=d(a),s=new Date(e),s.setMonth(11),s.setDate(31),s=l(s);break}return{start:a,end:s}}let D=!1;function pe(t){if(D===!1){const e=t.replace("-","_");D=!0;const a=7*24*60*60*1e3;return console.log('Will load language "'+e+'"'),C.use(B).init({load:"languageOnly",fallbackLng:"en",lng:e,debug:!1,backend:{backends:[x,O],backendOptions:[{load:"languageOnly",expirationTime:a},{loadPath:"./v2/i18n/{{lng}}.json"}]}})}return console.warn("Loading translations skipped."),Promise.resolve()}o.addPlugin(E);window.bootstrapped=!1;window.store=o;fe("lastActivity").then(t=>{const e=o.get("lastActivity");o.set("cacheValid",e===t),o.set("lastActivity",t),console.log("Server value: "+t),console.log("Local value: "+e),console.log("Cache valid: "+(e===t))}).then(()=>{Promise.all([w("viewRange"),w("darkMode"),w("locale"),w("language")]).then(t=>{if(!o.get("start")||!o.get("end")){const e=be(t[0],new Date);o.set("start",e.start),o.set("end",e.end)}window.__localeId__=t[2],o.set("language",t[3]),o.set("locale",t[3]),pe(t[3]).then(()=>{const e=new Event("firefly-iii-bootstrapped");document.dispatchEvent(e),window.bootstrapped=!0})})});window.axios=y;window.axios.defaults.headers.common["X-Requested-With"]="XMLHttpRequest";window.Alpine=T;const f={bg:S,cs:W,da:U,de:I,el:q,enGB:Q,enUS:V,es:Y,ca:$,fi:j,fr:z,hu:X,id:F,it:G,ja:H,ko:J,nb:K,nn:Z,nl:ee,pl:te,ptBR:ae,pt:se,ro:ne,ru:re,sk:le,sl:de,sv:oe,tr:ie,uk:ue,vi:ge,zhTW:ce,zhCN:we};function r(t,e="PP"){let a=window.__localeId__.replace("_","");return L(t,e,{locale:f[a]??f[a.slice(0,2)]??f.enUS})}const Me=()=>({range:{start:null,end:null},defaultRange:{start:null,end:null},language:"en_US",init(){this.range={start:new Date(window.store.get("start")),end:new Date(window.store.get("end"))},this.defaultRange={start:new Date(window.store.get("start")),end:new Date(window.store.get("end"))},this.language=window.store.get("language"),this.locale=window.store.get("locale"),this.locale=this.locale==="equal"?this.language:this.locale,window.__localeId__=this.language,this.buildDateRange(),window.store.observe("start",t=>{this.range.start=new Date(t)}),window.store.observe("end",t=>{this.range.end=new Date(t),this.buildDateRange()})},buildDateRange(){let t=this.getNextRange(),e=this.getPrevRange(),a=this.lastDays(7),s=this.lastDays(30),i=this.mtd(),u=this.ytd(),n=document.getElementsByClassName("daterange-holder")[0];n.textContent=r(this.range.start)+" - "+r(this.range.end),n.setAttribute("data-start",r(this.range.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(this.range.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-current")[0],n.textContent=r(this.defaultRange.start)+" - "+r(this.defaultRange.end),n.setAttribute("data-start",r(this.defaultRange.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(this.defaultRange.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-next")[0],n.textContent=r(t.start)+" - "+r(t.end),n.setAttribute("data-start",r(t.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(t.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-prev")[0],n.textContent=r(e.start)+" - "+r(e.end),n.setAttribute("data-start",r(e.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(e.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-7d")[0],n.setAttribute("data-start",r(a.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(a.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-90d")[0],n.setAttribute("data-start",r(s.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(s.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-mtd")[0],n.setAttribute("data-start",r(i.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(i.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-ytd")[0],n.setAttribute("data-start",r(u.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(u.end,"yyyy-MM-dd"))},getNextRange(){let t=c(this.range.start),e=he(t,1),a=b(e);return{start:e,end:a}},getPrevRange(){let t=c(this.range.start),e=ye(t,1),a=b(e);return{start:e,end:a}},ytd(){let t=new Date;return{start:v(this.range.start),end:t}},mtd(){let t=new Date;return{start:c(this.range.start),end:t}},lastDays(t){let e=new Date;return{start:g(e,t),end:e}},changeDateRange(t){t.preventDefault();let e=t.currentTarget,a=new Date(e.getAttribute("data-start")),s=new Date(e.getAttribute("data-end"));return window.store.set("start",a),window.store.set("end",s),!1}});function De(t,e){let a=window.__localeId__.replace("_","-");return Intl.NumberFormat(a,{style:"currency",currency:e}).format(t)}export{A as P,h as a,r as b,Me as d,De as f,w as g}; +import{q as y,s as d,r as l,t as p,u as _,v as c,w as b,x as N,y as P,z as v,D as g,i as C,E as B,G as x,H as O,J as o,K as E,N as T,f as L,O as S,Q as W,R as U,U as I,V as q,W as Q,X as V,Y,Z as $,_ as j,$ as z,a0 as X,a1 as F,a2 as G,a3 as H,a4 as J,a5 as K,a6 as Z,a7 as ee,a8 as te,a9 as ae,aa as se,ab as ne,ac as re,ad as le,ae as de,af as oe,ag as ie,ah as ue,ai as ge,aj as ce,ak as we,al as he,am as ye}from"./vendor-47e474ee.js";const k="/",h=y.create({baseURL:k,withCredentials:!0});y.defaults.withCredentials=!0;y.defaults.baseURL=k;class R{getByName(e){return h.get("/api/v1/preferences/"+e)}getByNameNow(e){return h.get("/api/v1/preferences/"+e)}postByName(e,a){return h.post("/api/v1/preferences",{name:e,data:a})}}class A{post(e,a){let s="/api/v1/preferences";return h.post(s,{name:e,data:a})}}function fe(t,e=null){return new R().getByName(t).then(s=>Promise.resolve(m(t,s))).catch(()=>{new A().post(t,e).then(i=>Promise.resolve(m(t,i)))})}function m(t,e){return e.data.data.attributes.data}function w(t,e=null){const a=window.store.get("cacheValid");if(a&&window.hasOwnProperty(t))return Promise.resolve(window[t]);const s=window.store.get(t);return a&&typeof s<"u"?Promise.resolve(s):new R().getByName(t).then(u=>Promise.resolve(M(t,u))).catch(()=>{new A().post(t,e).then(n=>Promise.resolve(M(t,n)))})}function M(t,e){let a=e.data.data.attributes.data;return window.store.set(t,a),a}function be(t,e){let a,s;switch(t){case"last365":a=d(g(e,365)),s=l(e);break;case"last90":a=d(g(e,90)),s=l(e);break;case"last30":a=d(g(e,30)),s=l(e);break;case"last7":a=d(g(e,7)),s=l(e);break;case"YTD":a=v(e),s=l(e);break;case"QTD":a=p(e),s=l(e);break;case"MTD":a=c(e),s=l(e);break;case"1D":a=d(e),s=l(e);break;case"1W":a=d(N(e,{weekStartsOn:1})),s=l(P(e,{weekStartsOn:1}));break;case"1M":a=d(c(e)),s=l(b(e));break;case"3M":a=d(p(e)),s=l(_(e));break;case"6M":e.getMonth()<=5&&(a=new Date(e),a.setMonth(0),a.setDate(1),a=d(a),s=new Date(e),s.setMonth(5),s.setDate(30),s=l(a)),e.getMonth()>5&&(a=new Date(e),a.setMonth(6),a.setDate(1),a=d(a),s=new Date(e),s.setMonth(11),s.setDate(31),s=l(a));break;case"1Y":a=new Date(e),a.setMonth(0),a.setDate(1),a=d(a),s=new Date(e),s.setMonth(11),s.setDate(31),s=l(s);break}return{start:a,end:s}}let D=!1;function pe(t){if(D===!1){const e=t.replace("-","_");D=!0;const a=7*24*60*60*1e3;return console.log('Will load language "'+e+'"'),C.use(B).init({load:"languageOnly",fallbackLng:"en",lng:e,debug:!1,backend:{backends:[x,O],backendOptions:[{load:"languageOnly",expirationTime:a},{loadPath:"./v2/i18n/{{lng}}.json"}]}})}return console.warn("Loading translations skipped."),Promise.resolve()}o.addPlugin(E);window.bootstrapped=!1;window.store=o;fe("lastActivity").then(t=>{const e=o.get("lastActivity");o.set("cacheValid",e===t),o.set("lastActivity",t),console.log("Server value: "+t),console.log("Local value: "+e),console.log("Cache valid: "+(e===t))}).then(()=>{Promise.all([w("viewRange"),w("darkMode"),w("locale"),w("language")]).then(t=>{if(!o.get("start")||!o.get("end")){const e=be(t[0],new Date);o.set("start",e.start),o.set("end",e.end)}window.__localeId__=t[2],o.set("language",t[3]),o.set("locale",t[3]),pe(t[3]).then(()=>{const e=new Event("firefly-iii-bootstrapped");document.dispatchEvent(e),window.bootstrapped=!0})})});window.axios=y;window.axios.defaults.headers.common["X-Requested-With"]="XMLHttpRequest";window.Alpine=T;const f={bg:S,cs:W,da:U,de:I,el:q,enGB:Q,enUS:V,es:Y,ca:$,fi:j,fr:z,hu:X,id:F,it:G,ja:H,ko:J,nb:K,nn:Z,nl:ee,pl:te,ptBR:ae,pt:se,ro:ne,ru:re,sk:le,sl:de,sv:oe,tr:ie,uk:ue,vi:ge,zhTW:ce,zhCN:we};function r(t,e="PP"){let a=window.__localeId__.replace("_","");return L(t,e,{locale:f[a]??f[a.slice(0,2)]??f.enUS})}const Me=()=>({range:{start:null,end:null},defaultRange:{start:null,end:null},language:"en_US",init(){this.range={start:new Date(window.store.get("start")),end:new Date(window.store.get("end"))},this.defaultRange={start:new Date(window.store.get("start")),end:new Date(window.store.get("end"))},this.language=window.store.get("language"),this.locale=window.store.get("locale"),this.locale=this.locale==="equal"?this.language:this.locale,window.__localeId__=this.language,this.buildDateRange(),window.store.observe("start",t=>{this.range.start=new Date(t)}),window.store.observe("end",t=>{this.range.end=new Date(t),this.buildDateRange()})},buildDateRange(){let t=this.getNextRange(),e=this.getPrevRange(),a=this.lastDays(7),s=this.lastDays(30),i=this.mtd(),u=this.ytd(),n=document.getElementsByClassName("daterange-holder")[0];n.textContent=r(this.range.start)+" - "+r(this.range.end),n.setAttribute("data-start",r(this.range.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(this.range.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-current")[0],n.textContent=r(this.defaultRange.start)+" - "+r(this.defaultRange.end),n.setAttribute("data-start",r(this.defaultRange.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(this.defaultRange.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-next")[0],n.textContent=r(t.start)+" - "+r(t.end),n.setAttribute("data-start",r(t.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(t.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-prev")[0],n.textContent=r(e.start)+" - "+r(e.end),n.setAttribute("data-start",r(e.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(e.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-7d")[0],n.setAttribute("data-start",r(a.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(a.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-90d")[0],n.setAttribute("data-start",r(s.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(s.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-mtd")[0],n.setAttribute("data-start",r(i.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(i.end,"yyyy-MM-dd")),n=document.getElementsByClassName("daterange-ytd")[0],n.setAttribute("data-start",r(u.start,"yyyy-MM-dd")),n.setAttribute("data-end",r(u.end,"yyyy-MM-dd"))},getNextRange(){let t=c(this.range.start),e=he(t,1),a=b(e);return{start:e,end:a}},getPrevRange(){let t=c(this.range.start),e=ye(t,1),a=b(e);return{start:e,end:a}},ytd(){let t=new Date;return{start:v(this.range.start),end:t}},mtd(){let t=new Date;return{start:c(this.range.start),end:t}},lastDays(t){let e=new Date;return{start:g(e,t),end:e}},changeDateRange(t){t.preventDefault();let e=t.currentTarget,a=new Date(e.getAttribute("data-start")),s=new Date(e.getAttribute("data-end"));return window.store.set("start",a),window.store.set("end",s),!1}});function De(t,e){let a=window.__localeId__.replace("_","-");return Intl.NumberFormat(a,{style:"currency",currency:e}).format(t)}export{A as P,h as a,r as b,Me as d,De as f,w as g}; diff --git a/public/build/assets/get-5385bfb8.js b/public/build/assets/get-4f3e9dd6.js similarity index 81% rename from public/build/assets/get-5385bfb8.js rename to public/build/assets/get-4f3e9dd6.js index 14594ef14b..d7626bad76 100644 --- a/public/build/assets/get-5385bfb8.js +++ b/public/build/assets/get-4f3e9dd6.js @@ -1 +1 @@ -import{a as s}from"./format-money-276370ed.js";let t=class{list(a){return s.get("/api/v2/subscriptions",{params:a})}paid(a){return s.get("/api/v2/subscriptions/sum/paid",{params:a})}unpaid(a){return s.get("/api/v2/subscriptions/sum/unpaid",{params:a})}};class e{list(a){return s.get("/api/v2/piggy-banks",{params:a})}}export{t as G,e as a}; +import{a as s}from"./format-money-2cbd3c32.js";let t=class{list(a){return s.get("/api/v2/subscriptions",{params:a})}paid(a){return s.get("/api/v2/subscriptions/sum/paid",{params:a})}unpaid(a){return s.get("/api/v2/subscriptions/sum/unpaid",{params:a})}};class e{list(a){return s.get("/api/v2/piggy-banks",{params:a})}}export{t as G,e as a}; diff --git a/public/build/assets/get-9c5eaf42.js b/public/build/assets/get-9c5eaf42.js deleted file mode 100644 index 14799802a0..0000000000 --- a/public/build/assets/get-9c5eaf42.js +++ /dev/null @@ -1 +0,0 @@ -import{a as t}from"./format-money-276370ed.js";class n{list(a){return t.get("/api/v2/transactions",{params:a})}listByCount(a){return t.get("/api/v2/transactions-inf",{params:a})}show(a,s){return t.get("/api/v2/transactions/"+a,{params:s})}}export{n as G}; diff --git a/public/build/assets/get-f02d6b9c.js b/public/build/assets/get-f02d6b9c.js new file mode 100644 index 0000000000..d008ed5195 --- /dev/null +++ b/public/build/assets/get-f02d6b9c.js @@ -0,0 +1 @@ +import{a as t}from"./format-money-2cbd3c32.js";class n{list(a){return t.get("/api/v2/transactions",{params:a})}infiniteList(a){return t.get("/api/v2/infinite/transactions",{params:a})}show(a,i){return t.get("/api/v2/transactions/"+a,{params:i})}}export{n as G}; diff --git a/public/build/assets/index-5175d98b.js b/public/build/assets/index-5175d98b.js deleted file mode 100644 index 2b146a0b37..0000000000 --- a/public/build/assets/index-5175d98b.js +++ /dev/null @@ -1 +0,0 @@ -import{b,d as V,f as u}from"./format-money-276370ed.js";import{M as E,I as j,f as h,i as d,o as C}from"./vendor-7d6e65fe.js";import{G as m}from"./get-9c5eaf42.js";import{P as c}from"./put-016ad2aa.js";class T{init(t){document.addEventListener("cellValueChanged",()=>{console.log("I just realized a cell value has changed.")}),console.log("AmountEditor.init"),this.params=t,this.originalValue=t.value,this.eGui=document.createElement("div"),this.input=document.createElement("input"),this.input.type="number",this.input.min="0",this.input.step="any",this.input.style.overflow="hidden",this.input.style.textOverflow="ellipsis",this.input.autofocus=!0,this.input.value=parseFloat(t.value.amount).toFixed(t.value.decimal_places)}onChange(t){console.log("AmountEditor.onChange"),this.params.onValueChange(t),this.params.stopEditing(t)}afterGuiAttached(){this.input.focus(),this.input.select()}getGui(){return console.log("AmountEditor.getGui"),this.eGui.appendChild(this.input),this.eGui}getValue(){return console.log("AmountEditor.getValue"),this.originalValue.amount=parseFloat(this.input.value),this.submitAmount(this.originalValue),this.originalValue}submitAmount(t){console.log("AmountEditor.submitAmount"),console.log(t);const i=t.amount;console.log('New value for field "amount" in transaction journal #'+t.transaction_journal_id+" of group #"+t.id+' is "'+i+'"');let n={transactions:[{transaction_journal_id:t.transaction_journal_id,amount:i}]};new c().put(n,{id:t.id})}}class v{constructor(){this.type="all",this.rowCount=null}rowCount(){return this.rowCount}getRows(t){new m().listByCount({start_row:t.startRow,end_row:t.endRow,type:this.type}).then(n=>{this.parseTransactions(n.data.data,t.successCallback),this.rowCount=n.data.meta.pagination.total}).catch(n=>{console.log(n)})}parseTransactions(t,i){let n=[];for(let r in t)if(t.hasOwnProperty(r)){let a=t[r],l=a.attributes.transactions.length>1,g=!0;for(let p in a.attributes.transactions)if(a.attributes.transactions.hasOwnProperty(p)){let o=a.attributes.transactions[p],s={};s.split=l,s.firstSplit=g,s.group_title=a.attributes.group_title,s.created_at=a.attributes.created_at,s.updated_at=a.attributes.updated_at,s.user=a.attributes.user,s.user_group=a.attributes.user_group,s.id=parseInt(a.id),s.transaction_journal_id=parseInt(o.transaction_journal_id),s.description=o.description,s.date=new Date(o.date),s.from={name:o.source_name,id:o.source_id,type:o.source_type},s.to={name:o.destination_name,id:o.destination_id,type:o.destination_type},s.category={name:o.category_name,id:o.category_id},s.budget={name:o.budget_name,id:o.budget_id},s.amount={id:parseInt(a.id),transaction_journal_id:parseInt(o.transaction_journal_id),type:o.type,amount:o.amount,currency_code:o.currency_code,decimal_places:o.currency_decimal_places,foreign_amount:o.foreign_amount,foreign_currency_code:o.foreign_currency_code,foreign_decimal_places:o.foreign_currency_decimal_places},s.icon={classes:"fa fa-solid fa-arrow-left",id:s.id},g=!1,n.push(s)}}return i(n,!1),n}setType(t){this.type=t}}class x{init(t){console.log("DateTimeEditor.init"),this.params=t,this.originalValue=t.value,this.eGui=document.createElement("div"),this.input=document.createElement("input"),this.input.type="datetime-local",this.input.style.overflow="hidden",this.input.style.textOverflow="ellipsis",this.input.value=b(t.value,"yyyy-MM-dd HH:mm")}onChange(t){console.log("DateTimeEditor.onChange"),this.params.onValueChange(t),this.params.stopEditing(t)}afterGuiAttached(){this.input.focus()}getGui(){return console.log("DateTimeEditor.getGui"),this.eGui.appendChild(this.input),this.eGui}getValue(){return console.log("DateTimeEditor.getValue"),this.originalValue=this.input.value,this.originalValue}submitAmount(t){console.log("AmountEditor.submitAmount"),console.log(t);const i=t.amount;console.log('New value for field "amount" in transaction journal #'+t.transaction_journal_id+" of group #"+t.id+' is "'+i+'"');let n={transactions:[{transaction_journal_id:t.transaction_journal_id,amount:i}]};new c().put(n,{id:t.id})}}const _=new v;_.setType("withdrawal");document.addEventListener("cellEditRequest",()=>{console.log("Loaded through event listener.")});let w;const A=["description","amount","date"],R=e=>{console.log("onCellEditRequestMethod");const t=e.data,i=e.colDef.field;let n=e.newValue;if(!A.includes(i)){console.log("Field "+i+" is not editable.");return}i==="amount"&&(n=e.newValue.amount,console.log("New value is now"+n)),console.log('New value for field "'+i+'" in transaction journal #'+t.transaction_journal_id+" of group #"+t.id+' is "'+n+'"'),t[i]=n,w.getRowNode(String(e.rowIndex)).updateData(t);let a={transactions:[{transaction_journal_id:t.transaction_journal_id}]};a.transactions[0][i]=n,new c().put(a,{id:t.id})};document.addEventListener("cellValueChanged",()=>{console.log("I just realized a cell value has changed.")});document.addEventListener("onCellValueChanged",()=>{console.log("I just realized a cell value has changed.")});const D={rowModelType:"infinite",datasource:_,onCellEditRequest:R,readOnlyEdit:!0,columnDefs:[{field:"icon",editable:!1,headerName:"",sortable:!1,width:40,cellRenderer:function(e){return e.getValue()?'':""}},{field:"description",cellDataType:"text",editable:!0},{field:"amount",editable:function(e){return e.data.amount.foreign_amount===null&&e.data.amount.foreign_currency_code===null},cellEditor:T,cellRenderer(e){if(e.getValue()){let t="",i=parseFloat(e.getValue().amount),n=e.getValue(),r="text-danger";if(n.type==="withdrawal"&&(i=i*-1),n.type==="deposit"&&(r="text-success"),n.type==="transfer"&&(r="text-info"),t+=''+u(i,e.getValue().currency_code)+"",n.foreign_amount){let a=parseFloat(e.getValue().foreign_amount);n.type==="withdrawal"&&(a=a*-1),t+=' ('+u(a,n.foreign_currency_code)+")"}return t}return""}},{field:"date",editable:!0,cellDataType:"date",cellEditor:x,cellEditorPopup:!0,cellEditorPopupPosition:"under",cellRenderer(e){return e.getValue()?h(e.getValue(),d.t("config.date_time_fns_short")):""}},{field:"from",cellDataType:"text",cellRenderer:function(e){if(e.getValue()){let t=e.getValue();return''+t.name+""}return""}},{field:"to",cellDataType:"text",cellRenderer:function(e){if(e.getValue()){let t=e.getValue();return''+t.name+""}return""}},{field:"category",cellDataType:"text",cellRenderer:function(e){if(e.getValue()){let t=e.getValue();if(t.id!==null)return''+t.name+""}return""}},{field:"budget",cellDataType:"text",cellRenderer:function(e){if(e.getValue()){let t=e.getValue();if(t.id!==null)return''+t.name+""}return""}}]};E.registerModules([j]);let G=function(){return{notifications:{error:{show:!1,text:"",url:""},success:{show:!1,text:"",url:""},wait:{show:!1,text:""}},transactions:[],totalPages:1,perPage:50,page:1,tableColumns:{description:{enabled:!0},source:{enabled:!0},destination:{enabled:!0},amount:{enabled:!0}},table:null,formatMoney(e,t){return u(e,t)},format(e){return h(e,d.t("config.date_time_fns"))},init(){this.notifications.wait.show=!0,this.notifications.wait.text=d.t("firefly.wait_loading_data"),w=C(document.querySelector("#grid"),D)},getTransactions(e){const t=window.location.href.split("/"),i=t[t.length-1];new m().list({page:e,type:i}).then(r=>{this.parseTransactions(r.data.data),this.totalPages=r.data.meta.pagination.total_pages,this.perPage=r.data.meta.pagination.per_page,this.page=r.data.meta.pagination.current_page}).catch(r=>{this.notifications.wait.show=!1,this.notifications.error.show=!0,this.notifications.error.text=r.response.data.message})},parseTransactions(e){for(let t in e)if(e.hasOwnProperty(t)){let i=e[t],n=i.attributes.transactions.length>1,r=!0;for(let a in i.attributes.transactions)if(i.attributes.transactions.hasOwnProperty(a)){let l=i.attributes.transactions[a];l.split=n,tranaction.icon="fa fa-solid fa-arrow-left",l.firstSplit=r,l.group_title=i.attributes.group_title,l.id=i.id,l.created_at=i.attributes.created_at,l.updated_at=i.attributes.updated_at,l.user=i.attributes.user,l.user_group=i.attributes.user_group,r=!1,this.transactions.push(l)}}this.notifications.wait.show=!1,console.log("refresh!")}}},f={index:G,dates:V};function y(){Object.keys(f).forEach(e=>{console.log(`Loading page component "${e}"`);let t=f[e]();Alpine.data(e,()=>t)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),y()});window.bootstrapped&&(console.log("Loaded through window variable."),y()); diff --git a/public/build/assets/index-b671e1f6.js b/public/build/assets/index-b671e1f6.js new file mode 100644 index 0000000000..54ccf92bcc --- /dev/null +++ b/public/build/assets/index-b671e1f6.js @@ -0,0 +1 @@ +import{b,d as V,f as u}from"./format-money-2cbd3c32.js";import{M as E,I as j,f as m,i as d,o as C}from"./vendor-47e474ee.js";import{P as c}from"./put-375c2f08.js";import{G as T}from"./get-f02d6b9c.js";class v{init(t){document.addEventListener("cellValueChanged",()=>{console.log("I just realized a cell value has changed.")}),console.log("AmountEditor.init"),this.params=t,this.originalValue=t.value,this.eGui=document.createElement("div"),this.input=document.createElement("input"),this.input.type="number",this.input.min="0",this.input.step="any",this.input.style.overflow="hidden",this.input.style.textOverflow="ellipsis",this.input.autofocus=!0,this.input.value=parseFloat(t.value.amount).toFixed(t.value.decimal_places)}onChange(t){console.log("AmountEditor.onChange"),this.params.onValueChange(t),this.params.stopEditing(t)}afterGuiAttached(){this.input.focus(),this.input.select()}getGui(){return console.log("AmountEditor.getGui"),this.eGui.appendChild(this.input),this.eGui}getValue(){return console.log("AmountEditor.getValue"),this.originalValue.amount=parseFloat(this.input.value),this.submitAmount(this.originalValue),this.originalValue}submitAmount(t){console.log("AmountEditor.submitAmount"),console.log(t);const i=t.amount;console.log('New value for field "amount" in transaction journal #'+t.transaction_journal_id+" of group #"+t.id+' is "'+i+'"');let o={transactions:[{transaction_journal_id:t.transaction_journal_id,amount:i}]};new c().put(o,{id:t.id})}}class x{constructor(){this.type="all",this.rowCount=null,this.sortModel=null}rowCount(){return this.rowCount}getRows(t){console.log("The sort model used is: ",t.sortModel);let i=[];for(let a in t.sortModel)if(t.sortModel.hasOwnProperty(a)){let n=t.sortModel[a];i.push({column:n.colId,direction:n.sort})}new T().infiniteList({start_row:t.startRow,end_row:t.endRow,type:this.type,sorting:i}).then(a=>{this.parseTransactions(a.data.data,t.successCallback),this.rowCount=a.data.meta.pagination.total}).catch(a=>{console.log(a)})}parseTransactions(t,i){let o=[];for(let a in t)if(t.hasOwnProperty(a)){let n=t[a],s=n.attributes.transactions.length>1,f=!0;for(let g in n.attributes.transactions)if(n.attributes.transactions.hasOwnProperty(g)){let r=n.attributes.transactions[g],l={};l.split=s,l.firstSplit=f,l.group_title=n.attributes.group_title,l.created_at=n.attributes.created_at,l.updated_at=n.attributes.updated_at,l.user=n.attributes.user,l.user_group=n.attributes.user_group,l.id=parseInt(n.id),l.transaction_journal_id=parseInt(r.transaction_journal_id),l.description=r.description,l.date=new Date(r.date),l.from={name:r.source_name,id:r.source_id,type:r.source_type},l.to={name:r.destination_name,id:r.destination_id,type:r.destination_type},l.category={name:r.category_name,id:r.category_id},l.budget={name:r.budget_name,id:r.budget_id},l.amount={id:parseInt(n.id),transaction_journal_id:parseInt(r.transaction_journal_id),type:r.type,amount:r.amount,currency_code:r.currency_code,decimal_places:r.currency_decimal_places,foreign_amount:r.foreign_amount,foreign_currency_code:r.foreign_currency_code,foreign_decimal_places:r.foreign_currency_decimal_places},l.icon={classes:"fa fa-solid fa-arrow-left",id:l.id},f=!1,o.push(l)}}return i(o,!1),o}setType(t){this.type=t}}class A{init(t){console.log("DateTimeEditor.init"),this.params=t,this.originalValue=t.value,this.eGui=document.createElement("div"),this.input=document.createElement("input"),this.input.type="datetime-local",this.input.style.overflow="hidden",this.input.style.textOverflow="ellipsis",this.input.value=b(t.value,"yyyy-MM-dd HH:mm")}onChange(t){console.log("DateTimeEditor.onChange"),this.params.onValueChange(t),this.params.stopEditing(t)}afterGuiAttached(){this.input.focus()}getGui(){return console.log("DateTimeEditor.getGui"),this.eGui.appendChild(this.input),this.eGui}getValue(){return console.log("DateTimeEditor.getValue"),this.originalValue=this.input.value,this.originalValue}submitAmount(t){console.log("AmountEditor.submitAmount"),console.log(t);const i=t.amount;console.log('New value for field "amount" in transaction journal #'+t.transaction_journal_id+" of group #"+t.id+' is "'+i+'"');let o={transactions:[{transaction_journal_id:t.transaction_journal_id,amount:i}]};new c().put(o,{id:t.id})}}const _=new x,p=window.location.href.split("/"),M=p[p.length-1];_.setType(M);document.addEventListener("cellEditRequest",()=>{console.log("Loaded through event listener.")});let w;const R=["description","amount","date"],D=e=>{console.log("onCellEditRequestMethod");const t=e.data,i=e.colDef.field;let o=e.newValue;if(!R.includes(i)){console.log("Field "+i+" is not editable.");return}i==="amount"&&(o=e.newValue.amount,console.log("New value is now"+o)),console.log('New value for field "'+i+'" in transaction journal #'+t.transaction_journal_id+" of group #"+t.id+' is "'+o+'"'),t[i]=o,w.getRowNode(String(e.rowIndex)).updateData(t);let n={transactions:[{transaction_journal_id:t.transaction_journal_id}]};n.transactions[0][i]=o,new c().put(n,{id:t.id})};document.addEventListener("cellValueChanged",()=>{console.log("I just realized a cell value has changed.")});document.addEventListener("onCellValueChanged",()=>{console.log("I just realized a cell value has changed.")});const G={rowModelType:"infinite",datasource:_,onCellEditRequest:D,readOnlyEdit:!0,columnDefs:[{field:"icon",editable:!1,headerName:"",sortable:!1,width:40,cellRenderer:function(e){return e.getValue()?'':""}},{field:"description",cellDataType:"text",editable:!0},{field:"amount",editable:function(e){return e.data.amount.foreign_amount===null&&e.data.amount.foreign_currency_code===null},cellEditor:v,cellRenderer(e){if(e.getValue()){let t="",i=parseFloat(e.getValue().amount),o=e.getValue(),a="text-danger";if(o.type==="withdrawal"&&(i=i*-1),o.type==="deposit"&&(a="text-success"),o.type==="transfer"&&(a="text-info"),t+=''+u(i,e.getValue().currency_code)+"",o.foreign_amount){let n=parseFloat(e.getValue().foreign_amount);o.type==="withdrawal"&&(n=n*-1),t+=' ('+u(n,o.foreign_currency_code)+")"}return t}return""}},{field:"date",editable:!0,cellDataType:"date",cellEditor:A,cellEditorPopup:!0,cellEditorPopupPosition:"under",cellRenderer(e){return e.getValue()?m(e.getValue(),d.t("config.date_time_fns_short")):""}},{field:"from",cellDataType:"text",cellRenderer:function(e){if(e.getValue()){let t=e.getValue();return''+t.name+""}return""}},{field:"to",cellDataType:"text",cellRenderer:function(e){if(e.getValue()){let t=e.getValue();return''+t.name+""}return""}},{field:"category",cellDataType:"text",cellRenderer:function(e){if(e.getValue()){let t=e.getValue();if(t.id!==null)return''+t.name+""}return""}},{field:"budget",cellDataType:"text",cellRenderer:function(e){if(e.getValue()){let t=e.getValue();if(t.id!==null)return''+t.name+""}return""}}]};E.registerModules([j]);let P=function(){return{notifications:{error:{show:!1,text:"",url:""},success:{show:!1,text:"",url:""},wait:{show:!1,text:""}},transactions:[],totalPages:1,perPage:50,page:1,tableColumns:{description:{enabled:!0},source:{enabled:!0},destination:{enabled:!0},amount:{enabled:!0}},table:null,formatMoney(e,t){return u(e,t)},format(e){return m(e,d.t("config.date_time_fns"))},init(){this.notifications.wait.show=!0,this.notifications.wait.text=d.t("firefly.wait_loading_data"),w=C(document.querySelector("#grid"),G)},parseTransactions(e){for(let t in e)if(e.hasOwnProperty(t)){let i=e[t],o=i.attributes.transactions.length>1,a=!0;for(let n in i.attributes.transactions)if(i.attributes.transactions.hasOwnProperty(n)){let s=i.attributes.transactions[n];s.split=o,tranaction.icon="fa fa-solid fa-arrow-left",s.firstSplit=a,s.group_title=i.attributes.group_title,s.id=i.id,s.created_at=i.attributes.created_at,s.updated_at=i.attributes.updated_at,s.user=i.attributes.user,s.user_group=i.attributes.user_group,a=!1,this.transactions.push(s)}}this.notifications.wait.show=!1,console.log("refresh!")}}},h={index:P,dates:V};function y(){Object.keys(h).forEach(e=>{console.log(`Loading page component "${e}"`);let t=h[e]();Alpine.data(e,()=>t)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),y()});window.bootstrapped&&(console.log("Loaded through window variable."),y()); diff --git a/public/build/assets/parse-downloaded-splits-7301d402.js b/public/build/assets/parse-downloaded-splits-a5d66b5f.js similarity index 91% rename from public/build/assets/parse-downloaded-splits-7301d402.js rename to public/build/assets/parse-downloaded-splits-a5d66b5f.js index 5c8aad0db4..510972ed9f 100644 --- a/public/build/assets/parse-downloaded-splits-7301d402.js +++ b/public/build/assets/parse-downloaded-splits-a5d66b5f.js @@ -1 +1 @@ -import{c as o}from"./create-empty-split-d23e6a0d.js";import{f as _}from"./vendor-7d6e65fe.js";function l(a,r){let n=[];for(let i in a)if(a.hasOwnProperty(i)){let e=a[i],t=o();t.transaction_journal_id=e.transaction_journal_id,t.transaction_group_id=r,t.bill_id=e.bill_id,t.bill_name=e.bill_name,t.budget_id=e.budget_id,t.budget_name=e.budget_name,t.category_name=e.category_name,t.category_id=e.category_id,t.piggy_bank_id=e.piggy_bank_id,t.piggy_bank_name=e.piggy_bank_name,t.book_date=e.book_date,t.due_date=e.due_date,t.interest_date=e.interest_date,t.invoice_date=e.invoice_date,t.payment_date=e.payment_date,t.process_date=e.process_date,t.external_url=e.external_url,t.internal_reference=e.internal_reference,t.notes=e.notes,t.tags=e.tags,t.amount=parseFloat(e.amount).toFixed(e.currency_decimal_places),t.currency_code=e.currency_code,e.foreign_amount!==null&&(t.forein_currency_code=e.foreign_currency_code,t.foreign_amount=parseFloat(e.foreign_amount).toFixed(e.foreign_currency_decimal_places)),t.date=_(new Date(e.date),"yyyy-MM-dd HH:mm"),t.description=e.description,t.destination_account={id:e.destination_id,name:e.destination_name,type:e.destination_type,alpine_name:e.destination_name},t.source_account={id:e.source_id,name:e.source_name,type:e.source_type,alpine_name:e.source_name},e.latitude!==null&&(t.hasLocation=!0,t.latitude=e.latitude,t.longitude=e.longitude,t.zoomLevel=e.zoom_level),n.push(t)}return n}export{l as p}; +import{c as o}from"./create-empty-split-c1e678fd.js";import{f as _}from"./vendor-47e474ee.js";function l(a,r){let n=[];for(let i in a)if(a.hasOwnProperty(i)){let e=a[i],t=o();t.transaction_journal_id=e.transaction_journal_id,t.transaction_group_id=r,t.bill_id=e.bill_id,t.bill_name=e.bill_name,t.budget_id=e.budget_id,t.budget_name=e.budget_name,t.category_name=e.category_name,t.category_id=e.category_id,t.piggy_bank_id=e.piggy_bank_id,t.piggy_bank_name=e.piggy_bank_name,t.book_date=e.book_date,t.due_date=e.due_date,t.interest_date=e.interest_date,t.invoice_date=e.invoice_date,t.payment_date=e.payment_date,t.process_date=e.process_date,t.external_url=e.external_url,t.internal_reference=e.internal_reference,t.notes=e.notes,t.tags=e.tags,t.amount=parseFloat(e.amount).toFixed(e.currency_decimal_places),t.currency_code=e.currency_code,e.foreign_amount!==null&&(t.forein_currency_code=e.foreign_currency_code,t.foreign_amount=parseFloat(e.foreign_amount).toFixed(e.foreign_currency_decimal_places)),t.date=_(new Date(e.date),"yyyy-MM-dd HH:mm"),t.description=e.description,t.destination_account={id:e.destination_id,name:e.destination_name,type:e.destination_type,alpine_name:e.destination_name},t.source_account={id:e.source_id,name:e.source_name,type:e.source_type,alpine_name:e.source_name},e.latitude!==null&&(t.hasLocation=!0,t.latitude=e.latitude,t.longitude=e.longitude,t.zoomLevel=e.zoom_level),n.push(t)}return n}export{l as p}; diff --git a/public/build/assets/put-016ad2aa.js b/public/build/assets/put-375c2f08.js similarity index 55% rename from public/build/assets/put-016ad2aa.js rename to public/build/assets/put-375c2f08.js index 4fcbfb3dc5..afbebf5972 100644 --- a/public/build/assets/put-016ad2aa.js +++ b/public/build/assets/put-375c2f08.js @@ -1 +1 @@ -import{a as p}from"./format-money-276370ed.js";class u{put(t,a){let r="/api/v2/transactions/"+parseInt(a.id);return p.put(r,t)}}export{u as P}; +import{a as p}from"./format-money-2cbd3c32.js";class u{put(t,a){let r="/api/v2/transactions/"+parseInt(a.id);return p.put(r,t)}}export{u as P}; diff --git a/public/build/assets/show-02715d84.js b/public/build/assets/show-56332d03.js similarity index 98% rename from public/build/assets/show-02715d84.js rename to public/build/assets/show-56332d03.js index da19b80ce7..26fcb938be 100644 --- a/public/build/assets/show-02715d84.js +++ b/public/build/assets/show-56332d03.js @@ -1 +1 @@ -var y=Object.defineProperty;var w=(i,t,e)=>t in i?y(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var r=(i,t,e)=>(w(i,typeof t!="symbol"?t+"":t,e),e);import{d as v,f as b}from"./format-money-276370ed.js";import{f as g,i as h}from"./vendor-7d6e65fe.js";import{G as E}from"./get-9c5eaf42.js";import{p as _}from"./parse-downloaded-splits-7301d402.js";import"./create-empty-split-d23e6a0d.js";class l{constructor(t){if(this.constructor===l)throw new Error("It's abstract class");this.context=t}event_show(){this.context.typeElement.hideError(),this.context.typeElement.element.value=this.context.value,this.context.element.dispatchEvent(new CustomEvent("show"))}event_shown(){this.context.element.dispatchEvent(new CustomEvent("shown"))}event_hide(){this.context.element.dispatchEvent(new CustomEvent("hide"))}event_hidden(){this.context.element.dispatchEvent(new CustomEvent("hidden"))}init(){throw new Error("Method `init` not define!")}enable(){throw new Error("Method `enable` not define!")}disable(){throw new Error("Method `disable` not define!")}hide(){throw new Error("Method `hide` not define!")}}class L extends l{init(){this.popover=new bootstrap.Popover(this.context.element,{container:"body",content:this.context.typeElement.create(),html:!0,customClass:"dark-editable",title:this.context.title}),this.context.element.addEventListener("show.bs.popover",()=>{this.event_show()}),this.context.element.addEventListener("shown.bs.popover",()=>{this.event_shown()}),this.context.element.addEventListener("hide.bs.popover",()=>{this.event_hide()}),this.context.element.addEventListener("hidden.bs.popover",()=>{this.event_hidden()}),document.addEventListener("click",t=>{const e=t.target;if(e===this.popover.tip||e===this.context.element)return;let n=e;for(;n=n.parentNode;)if(n===this.popover.tip)return;this.hide()})}enable(){this.popover.enable()}disable(){this.popover.disable()}hide(){this.popover.hide()}}class T extends l{init(){const t=()=>{if(!this.context.disabled){const e=this.context.typeElement.create();this.event_show(),this.context.element.removeEventListener("click",t),this.context.element.innerHTML="",this.context.element.append(e),this.event_shown()}};this.context.element.addEventListener("click",t)}enable(){}disable(){}hide(){this.event_hide(),this.context.element.innerHTML=this.context.value,setTimeout(()=>{this.init(),this.event_hidden()},100)}}class c{constructor(t){r(this,"context",null);r(this,"element",null);r(this,"error",null);r(this,"form",null);r(this,"load",null);r(this,"buttonGroup",null);r(this,"buttons",{success:null,cancel:null});if(this.constructor===c)throw new Error("It's abstract class");this.context=t}create(){throw new Error("Method `create` not define!")}createContainer(t){const e=document.createElement("div");this.element=t,this.error=this.createContainerError(),this.form=this.createContainerForm(),this.load=this.createContainerLoad(),this.buttons.success=this.createButtonSuccess(),this.buttons.cancel=this.createButtonCancel();const n=document.createElement("div");n.classList.add("col-12");const s=document.createElement("label");s.classList.add("visually-hidden"),s.for=t.id,n.append(s,t);const o=document.createElement("div");return o.classList.add("col-12"),this.buttonGroup=this.createButtonGroup(),this.buttonGroup.append(this.buttons.success,this.buttons.cancel),o.append(this.buttonGroup),this.form.append(n,o),e.append(this.error,this.form),e}createButtonGroup(){const t=document.createElement("div");return t.classList.add("btn-group","btn-group-sm"),t}createContainerError(){const t=document.createElement("div");return t.classList.add("text-danger","fst-italic","mb-2","fw-bold"),t.style.display="none",t}createContainerForm(){const t=document.createElement("form");return t.classList.add("row","row-cols-lg-auto","g-3","align-items-center"),t.addEventListener("submit",async e=>{e.preventDefault();const n=this.getValue();if(this.context.send&&this.context.pk&&this.context.url&&this.context.value!==n){this.showLoad();let s;try{const o=await this.ajax(n);o.ok?s=await this.context.success(o,n):s=await this.context.error(o,n)||`${o.status} ${o.statusText}`}catch(o){console.error(o),s=o}s?(this.setError(s),this.showError()):(this.setError(null),this.hideError(),this.context.value=this.getValue(),this.context.modeElement.hide(),this.initText()),this.hideLoad()}else this.context.value=this.getValue(),this.context.modeElement.hide(),this.initText();this.context.element.dispatchEvent(new CustomEvent("save"))}),t}createContainerLoad(){const t=document.createElement("div");t.style.display="none",t.style.position="absolute",t.style.background="white",t.style.width="100%",t.style.height="100%",t.style.top=0,t.style.left=0;const e=document.createElement("div");return e.classList.add("dark-editable-loader"),t.append(e),t}createButton(){const t=document.createElement("button");return t.type="button",t.classList.add("btn","btn-sm"),t.style.color="transparent",t.style.textShadow="0 0 0 white",t}createButtonSuccess(){const t=this.createButton();return t.type="submit",t.classList.add("btn-success"),t.innerHTML="✔",t}createButtonCancel(){const t=this.createButton();t.classList.add("btn-danger");const e=document.createElement("div");return e.innerHTML="✖",t.append(e),t.addEventListener("click",()=>{this.context.modeElement.hide()}),t}hideLoad(){this.load.style.display="none"}showLoad(){this.load.style.display="block"}ajax(t){let e=this.context.url,n,s=!1;console.log(this.context),this.context.options.formType==="journal_description"&&(s=!0,n={transactions:[{transaction_journal_id:this.context.options.journalId,description:t}]}),s===!1&&console.error('Cannot deal with form type "'+this.context.formType+'"');const o={headers:{"Content-Type":"application/json","X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}};return o.method=this.context.ajaxOptions.method,this.context.options.method&&(o.method=this.context.options.method),o.method==="POST"||this.context.options.method==="PUT"?o.body=JSON.stringify(n):e+="?"+new URLSearchParams(form).toString(),fetch(e,o)}async successResponse(t,e){}async errorResponse(t,e){}setError(t){this.error.innerHTML=t}showError(){this.error.style.display="block"}hideError(){this.error&&(this.error.style.display="none")}createElement(t){const e=document.createElement(t);return console.log(e),e.classList.add("form-control"),this.context.required&&(e.required=this.context.required),this.add_focus(e),e}add_focus(t){this.context.element.addEventListener("shown",function(){t.focus()})}initText(){return this.context.value===""?(this.context.element.innerHTML=this.context.emptytext,!0):(this.context.element.innerHTML=this.context.value,!1)}initOptions(){}getValue(){return this.element.value}}class M extends c{create(){const t=this.createElement("input"),e=this.context.element.id+"_input";return t.type=this.context.type,t.id=e,t.autocomplete="off",t.placeholder=this.context.element.innerText,t.classList.add("form-control","form-control-md"),this.createContainer(t)}}class C extends c{create(){const t=this.createElement("textarea");return this.createContainer(t)}}class k extends c{create(){const t=this.createElement("select");return this.context.source.forEach(e=>{const n=document.createElement("option");n.value=e.value,n.innerHTML=e.text,t.append(n)}),this.createContainer(t)}initText(){if(this.context.element.innerHTML=this.context.emptytext,this.context.value!==""&&this.context.source.length>0)for(const t in this.context.source){const e=this.context.source[t];if(e.value==this.context.value)return this.context.element.innerHTML=e.text,!1}return!0}initOptions(){this.context.get_opt("source",[]),typeof this.context.source=="string"&&this.context.source!==""&&(this.context.source=JSON.parse(this.context.source))}}class f extends c{create(){const t=this.createElement("input");return t.type="date",this.createContainer(t)}initText(){return this.value===""?(this.context.element.innerHTML=this.context.emptytext,!0):(this.context.element.innerHTML=moment(this.context.value).format(this.context.viewformat),!1)}initOptions(){this.context.get_opt("format","YYYY-MM-DD"),this.context.get_opt("viewformat","YYYY-MM-DD")}}class D extends f{create(){const t=this.createElement("input");return t.type="datetime-local",this.createContainer(t)}initOptions(){this.context.get_opt("format","YYYY-MM-DD HH:mm"),this.context.get_opt("viewformat","YYYY-MM-DD HH:mm"),this.context.value=moment(this.context.value).format("YYYY-MM-DDTHH:mm")}}class Y{constructor(t,e={}){r(this,"modeElement",null);r(this,"typeElement",null);r(this,"mode",null);r(this,"type",null);r(this,"emptytext",null);r(this,"viewformat",null);r(this,"pk",null);r(this,"name",null);this.element=t,this.options=e,this.init_options(),this.typeElement=this.route_type(),this.typeElement.initOptions(),this.modeElement=this.route_mode(),this.modeElement.init(),this.init_text(),this.init_style(),this.disabled&&this.disable(),this.element.dispatchEvent(new CustomEvent("init"))}get_opt(t,e){var n,s;return this[t]=((n=this.element.dataset)==null?void 0:n[t])??((s=this.options)==null?void 0:s[t])??e}get_opt_bool(t,e){return this.get_opt(t,e),typeof this[t]!="boolean"&&(this[t]==="true"?this[t]=!0:this[t]==="false"?this[t]=!1:this[t]=e),this[t]}init_options(){var t,e,n,s;this.get_opt("value",this.element.innerHTML),this.get_opt("name",this.element.id),this.get_opt("pk",null),this.get_opt("title",""),this.get_opt("type","text"),this.get_opt("emptytext","Empty"),this.get_opt("mode","popup"),this.get_opt("url",null),this.get_opt("ajaxOptions",{}),this.ajaxOptions=Object.assign({method:"POST",dataType:"text"},this.ajaxOptions),this.get_opt_bool("send",!0),this.get_opt_bool("disabled",!1),this.get_opt_bool("required",!1),(t=this.options)!=null&&t.success&&typeof((e=this.options)==null?void 0:e.success)=="function"&&(this.success=this.options.success),(n=this.options)!=null&&n.error&&typeof((s=this.options)==null?void 0:s.error)=="function"&&(this.error=this.options.error)}init_text(){const t="dark-editable-element-empty";this.element.classList.remove(t),this.typeElement.initText()&&this.element.classList.add(t)}init_style(){this.element.classList.add("dark-editable-element")}route_mode(){switch(this.mode){default:throw new Error(`Mode ${this.mode} not found!`);case"popup":return new L(this);case"inline":return new T(this)}}route_type(){if(this.type.prototype instanceof c)return new this.type(this);if(typeof this.type=="string")switch(this.type){case"text":case"password":case"email":case"url":case"tel":case"number":case"range":case"time":return new M(this);case"textarea":return new C(this);case"select":return new k(this);case"date":return new f(this);case"datetime":return new D(this)}throw new Error("Undefined type")}async success(t,e){return await this.typeElement.successResponse(t,e)}async error(t,e){return await this.typeElement.errorResponse(t,e)}enable(){this.disabled=!1,this.element.classList.remove("dark-editable-element-disabled"),this.modeElement.enable()}disable(){this.disabled=!0,this.element.classList.add("dark-editable-element-disabled"),this.modeElement.enable()}setValue(t){this.value=t,this.init_text()}getValue(){return this.value}}function H(i){const t=parseInt(i.dataset.id),e=parseInt(i.dataset.group),n={pk:e,mode:"inline",url:"./api/v2/transactions/"+e,formType:"journal_description",journalId:t,method:"PUT"};new Y(i,n)}let I=function(){return{notifications:{error:{show:!1,text:"",url:""},success:{show:!1,text:"",url:""},wait:{show:!1,text:""}},groupProperties:{id:0,transactionType:"",transactionTypeTranslated:"",title:"",date:new Date},dateFields:["book_date","due_date","interest_date","invoice_date","payment_date","process_date"],metaFields:["external_id","internal_reference","sepa_batch_id","sepa_ct_id","sepa_ct_op","sepa_db","sepa_country","sepa_cc","sepa_ep","sepa_ci","external_url"],amounts:{},entries:[],pageProperties:{},formatMoney(i,t){return console.log("formatting",i,t),t===""&&(t="EUR"),b(i,t)},format(i){return g(i,h.t("config.date_time_fns"))},init(){this.notifications.wait.show=!0,this.notifications.wait.text=h.t("firefly.wait_loading_data");const i=window.location.href.split("/"),t=parseInt(i[i.length-1]);new E().show(t,{}).then(n=>{const s=n.data.data;this.groupProperties.id=parseInt(s.id),this.groupProperties.transactionType=s.attributes.transactions[0].type,this.groupProperties.transactionTypeTranslated=h.t("firefly."+s.attributes.transactions[0].type),this.groupProperties.title=s.attributes.title??s.attributes.transactions[0].description,this.entries=_(s.attributes.transactions,parseInt(s.id)),this.notifications.wait.show=!1}).then(()=>{for(let s in this.entries)if(this.entries.hasOwnProperty(s)){const o=this.entries[s].currency_code,a=this.entries[s].foreign_currency_code;this.amounts[o]===void 0&&(this.amounts[o]=0,this.amounts[o]+=parseFloat(this.entries[s].amount)),a!==null&&a!==""&&this.amounts[a]===void 0&&(this.amounts[a]=0,this.amounts[a]+=parseFloat(this.entries[s].foreign_amount)),parseInt(s)===0&&(this.groupProperties.date=this.entries[s].date)}const n=document.querySelectorAll(".journal_description");for(const s in n)if(n.hasOwnProperty(s)){const o=n[s];o.addEventListener("save",function(a){parseInt(a.currentTarget.dataset.id);const d=parseInt(a.currentTarget.dataset.group),u=parseInt(a.currentTarget.dataset.length),p=a.currentTarget.textContent;console.log(u),u===1&&(document.querySelector('.group_title[data-group="'+d+'"]').textContent=p,document.querySelector('.group_title_title[data-group="'+d+'"]').textContent=p)}),H(o)}}).catch(n=>{this.notifications.error.show=!0,this.notifications.error.text=n.message})}}},m={show:I,dates:v};function x(){Object.keys(m).forEach(i=>{console.log(`Loading page component "${i}"`);let t=m[i]();Alpine.data(i,()=>t)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),x()});window.bootstrapped&&(console.log("Loaded through window variable."),x()); +var y=Object.defineProperty;var w=(i,t,e)=>t in i?y(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var r=(i,t,e)=>(w(i,typeof t!="symbol"?t+"":t,e),e);import{d as v,f as b}from"./format-money-2cbd3c32.js";import{f as g,i as h}from"./vendor-47e474ee.js";import{G as E}from"./get-f02d6b9c.js";import{p as _}from"./parse-downloaded-splits-a5d66b5f.js";import"./create-empty-split-c1e678fd.js";class l{constructor(t){if(this.constructor===l)throw new Error("It's abstract class");this.context=t}event_show(){this.context.typeElement.hideError(),this.context.typeElement.element.value=this.context.value,this.context.element.dispatchEvent(new CustomEvent("show"))}event_shown(){this.context.element.dispatchEvent(new CustomEvent("shown"))}event_hide(){this.context.element.dispatchEvent(new CustomEvent("hide"))}event_hidden(){this.context.element.dispatchEvent(new CustomEvent("hidden"))}init(){throw new Error("Method `init` not define!")}enable(){throw new Error("Method `enable` not define!")}disable(){throw new Error("Method `disable` not define!")}hide(){throw new Error("Method `hide` not define!")}}class L extends l{init(){this.popover=new bootstrap.Popover(this.context.element,{container:"body",content:this.context.typeElement.create(),html:!0,customClass:"dark-editable",title:this.context.title}),this.context.element.addEventListener("show.bs.popover",()=>{this.event_show()}),this.context.element.addEventListener("shown.bs.popover",()=>{this.event_shown()}),this.context.element.addEventListener("hide.bs.popover",()=>{this.event_hide()}),this.context.element.addEventListener("hidden.bs.popover",()=>{this.event_hidden()}),document.addEventListener("click",t=>{const e=t.target;if(e===this.popover.tip||e===this.context.element)return;let n=e;for(;n=n.parentNode;)if(n===this.popover.tip)return;this.hide()})}enable(){this.popover.enable()}disable(){this.popover.disable()}hide(){this.popover.hide()}}class T extends l{init(){const t=()=>{if(!this.context.disabled){const e=this.context.typeElement.create();this.event_show(),this.context.element.removeEventListener("click",t),this.context.element.innerHTML="",this.context.element.append(e),this.event_shown()}};this.context.element.addEventListener("click",t)}enable(){}disable(){}hide(){this.event_hide(),this.context.element.innerHTML=this.context.value,setTimeout(()=>{this.init(),this.event_hidden()},100)}}class c{constructor(t){r(this,"context",null);r(this,"element",null);r(this,"error",null);r(this,"form",null);r(this,"load",null);r(this,"buttonGroup",null);r(this,"buttons",{success:null,cancel:null});if(this.constructor===c)throw new Error("It's abstract class");this.context=t}create(){throw new Error("Method `create` not define!")}createContainer(t){const e=document.createElement("div");this.element=t,this.error=this.createContainerError(),this.form=this.createContainerForm(),this.load=this.createContainerLoad(),this.buttons.success=this.createButtonSuccess(),this.buttons.cancel=this.createButtonCancel();const n=document.createElement("div");n.classList.add("col-12");const s=document.createElement("label");s.classList.add("visually-hidden"),s.for=t.id,n.append(s,t);const o=document.createElement("div");return o.classList.add("col-12"),this.buttonGroup=this.createButtonGroup(),this.buttonGroup.append(this.buttons.success,this.buttons.cancel),o.append(this.buttonGroup),this.form.append(n,o),e.append(this.error,this.form),e}createButtonGroup(){const t=document.createElement("div");return t.classList.add("btn-group","btn-group-sm"),t}createContainerError(){const t=document.createElement("div");return t.classList.add("text-danger","fst-italic","mb-2","fw-bold"),t.style.display="none",t}createContainerForm(){const t=document.createElement("form");return t.classList.add("row","row-cols-lg-auto","g-3","align-items-center"),t.addEventListener("submit",async e=>{e.preventDefault();const n=this.getValue();if(this.context.send&&this.context.pk&&this.context.url&&this.context.value!==n){this.showLoad();let s;try{const o=await this.ajax(n);o.ok?s=await this.context.success(o,n):s=await this.context.error(o,n)||`${o.status} ${o.statusText}`}catch(o){console.error(o),s=o}s?(this.setError(s),this.showError()):(this.setError(null),this.hideError(),this.context.value=this.getValue(),this.context.modeElement.hide(),this.initText()),this.hideLoad()}else this.context.value=this.getValue(),this.context.modeElement.hide(),this.initText();this.context.element.dispatchEvent(new CustomEvent("save"))}),t}createContainerLoad(){const t=document.createElement("div");t.style.display="none",t.style.position="absolute",t.style.background="white",t.style.width="100%",t.style.height="100%",t.style.top=0,t.style.left=0;const e=document.createElement("div");return e.classList.add("dark-editable-loader"),t.append(e),t}createButton(){const t=document.createElement("button");return t.type="button",t.classList.add("btn","btn-sm"),t.style.color="transparent",t.style.textShadow="0 0 0 white",t}createButtonSuccess(){const t=this.createButton();return t.type="submit",t.classList.add("btn-success"),t.innerHTML="✔",t}createButtonCancel(){const t=this.createButton();t.classList.add("btn-danger");const e=document.createElement("div");return e.innerHTML="✖",t.append(e),t.addEventListener("click",()=>{this.context.modeElement.hide()}),t}hideLoad(){this.load.style.display="none"}showLoad(){this.load.style.display="block"}ajax(t){let e=this.context.url,n,s=!1;console.log(this.context),this.context.options.formType==="journal_description"&&(s=!0,n={transactions:[{transaction_journal_id:this.context.options.journalId,description:t}]}),s===!1&&console.error('Cannot deal with form type "'+this.context.formType+'"');const o={headers:{"Content-Type":"application/json","X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}};return o.method=this.context.ajaxOptions.method,this.context.options.method&&(o.method=this.context.options.method),o.method==="POST"||this.context.options.method==="PUT"?o.body=JSON.stringify(n):e+="?"+new URLSearchParams(form).toString(),fetch(e,o)}async successResponse(t,e){}async errorResponse(t,e){}setError(t){this.error.innerHTML=t}showError(){this.error.style.display="block"}hideError(){this.error&&(this.error.style.display="none")}createElement(t){const e=document.createElement(t);return console.log(e),e.classList.add("form-control"),this.context.required&&(e.required=this.context.required),this.add_focus(e),e}add_focus(t){this.context.element.addEventListener("shown",function(){t.focus()})}initText(){return this.context.value===""?(this.context.element.innerHTML=this.context.emptytext,!0):(this.context.element.innerHTML=this.context.value,!1)}initOptions(){}getValue(){return this.element.value}}class M extends c{create(){const t=this.createElement("input"),e=this.context.element.id+"_input";return t.type=this.context.type,t.id=e,t.autocomplete="off",t.placeholder=this.context.element.innerText,t.classList.add("form-control","form-control-md"),this.createContainer(t)}}class C extends c{create(){const t=this.createElement("textarea");return this.createContainer(t)}}class k extends c{create(){const t=this.createElement("select");return this.context.source.forEach(e=>{const n=document.createElement("option");n.value=e.value,n.innerHTML=e.text,t.append(n)}),this.createContainer(t)}initText(){if(this.context.element.innerHTML=this.context.emptytext,this.context.value!==""&&this.context.source.length>0)for(const t in this.context.source){const e=this.context.source[t];if(e.value==this.context.value)return this.context.element.innerHTML=e.text,!1}return!0}initOptions(){this.context.get_opt("source",[]),typeof this.context.source=="string"&&this.context.source!==""&&(this.context.source=JSON.parse(this.context.source))}}class f extends c{create(){const t=this.createElement("input");return t.type="date",this.createContainer(t)}initText(){return this.value===""?(this.context.element.innerHTML=this.context.emptytext,!0):(this.context.element.innerHTML=moment(this.context.value).format(this.context.viewformat),!1)}initOptions(){this.context.get_opt("format","YYYY-MM-DD"),this.context.get_opt("viewformat","YYYY-MM-DD")}}class D extends f{create(){const t=this.createElement("input");return t.type="datetime-local",this.createContainer(t)}initOptions(){this.context.get_opt("format","YYYY-MM-DD HH:mm"),this.context.get_opt("viewformat","YYYY-MM-DD HH:mm"),this.context.value=moment(this.context.value).format("YYYY-MM-DDTHH:mm")}}class Y{constructor(t,e={}){r(this,"modeElement",null);r(this,"typeElement",null);r(this,"mode",null);r(this,"type",null);r(this,"emptytext",null);r(this,"viewformat",null);r(this,"pk",null);r(this,"name",null);this.element=t,this.options=e,this.init_options(),this.typeElement=this.route_type(),this.typeElement.initOptions(),this.modeElement=this.route_mode(),this.modeElement.init(),this.init_text(),this.init_style(),this.disabled&&this.disable(),this.element.dispatchEvent(new CustomEvent("init"))}get_opt(t,e){var n,s;return this[t]=((n=this.element.dataset)==null?void 0:n[t])??((s=this.options)==null?void 0:s[t])??e}get_opt_bool(t,e){return this.get_opt(t,e),typeof this[t]!="boolean"&&(this[t]==="true"?this[t]=!0:this[t]==="false"?this[t]=!1:this[t]=e),this[t]}init_options(){var t,e,n,s;this.get_opt("value",this.element.innerHTML),this.get_opt("name",this.element.id),this.get_opt("pk",null),this.get_opt("title",""),this.get_opt("type","text"),this.get_opt("emptytext","Empty"),this.get_opt("mode","popup"),this.get_opt("url",null),this.get_opt("ajaxOptions",{}),this.ajaxOptions=Object.assign({method:"POST",dataType:"text"},this.ajaxOptions),this.get_opt_bool("send",!0),this.get_opt_bool("disabled",!1),this.get_opt_bool("required",!1),(t=this.options)!=null&&t.success&&typeof((e=this.options)==null?void 0:e.success)=="function"&&(this.success=this.options.success),(n=this.options)!=null&&n.error&&typeof((s=this.options)==null?void 0:s.error)=="function"&&(this.error=this.options.error)}init_text(){const t="dark-editable-element-empty";this.element.classList.remove(t),this.typeElement.initText()&&this.element.classList.add(t)}init_style(){this.element.classList.add("dark-editable-element")}route_mode(){switch(this.mode){default:throw new Error(`Mode ${this.mode} not found!`);case"popup":return new L(this);case"inline":return new T(this)}}route_type(){if(this.type.prototype instanceof c)return new this.type(this);if(typeof this.type=="string")switch(this.type){case"text":case"password":case"email":case"url":case"tel":case"number":case"range":case"time":return new M(this);case"textarea":return new C(this);case"select":return new k(this);case"date":return new f(this);case"datetime":return new D(this)}throw new Error("Undefined type")}async success(t,e){return await this.typeElement.successResponse(t,e)}async error(t,e){return await this.typeElement.errorResponse(t,e)}enable(){this.disabled=!1,this.element.classList.remove("dark-editable-element-disabled"),this.modeElement.enable()}disable(){this.disabled=!0,this.element.classList.add("dark-editable-element-disabled"),this.modeElement.enable()}setValue(t){this.value=t,this.init_text()}getValue(){return this.value}}function H(i){const t=parseInt(i.dataset.id),e=parseInt(i.dataset.group),n={pk:e,mode:"inline",url:"./api/v2/transactions/"+e,formType:"journal_description",journalId:t,method:"PUT"};new Y(i,n)}let I=function(){return{notifications:{error:{show:!1,text:"",url:""},success:{show:!1,text:"",url:""},wait:{show:!1,text:""}},groupProperties:{id:0,transactionType:"",transactionTypeTranslated:"",title:"",date:new Date},dateFields:["book_date","due_date","interest_date","invoice_date","payment_date","process_date"],metaFields:["external_id","internal_reference","sepa_batch_id","sepa_ct_id","sepa_ct_op","sepa_db","sepa_country","sepa_cc","sepa_ep","sepa_ci","external_url"],amounts:{},entries:[],pageProperties:{},formatMoney(i,t){return console.log("formatting",i,t),t===""&&(t="EUR"),b(i,t)},format(i){return g(i,h.t("config.date_time_fns"))},init(){this.notifications.wait.show=!0,this.notifications.wait.text=h.t("firefly.wait_loading_data");const i=window.location.href.split("/"),t=parseInt(i[i.length-1]);new E().show(t,{}).then(n=>{const s=n.data.data;this.groupProperties.id=parseInt(s.id),this.groupProperties.transactionType=s.attributes.transactions[0].type,this.groupProperties.transactionTypeTranslated=h.t("firefly."+s.attributes.transactions[0].type),this.groupProperties.title=s.attributes.title??s.attributes.transactions[0].description,this.entries=_(s.attributes.transactions,parseInt(s.id)),this.notifications.wait.show=!1}).then(()=>{for(let s in this.entries)if(this.entries.hasOwnProperty(s)){const o=this.entries[s].currency_code,a=this.entries[s].foreign_currency_code;this.amounts[o]===void 0&&(this.amounts[o]=0,this.amounts[o]+=parseFloat(this.entries[s].amount)),a!==null&&a!==""&&this.amounts[a]===void 0&&(this.amounts[a]=0,this.amounts[a]+=parseFloat(this.entries[s].foreign_amount)),parseInt(s)===0&&(this.groupProperties.date=this.entries[s].date)}const n=document.querySelectorAll(".journal_description");for(const s in n)if(n.hasOwnProperty(s)){const o=n[s];o.addEventListener("save",function(a){parseInt(a.currentTarget.dataset.id);const d=parseInt(a.currentTarget.dataset.group),u=parseInt(a.currentTarget.dataset.length),p=a.currentTarget.textContent;console.log(u),u===1&&(document.querySelector('.group_title[data-group="'+d+'"]').textContent=p,document.querySelector('.group_title_title[data-group="'+d+'"]').textContent=p)}),H(o)}}).catch(n=>{this.notifications.error.show=!0,this.notifications.error.text=n.message})}}},m={show:I,dates:v};function x(){Object.keys(m).forEach(i=>{console.log(`Loading page component "${i}"`);let t=m[i]();Alpine.data(i,()=>t)}),Alpine.start()}document.addEventListener("firefly-iii-bootstrapped",()=>{console.log("Loaded through event listener."),x()});window.bootstrapped&&(console.log("Loaded through window variable."),x()); diff --git a/public/build/assets/splice-errors-into-transactions-5f35da56.js b/public/build/assets/splice-errors-into-transactions-8731db70.js similarity index 98% rename from public/build/assets/splice-errors-into-transactions-5f35da56.js rename to public/build/assets/splice-errors-into-transactions-8731db70.js index c240ac9d36..63986ae1c5 100644 --- a/public/build/assets/splice-errors-into-transactions-5f35da56.js +++ b/public/build/assets/splice-errors-into-transactions-8731db70.js @@ -1 +1 @@ -import{a as l}from"./format-money-276370ed.js";import{a as p,G as f}from"./get-5385bfb8.js";import{n as m,i as _}from"./vendor-7d6e65fe.js";function x(r,t,a){let n=[];for(let o in r)if(r.hasOwnProperty(o)){const e=r[o];let i=!1,u={};t!==null&&t.hasOwnProperty(o)&&(i=!0,t[o]);let c={};(i&&u.description!==e.description||!i)&&(c.description=e.description),c.source_name=e.source_account.name,c.destination_name=e.destination_account.name,c.amount=e.amount,c.currency_code=e.currency_code,c.date=e.date,c.interest_date=e.interest_date,c.book_date=e.book_date,c.process_date=e.process_date,c.due_date=e.due_date,c.payment_date=e.payment_date,c.invoice_date=e.invoice_date,c.budget_id=e.budget_id,c.category_name=e.category_name,c.piggy_bank_id=e.piggy_bank_id,c.bill_id=e.bill_id,c.tags=e.tags,c.notes=e.notes,c.internal_reference=e.internal_reference,c.external_url=e.external_url,c.store_location=!1,e.hasLocation&&(c.store_location=!0,c.longitude=e.longitude.toString(),c.latitude=e.latitude.toString(),c.zoom_level=e.zoomLevel),typeof e.foreign_currency_code<"u"&&e.foreign_currency_code.toString()!==""&&(c.foreign_currency_code=e.foreign_currency_code,typeof e.foreign_amount<"u"&&e.foreign_amount.toString()!==""&&(c.foreign_amount=e.foreign_amount),(typeof e.foreign_amount>"u"||e.foreign_amount.toString()==="")&&(delete c.foreign_amount,delete c.foreign_currency_code)),typeof e.source_account.id<"u"&&e.source_account.id.toString()!==""&&(c.source_id=e.source_account.id),typeof e.destination_account.id<"u"&&e.destination_account.id.toString()!==""&&(c.destination_id=e.destination_account.id),c.type=a,n.push(c)}return n}let g=class{list(t){return l.get("/api/v2/currencies",{params:t})}};function C(){let r={page:1,limit:1337};return new g().list(r).then(a=>{let n={defaultCurrency:{},nativeCurrencies:[],foreignCurrencies:[],enabledCurrencies:[]};n.foreignCurrencies.push({id:0,name:"(no foreign currency)",code:"",default:!1,symbol:"",decimal_places:2});for(let o in a.data.data)if(a.data.data.hasOwnProperty(o)){let e=a.data.data[o];if(e.attributes.enabled){let i={id:e.id,name:e.attributes.name,code:e.attributes.code,default:e.attributes.default,symbol:e.attributes.symbol,decimal_places:e.attributes.decimal_places};i.default&&(n.defaultCurrency=i),n.enabledCurrencies.push(i),n.nativeCurrencies.push(i),n.foreignCurrencies.push(i)}}return n})}class y{list(t){return l.get("/api/v2/budgets",{params:t})}}function $(){let r={page:1,limit:1337};return new y().list(r).then(a=>{let n=[{id:0,name:"(no budget)"}];for(let o in a.data.data)if(a.data.data.hasOwnProperty(o)){let e=a.data.data[o],i={id:e.id,name:e.attributes.name};n.push(i)}return n})}function O(){let r={page:1,limit:1337};return new p().list(r).then(a=>{let n={0:{id:0,name:"(no group)",order:0,piggyBanks:[{id:0,name:"(no piggy bank)",order:0}]}};for(let o in a.data.data)if(a.data.data.hasOwnProperty(o)){let e=a.data.data[o],i=e.attributes.object_group_id??"0",u=e.attributes.object_group_title??"(no group)",c={id:e.id,name:e.attributes.name,order:e.attributes.order};n.hasOwnProperty(i)||(n[i]={id:i,name:u,order:e.attributes.object_group_order??0,piggyBanks:[]}),n[i].piggyBanks.push(c),n[i].piggyBanks.sort((d,s)=>d.order-s.order)}return Object.keys(n).sort().reduce((o,e)=>(o[e]=n[e],o),{})})}function P(){let r={page:1,limit:1337};return new f().list(r).then(a=>{let n={0:{id:0,name:"(no group)",order:0,subscriptions:[{id:0,name:"(no subscription)",order:0}]}};for(let o in a.data.data)if(a.data.data.hasOwnProperty(o)){let e=a.data.data[o],i=e.attributes.object_group_id??"0",u=e.attributes.object_group_title??"(no group)",c={id:e.id,name:e.attributes.name,order:e.attributes.order};n.hasOwnProperty(i)||(n[i]={id:i,name:u,order:e.attributes.object_group_order??0,subscriptions:[]}),n[i].subscriptions.push(c),n[i].subscriptions.sort((d,s)=>d.order-s.order)}return Object.keys(n).sort().reduce((o,e)=>(o[e]=n[e],o),{})})}function j(){return{description:"/api/v2/autocomplete/transaction-descriptions",account:"/api/v2/autocomplete/accounts",category:"/api/v2/autocomplete/categories",tag:"/api/v2/autocomplete/tags"}}function A(r){const t={server:r.serverUrl,serverParams:{},fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}},hiddenInput:!0,highlightTyped:!0,liveServer:!0};typeof r.filters<"u"&&r.filters.length>0&&(t.serverParams.types=r.filters),typeof r.onRenderItem<"u"&&r.onRenderItem!==null&&(t.onRenderItem=r.onRenderItem),r.valueField&&(t.valueField=r.valueField),r.labelField&&(t.labelField=r.labelField),r.onSelectItem&&(t.onSelectItem=r.onSelectItem),r.onChange&&(t.onChange=r.onChange),r.hiddenValue&&(t.hiddenValue=r.hiddenValue),m.init(r.selector,t)}function q(r,t){const a=parseInt(t._searchInput.attributes["data-index"].value);if(typeof r<"u"&&r.name){document.querySelector("#form")._x_dataStack[0].$data.entries[a].category_name=r.name;return}document.querySelector("#form")._x_dataStack[0].$data.entries[a].category_name=t._searchInput.value}function E(r,t){const a=parseInt(t._searchInput.attributes["data-index"].value);if(typeof r<"u"&&r.description){document.querySelector("#form")._x_dataStack[0].$data.entries[a].description=r.description;return}document.querySelector("#form")._x_dataStack[0].$data.entries[a].description=t._searchInput.value}function B(r,t){if(typeof r>"u"){const a=parseInt(t._searchInput.attributes["data-index"].value);if(document.querySelector("#form")._x_dataStack[0].$data.entries[a].destination_account.name===t._searchInput.value){console.warn('Ignore hallucinated destination account name change to "'+t._searchInput.value+'"');return}document.querySelector("#form")._x_dataStack[0].$data.entries[a].destination_account={name:t._searchInput.value,alpine_name:t._searchInput.value},document.querySelector("#form")._x_dataStack[0].changedDestinationAccount()}}function F(r,t){const a=parseInt(t._searchInput.attributes["data-index"].value);document.querySelector("#form")._x_dataStack[0].$data.entries[a].destination_account={id:r.id,name:r.name,alpine_name:r.name,type:r.type,currency_code:r.currency_code},document.querySelector("#form")._x_dataStack[0].changedDestinationAccount()}function G(r,t){if(typeof r>"u"){const a=parseInt(t._searchInput.attributes["data-index"].value);if(document.querySelector("#form")._x_dataStack[0].$data.entries[a].source_account.name===t._searchInput.value)return;document.querySelector("#form")._x_dataStack[0].$data.entries[a].source_account={name:t._searchInput.value,alpine_name:t._searchInput.value},document.querySelector("#form")._x_dataStack[0].changedSourceAccount()}}function R(r,t){const a=parseInt(t._searchInput.attributes["data-index"].value);document.querySelector("#form")._x_dataStack[0].$data.entries[a].source_account={id:r.id,name:r.name,alpine_name:r.name,type:r.type,currency_code:r.currency_code},document.querySelector("#form")._x_dataStack[0].changedSourceAccount()}class h{post(t,a,n){let o="/api/v1/attachments";return l.post(o,{filename:t,attachable_type:a,attachable_id:n})}upload(t,a){let n="./api/v1/attachments/"+t+"/upload";return axios.post(n,a)}}let b=function(r){let t=r.length,a=0,n=!1;for(const o in r)if(r.hasOwnProperty(o)&&/^0$|^[1-9]\d*$/.test(o)&&o<=4294967294&&n===!1){let e=new h;e.post(r[o].name,"TransactionJournal",r[o].journal).then(i=>{let u=parseInt(i.data.data.id);e.upload(u,r[o].content).then(c=>{if(a++,a===t){const d=new CustomEvent("upload-success",{some:"details"});document.dispatchEvent(d)}}).catch(c=>{console.error("Could not upload"),console.error(c),a++;const d=new CustomEvent("upload-failed",{error:c});document.dispatchEvent(d),n=!0})}).catch(i=>{console.error("Could not create upload."),console.error(i),a++;const u=new CustomEvent("upload-failed",{error:i});document.dispatchEvent(u),n=!0})}};function T(r,t){t=t.reverse();let a=[],n=0,o=[],e=document.querySelectorAll('input[name="attachments[]"]');for(const i in e)if(e.hasOwnProperty(i)&&/^0$|^[1-9]\d*$/.test(i)&&i<=4294967294)for(const u in e[i].files)e[i].files.hasOwnProperty(u)&&/^0$|^[1-9]\d*$/.test(u)&&u<=4294967294&&(a.push({journal:t[i].transaction_journal_id,file:e[i].files[u]}),n++);for(const i in a)a.hasOwnProperty(i)&&/^0$|^[1-9]\d*$/.test(i)&&i<=4294967294&&function(u,c){let d=new FileReader;d.onloadend=function(s){s.target.readyState===FileReader.DONE&&(o.push({name:a[c].file.name,journal:a[c].journal,content:new Blob([s.target.result])}),o.length===n&&b(o))},d.readAsArrayBuffer(u.file)}(a[i],i);return n}function v(r,t,a){let n=[];for(let o in a)a.hasOwnProperty(o)&&n.push(a[o].replace(r,t));return n}function D(r,t){let a,n,o;for(const e in r)if(r.hasOwnProperty(e)){if(e==="group_title"){console.error("Cannot handle error in group title.");continue}if(a=parseInt(e.split(".")[1]),n=e.split(".")[2],o=v(e,n,r[e]),!t.hasOwnProperty(a)){console.error("Cannot handle errors in index #"+a);continue}switch(n){case"currency_code":case"foreign_currency_code":case"category_name":case"piggy_bank_id":case"notes":case"internal_reference":case"external_url":case"latitude":case"longitude":case"zoom_level":case"interest_date":case"book_date":case"process_date":case"due_date":case"payment_date":case"invoice_date":case"amount":case"date":case"budget_id":case"bill_id":case"description":case"tags":t[a].errors[n]=o;break;case"source_name":case"source_id":t[a].errors.source_account=t[a].errors.source_account.concat(o);break;case"type":t[a].errors.source_account=t[a].errors.source_account.concat([_.t("validation.bad_type_source")]),t[a].errors.destination_account=t[a].errors.destination_account.concat([_.t("validation.bad_type_destination")]);break;case"destination_name":case"destination_id":t[a].errors.destination_account=t[a].errors.destination_account.concat(o);break;case"foreign_amount":case"foreign_currency_id":t[a].errors.foreign_amount=t[a].errors.foreign_amount.concat(o);break}typeof t[a]<"u"&&(t[a].errors.source_account=Array.from(new Set(t[a].errors.source_account)),t[a].errors.destination_account=Array.from(new Set(t[a].errors.destination_account)))}return console.log(t[0].errors),t}export{$ as a,O as b,P as c,T as d,A as e,G as f,R as g,B as h,F as i,j,q as k,C as l,E as m,x as p,D as s}; +import{a as l}from"./format-money-2cbd3c32.js";import{a as p,G as f}from"./get-4f3e9dd6.js";import{n as m,i as _}from"./vendor-47e474ee.js";function x(r,t,a){let n=[];for(let o in r)if(r.hasOwnProperty(o)){const e=r[o];let i=!1,u={};t!==null&&t.hasOwnProperty(o)&&(i=!0,t[o]);let c={};(i&&u.description!==e.description||!i)&&(c.description=e.description),c.source_name=e.source_account.name,c.destination_name=e.destination_account.name,c.amount=e.amount,c.currency_code=e.currency_code,c.date=e.date,c.interest_date=e.interest_date,c.book_date=e.book_date,c.process_date=e.process_date,c.due_date=e.due_date,c.payment_date=e.payment_date,c.invoice_date=e.invoice_date,c.budget_id=e.budget_id,c.category_name=e.category_name,c.piggy_bank_id=e.piggy_bank_id,c.bill_id=e.bill_id,c.tags=e.tags,c.notes=e.notes,c.internal_reference=e.internal_reference,c.external_url=e.external_url,c.store_location=!1,e.hasLocation&&(c.store_location=!0,c.longitude=e.longitude.toString(),c.latitude=e.latitude.toString(),c.zoom_level=e.zoomLevel),typeof e.foreign_currency_code<"u"&&e.foreign_currency_code.toString()!==""&&(c.foreign_currency_code=e.foreign_currency_code,typeof e.foreign_amount<"u"&&e.foreign_amount.toString()!==""&&(c.foreign_amount=e.foreign_amount),(typeof e.foreign_amount>"u"||e.foreign_amount.toString()==="")&&(delete c.foreign_amount,delete c.foreign_currency_code)),typeof e.source_account.id<"u"&&e.source_account.id.toString()!==""&&(c.source_id=e.source_account.id),typeof e.destination_account.id<"u"&&e.destination_account.id.toString()!==""&&(c.destination_id=e.destination_account.id),c.type=a,n.push(c)}return n}let g=class{list(t){return l.get("/api/v2/currencies",{params:t})}};function C(){let r={page:1,limit:1337};return new g().list(r).then(a=>{let n={defaultCurrency:{},nativeCurrencies:[],foreignCurrencies:[],enabledCurrencies:[]};n.foreignCurrencies.push({id:0,name:"(no foreign currency)",code:"",default:!1,symbol:"",decimal_places:2});for(let o in a.data.data)if(a.data.data.hasOwnProperty(o)){let e=a.data.data[o];if(e.attributes.enabled){let i={id:e.id,name:e.attributes.name,code:e.attributes.code,default:e.attributes.default,symbol:e.attributes.symbol,decimal_places:e.attributes.decimal_places};i.default&&(n.defaultCurrency=i),n.enabledCurrencies.push(i),n.nativeCurrencies.push(i),n.foreignCurrencies.push(i)}}return n})}class y{list(t){return l.get("/api/v2/budgets",{params:t})}}function $(){let r={page:1,limit:1337};return new y().list(r).then(a=>{let n=[{id:0,name:"(no budget)"}];for(let o in a.data.data)if(a.data.data.hasOwnProperty(o)){let e=a.data.data[o],i={id:e.id,name:e.attributes.name};n.push(i)}return n})}function O(){let r={page:1,limit:1337};return new p().list(r).then(a=>{let n={0:{id:0,name:"(no group)",order:0,piggyBanks:[{id:0,name:"(no piggy bank)",order:0}]}};for(let o in a.data.data)if(a.data.data.hasOwnProperty(o)){let e=a.data.data[o],i=e.attributes.object_group_id??"0",u=e.attributes.object_group_title??"(no group)",c={id:e.id,name:e.attributes.name,order:e.attributes.order};n.hasOwnProperty(i)||(n[i]={id:i,name:u,order:e.attributes.object_group_order??0,piggyBanks:[]}),n[i].piggyBanks.push(c),n[i].piggyBanks.sort((d,s)=>d.order-s.order)}return Object.keys(n).sort().reduce((o,e)=>(o[e]=n[e],o),{})})}function P(){let r={page:1,limit:1337};return new f().list(r).then(a=>{let n={0:{id:0,name:"(no group)",order:0,subscriptions:[{id:0,name:"(no subscription)",order:0}]}};for(let o in a.data.data)if(a.data.data.hasOwnProperty(o)){let e=a.data.data[o],i=e.attributes.object_group_id??"0",u=e.attributes.object_group_title??"(no group)",c={id:e.id,name:e.attributes.name,order:e.attributes.order};n.hasOwnProperty(i)||(n[i]={id:i,name:u,order:e.attributes.object_group_order??0,subscriptions:[]}),n[i].subscriptions.push(c),n[i].subscriptions.sort((d,s)=>d.order-s.order)}return Object.keys(n).sort().reduce((o,e)=>(o[e]=n[e],o),{})})}function j(){return{description:"/api/v2/autocomplete/transaction-descriptions",account:"/api/v2/autocomplete/accounts",category:"/api/v2/autocomplete/categories",tag:"/api/v2/autocomplete/tags"}}function A(r){const t={server:r.serverUrl,serverParams:{},fetchOptions:{headers:{"X-CSRF-TOKEN":document.head.querySelector('meta[name="csrf-token"]').content}},hiddenInput:!0,highlightTyped:!0,liveServer:!0};typeof r.filters<"u"&&r.filters.length>0&&(t.serverParams.types=r.filters),typeof r.onRenderItem<"u"&&r.onRenderItem!==null&&(t.onRenderItem=r.onRenderItem),r.valueField&&(t.valueField=r.valueField),r.labelField&&(t.labelField=r.labelField),r.onSelectItem&&(t.onSelectItem=r.onSelectItem),r.onChange&&(t.onChange=r.onChange),r.hiddenValue&&(t.hiddenValue=r.hiddenValue),m.init(r.selector,t)}function q(r,t){const a=parseInt(t._searchInput.attributes["data-index"].value);if(typeof r<"u"&&r.name){document.querySelector("#form")._x_dataStack[0].$data.entries[a].category_name=r.name;return}document.querySelector("#form")._x_dataStack[0].$data.entries[a].category_name=t._searchInput.value}function E(r,t){const a=parseInt(t._searchInput.attributes["data-index"].value);if(typeof r<"u"&&r.description){document.querySelector("#form")._x_dataStack[0].$data.entries[a].description=r.description;return}document.querySelector("#form")._x_dataStack[0].$data.entries[a].description=t._searchInput.value}function B(r,t){if(typeof r>"u"){const a=parseInt(t._searchInput.attributes["data-index"].value);if(document.querySelector("#form")._x_dataStack[0].$data.entries[a].destination_account.name===t._searchInput.value){console.warn('Ignore hallucinated destination account name change to "'+t._searchInput.value+'"');return}document.querySelector("#form")._x_dataStack[0].$data.entries[a].destination_account={name:t._searchInput.value,alpine_name:t._searchInput.value},document.querySelector("#form")._x_dataStack[0].changedDestinationAccount()}}function F(r,t){const a=parseInt(t._searchInput.attributes["data-index"].value);document.querySelector("#form")._x_dataStack[0].$data.entries[a].destination_account={id:r.id,name:r.name,alpine_name:r.name,type:r.type,currency_code:r.currency_code},document.querySelector("#form")._x_dataStack[0].changedDestinationAccount()}function G(r,t){if(typeof r>"u"){const a=parseInt(t._searchInput.attributes["data-index"].value);if(document.querySelector("#form")._x_dataStack[0].$data.entries[a].source_account.name===t._searchInput.value)return;document.querySelector("#form")._x_dataStack[0].$data.entries[a].source_account={name:t._searchInput.value,alpine_name:t._searchInput.value},document.querySelector("#form")._x_dataStack[0].changedSourceAccount()}}function R(r,t){const a=parseInt(t._searchInput.attributes["data-index"].value);document.querySelector("#form")._x_dataStack[0].$data.entries[a].source_account={id:r.id,name:r.name,alpine_name:r.name,type:r.type,currency_code:r.currency_code},document.querySelector("#form")._x_dataStack[0].changedSourceAccount()}class h{post(t,a,n){let o="/api/v1/attachments";return l.post(o,{filename:t,attachable_type:a,attachable_id:n})}upload(t,a){let n="./api/v1/attachments/"+t+"/upload";return axios.post(n,a)}}let b=function(r){let t=r.length,a=0,n=!1;for(const o in r)if(r.hasOwnProperty(o)&&/^0$|^[1-9]\d*$/.test(o)&&o<=4294967294&&n===!1){let e=new h;e.post(r[o].name,"TransactionJournal",r[o].journal).then(i=>{let u=parseInt(i.data.data.id);e.upload(u,r[o].content).then(c=>{if(a++,a===t){const d=new CustomEvent("upload-success",{some:"details"});document.dispatchEvent(d)}}).catch(c=>{console.error("Could not upload"),console.error(c),a++;const d=new CustomEvent("upload-failed",{error:c});document.dispatchEvent(d),n=!0})}).catch(i=>{console.error("Could not create upload."),console.error(i),a++;const u=new CustomEvent("upload-failed",{error:i});document.dispatchEvent(u),n=!0})}};function T(r,t){t=t.reverse();let a=[],n=0,o=[],e=document.querySelectorAll('input[name="attachments[]"]');for(const i in e)if(e.hasOwnProperty(i)&&/^0$|^[1-9]\d*$/.test(i)&&i<=4294967294)for(const u in e[i].files)e[i].files.hasOwnProperty(u)&&/^0$|^[1-9]\d*$/.test(u)&&u<=4294967294&&(a.push({journal:t[i].transaction_journal_id,file:e[i].files[u]}),n++);for(const i in a)a.hasOwnProperty(i)&&/^0$|^[1-9]\d*$/.test(i)&&i<=4294967294&&function(u,c){let d=new FileReader;d.onloadend=function(s){s.target.readyState===FileReader.DONE&&(o.push({name:a[c].file.name,journal:a[c].journal,content:new Blob([s.target.result])}),o.length===n&&b(o))},d.readAsArrayBuffer(u.file)}(a[i],i);return n}function v(r,t,a){let n=[];for(let o in a)a.hasOwnProperty(o)&&n.push(a[o].replace(r,t));return n}function D(r,t){let a,n,o;for(const e in r)if(r.hasOwnProperty(e)){if(e==="group_title"){console.error("Cannot handle error in group title.");continue}if(a=parseInt(e.split(".")[1]),n=e.split(".")[2],o=v(e,n,r[e]),!t.hasOwnProperty(a)){console.error("Cannot handle errors in index #"+a);continue}switch(n){case"currency_code":case"foreign_currency_code":case"category_name":case"piggy_bank_id":case"notes":case"internal_reference":case"external_url":case"latitude":case"longitude":case"zoom_level":case"interest_date":case"book_date":case"process_date":case"due_date":case"payment_date":case"invoice_date":case"amount":case"date":case"budget_id":case"bill_id":case"description":case"tags":t[a].errors[n]=o;break;case"source_name":case"source_id":t[a].errors.source_account=t[a].errors.source_account.concat(o);break;case"type":t[a].errors.source_account=t[a].errors.source_account.concat([_.t("validation.bad_type_source")]),t[a].errors.destination_account=t[a].errors.destination_account.concat([_.t("validation.bad_type_destination")]);break;case"destination_name":case"destination_id":t[a].errors.destination_account=t[a].errors.destination_account.concat(o);break;case"foreign_amount":case"foreign_currency_id":t[a].errors.foreign_amount=t[a].errors.foreign_amount.concat(o);break}typeof t[a]<"u"&&(t[a].errors.source_account=Array.from(new Set(t[a].errors.source_account)),t[a].errors.destination_account=Array.from(new Set(t[a].errors.destination_account)))}return console.log(t[0].errors),t}export{$ as a,O as b,P as c,T as d,A as e,G as f,R as g,B as h,F as i,j,q as k,C as l,E as m,x as p,D as s}; diff --git a/public/build/assets/vendor-47e474ee.js b/public/build/assets/vendor-47e474ee.js new file mode 100644 index 0000000000..dbf9b764e5 --- /dev/null +++ b/public/build/assets/vendor-47e474ee.js @@ -0,0 +1,314 @@ +var co=Object.defineProperty;var uo=(n,e,t)=>e in n?co(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var G=(n,e,t)=>(uo(n,typeof e!="symbol"?e+"":e,t),t);function _mergeNamespaces(n,e){for(var t=0;ti[s]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}function bind$4(n,e){return function(){return n.apply(e,arguments)}}const{toString}=Object.prototype,{getPrototypeOf}=Object,kindOf=(n=>e=>{const t=toString.call(e);return n[t]||(n[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=n=>(n=n.toLowerCase(),e=>kindOf(e)===n),typeOfTest=n=>e=>typeof e===n,{isArray:isArray$2}=Array,isUndefined=typeOfTest("undefined");function isBuffer(n){return n!==null&&!isUndefined(n)&&n.constructor!==null&&!isUndefined(n.constructor)&&isFunction$4(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(n){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(n):e=n&&n.buffer&&isArrayBuffer(n.buffer),e}const isString$1=typeOfTest("string"),isFunction$4=typeOfTest("function"),isNumber$1=typeOfTest("number"),isObject$4=n=>n!==null&&typeof n=="object",isBoolean=n=>n===!0||n===!1,isPlainObject=n=>{if(kindOf(n)!=="object")return!1;const e=getPrototypeOf(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)},isDate$1=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=n=>isObject$4(n)&&isFunction$4(n.pipe),isFormData=n=>{let e;return n&&(typeof FormData=="function"&&n instanceof FormData||isFunction$4(n.append)&&((e=kindOf(n))==="formdata"||e==="object"&&isFunction$4(n.toString)&&n.toString()==="[object FormData]"))},isURLSearchParams=kindOfTest("URLSearchParams"),trim$2=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(n,e,{allOwnKeys:t=!1}={}){if(n===null||typeof n>"u")return;let i,s;if(typeof n!="object"&&(n=[n]),isArray$2(n))for(i=0,s=n.length;i0;)if(s=t[i],e===s.toLowerCase())return s;return null}const _global=(()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global)(),isContextDefined=n=>!isUndefined(n)&&n!==_global;function merge$1(){const{caseless:n}=isContextDefined(this)&&this||{},e={},t=(i,s)=>{const o=n&&findKey$1(e,s)||s;isPlainObject(e[o])&&isPlainObject(i)?e[o]=merge$1(e[o],i):isPlainObject(i)?e[o]=merge$1({},i):isArray$2(i)?e[o]=i.slice():e[o]=i};for(let i=0,s=arguments.length;i(forEach(e,(s,o)=>{t&&isFunction$4(s)?n[o]=bind$4(s,t):n[o]=s},{allOwnKeys:i}),n),stripBOM=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),inherits=(n,e,t,i)=>{n.prototype=Object.create(e.prototype,i),n.prototype.constructor=n,Object.defineProperty(n,"super",{value:e.prototype}),t&&Object.assign(n.prototype,t)},toFlatObject=(n,e,t,i)=>{let s,o,r;const a={};if(e=e||{},n==null)return e;do{for(s=Object.getOwnPropertyNames(n),o=s.length;o-- >0;)r=s[o],(!i||i(r,n,e))&&!a[r]&&(e[r]=n[r],a[r]=!0);n=t!==!1&&getPrototypeOf(n)}while(n&&(!t||t(n,e))&&n!==Object.prototype);return e},endsWith=(n,e,t)=>{n=String(n),(t===void 0||t>n.length)&&(t=n.length),t-=e.length;const i=n.indexOf(e,t);return i!==-1&&i===t},toArray=n=>{if(!n)return null;if(isArray$2(n))return n;let e=n.length;if(!isNumber$1(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=n[e];return t},isTypedArray=(n=>e=>n&&e instanceof n)(typeof Uint8Array<"u"&&getPrototypeOf(Uint8Array)),forEachEntry=(n,e)=>{const i=(n&&n[Symbol.iterator]).call(n);let s;for(;(s=i.next())&&!s.done;){const o=s.value;e.call(n,o[0],o[1])}},matchAll=(n,e)=>{let t;const i=[];for(;(t=n.exec(e))!==null;)i.push(t);return i},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,i,s){return i.toUpperCase()+s}),hasOwnProperty$1=(({hasOwnProperty:n})=>(e,t)=>n.call(e,t))(Object.prototype),isRegExp=kindOfTest("RegExp"),reduceDescriptors=(n,e)=>{const t=Object.getOwnPropertyDescriptors(n),i={};forEach(t,(s,o)=>{let r;(r=e(s,o,n))!==!1&&(i[o]=r||s)}),Object.defineProperties(n,i)},freezeMethods=n=>{reduceDescriptors(n,(e,t)=>{if(isFunction$4(n)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const i=n[t];if(isFunction$4(i)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},toObjectSet=(n,e)=>{const t={},i=s=>{s.forEach(o=>{t[o]=!0})};return isArray$2(n)?i(n):i(String(n).split(e)),t},noop$4=()=>{},toFiniteNumber=(n,e)=>(n=+n,Number.isFinite(n)?n:e),ALPHA="abcdefghijklmnopqrstuvwxyz",DIGIT="0123456789",ALPHABET={DIGIT,ALPHA,ALPHA_DIGIT:ALPHA+ALPHA.toUpperCase()+DIGIT},generateString=(n=16,e=ALPHABET.ALPHA_DIGIT)=>{let t="";const{length:i}=e;for(;n--;)t+=e[Math.random()*i|0];return t};function isSpecCompliantForm(n){return!!(n&&isFunction$4(n.append)&&n[Symbol.toStringTag]==="FormData"&&n[Symbol.iterator])}const toJSONObject=n=>{const e=new Array(10),t=(i,s)=>{if(isObject$4(i)){if(e.indexOf(i)>=0)return;if(!("toJSON"in i)){e[s]=i;const o=isArray$2(i)?[]:{};return forEach(i,(r,a)=>{const l=t(r,s+1);!isUndefined(l)&&(o[a]=l)}),e[s]=void 0,o}}return i};return t(n,0)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=n=>n&&(isObject$4(n)||isFunction$4(n))&&isFunction$4(n.then)&&isFunction$4(n.catch),utils$2={isArray:isArray$2,isArrayBuffer,isBuffer,isFormData,isArrayBufferView,isString:isString$1,isNumber:isNumber$1,isBoolean,isObject:isObject$4,isPlainObject,isUndefined,isDate:isDate$1,isFile,isBlob,isRegExp,isFunction:isFunction$4,isStream,isURLSearchParams,isTypedArray,isFileList,forEach,merge:merge$1,extend,trim:trim$2,stripBOM,inherits,toFlatObject,kindOf,kindOfTest,endsWith,toArray,forEachEntry,matchAll,isHTMLForm,hasOwnProperty:hasOwnProperty$1,hasOwnProp:hasOwnProperty$1,reduceDescriptors,freezeMethods,toObjectSet,toCamelCase,noop:noop$4,toFiniteNumber,findKey:findKey$1,global:_global,isContextDefined,ALPHABET,generateString,isSpecCompliantForm,toJSONObject,isAsyncFn,isThenable};function AxiosError(n,e,t,i,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=n,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),i&&(this.request=i),s&&(this.response=s)}utils$2.inherits(AxiosError,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:utils$2.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const prototype$1=AxiosError.prototype,descriptors$1={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(n=>{descriptors$1[n]={value:n}});Object.defineProperties(AxiosError,descriptors$1);Object.defineProperty(prototype$1,"isAxiosError",{value:!0});AxiosError.from=(n,e,t,i,s,o)=>{const r=Object.create(prototype$1);return utils$2.toFlatObject(n,r,function(l){return l!==Error.prototype},a=>a!=="isAxiosError"),AxiosError.call(r,n.message,e,t,i,s),r.cause=n,r.name=n.name,o&&Object.assign(r,o),r};const httpAdapter=null;function isVisitable(n){return utils$2.isPlainObject(n)||utils$2.isArray(n)}function removeBrackets(n){return utils$2.endsWith(n,"[]")?n.slice(0,-2):n}function renderKey(n,e,t){return n?n.concat(e).map(function(s,o){return s=removeBrackets(s),!t&&o?"["+s+"]":s}).join(t?".":""):e}function isFlatArray(n){return utils$2.isArray(n)&&!n.some(isVisitable)}const predicates=utils$2.toFlatObject(utils$2,{},null,function(e){return/^is[A-Z]/.test(e)});function toFormData(n,e,t){if(!utils$2.isObject(n))throw new TypeError("target must be an object");e=e||new FormData,t=utils$2.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(b,S){return!utils$2.isUndefined(S[b])});const i=t.metaTokens,s=t.visitor||h,o=t.dots,r=t.indexes,l=(t.Blob||typeof Blob<"u"&&Blob)&&utils$2.isSpecCompliantForm(e);if(!utils$2.isFunction(s))throw new TypeError("visitor must be a function");function d(y){if(y===null)return"";if(utils$2.isDate(y))return y.toISOString();if(!l&&utils$2.isBlob(y))throw new AxiosError("Blob is not supported. Use a Buffer instead.");return utils$2.isArrayBuffer(y)||utils$2.isTypedArray(y)?l&&typeof Blob=="function"?new Blob([y]):Buffer.from(y):y}function h(y,b,S){let E=y;if(y&&!S&&typeof y=="object"){if(utils$2.endsWith(b,"{}"))b=i?b:b.slice(0,-2),y=JSON.stringify(y);else if(utils$2.isArray(y)&&isFlatArray(y)||(utils$2.isFileList(y)||utils$2.endsWith(b,"[]"))&&(E=utils$2.toArray(y)))return b=removeBrackets(b),E.forEach(function(R,A){!(utils$2.isUndefined(R)||R===null)&&e.append(r===!0?renderKey([b],A,o):r===null?b:b+"[]",d(R))}),!1}return isVisitable(y)?!0:(e.append(renderKey(S,b,o),d(y)),!1)}const p=[],m=Object.assign(predicates,{defaultVisitor:h,convertValue:d,isVisitable});function v(y,b){if(!utils$2.isUndefined(y)){if(p.indexOf(y)!==-1)throw Error("Circular reference detected in "+b.join("."));p.push(y),utils$2.forEach(y,function(E,T){(!(utils$2.isUndefined(E)||E===null)&&s.call(e,E,utils$2.isString(T)?T.trim():T,b,m))===!0&&v(E,b?b.concat(T):[T])}),p.pop()}}if(!utils$2.isObject(n))throw new TypeError("data must be an object");return v(n),e}function encode$1(n){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(n).replace(/[!'()~]|%20|%00/g,function(i){return e[i]})}function AxiosURLSearchParams(n,e){this._pairs=[],n&&toFormData(n,this,e)}const prototype=AxiosURLSearchParams.prototype;prototype.append=function(e,t){this._pairs.push([e,t])};prototype.toString=function(e){const t=e?function(i){return e.call(this,i,encode$1)}:encode$1;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function encode(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function buildURL(n,e,t){if(!e)return n;const i=t&&t.encode||encode,s=t&&t.serialize;let o;if(s?o=s(e,t):o=utils$2.isURLSearchParams(e)?e.toString():new AxiosURLSearchParams(e,t).toString(i),o){const r=n.indexOf("#");r!==-1&&(n=n.slice(0,r)),n+=(n.indexOf("?")===-1?"?":"&")+o}return n}class InterceptorManager{constructor(){this.handlers=[]}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){utils$2.forEach(this.handlers,function(i){i!==null&&e(i)})}}const InterceptorManager$1=InterceptorManager,transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},URLSearchParams$1=typeof URLSearchParams<"u"?URLSearchParams:AxiosURLSearchParams,FormData$1=typeof FormData<"u"?FormData:null,Blob$1=typeof Blob<"u"?Blob:null,platform$1={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$1,FormData:FormData$1,Blob:Blob$1},protocols:["http","https","file","blob","url","data"]},hasBrowserEnv=typeof window<"u"&&typeof document<"u",hasStandardBrowserEnv=(n=>hasBrowserEnv&&["ReactNative","NativeScript","NS"].indexOf(n)<0)(typeof navigator<"u"&&navigator.product),hasStandardBrowserWebWorkerEnv=(()=>typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function")(),utils$1=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv,hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv},Symbol.toStringTag,{value:"Module"})),platform={...utils$1,...platform$1};function toURLEncodedForm(n,e){return toFormData(n,new platform.classes.URLSearchParams,Object.assign({visitor:function(t,i,s,o){return platform.isNode&&utils$2.isBuffer(t)?(this.append(i,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},e))}function parsePropPath(n){return utils$2.matchAll(/\w+|\[(\w*)]/g,n).map(e=>e[0]==="[]"?"":e[1]||e[0])}function arrayToObject(n){const e={},t=Object.keys(n);let i;const s=t.length;let o;for(i=0;i=t.length;return r=!r&&utils$2.isArray(s)?s.length:r,l?(utils$2.hasOwnProp(s,r)?s[r]=[s[r],i]:s[r]=i,!a):((!s[r]||!utils$2.isObject(s[r]))&&(s[r]=[]),e(t,i,s[r],o)&&utils$2.isArray(s[r])&&(s[r]=arrayToObject(s[r])),!a)}if(utils$2.isFormData(n)&&utils$2.isFunction(n.entries)){const t={};return utils$2.forEachEntry(n,(i,s)=>{e(parsePropPath(i),s,t,0)}),t}return null}function stringifySafely(n,e,t){if(utils$2.isString(n))try{return(e||JSON.parse)(n),utils$2.trim(n)}catch(i){if(i.name!=="SyntaxError")throw i}return(t||JSON.stringify)(n)}const defaults$2={transitional:transitionalDefaults,adapter:["xhr","http"],transformRequest:[function(e,t){const i=t.getContentType()||"",s=i.indexOf("application/json")>-1,o=utils$2.isObject(e);if(o&&utils$2.isHTMLForm(e)&&(e=new FormData(e)),utils$2.isFormData(e))return s?JSON.stringify(formDataToJSON(e)):e;if(utils$2.isArrayBuffer(e)||utils$2.isBuffer(e)||utils$2.isStream(e)||utils$2.isFile(e)||utils$2.isBlob(e))return e;if(utils$2.isArrayBufferView(e))return e.buffer;if(utils$2.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(i.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(e,this.formSerializer).toString();if((a=utils$2.isFileList(e))||i.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return toFormData(a?{"files[]":e}:e,l&&new l,this.formSerializer)}}return o||s?(t.setContentType("application/json",!1),stringifySafely(e)):e}],transformResponse:[function(e){const t=this.transitional||defaults$2.transitional,i=t&&t.forcedJSONParsing,s=this.responseType==="json";if(e&&utils$2.isString(e)&&(i&&!this.responseType||s)){const r=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(a){if(r)throw a.name==="SyntaxError"?AxiosError.from(a,AxiosError.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$2.forEach(["delete","get","head","post","put","patch"],n=>{defaults$2.headers[n]={}});const defaults$3=defaults$2,ignoreDuplicateOf=utils$2.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),parseHeaders=n=>{const e={};let t,i,s;return n&&n.split(` +`).forEach(function(r){s=r.indexOf(":"),t=r.substring(0,s).trim().toLowerCase(),i=r.substring(s+1).trim(),!(!t||e[t]&&ignoreDuplicateOf[t])&&(t==="set-cookie"?e[t]?e[t].push(i):e[t]=[i]:e[t]=e[t]?e[t]+", "+i:i)}),e},$internals=Symbol("internals");function normalizeHeader(n){return n&&String(n).trim().toLowerCase()}function normalizeValue(n){return n===!1||n==null?n:utils$2.isArray(n)?n.map(normalizeValue):String(n)}function parseTokens(n){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=t.exec(n);)e[i[1]]=i[2];return e}const isValidHeaderName=n=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(n.trim());function matchHeaderValue(n,e,t,i,s){if(utils$2.isFunction(i))return i.call(this,e,t);if(s&&(e=t),!!utils$2.isString(e)){if(utils$2.isString(i))return e.indexOf(i)!==-1;if(utils$2.isRegExp(i))return i.test(e)}}function formatHeader(n){return n.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,i)=>t.toUpperCase()+i)}function buildAccessors(n,e){const t=utils$2.toCamelCase(" "+e);["get","set","has"].forEach(i=>{Object.defineProperty(n,i+t,{value:function(s,o,r){return this[i].call(this,e,s,o,r)},configurable:!0})})}class AxiosHeaders{constructor(e){e&&this.set(e)}set(e,t,i){const s=this;function o(a,l,d){const h=normalizeHeader(l);if(!h)throw new Error("header name must be a non-empty string");const p=utils$2.findKey(s,h);(!p||s[p]===void 0||d===!0||d===void 0&&s[p]!==!1)&&(s[p||l]=normalizeValue(a))}const r=(a,l)=>utils$2.forEach(a,(d,h)=>o(d,h,l));return utils$2.isPlainObject(e)||e instanceof this.constructor?r(e,t):utils$2.isString(e)&&(e=e.trim())&&!isValidHeaderName(e)?r(parseHeaders(e),t):e!=null&&o(t,e,i),this}get(e,t){if(e=normalizeHeader(e),e){const i=utils$2.findKey(this,e);if(i){const s=this[i];if(!t)return s;if(t===!0)return parseTokens(s);if(utils$2.isFunction(t))return t.call(this,s,i);if(utils$2.isRegExp(t))return t.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=normalizeHeader(e),e){const i=utils$2.findKey(this,e);return!!(i&&this[i]!==void 0&&(!t||matchHeaderValue(this,this[i],i,t)))}return!1}delete(e,t){const i=this;let s=!1;function o(r){if(r=normalizeHeader(r),r){const a=utils$2.findKey(i,r);a&&(!t||matchHeaderValue(i,i[a],a,t))&&(delete i[a],s=!0)}}return utils$2.isArray(e)?e.forEach(o):o(e),s}clear(e){const t=Object.keys(this);let i=t.length,s=!1;for(;i--;){const o=t[i];(!e||matchHeaderValue(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const t=this,i={};return utils$2.forEach(this,(s,o)=>{const r=utils$2.findKey(i,o);if(r){t[r]=normalizeValue(s),delete t[o];return}const a=e?formatHeader(o):String(o).trim();a!==o&&delete t[o],t[a]=normalizeValue(s),i[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return utils$2.forEach(this,(i,s)=>{i!=null&&i!==!1&&(t[s]=e&&utils$2.isArray(i)?i.join(", "):i)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const i=new this(e);return t.forEach(s=>i.set(s)),i}static accessor(e){const i=(this[$internals]=this[$internals]={accessors:{}}).accessors,s=this.prototype;function o(r){const a=normalizeHeader(r);i[a]||(buildAccessors(s,r),i[a]=!0)}return utils$2.isArray(e)?e.forEach(o):o(e),this}}AxiosHeaders.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);utils$2.reduceDescriptors(AxiosHeaders.prototype,({value:n},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>n,set(i){this[t]=i}}});utils$2.freezeMethods(AxiosHeaders);const AxiosHeaders$1=AxiosHeaders;function transformData(n,e){const t=this||defaults$3,i=e||t,s=AxiosHeaders$1.from(i.headers);let o=i.data;return utils$2.forEach(n,function(a){o=a.call(t,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function isCancel(n){return!!(n&&n.__CANCEL__)}function CanceledError(n,e,t){AxiosError.call(this,n??"canceled",AxiosError.ERR_CANCELED,e,t),this.name="CanceledError"}utils$2.inherits(CanceledError,AxiosError,{__CANCEL__:!0});function settle(n,e,t){const i=t.config.validateStatus;!t.status||!i||i(t.status)?n(t):e(new AxiosError("Request failed with status code "+t.status,[AxiosError.ERR_BAD_REQUEST,AxiosError.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}const cookies=platform.hasStandardBrowserEnv?{write(n,e,t,i,s,o){const r=[n+"="+encodeURIComponent(e)];utils$2.isNumber(t)&&r.push("expires="+new Date(t).toGMTString()),utils$2.isString(i)&&r.push("path="+i),utils$2.isString(s)&&r.push("domain="+s),o===!0&&r.push("secure"),document.cookie=r.join("; ")},read(n){const e=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(n){this.write(n,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function isAbsoluteURL(n){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(n)}function combineURLs(n,e){return e?n.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):n}function buildFullPath(n,e){return n&&!isAbsoluteURL(e)?combineURLs(n,e):e}const isURLSameOrigin=platform.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let i;function s(o){let r=o;return e&&(t.setAttribute("href",r),r=t.href),t.setAttribute("href",r),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:t.pathname.charAt(0)==="/"?t.pathname:"/"+t.pathname}}return i=s(window.location.href),function(r){const a=utils$2.isString(r)?s(r):r;return a.protocol===i.protocol&&a.host===i.host}}():function(){return function(){return!0}}();function parseProtocol(n){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(n);return e&&e[1]||""}function speedometer(n,e){n=n||10;const t=new Array(n),i=new Array(n);let s=0,o=0,r;return e=e!==void 0?e:1e3,function(l){const d=Date.now(),h=i[o];r||(r=d),t[s]=l,i[s]=d;let p=o,m=0;for(;p!==s;)m+=t[p++],p=p%n;if(s=(s+1)%n,s===o&&(o=(o+1)%n),d-r{const o=s.loaded,r=s.lengthComputable?s.total:void 0,a=o-t,l=i(a),d=o<=r;t=o;const h={loaded:o,total:r,progress:r?o/r:void 0,bytes:a,rate:l||void 0,estimated:l&&r&&d?(r-o)/l:void 0,event:s};h[e?"download":"upload"]=!0,n(h)}}const isXHRAdapterSupported=typeof XMLHttpRequest<"u",xhrAdapter=isXHRAdapterSupported&&function(n){return new Promise(function(t,i){let s=n.data;const o=AxiosHeaders$1.from(n.headers).normalize();let{responseType:r,withXSRFToken:a}=n,l;function d(){n.cancelToken&&n.cancelToken.unsubscribe(l),n.signal&&n.signal.removeEventListener("abort",l)}let h;if(utils$2.isFormData(s)){if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)o.setContentType(!1);else if((h=o.getContentType())!==!1){const[b,...S]=h?h.split(";").map(E=>E.trim()).filter(Boolean):[];o.setContentType([b||"multipart/form-data",...S].join("; "))}}let p=new XMLHttpRequest;if(n.auth){const b=n.auth.username||"",S=n.auth.password?unescape(encodeURIComponent(n.auth.password)):"";o.set("Authorization","Basic "+btoa(b+":"+S))}const m=buildFullPath(n.baseURL,n.url);p.open(n.method.toUpperCase(),buildURL(m,n.params,n.paramsSerializer),!0),p.timeout=n.timeout;function v(){if(!p)return;const b=AxiosHeaders$1.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),E={data:!r||r==="text"||r==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:b,config:n,request:p};settle(function(R){t(R),d()},function(R){i(R),d()},E),p=null}if("onloadend"in p?p.onloadend=v:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(v)},p.onabort=function(){p&&(i(new AxiosError("Request aborted",AxiosError.ECONNABORTED,n,p)),p=null)},p.onerror=function(){i(new AxiosError("Network Error",AxiosError.ERR_NETWORK,n,p)),p=null},p.ontimeout=function(){let S=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const E=n.transitional||transitionalDefaults;n.timeoutErrorMessage&&(S=n.timeoutErrorMessage),i(new AxiosError(S,E.clarifyTimeoutError?AxiosError.ETIMEDOUT:AxiosError.ECONNABORTED,n,p)),p=null},platform.hasStandardBrowserEnv&&(a&&utils$2.isFunction(a)&&(a=a(n)),a||a!==!1&&isURLSameOrigin(m))){const b=n.xsrfHeaderName&&n.xsrfCookieName&&cookies.read(n.xsrfCookieName);b&&o.set(n.xsrfHeaderName,b)}s===void 0&&o.setContentType(null),"setRequestHeader"in p&&utils$2.forEach(o.toJSON(),function(S,E){p.setRequestHeader(E,S)}),utils$2.isUndefined(n.withCredentials)||(p.withCredentials=!!n.withCredentials),r&&r!=="json"&&(p.responseType=n.responseType),typeof n.onDownloadProgress=="function"&&p.addEventListener("progress",progressEventReducer(n.onDownloadProgress,!0)),typeof n.onUploadProgress=="function"&&p.upload&&p.upload.addEventListener("progress",progressEventReducer(n.onUploadProgress)),(n.cancelToken||n.signal)&&(l=b=>{p&&(i(!b||b.type?new CanceledError(null,n,p):b),p.abort(),p=null)},n.cancelToken&&n.cancelToken.subscribe(l),n.signal&&(n.signal.aborted?l():n.signal.addEventListener("abort",l)));const y=parseProtocol(m);if(y&&platform.protocols.indexOf(y)===-1){i(new AxiosError("Unsupported protocol "+y+":",AxiosError.ERR_BAD_REQUEST,n));return}p.send(s||null)})},knownAdapters={http:httpAdapter,xhr:xhrAdapter};utils$2.forEach(knownAdapters,(n,e)=>{if(n){try{Object.defineProperty(n,"name",{value:e})}catch{}Object.defineProperty(n,"adapterName",{value:e})}});const renderReason=n=>`- ${n}`,isResolvedHandle=n=>utils$2.isFunction(n)||n===null||n===!1,adapters$1={getAdapter:n=>{n=utils$2.isArray(n)?n:[n];const{length:e}=n;let t,i;const s={};for(let o=0;o`adapter ${a} `+(l===!1?"is not supported by the environment":"is not available in the build"));let r=e?o.length>1?`since : +`+o.map(renderReason).join(` +`):" "+renderReason(o[0]):"as no adapter specified";throw new AxiosError("There is no suitable adapter to dispatch the request "+r,"ERR_NOT_SUPPORT")}return i},adapters:knownAdapters};function throwIfCancellationRequested(n){if(n.cancelToken&&n.cancelToken.throwIfRequested(),n.signal&&n.signal.aborted)throw new CanceledError(null,n)}function dispatchRequest(n){return throwIfCancellationRequested(n),n.headers=AxiosHeaders$1.from(n.headers),n.data=transformData.call(n,n.transformRequest),["post","put","patch"].indexOf(n.method)!==-1&&n.headers.setContentType("application/x-www-form-urlencoded",!1),adapters$1.getAdapter(n.adapter||defaults$3.adapter)(n).then(function(i){return throwIfCancellationRequested(n),i.data=transformData.call(n,n.transformResponse,i),i.headers=AxiosHeaders$1.from(i.headers),i},function(i){return isCancel(i)||(throwIfCancellationRequested(n),i&&i.response&&(i.response.data=transformData.call(n,n.transformResponse,i.response),i.response.headers=AxiosHeaders$1.from(i.response.headers))),Promise.reject(i)})}const headersToObject=n=>n instanceof AxiosHeaders$1?n.toJSON():n;function mergeConfig(n,e){e=e||{};const t={};function i(d,h,p){return utils$2.isPlainObject(d)&&utils$2.isPlainObject(h)?utils$2.merge.call({caseless:p},d,h):utils$2.isPlainObject(h)?utils$2.merge({},h):utils$2.isArray(h)?h.slice():h}function s(d,h,p){if(utils$2.isUndefined(h)){if(!utils$2.isUndefined(d))return i(void 0,d,p)}else return i(d,h,p)}function o(d,h){if(!utils$2.isUndefined(h))return i(void 0,h)}function r(d,h){if(utils$2.isUndefined(h)){if(!utils$2.isUndefined(d))return i(void 0,d)}else return i(void 0,h)}function a(d,h,p){if(p in e)return i(d,h);if(p in n)return i(void 0,d)}const l={url:o,method:o,data:o,baseURL:r,transformRequest:r,transformResponse:r,paramsSerializer:r,timeout:r,timeoutMessage:r,withCredentials:r,withXSRFToken:r,adapter:r,responseType:r,xsrfCookieName:r,xsrfHeaderName:r,onUploadProgress:r,onDownloadProgress:r,decompress:r,maxContentLength:r,maxBodyLength:r,beforeRedirect:r,transport:r,httpAgent:r,httpsAgent:r,cancelToken:r,socketPath:r,responseEncoding:r,validateStatus:a,headers:(d,h)=>s(headersToObject(d),headersToObject(h),!0)};return utils$2.forEach(Object.keys(Object.assign({},n,e)),function(h){const p=l[h]||s,m=p(n[h],e[h],h);utils$2.isUndefined(m)&&p!==a||(t[h]=m)}),t}const VERSION$2="1.6.7",validators$1={};["object","boolean","number","function","string","symbol"].forEach((n,e)=>{validators$1[n]=function(i){return typeof i===n||"a"+(e<1?"n ":" ")+n}});const deprecatedWarnings={};validators$1.transitional=function(e,t,i){function s(o,r){return"[Axios v"+VERSION$2+"] Transitional option '"+o+"'"+r+(i?". "+i:"")}return(o,r,a)=>{if(e===!1)throw new AxiosError(s(r," has been removed"+(t?" in "+t:"")),AxiosError.ERR_DEPRECATED);return t&&!deprecatedWarnings[r]&&(deprecatedWarnings[r]=!0,console.warn(s(r," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(o,r,a):!0}};function assertOptions(n,e,t){if(typeof n!="object")throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);const i=Object.keys(n);let s=i.length;for(;s-- >0;){const o=i[s],r=e[o];if(r){const a=n[o],l=a===void 0||r(a,o,n);if(l!==!0)throw new AxiosError("option "+o+" must be "+l,AxiosError.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new AxiosError("Unknown option "+o,AxiosError.ERR_BAD_OPTION)}}const validator={assertOptions,validators:validators$1},validators=validator.validators;class Axios{constructor(e){this.defaults=e,this.interceptors={request:new InterceptorManager$1,response:new InterceptorManager$1}}async request(e,t){try{return await this._request(e,t)}catch(i){if(i instanceof Error){let s;Error.captureStackTrace?Error.captureStackTrace(s={}):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";i.stack?o&&!String(i.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(i.stack+=` +`+o):i.stack=o}throw i}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=mergeConfig(this.defaults,t);const{transitional:i,paramsSerializer:s,headers:o}=t;i!==void 0&&validator.assertOptions(i,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),s!=null&&(utils$2.isFunction(s)?t.paramsSerializer={serialize:s}:validator.assertOptions(s,{encode:validators.function,serialize:validators.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let r=o&&utils$2.merge(o.common,o[t.method]);o&&utils$2.forEach(["delete","get","head","post","put","patch","common"],y=>{delete o[y]}),t.headers=AxiosHeaders$1.concat(r,o);const a=[];let l=!0;this.interceptors.request.forEach(function(b){typeof b.runWhen=="function"&&b.runWhen(t)===!1||(l=l&&b.synchronous,a.unshift(b.fulfilled,b.rejected))});const d=[];this.interceptors.response.forEach(function(b){d.push(b.fulfilled,b.rejected)});let h,p=0,m;if(!l){const y=[dispatchRequest.bind(this),void 0];for(y.unshift.apply(y,a),y.push.apply(y,d),m=y.length,h=Promise.resolve(t);p{if(!i._listeners)return;let o=i._listeners.length;for(;o-- >0;)i._listeners[o](s);i._listeners=null}),this.promise.then=s=>{let o;const r=new Promise(a=>{i.subscribe(a),o=a}).then(s);return r.cancel=function(){i.unsubscribe(o)},r},e(function(o,r,a){i.reason||(i.reason=new CanceledError(o,r,a),t(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}static source(){let e;return{token:new CancelToken(function(s){e=s}),cancel:e}}}const CancelToken$1=CancelToken;function spread(n){return function(t){return n.apply(null,t)}}function isAxiosError(n){return utils$2.isObject(n)&&n.isAxiosError===!0}const HttpStatusCode={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(HttpStatusCode).forEach(([n,e])=>{HttpStatusCode[e]=n});const HttpStatusCode$1=HttpStatusCode;function createInstance(n){const e=new Axios$1(n),t=bind$4(Axios$1.prototype.request,e);return utils$2.extend(t,Axios$1.prototype,e,{allOwnKeys:!0}),utils$2.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return createInstance(mergeConfig(n,s))},t}const axios=createInstance(defaults$3);axios.Axios=Axios$1;axios.CanceledError=CanceledError;axios.CancelToken=CancelToken$1;axios.isCancel=isCancel;axios.VERSION=VERSION$2;axios.toFormData=toFormData;axios.AxiosError=AxiosError;axios.Cancel=axios.CanceledError;axios.all=function(e){return Promise.all(e)};axios.spread=spread;axios.isAxiosError=isAxiosError;axios.mergeConfig=mergeConfig;axios.AxiosHeaders=AxiosHeaders$1;axios.formToJSON=n=>formDataToJSON(utils$2.isHTMLForm(n)?new FormData(n):n);axios.getAdapter=adapters$1.getAdapter;axios.HttpStatusCode=HttpStatusCode$1;axios.default=axios;const axios$1=axios;var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var assign=make_assign(),create$2=make_create(),trim$1=make_trim(),Global$5=typeof window<"u"?window:commonjsGlobal,util$7={assign,create:create$2,trim:trim$1,bind:bind$3,slice:slice$3,each:each$a,map:map$2,pluck:pluck$1,isList:isList$1,isFunction:isFunction$3,isObject:isObject$3,Global:Global$5};function make_assign(){return Object.assign?Object.assign:function(e,t,i,s){for(var o=1;o"u"?null:console;if(n){var e=n.warn?n.warn:n.log;e.apply(n,arguments)}}function createStore(n,e,t){t||(t=""),n&&!isList(n)&&(n=[n]),e&&!isList(e)&&(e=[e]);var i=t?"__storejs_"+t+"_":"",s=t?new RegExp("^"+i):null,o=/^[a-zA-Z0-9_\-]*$/;if(!o.test(t))throw new Error("store.js namespaces can only have alphanumerics + underscores and dashes");var r={_namespacePrefix:i,_namespaceRegexp:s,_testStorage:function(l){try{var d="__storejs__test__";l.write(d,d);var h=l.read(d)===d;return l.remove(d),h}catch{return!1}},_assignPluginFnProp:function(l,d){var h=this[d];this[d]=function(){var m=slice$2(arguments,0),v=this;function y(){if(h)return each$9(arguments,function(S,E){m[E]=S}),h.apply(v,m)}var b=[y].concat(m);return l.apply(v,b)}},_serialize:function(l){return JSON.stringify(l)},_deserialize:function(l,d){if(!l)return d;var h="";try{h=JSON.parse(l)}catch{h=l}return h!==void 0?h:d},_addStorage:function(l){this.enabled||this._testStorage(l)&&(this.storage=l,this.enabled=!0)},_addPlugin:function(l){var d=this;if(isList(l)){each$9(l,function(m){d._addPlugin(m)});return}var h=pluck(this.plugins,function(m){return l===m});if(!h){if(this.plugins.push(l),!isFunction$2(l))throw new Error("Plugins must be function values that return objects");var p=l.call(this);if(!isObject$2(p))throw new Error("Plugins must return an object of function properties");each$9(p,function(m,v){if(!isFunction$2(m))throw new Error("Bad plugin property: "+v+" from plugin "+l.name+". Plugins should only return functions.");d._assignPluginFnProp(m,v)})}},addStorage:function(l){_warn("store.addStorage(storage) is deprecated. Use createStore([storages])"),this._addStorage(l)}},a=create$1(r,storeAPI,{plugins:[]});return a.raw={},each$9(a,function(l,d){isFunction$2(l)&&(a.raw[d]=bind$2(a,l))}),each$9(n,function(l){a._addStorage(l)}),each$9(e,function(l){a._addPlugin(l)}),a}var util$5=util$7,Global$4=util$5.Global,localStorage_1={name:"localStorage",read:read$6,write:write$6,each:each$8,remove:remove$5,clearAll:clearAll$5};function localStorage(){return Global$4.localStorage}function read$6(n){return localStorage().getItem(n)}function write$6(n,e){return localStorage().setItem(n,e)}function each$8(n){for(var e=localStorage().length-1;e>=0;e--){var t=localStorage().key(e);n(read$6(t),t)}}function remove$5(n){return localStorage().removeItem(n)}function clearAll$5(){return localStorage().clear()}var util$4=util$7,Global$3=util$4.Global,oldFFGlobalStorage={name:"oldFF-globalStorage",read:read$5,write:write$5,each:each$7,remove:remove$4,clearAll:clearAll$4},globalStorage=Global$3.globalStorage;function read$5(n){return globalStorage[n]}function write$5(n,e){globalStorage[n]=e}function each$7(n){for(var e=globalStorage.length-1;e>=0;e--){var t=globalStorage.key(e);n(globalStorage[t],t)}}function remove$4(n){return globalStorage.removeItem(n)}function clearAll$4(){each$7(function(n,e){delete globalStorage[n]})}var util$3=util$7,Global$2=util$3.Global,oldIEUserDataStorage={name:"oldIE-userDataStorage",write:write$4,read:read$4,each:each$6,remove:remove$3,clearAll:clearAll$3},storageName="storejs",doc$1=Global$2.document,_withStorageEl=_makeIEStorageElFunction(),disable=(Global$2.navigator?Global$2.navigator.userAgent:"").match(/ (MSIE 8|MSIE 9|MSIE 10)\./);function write$4(n,e){if(!disable){var t=fixKey(n);_withStorageEl(function(i){i.setAttribute(t,e),i.save(storageName)})}}function read$4(n){if(!disable){var e=fixKey(n),t=null;return _withStorageEl(function(i){t=i.getAttribute(e)}),t}}function each$6(n){_withStorageEl(function(e){for(var t=e.XMLDocument.documentElement.attributes,i=t.length-1;i>=0;i--){var s=t[i];n(e.getAttribute(s.name),s.name)}})}function remove$3(n){var e=fixKey(n);_withStorageEl(function(t){t.removeAttribute(e),t.save(storageName)})}function clearAll$3(){_withStorageEl(function(n){var e=n.XMLDocument.documentElement.attributes;n.load(storageName);for(var t=e.length-1;t>=0;t--)n.removeAttribute(e[t].name);n.save(storageName)})}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function fixKey(n){return n.replace(/^\d/,"___$&").replace(forbiddenCharsRegex,"___")}function _makeIEStorageElFunction(){if(!doc$1||!doc$1.documentElement||!doc$1.documentElement.addBehavior)return null;var n="script",e,t,i;try{t=new ActiveXObject("htmlfile"),t.open(),t.write("<"+n+">document.w=window'),t.close(),e=t.w.frames[0].document,i=e.createElement("div")}catch{i=doc$1.createElement("div"),e=doc$1.body}return function(s){var o=[].slice.call(arguments,0);o.unshift(i),e.appendChild(i),i.addBehavior("#default#userData"),i.load(storageName),s.apply(this,o),e.removeChild(i)}}var util$2=util$7,Global$1=util$2.Global,trim=util$2.trim,cookieStorage={name:"cookieStorage",read:read$3,write:write$3,each:each$5,remove:remove$2,clearAll:clearAll$2},doc=Global$1.document;function read$3(n){if(!n||!_has(n))return null;var e="(?:^|.*;\\s*)"+escape(n).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(doc.cookie.replace(new RegExp(e),"$1"))}function each$5(n){for(var e=doc.cookie.split(/; ?/g),t=e.length-1;t>=0;t--)if(trim(e[t])){var i=e[t].split("="),s=unescape(i[0]),o=unescape(i[1]);n(o,s)}}function write$3(n,e){n&&(doc.cookie=escape(n)+"="+escape(e)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/")}function remove$2(n){!n||!_has(n)||(doc.cookie=escape(n)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function clearAll$2(){each$5(function(n,e){remove$2(e)})}function _has(n){return new RegExp("(?:^|;\\s*)"+escape(n).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(doc.cookie)}var util$1=util$7,Global=util$1.Global,sessionStorage_1={name:"sessionStorage",read:read$2,write:write$2,each:each$4,remove:remove$1,clearAll:clearAll$1};function sessionStorage(){return Global.sessionStorage}function read$2(n){return sessionStorage().getItem(n)}function write$2(n,e){return sessionStorage().setItem(n,e)}function each$4(n){for(var e=sessionStorage().length-1;e>=0;e--){var t=sessionStorage().key(e);n(read$2(t),t)}}function remove$1(n){return sessionStorage().removeItem(n)}function clearAll$1(){return sessionStorage().clear()}var memoryStorage_1={name:"memoryStorage",read:read$1,write:write$1,each:each$3,remove,clearAll},memoryStorage={};function read$1(n){return memoryStorage[n]}function write$1(n,e){memoryStorage[n]=e}function each$3(n){for(var e in memoryStorage)memoryStorage.hasOwnProperty(e)&&n(memoryStorage[e],e)}function remove(n){delete memoryStorage[n]}function clearAll(n){memoryStorage={}}var all=[localStorage_1,oldFFGlobalStorage,oldIEUserDataStorage,cookieStorage,sessionStorage_1,memoryStorage_1],json2$1={},hasRequiredJson2;function requireJson2(){return hasRequiredJson2||(hasRequiredJson2=1,typeof JSON!="object"&&(JSON={}),function(){var rx_one=/^[\],:{}\s]*$/,rx_two=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,rx_three=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,rx_four=/(?:^|:|,)(?:\s*\[)+/g,rx_escapable=/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,rx_dangerous=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;function f(n){return n<10?"0"+n:n}function this_value(){return this.valueOf()}typeof Date.prototype.toJSON!="function"&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},Boolean.prototype.toJSON=this_value,Number.prototype.toJSON=this_value,String.prototype.toJSON=this_value);var gap,indent,meta,rep;function quote(n){return rx_escapable.lastIndex=0,rx_escapable.test(n)?'"'+n.replace(rx_escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+n+'"'}function str(n,e){var t,i,s,o,r=gap,a,l=e[n];switch(l&&typeof l=="object"&&typeof l.toJSON=="function"&&(l=l.toJSON(n)),typeof rep=="function"&&(l=rep.call(e,n,l)),typeof l){case"string":return quote(l);case"number":return isFinite(l)?String(l):"null";case"boolean":case"null":return String(l);case"object":if(!l)return"null";if(gap+=indent,a=[],Object.prototype.toString.apply(l)==="[object Array]"){for(o=l.length,t=0;tlastFlushedIndex&&queue.splice(e,1)}function queueFlush(){!flushing&&!flushPending&&(flushPending=!0,queueMicrotask(flushJobs))}function flushJobs(){flushPending=!1,flushing=!0;for(let n=0;nn.effect(e,{scheduler:t=>{shouldSchedule?scheduler(t):t()}}),raw=n.raw}function overrideEffect(n){effect$3=n}function elementBoundEffect(n){let e=()=>{};return[i=>{let s=effect$3(i);return n._x_effects||(n._x_effects=new Set,n._x_runEffects=()=>{n._x_effects.forEach(o=>o())}),n._x_effects.add(s),e=()=>{s!==void 0&&(n._x_effects.delete(s),release(s))},s},()=>{e()}]}function watch(n,e){let t=!0,i,s=effect$3(()=>{let o=n();JSON.stringify(o),t?i=o:queueMicrotask(()=>{e(o,i),i=o}),t=!1});return()=>release(s)}function dispatch(n,e,t={}){n.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0,cancelable:!0}))}function walk(n,e){if(typeof ShadowRoot=="function"&&n instanceof ShadowRoot){Array.from(n.children).forEach(s=>walk(s,e));return}let t=!1;if(e(n,()=>t=!0),t)return;let i=n.firstElementChild;for(;i;)walk(i,e),i=i.nextElementSibling}function warn(n,...e){console.warn(`Alpine Warning: ${n}`,...e)}var started=!1;function start$1(){started&&warn("Alpine has already been initialized on this page. Calling Alpine.start() more than once can cause problems."),started=!0,document.body||warn("Unable to initialize. Trying to load Alpine before `` is available. Did you forget to add `defer` in Alpine's `