diff --git a/.env b/.env index fefb9f77..6d0b63b0 100644 --- a/.env +++ b/.env @@ -1,8 +1,8 @@ -APP_NAME=Laravel +APP_NAME=JBTINTAS APP_ENV=local APP_KEY=base64:mln1keRjYJYz06TPXJg8SZhJ7JN+oToy08vrPQhoq78= APP_DEBUG=true -APP_URL=http://localhost +APP_URL=http://JB.test APP_LOCALE=en APP_FALLBACK_LOCALE=en @@ -22,10 +22,10 @@ LOG_LEVEL=debug DB_CONNECTION=mysql DB_HOST=127.0.0.1 -DB_PORT=3306 -DB_DATABASE=laravel +DB_PORT=8889 +DB_DATABASE=jb DB_USERNAME=root -DB_PASSWORD= +DB_PASSWORD=root SESSION_DRIVER=database SESSION_LIFETIME=120 diff --git a/.gitignore b/.gitignore index a07a0dc9..1694b1c0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ /.phpunit.cache /node_modules -/public/build + /public/hot /public/storage /storage/*.key diff --git a/.user.ini b/.user.ini new file mode 100644 index 00000000..1d677be4 --- /dev/null +++ b/.user.ini @@ -0,0 +1,3 @@ +upload_max_filesize = 128M +post_max_size = 256M +max_file_uploads = 2000 diff --git a/app/Http/Controllers/Auth/AuthenticatedSessionController.php b/app/Http/Controllers/Auth/AuthenticatedSessionController.php new file mode 100644 index 00000000..613bcd9d --- /dev/null +++ b/app/Http/Controllers/Auth/AuthenticatedSessionController.php @@ -0,0 +1,47 @@ +authenticate(); + + $request->session()->regenerate(); + + return redirect()->intended(route('dashboard', absolute: false)); + } + + /** + * Destroy an authenticated session. + */ + public function destroy(Request $request): RedirectResponse + { + Auth::guard('web')->logout(); + + $request->session()->invalidate(); + + $request->session()->regenerateToken(); + + return redirect('/'); + } +} diff --git a/app/Http/Controllers/Auth/ConfirmablePasswordController.php b/app/Http/Controllers/Auth/ConfirmablePasswordController.php new file mode 100644 index 00000000..712394a5 --- /dev/null +++ b/app/Http/Controllers/Auth/ConfirmablePasswordController.php @@ -0,0 +1,40 @@ +validate([ + 'email' => $request->user()->email, + 'password' => $request->password, + ])) { + throw ValidationException::withMessages([ + 'password' => __('auth.password'), + ]); + } + + $request->session()->put('auth.password_confirmed_at', time()); + + return redirect()->intended(route('dashboard', absolute: false)); + } +} diff --git a/app/Http/Controllers/Auth/EmailVerificationNotificationController.php b/app/Http/Controllers/Auth/EmailVerificationNotificationController.php new file mode 100644 index 00000000..f64fa9ba --- /dev/null +++ b/app/Http/Controllers/Auth/EmailVerificationNotificationController.php @@ -0,0 +1,24 @@ +user()->hasVerifiedEmail()) { + return redirect()->intended(route('dashboard', absolute: false)); + } + + $request->user()->sendEmailVerificationNotification(); + + return back()->with('status', 'verification-link-sent'); + } +} diff --git a/app/Http/Controllers/Auth/EmailVerificationPromptController.php b/app/Http/Controllers/Auth/EmailVerificationPromptController.php new file mode 100644 index 00000000..ee3cb6fa --- /dev/null +++ b/app/Http/Controllers/Auth/EmailVerificationPromptController.php @@ -0,0 +1,21 @@ +user()->hasVerifiedEmail() + ? redirect()->intended(route('dashboard', absolute: false)) + : view('auth.verify-email'); + } +} diff --git a/app/Http/Controllers/Auth/NewPasswordController.php b/app/Http/Controllers/Auth/NewPasswordController.php new file mode 100644 index 00000000..fc16e14b --- /dev/null +++ b/app/Http/Controllers/Auth/NewPasswordController.php @@ -0,0 +1,63 @@ + $request]); + } + + /** + * Handle an incoming new password request. + * + * @throws ValidationException + */ + public function store(Request $request): RedirectResponse + { + $request->validate([ + 'token' => ['required'], + 'email' => ['required', 'email'], + 'password' => ['required', 'confirmed', Rules\Password::defaults()], + ]); + + // Here we will attempt to reset the user's password. If it is successful we + // will update the password on an actual user model and persist it to the + // database. Otherwise we will parse the error and return the response. + $status = Password::reset( + $request->only('email', 'password', 'password_confirmation', 'token'), + function (User $user) use ($request) { + $user->forceFill([ + 'password' => Hash::make($request->password), + 'remember_token' => Str::random(60), + ])->save(); + + event(new PasswordReset($user)); + } + ); + + // If the password was successfully reset, we will redirect the user back to + // the application's home authenticated view. If there is an error we can + // redirect them back to where they came from with their error message. + return $status == Password::PASSWORD_RESET + ? redirect()->route('login')->with('status', __($status)) + : back()->withInput($request->only('email')) + ->withErrors(['email' => __($status)]); + } +} diff --git a/app/Http/Controllers/Auth/PasswordController.php b/app/Http/Controllers/Auth/PasswordController.php new file mode 100644 index 00000000..69164091 --- /dev/null +++ b/app/Http/Controllers/Auth/PasswordController.php @@ -0,0 +1,29 @@ +validateWithBag('updatePassword', [ + 'current_password' => ['required', 'current_password'], + 'password' => ['required', Password::defaults(), 'confirmed'], + ]); + + $request->user()->update([ + 'password' => Hash::make($validated['password']), + ]); + + return back()->with('status', 'password-updated'); + } +} diff --git a/app/Http/Controllers/Auth/PasswordResetLinkController.php b/app/Http/Controllers/Auth/PasswordResetLinkController.php new file mode 100644 index 00000000..1bc9c115 --- /dev/null +++ b/app/Http/Controllers/Auth/PasswordResetLinkController.php @@ -0,0 +1,45 @@ +validate([ + 'email' => ['required', 'email'], + ]); + + // We will send the password reset link to this user. Once we have attempted + // to send the link, we will examine the response then see the message we + // need to show to the user. Finally, we'll send out a proper response. + $status = Password::sendResetLink( + $request->only('email') + ); + + return $status == Password::RESET_LINK_SENT + ? back()->with('status', __($status)) + : back()->withInput($request->only('email')) + ->withErrors(['email' => __($status)]); + } +} diff --git a/app/Http/Controllers/Auth/RegisteredUserController.php b/app/Http/Controllers/Auth/RegisteredUserController.php new file mode 100644 index 00000000..44a3930f --- /dev/null +++ b/app/Http/Controllers/Auth/RegisteredUserController.php @@ -0,0 +1,51 @@ +validate([ + 'name' => ['required', 'string', 'max:255'], + 'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class], + 'password' => ['required', 'confirmed', Rules\Password::defaults()], + ]); + + $user = User::create([ + 'name' => $request->name, + 'email' => $request->email, + 'password' => Hash::make($request->password), + ]); + + event(new Registered($user)); + + Auth::login($user); + + return redirect(route('dashboard', absolute: false)); + } +} diff --git a/app/Http/Controllers/Auth/VerifyEmailController.php b/app/Http/Controllers/Auth/VerifyEmailController.php new file mode 100644 index 00000000..784765e3 --- /dev/null +++ b/app/Http/Controllers/Auth/VerifyEmailController.php @@ -0,0 +1,27 @@ +user()->hasVerifiedEmail()) { + return redirect()->intended(route('dashboard', absolute: false).'?verified=1'); + } + + if ($request->user()->markEmailAsVerified()) { + event(new Verified($request->user())); + } + + return redirect()->intended(route('dashboard', absolute: false).'?verified=1'); + } +} diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php new file mode 100644 index 00000000..a48eb8d8 --- /dev/null +++ b/app/Http/Controllers/ProfileController.php @@ -0,0 +1,60 @@ + $request->user(), + ]); + } + + /** + * Update the user's profile information. + */ + public function update(ProfileUpdateRequest $request): RedirectResponse + { + $request->user()->fill($request->validated()); + + if ($request->user()->isDirty('email')) { + $request->user()->email_verified_at = null; + } + + $request->user()->save(); + + return Redirect::route('profile.edit')->with('status', 'profile-updated'); + } + + /** + * Delete the user's account. + */ + public function destroy(Request $request): RedirectResponse + { + $request->validateWithBag('userDeletion', [ + 'password' => ['required', 'current_password'], + ]); + + $user = $request->user(); + + Auth::logout(); + + $user->delete(); + + $request->session()->invalidate(); + $request->session()->regenerateToken(); + + return Redirect::to('/'); + } +} diff --git a/app/Http/Controllers/administrativo/AuditoriaController.php b/app/Http/Controllers/administrativo/AuditoriaController.php new file mode 100644 index 00000000..ea6cb5ca --- /dev/null +++ b/app/Http/Controllers/administrativo/AuditoriaController.php @@ -0,0 +1,118 @@ +assertAcessoGerencial($request->user()); + + $query = $this->applyFilters( + AuditoriaLog::query()->with('usuario:id,name')->latest(), + $request + ); + + return view('content.administrativo.auditoria.index', [ + 'logs' => $query->paginate(30)->withQueryString(), + 'filtros' => $request->only(['acao', 'entidade_tipo', 'usuario_id', 'data_inicio', 'data_fim']), + 'acoes' => AuditoriaLog::query()->select('acao')->distinct()->orderBy('acao')->pluck('acao')->values(), + 'entidades' => AuditoriaLog::query()->select('entidade_tipo')->distinct()->orderBy('entidade_tipo')->pluck('entidade_tipo')->values(), + 'usuarios' => User::query()->orderBy('name')->get(['id', 'name']), + ]); + } + + public function exportCsv(Request $request): Response + { + $this->assertAcessoGerencial($request->user()); + + $query = $this->applyFilters( + AuditoriaLog::query()->with('usuario:id,name')->latest(), + $request + ); + + $filename = 'auditoria_' . now()->format('Ymd_His') . '.csv'; + + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$filename}\"", + ]; + + return response()->streamDownload(function () use ($query) { + $output = fopen('php://output', 'w'); + fwrite($output, "\xEF\xBB\xBF"); + + fputcsv($output, [ + 'data_hora', + 'acao', + 'entidade_tipo', + 'entidade_id', + 'usuario', + 'dados_antes', + 'dados_depois', + 'ip', + 'user_agent', + ], ';'); + + $query->chunk(500, function ($logs) use ($output) { + foreach ($logs as $log) { + fputcsv($output, [ + optional($log->created_at)->format('Y-m-d H:i:s'), + $log->acao, + $log->entidade_tipo, + $log->entidade_id, + $log->usuario?->name ?? 'Sistema', + json_encode($log->dados_antes, JSON_UNESCAPED_UNICODE), + json_encode($log->dados_depois, JSON_UNESCAPED_UNICODE), + $log->ip, + $log->user_agent, + ], ';'); + } + }); + + fclose($output); + }, $filename, $headers); + } + + private function applyFilters($query, Request $request) + { + if ($request->filled('acao')) { + $query->where('acao', (string) $request->string('acao')); + } + + if ($request->filled('entidade_tipo')) { + $query->where('entidade_tipo', (string) $request->string('entidade_tipo')); + } + + if ($request->filled('usuario_id')) { + $query->where('usuario_id', (int) $request->integer('usuario_id')); + } + + if ($request->filled('data_inicio')) { + $inicio = Carbon::parse((string) $request->string('data_inicio'))->startOfDay(); + $query->where('created_at', '>=', $inicio); + } + + if ($request->filled('data_fim')) { + $fim = Carbon::parse((string) $request->string('data_fim'))->endOfDay(); + $query->where('created_at', '<=', $fim); + } + + return $query; + } + + private function assertAcessoGerencial(?User $user): void + { + if (!$user || !$user->possuiAcessoGerencial()) { + abort(403, 'Apenas GERENTE/ADMIN podem acessar auditoria.'); + } + } +} diff --git a/app/Http/Controllers/administrativo/UsuarioController.php b/app/Http/Controllers/administrativo/UsuarioController.php new file mode 100644 index 00000000..73221cf7 --- /dev/null +++ b/app/Http/Controllers/administrativo/UsuarioController.php @@ -0,0 +1,109 @@ +assertPermission($request->user(), 'usuarios.view', 'Sem permissao para visualizar usuarios.'); + + $query = User::query()->orderBy('name'); + + if ($request->filled('busca')) { + $busca = trim((string) $request->string('busca')); + $query->where(function ($q) use ($busca) { + $q->where('name', 'like', "%{$busca}%") + ->orWhere('email', 'like', "%{$busca}%"); + }); + } + + if ($request->filled('nivel_acesso')) { + $query->where('nivel_acesso', (string) $request->string('nivel_acesso')); + } + + return view('content.administrativo.usuarios.index', [ + 'usuarios' => $query->paginate(20)->withQueryString(), + 'filtros' => $request->only(['busca', 'nivel_acesso']), + 'niveis' => ['OPERADOR', 'GERENTE', 'ADMIN'], + 'logsRecentes' => AuditoriaLog::query() + ->with('usuario:id,name') + ->where('acao', 'NIVEL_ACESSO_USUARIO') + ->latest() + ->limit(15) + ->get(), + ]); + } + + public function updateAcesso(UpdateUsuarioAcessoRequest $request, User $user): RedirectResponse + { + $this->assertPermission($request->user(), 'usuarios.manage', 'Sem permissao para alterar acessos.'); + $this->assertAdmin($request->user()); + + $nivelAnterior = (string) ($user->nivel_acesso ?? 'OPERADOR'); + $nivelNovo = (string) $request->validated('nivel_acesso'); + + $user->update([ + 'nivel_acesso' => $nivelNovo, + ]); + + if ($nivelAnterior !== $nivelNovo) { + AuditoriaLog::create([ + 'usuario_id' => $request->user()->id, + 'acao' => 'NIVEL_ACESSO_USUARIO', + 'entidade_tipo' => 'USER', + 'entidade_id' => $user->id, + 'dados_antes' => [ + 'nome' => $user->name, + 'email' => $user->email, + 'nivel_acesso' => $nivelAnterior, + ], + 'dados_depois' => [ + 'nome' => $user->name, + 'email' => $user->email, + 'nivel_acesso' => $nivelNovo, + ], + 'ip' => $request->ip(), + 'user_agent' => mb_substr((string) $request->userAgent(), 0, 255), + ]); + } + + return redirect() + ->route('usuarios.index') + ->with('success', "Nivel de acesso de {$user->name} atualizado."); + } + + public function permissoes(Request $request): View + { + $this->assertPermission($request->user(), 'usuarios.view', 'Sem permissao para visualizar permissoes.'); + + $matriz = (array) config('rbac.permissions_by_role', []); + ksort($matriz); + + return view('content.administrativo.usuarios.permissoes', [ + 'matriz' => $matriz, + ]); + } + + private function assertAdmin(?User $user): void + { + if (!$user || (string) $user->nivel_acesso !== 'ADMIN') { + abort(403, 'Apenas ADMIN pode gerir usuarios.'); + } + } + + private function assertPermission(?User $user, string $permission, string $message): void + { + if (!$user || !$user->hasPermission($permission)) { + abort(403, $message); + } + } +} diff --git a/app/Http/Controllers/cadastros/CategoriaProdutoController.php b/app/Http/Controllers/cadastros/CategoriaProdutoController.php new file mode 100644 index 00000000..bafc1964 --- /dev/null +++ b/app/Http/Controllers/cadastros/CategoriaProdutoController.php @@ -0,0 +1,70 @@ +filled('busca')) { + $busca = trim((string) $request->string('busca')); + $query->where('nome', 'like', "%{$busca}%"); + } + + if ($request->filled('ativo')) { + $query->where('ativo', (bool) $request->integer('ativo')); + } + + return view('content.cadastros.categorias.index', [ + 'categorias' => $query->orderBy('nome')->paginate(15)->withQueryString(), + 'filtros' => $request->only(['busca', 'ativo']), + ]); + } + + public function create(): View + { + return view('content.cadastros.categorias.create', [ + 'categoriaProduto' => new CategoriaProduto(['ativo' => true]), + ]); + } + + public function store(StoreCategoriaProdutoRequest $request): RedirectResponse + { + CategoriaProduto::create($request->validated()); + + return redirect()->route('categorias-produto.index')->with('success', 'Categoria criada com sucesso.'); + } + + public function edit(CategoriaProduto $categoriaProduto): View + { + return view('content.cadastros.categorias.edit', compact('categoriaProduto')); + } + + public function update(UpdateCategoriaProdutoRequest $request, CategoriaProduto $categoriaProduto): RedirectResponse + { + $categoriaProduto->update($request->validated()); + + return redirect()->route('categorias-produto.index')->with('success', 'Categoria atualizada com sucesso.'); + } + + public function destroy(CategoriaProduto $categoriaProduto): RedirectResponse + { + if ($categoriaProduto->produtos()->exists()) { + return redirect()->route('categorias-produto.index')->with('error', 'Nao e possivel excluir categoria com produtos vinculados.'); + } + + $categoriaProduto->delete(); + + return redirect()->route('categorias-produto.index')->with('success', 'Categoria removida com sucesso.'); + } +} diff --git a/app/Http/Controllers/cadastros/TabelaPrecoController.php b/app/Http/Controllers/cadastros/TabelaPrecoController.php new file mode 100644 index 00000000..283ddade --- /dev/null +++ b/app/Http/Controllers/cadastros/TabelaPrecoController.php @@ -0,0 +1,82 @@ +filled('busca')) { + $busca = trim((string) $request->string('busca')); + $query->where(function ($q) use ($busca) { + $q->where('nome', 'like', "%{$busca}%") + ->orWhere('codigo', 'like', "%{$busca}%"); + }); + } + + if ($request->filled('tipo')) { + $query->where('tipo', (string) $request->string('tipo')); + } + + if ($request->filled('ativo')) { + $query->where('ativo', (bool) $request->integer('ativo')); + } + + return view('content.cadastros.tabelas-preco.index', [ + 'tabelas' => $query->orderBy('prioridade')->orderBy('nome')->paginate(15)->withQueryString(), + 'filtros' => $request->only(['busca', 'tipo', 'ativo']), + 'tipos' => ['VAREJO', 'ATACADO', 'PROMOCAO', 'ESPECIAL'], + ]); + } + + public function create(): View + { + return view('content.cadastros.tabelas-preco.create', [ + 'tabelaPreco' => new TabelaPreco(['ativo' => true, 'tipo' => 'VAREJO', 'prioridade' => 0]), + 'tipos' => ['VAREJO', 'ATACADO', 'PROMOCAO', 'ESPECIAL'], + ]); + } + + public function store(StoreTabelaPrecoRequest $request): RedirectResponse + { + TabelaPreco::create($request->validated()); + + return redirect()->route('tabelas-preco.index')->with('success', 'Tabela de preco criada com sucesso.'); + } + + public function edit(TabelaPreco $tabelaPreco): View + { + return view('content.cadastros.tabelas-preco.edit', [ + 'tabelaPreco' => $tabelaPreco, + 'tipos' => ['VAREJO', 'ATACADO', 'PROMOCAO', 'ESPECIAL'], + ]); + } + + public function update(UpdateTabelaPrecoRequest $request, TabelaPreco $tabelaPreco): RedirectResponse + { + $tabelaPreco->update($request->validated()); + + return redirect()->route('tabelas-preco.index')->with('success', 'Tabela de preco atualizada com sucesso.'); + } + + public function destroy(TabelaPreco $tabelaPreco): RedirectResponse + { + if ($tabelaPreco->produtoPrecos()->exists()) { + return redirect()->route('tabelas-preco.index')->with('error', 'Nao e possivel excluir tabela vinculada a produtos.'); + } + + $tabelaPreco->delete(); + + return redirect()->route('tabelas-preco.index')->with('success', 'Tabela de preco removida com sucesso.'); + } +} diff --git a/app/Http/Controllers/cadastros/UnidadeMedidaController.php b/app/Http/Controllers/cadastros/UnidadeMedidaController.php new file mode 100644 index 00000000..c1d8f5ac --- /dev/null +++ b/app/Http/Controllers/cadastros/UnidadeMedidaController.php @@ -0,0 +1,73 @@ +filled('busca')) { + $busca = trim((string) $request->string('busca')); + $query->where(function ($q) use ($busca) { + $q->where('sigla', 'like', "%{$busca}%") + ->orWhere('nome', 'like', "%{$busca}%"); + }); + } + + if ($request->filled('ativo')) { + $query->where('ativo', (bool) $request->integer('ativo')); + } + + return view('content.cadastros.unidades.index', [ + 'unidades' => $query->orderBy('sigla')->paginate(15)->withQueryString(), + 'filtros' => $request->only(['busca', 'ativo']), + ]); + } + + public function create(): View + { + return view('content.cadastros.unidades.create', [ + 'unidadeMedida' => new UnidadeMedida(['ativo' => true, 'casas_decimais' => 3]), + ]); + } + + public function store(StoreUnidadeMedidaRequest $request): RedirectResponse + { + UnidadeMedida::create($request->validated()); + + return redirect()->route('unidades-medida.index')->with('success', 'Unidade criada com sucesso.'); + } + + public function edit(UnidadeMedida $unidadeMedida): View + { + return view('content.cadastros.unidades.edit', compact('unidadeMedida')); + } + + public function update(UpdateUnidadeMedidaRequest $request, UnidadeMedida $unidadeMedida): RedirectResponse + { + $unidadeMedida->update($request->validated()); + + return redirect()->route('unidades-medida.index')->with('success', 'Unidade atualizada com sucesso.'); + } + + public function destroy(UnidadeMedida $unidadeMedida): RedirectResponse + { + if ($unidadeMedida->produtos()->exists()) { + return redirect()->route('unidades-medida.index')->with('error', 'Nao e possivel excluir unidade vinculada a produtos.'); + } + + $unidadeMedida->delete(); + + return redirect()->route('unidades-medida.index')->with('success', 'Unidade removida com sucesso.'); + } +} diff --git a/app/Http/Controllers/clientes/ClienteController.php b/app/Http/Controllers/clientes/ClienteController.php new file mode 100644 index 00000000..2a4d7d8c --- /dev/null +++ b/app/Http/Controllers/clientes/ClienteController.php @@ -0,0 +1,278 @@ +buildIndexQuery($request); + $clientes = $query->orderByDesc('id')->paginate(15)->withQueryString(); + + return view('content.clientes.index', [ + 'clientes' => $clientes, + 'ufs' => config('brasil.ufs'), + 'filtros' => $request->only(['busca', 'tipo_pessoa', 'uf', 'ativo']), + ]); + } + + public function exportCsv(Request $request) + { + $clientes = $this->buildIndexQuery($request)->orderByDesc('id')->get(); + $fileName = 'clientes_' . now()->format('Ymd_His') . '.csv'; + + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$fileName}\"", + ]; + + return response()->stream(function () use ($clientes): void { + $out = fopen('php://output', 'w'); + fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); + + fputcsv($out, [ + 'ID', + 'Nome', + 'Tipo', + 'CPF/CNPJ', + 'Email', + 'Telefone', + 'Celular', + 'Cidade', + 'UF', + 'Status', + ], ';'); + + foreach ($clientes as $cliente) { + fputcsv($out, [ + $cliente->id, + $cliente->nome, + $cliente->tipo_pessoa, + $cliente->cpf_cnpj, + $cliente->email ?? '', + $cliente->telefone ?? '', + $cliente->celular ?? '', + $cliente->cidade ?? '', + $cliente->uf ?? '', + $cliente->ativo ? 'ATIVO' : 'INATIVO', + ], ';'); + } + + fclose($out); + }, 200, $headers); + } + + public function create(): View + { + return view('content.clientes.create', [ + 'cliente' => new Cliente([ + 'tipo_pessoa' => 'PF', + 'ativo' => true, + 'pais' => 'Brasil', + 'sexo' => 'N', + 'saldo_credito' => 0, + 'limite_prazo' => 0, + ]), + 'ufs' => config('brasil.ufs'), + 'cidades' => [], + ]); + } + + public function store(StoreClienteRequest $request): RedirectResponse + { + $cliente = Cliente::create($this->sanitizePayload($request->validated())); + + return redirect() + ->route('clientes.show', $cliente) + ->with('success', 'Cliente cadastrado com sucesso.'); + } + + public function show(Cliente $cliente): View + { + $resumoComercial = [ + 'documentos_total' => DocumentoComercial::where('cliente_id', $cliente->id)->count(), + 'vendas_faturadas' => DocumentoComercial::where('cliente_id', $cliente->id)->where('status', 'FATURADO')->count(), + 'ultima_venda' => DocumentoComercial::where('cliente_id', $cliente->id)->where('status', 'FATURADO')->max('data_emissao'), + 'receber_em_aberto' => (float) ContaReceber::where('cliente_id', $cliente->id)->whereIn('status', ['ABERTO', 'PARCIAL'])->sum('valor_aberto'), + ]; + + return view('content.clientes.show', compact('cliente', 'resumoComercial')); + } + + public function edit(Cliente $cliente): View + { + return view('content.clientes.edit', [ + 'cliente' => $cliente, + 'ufs' => config('brasil.ufs'), + 'cidades' => $cliente->uf ? $this->getCidadesByUf($cliente->uf) : [], + ]); + } + + public function update(UpdateClienteRequest $request, Cliente $cliente): RedirectResponse + { + $cliente->update($this->sanitizePayload($request->validated())); + + return redirect() + ->route('clientes.show', $cliente) + ->with('success', 'Cliente atualizado com sucesso.'); + } + + public function destroy(Cliente $cliente): RedirectResponse + { + $cliente->delete(); + + return redirect() + ->route('clientes.index') + ->with('success', 'Cliente removido com sucesso.'); + } + + public function buscarCnpj(string $cnpj): JsonResponse + { + $cnpjDigits = preg_replace('/\D/', '', $cnpj); + + if (strlen($cnpjDigits) !== 14) { + return response()->json(['message' => 'CNPJ invalido.'], 422); + } + + $response = Http::timeout(10)->get("https://brasilapi.com.br/api/cnpj/v1/{$cnpjDigits}"); + + if (!$response->successful()) { + return response()->json(['message' => 'Nao foi possivel consultar o CNPJ agora.'], 422); + } + + $data = $response->json(); + + return response()->json([ + 'nome' => $data['razao_social'] ?? null, + 'nome_fantasia' => $data['nome_fantasia'] ?? null, + 'email' => $data['email'] ?? null, + 'telefone' => $data['ddd_telefone_1'] ?? null, + 'cep' => $data['cep'] ?? null, + 'logradouro' => $data['logradouro'] ?? null, + 'numero' => $data['numero'] ?? null, + 'complemento' => $data['complemento'] ?? null, + 'bairro' => $data['bairro'] ?? null, + 'cidade' => $data['municipio'] ?? null, + 'uf' => $data['uf'] ?? null, + 'codigo_ibge' => $data['codigo_municipio_ibge'] ?? null, + 'pais' => 'Brasil', + ]); + } + + public function cidadesPorUf(string $uf): JsonResponse + { + $uf = strtoupper($uf); + $cidades = $this->getCidadesByUf($uf); + + return response()->json(['cidades' => $cidades]); + } + + private function sanitizePayload(array $data): array + { + $nullableFields = [ + 'codigo', + 'nome_fantasia', + 'rg_ie', + 'email', + 'telefone', + 'celular', + 'contato_nome', + 'cep', + 'logradouro', + 'numero', + 'complemento', + 'bairro', + 'cidade', + 'uf', + 'codigo_ibge', + 'data_nascimento_fundacao', + 'sexo', + 'observacoes', + ]; + + foreach ($nullableFields as $field) { + if (array_key_exists($field, $data) && $data[$field] === '') { + $data[$field] = null; + } + } + + $data['ativo'] = (bool) ($data['ativo'] ?? true); + $data['saldo_credito'] = $data['saldo_credito'] ?? 0; + $data['limite_prazo'] = $data['limite_prazo'] ?? 0; + $data['pais'] = $data['pais'] ?? 'Brasil'; + + if (($data['tipo_pessoa'] ?? null) === 'PF') { + $data['nome_fantasia'] = null; + $data['contato_nome'] = null; + } + + return $data; + } + + private function getCidadesByUf(string $uf): array + { + if (!array_key_exists($uf, config('brasil.ufs'))) { + return []; + } + + return Cache::remember("ibge-cidades-{$uf}", now()->addDays(30), function () use ($uf) { + $response = Http::timeout(10)->get("https://servicodados.ibge.gov.br/api/v1/localidades/estados/{$uf}/municipios"); + + if (!$response->successful()) { + return []; + } + + return collect($response->json()) + ->pluck('nome') + ->filter() + ->sort() + ->values() + ->all(); + }); + } + + private function buildIndexQuery(Request $request) + { + $query = Cliente::query(); + + if ($request->filled('busca')) { + $busca = trim((string) $request->string('busca')); + $doc = preg_replace('/\D/', '', $busca); + + $query->where(function ($q) use ($busca, $doc) { + $q->where('nome', 'like', "%{$busca}%") + ->orWhere('email', 'like', "%{$busca}%") + ->orWhere('telefone', 'like', "%{$doc}%") + ->orWhere('celular', 'like', "%{$doc}%") + ->orWhere('cpf_cnpj', 'like', "%{$doc}%"); + }); + } + + if ($request->filled('tipo_pessoa')) { + $query->where('tipo_pessoa', $request->string('tipo_pessoa')); + } + + if ($request->filled('uf')) { + $query->where('uf', strtoupper((string) $request->string('uf'))); + } + + if ($request->filled('ativo')) { + $query->where('ativo', (bool) $request->integer('ativo')); + } + + return $query; + } +} diff --git a/app/Http/Controllers/comercial/DocumentoComercialController.php b/app/Http/Controllers/comercial/DocumentoComercialController.php new file mode 100644 index 00000000..16b959ea --- /dev/null +++ b/app/Http/Controllers/comercial/DocumentoComercialController.php @@ -0,0 +1,659 @@ +buildIndexQuery($request); + + $documentos = $query->paginate(20)->withQueryString(); + + $cards = [ + 'total' => DocumentoComercial::count(), + 'orcamentos_pendentes' => DocumentoComercial::where('tipo', 'ORCAMENTO')->where('status', 'PENDENTE')->count(), + 'aguardando_faturamento' => DocumentoComercial::whereIn('tipo', ['PEDIDO', 'VENDA'])->where('status', 'AGUARDANDO_FATURAMENTO')->count(), + 'faturados_mes' => DocumentoComercial::where('status', 'FATURADO')->whereMonth('data_emissao', now()->month)->count(), + ]; + + return view('content.comercial.documentos.index', [ + 'documentos' => $documentos, + 'clientes' => Cliente::orderBy('nome')->get(['id', 'nome']), + 'tipos' => ['ORCAMENTO', 'PREVENDA', 'PEDIDO', 'VENDA'], + 'statusList' => [ + 'RASCUNHO', + 'PENDENTE', + 'AGUARDANDO_PAGAMENTO', + 'EM_SEPARACAO', + 'AGUARDANDO_FATURAMENTO', + 'CONCLUIDO', + 'FATURADO', + 'CANCELADO', + ], + 'cards' => $cards, + 'filtros' => $request->only(['tipo', 'status', 'cliente_id', 'numero', 'data_inicio', 'data_fim']), + ]); + } + + public function exportCsv(Request $request): StreamedResponse + { + $documentos = $this->buildIndexQuery($request)->get(); + $filename = 'documentos_comerciais_' . now()->format('Ymd_His') . '.csv'; + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$filename}\"", + ]; + + return response()->streamDownload(function () use ($documentos): void { + $handle = fopen('php://output', 'w'); + fwrite($handle, "\xEF\xBB\xBF"); + + fputcsv($handle, [ + 'ID', + 'Numero', + 'Tipo', + 'Status', + 'Cliente', + 'Data Emissao', + 'Subtotal', + 'Desconto', + 'Acrescimo', + 'Impostos', + 'Total Liquido', + ], ';'); + + foreach ($documentos as $documento) { + fputcsv($handle, [ + $documento->id, + $documento->numero, + $documento->tipo, + $documento->status, + $documento->cliente->nome ?? '', + optional($documento->data_emissao)->format('Y-m-d H:i:s'), + number_format((float) $documento->subtotal, 2, '.', ''), + number_format((float) $documento->desconto_total, 2, '.', ''), + number_format((float) $documento->acrescimo_total, 2, '.', ''), + number_format((float) $documento->impostos_total, 2, '.', ''), + number_format((float) $documento->total_liquido, 2, '.', ''), + ], ';'); + } + + fclose($handle); + }, $filename, $headers); + } + + public function create(Request $request): View + { + $tipo = (string) $request->string('tipo', 'ORCAMENTO'); + + return view('content.comercial.documentos.create', [ + 'documento' => new DocumentoComercial([ + 'tipo' => $tipo, + 'status' => 'PENDENTE', + 'desconto_total' => 0, + 'acrescimo_total' => 0, + 'impostos_total' => 0, + ]), + 'filiais' => Filial::where('ativa', true)->orderBy('nome')->get(['id', 'nome']), + 'tabelasPreco' => TabelaPreco::where('ativo', true)->orderBy('prioridade')->orderBy('nome')->get(['id', 'nome', 'codigo']), + 'tipos' => ['ORCAMENTO', 'PREVENDA', 'PEDIDO', 'VENDA'], + 'statusOptionsByTipo' => DocumentoComercialService::STATUS_POR_TIPO, + 'regrasEdicao' => [ + 'pode_editar' => true, + 'permite_alterar_itens' => true, + 'permite_alterar_cabecalho' => true, + 'motivo' => null, + ], + 'isEdit' => false, + ]); + } + + public function store(StoreDocumentoComercialRequest $request): RedirectResponse + { + $documento = $this->service->create($request->validated(), $request->user()); + + return redirect()->route('documentos-comerciais.show', $documento)->with('success', 'Documento criado com sucesso.'); + } + + public function show(DocumentoComercial $documento): View + { + $documento = $documento; + $regrasEdicao = $this->service->regrasEdicao($documento); + $usuario = request()->user(); + $acoesFluxo = $this->service->acoesFluxoDisponiveis($documento); + + $documento->load([ + 'cliente', + 'vendedor', + 'operador', + 'filial', + 'origem', + 'itens.produto', + 'itens.reserva', + 'eventos.usuario', + 'pagamentos', + 'faturamento', + ]); + + return view('content.comercial.documentos.show', [ + 'documento' => $documento, + 'analise' => $this->buildAnalise($documento), + 'regrasEdicao' => $regrasEdicao, + 'podeGerenciarCancelamento' => $usuario?->hasPermission('vendas.documentos.cancelar') ?? false, + 'acoesFluxo' => $acoesFluxo, + ]); + } + + public function edit(DocumentoComercial $documento): View|RedirectResponse + { + $documento = $documento; + $regrasEdicao = $this->service->regrasEdicao($documento); + if (!$regrasEdicao['pode_editar']) { + return redirect() + ->route('documentos-comerciais.show', $documento) + ->with('error', $regrasEdicao['motivo'] ?? 'Documento nao pode ser alterado nesta etapa.'); + } + + $documento->load(['itens.produto', 'cliente']); + + return view('content.comercial.documentos.edit', [ + 'documento' => $documento, + 'filiais' => Filial::where('ativa', true)->orderBy('nome')->get(['id', 'nome']), + 'tabelasPreco' => TabelaPreco::where('ativo', true)->orderBy('prioridade')->orderBy('nome')->get(['id', 'nome', 'codigo']), + 'tipos' => ['ORCAMENTO', 'PREVENDA', 'PEDIDO', 'VENDA'], + 'statusOptionsByTipo' => DocumentoComercialService::STATUS_POR_TIPO, + 'regrasEdicao' => $regrasEdicao, + 'isEdit' => true, + ]); + } + + public function update(UpdateDocumentoComercialRequest $request, DocumentoComercial $documento): RedirectResponse + { + $documento = $this->service->update($documento, $request->validated(), $request->user()); + + return redirect()->route('documentos-comerciais.show', $documento)->with('success', 'Documento atualizado com sucesso.'); + } + + public function destroy(DocumentoComercial $documento): RedirectResponse + { + $this->assertPermission('vendas.documentos.cancelar', 'Voce nao possui permissao para cancelar documentos.'); + + $data = request()->validate([ + 'motivo_cancelamento' => ['required', 'string', 'min:5', 'max:500'], + ], [ + 'motivo_cancelamento.required' => 'Informe o motivo do cancelamento.', + 'motivo_cancelamento.min' => 'Motivo do cancelamento muito curto.', + ]); + + $this->service->cancelar($documento, request()->user(), (string) $data['motivo_cancelamento']); + + return redirect()->route('documentos-comerciais.show', $documento)->with('success', 'Documento cancelado com sucesso.'); + } + + public function reabrir(DocumentoComercial $documento): RedirectResponse + { + $this->assertPermission('vendas.documentos.cancelar', 'Voce nao possui permissao para reabrir documentos.'); + + $data = request()->validate([ + 'motivo_reabertura' => ['required', 'string', 'min:5', 'max:500'], + ], [ + 'motivo_reabertura.required' => 'Informe o motivo da reabertura.', + 'motivo_reabertura.min' => 'Motivo da reabertura muito curto.', + ]); + + $documento = $this->service->reabrir($documento, request()->user(), (string) $data['motivo_reabertura']); + + return redirect()->route('documentos-comerciais.show', $documento)->with('success', 'Documento reaberto com sucesso.'); + } + + private function assertPermission(string $permission, string $message): void + { + $user = request()->user(); + if (!$user || !$user->hasPermission($permission)) { + abort(403, $message); + } + } + + public function converterPedido(DocumentoComercial $documento): RedirectResponse + { + $pedido = $this->service->converterOrcamentoParaPedido($documento, request()->user()); + + return redirect()->route('documentos-comerciais.show', $pedido)->with('success', 'Orcamento convertido em pedido.'); + } + + public function converterVenda(DocumentoComercial $documento): RedirectResponse + { + $venda = $this->service->converterPedidoParaVenda($documento, request()->user()); + + return redirect()->route('documentos-comerciais.show', $venda)->with('success', 'Pedido convertido em venda.'); + } + + public function faturar(DocumentoComercial $documento): RedirectResponse + { + $documento = $this->service->faturar($documento, request()->user()); + + return redirect()->route('documentos-comerciais.show', $documento)->with('success', 'Faturamento concluido com sucesso.'); + } + + public function analise(DocumentoComercial $documento): View + { + $documento = $documento->load(['itens.produto']); + + return view('content.comercial.documentos.analise', [ + 'documento' => $documento, + 'analise' => $this->buildAnalise($documento), + ]); + } + + public function exportAnaliseCsv(DocumentoComercial $documento): StreamedResponse + { + $documento = $documento->load(['itens.produto']); + $analise = $this->buildAnalise($documento); + $filename = 'analise_' . $documento->numero . '_' . now()->format('Ymd_His') . '.csv'; + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$filename}\"", + ]; + + return response()->streamDownload(function () use ($analise): void { + $handle = fopen('php://output', 'w'); + fwrite($handle, "\xEF\xBB\xBF"); + + fputcsv($handle, [ + 'Item', + 'Quantidade', + 'Receita Bruta', + 'Desconto Rateado', + 'Acrescimo Rateado', + 'Imposto Rateado', + 'Custo Ref Unitario', + 'Custo Total', + 'Receita Liquida', + 'Margem', + 'Margem (%)', + ], ';'); + + foreach ($analise['itens'] as $row) { + fputcsv($handle, [ + $row['item']->descricao, + number_format((float) $row['item']->quantidade, 3, '.', ''), + number_format((float) $row['receita_bruta'], 2, '.', ''), + number_format((float) $row['desconto_rateado'], 2, '.', ''), + number_format((float) $row['acrescimo_rateado'], 2, '.', ''), + number_format((float) $row['imposto_rateado'], 2, '.', ''), + number_format((float) $row['custo_ref_unitario'], 2, '.', ''), + number_format((float) $row['custo_total'], 2, '.', ''), + number_format((float) $row['receita'], 2, '.', ''), + number_format((float) $row['margem'], 2, '.', ''), + number_format((float) $row['margem_percentual'], 2, '.', ''), + ], ';'); + } + + fclose($handle); + }, $filename, $headers); + } + + public function buscarProdutos(Request $request): JsonResponse + { + $termo = trim((string) $request->string('termo')); + if (mb_strlen($termo) < 2) { + return response()->json(['produtos' => []]); + } + + $produtos = Produto::query() + ->with('unidadePrincipal:id,sigla') + ->where('ativo', true) + ->where('permite_venda', true) + ->where(function ($q) use ($termo) { + $q->where('nome', 'like', "%{$termo}%") + ->orWhere('sku', 'like', "%{$termo}%") + ->orWhere('codigo_barras', 'like', "%{$termo}%"); + }) + ->orderByRaw('nome LIKE ? DESC', ["{$termo}%"]) + ->orderBy('nome') + ->limit(20) + ->get(['id', 'nome', 'sku', 'codigo_barras', 'unidade_principal_id']); + + $precos = ProdutoPreco::query() + ->whereIn('produto_id', $produtos->pluck('id')) + ->where('ativo', true) + ->orderByDesc('vigencia_inicio') + ->get() + ->groupBy('produto_id') + ->map(fn ($items) => (float) ($items->first()->preco ?? 0)); + + return response()->json([ + 'produtos' => $produtos->map(fn ($p) => [ + 'id' => $p->id, + 'nome' => $p->nome, + 'sku' => $p->sku, + 'ean' => $p->codigo_barras, + 'unidade' => $p->unidadePrincipal?->sigla ?? 'UN', + 'preco' => (float) ($precos[$p->id] ?? 0), + ])->values(), + ]); + } + + public function buscarClientes(Request $request): JsonResponse + { + $termo = trim((string) $request->string('termo')); + if (mb_strlen($termo) < 2) { + return response()->json(['clientes' => []]); + } + + $clientes = Cliente::query() + ->where('ativo', true) + ->where(function ($q) use ($termo) { + $q->where('nome', 'like', "%{$termo}%") + ->orWhere('cpf_cnpj', 'like', "%{$termo}%") + ->orWhere('telefone', 'like', "%{$termo}%") + ->orWhere('email', 'like', "%{$termo}%"); + }) + ->orderByRaw('nome LIKE ? DESC', ["{$termo}%"]) + ->orderBy('nome') + ->limit(20) + ->get(['id', 'nome', 'cpf_cnpj', 'telefone', 'email', 'tipo_pessoa']); + + return response()->json([ + 'clientes' => $clientes->map(fn ($cliente) => [ + 'id' => $cliente->id, + 'nome' => $cliente->nome, + 'cpf_cnpj' => $cliente->cpf_cnpj, + 'telefone' => $cliente->telefone, + 'email' => $cliente->email, + 'tipo_cliente' => $cliente->tipo_pessoa, + ])->values(), + ]); + } + + public function pdv(): View + { + $produtos = Produto::query() + ->with(['unidadePrincipal', 'estoqueSaldo']) + ->where('ativo', true) + ->where('permite_venda', true) + ->orderBy('nome') + ->get(); + + $tabelaPrecoVarejoId = TabelaPreco::where('codigo', 'VAREJO')->value('id'); + $precos = ProdutoPreco::query() + ->where('ativo', true) + ->when($tabelaPrecoVarejoId, fn ($q) => $q->where('tabela_preco_id', $tabelaPrecoVarejoId)) + ->orderByDesc('vigencia_inicio') + ->get() + ->keyBy('produto_id'); + + return view('content.comercial.pdv.index', [ + 'clientes' => Cliente::orderBy('nome')->get(['id', 'nome', 'cpf_cnpj']), + 'produtos' => $produtos, + 'precos' => $precos, + ]); + } + + public function pdvFinalizar(StoreDocumentoComercialRequest $request): RedirectResponse + { + $payload = $request->validated(); + $payload['tipo'] = 'VENDA'; + $payload['status'] = 'AGUARDANDO_FATURAMENTO'; + + $documento = $this->service->create($payload, $request->user()); + + return redirect()->route('documentos-comerciais.show', $documento)->with('success', 'Venda registrada no PDV.'); + } + + public function importarPdfLegado( + ImportVendasLegadoPdfRequest $request, + LegacyVendaPdfParser $parser, + LegacyVendaImportService $importService + ): RedirectResponse { + $arquivos = $this->normalizarArquivos($request); + $inicio = microtime(true); + $sucesso = []; + $falhas = []; + $ignorados = []; + + foreach ($arquivos as $arquivo) { + try { + $dados = $parser->parse($arquivo); + $documento = $importService->importar($dados, $request->user()); + $sucesso[] = [ + 'arquivo' => $arquivo->getClientOriginalName(), + 'numero' => $documento->numero, + ]; + } catch (Throwable $e) { + if ($this->isDuplicidadeImportacao($e)) { + $ignorados[] = [ + 'arquivo' => $arquivo->getClientOriginalName(), + 'motivo' => $e->getMessage(), + ]; + continue; + } + + $falhas[] = [ + 'arquivo' => $arquivo->getClientOriginalName(), + 'erro' => $e->getMessage(), + ]; + } + } + + $tempoMs = (int) round((microtime(true) - $inicio) * 1000); + $total = count($arquivos); + + $redirect = redirect()->route('documentos-comerciais.index'); + + if (count($sucesso) > 0) { + $redirect->with('success', count($sucesso) . ' PDF(s) importado(s) como venda faturada.'); + } + + if (count($falhas) > 0) { + $redirect->with( + 'error', + count($falhas) . ' arquivo(s) nao foram importados. Veja os detalhes abaixo.' + ); + } + + if (count($ignorados) > 0) { + $redirect->with('warning', count($ignorados) . ' arquivo(s) ignorados (duplicidade).'); + } + + return $redirect->with('import_feedback', [ + 'sucesso' => $sucesso, + 'falhas' => $falhas, + 'ignorados' => $ignorados, + 'stats' => [ + 'total' => $total, + 'sucesso' => count($sucesso), + 'falhas' => count($falhas), + 'ignorados' => count($ignorados), + 'tempo_ms' => $tempoMs, + ], + ]); + } + + /** + * @return array + */ + private function normalizarArquivos(Request $request): array + { + $arquivosUpload = Arr::flatten([ + $request->file('arquivos', []), + $request->file('pasta_arquivos', []), + ]); + + $arquivos = array_values(array_filter($arquivosUpload, function ($arquivo): bool { + if (!$arquivo instanceof UploadedFile) { + return false; + } + + $mime = (string) $arquivo->getMimeType(); + $ext = strtolower((string) $arquivo->getClientOriginalExtension()); + + return $mime === 'application/pdf' || $ext === 'pdf'; + })); + + $caminhoPasta = trim((string) $request->input('caminho_pasta')); + if ($caminhoPasta !== '' && File::isDirectory($caminhoPasta)) { + foreach ($this->buscarPdfsDaPasta($caminhoPasta) as $pdfPath) { + $arquivos[] = new UploadedFile( + $pdfPath, + basename($pdfPath), + 'application/pdf', + null, + true + ); + } + } + + return $arquivos; + } + + /** + * @return array + */ + private function buscarPdfsDaPasta(string $caminhoPasta): array + { + $arquivos = []; + + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($caminhoPasta, \FilesystemIterator::SKIP_DOTS) + ); + + foreach ($iterator as $fileInfo) { + if (!$fileInfo->isFile()) { + continue; + } + + if (strtolower((string) $fileInfo->getExtension()) !== 'pdf') { + continue; + } + + $arquivos[] = $fileInfo->getPathname(); + } + + return $arquivos; + } + + private function isDuplicidadeImportacao(Throwable $e): bool + { + $msg = mb_strtolower($e->getMessage()); + return str_contains($msg, 'ja importada') || str_contains($msg, 'duplic'); + } + + private function buildAnalise(DocumentoComercial $documento): array + { + $documento->loadMissing('itens.produto'); + + $subtotalItens = (float) $documento->itens->sum('subtotal_bruto'); + $descontoTotal = (float) $documento->desconto_total; + $acrescimoTotal = (float) $documento->acrescimo_total; + $impostoTotal = (float) $documento->impostos_total; + + $itens = $documento->itens->map(function ($item) use ($subtotalItens, $descontoTotal, $acrescimoTotal, $impostoTotal) { + $custoRef = (float) ProdutoPreco::query() + ->where('produto_id', $item->produto_id) + ->where('ativo', true) + ->orderByDesc('vigencia_inicio') + ->value('custo_referencia'); + + $subtotalBrutoItem = (float) $item->subtotal_bruto; + $pesoRateio = $subtotalItens > 0 ? ($subtotalBrutoItem / $subtotalItens) : 0; + $descontoRateado = round($descontoTotal * $pesoRateio, 2); + $acrescimoRateado = round($acrescimoTotal * $pesoRateio, 2); + $impostoRateado = round($impostoTotal * $pesoRateio, 2); + + $receitaBruta = $subtotalBrutoItem; + $receitaLiquida = round($receitaBruta - $descontoRateado + $acrescimoRateado + $impostoRateado, 2); + $custoTotal = $custoRef * (float) $item->quantidade; + $margem = $receitaLiquida - $custoTotal; + $margemPercentual = $receitaLiquida > 0 ? round(($margem / $receitaLiquida) * 100, 2) : 0; + + return [ + 'item' => $item, + 'peso_rateio' => $pesoRateio, + 'desconto_rateado' => $descontoRateado, + 'acrescimo_rateado' => $acrescimoRateado, + 'imposto_rateado' => $impostoRateado, + 'custo_ref_unitario' => $custoRef, + 'custo_total' => $custoTotal, + 'receita_bruta' => $receitaBruta, + 'receita' => $receitaLiquida, + 'margem' => $margem, + 'margem_percentual' => $margemPercentual, + ]; + }); + + return [ + 'itens' => $itens, + 'subtotal_itens' => $subtotalItens, + 'desconto_rateado_total' => $descontoTotal, + 'acrescimo_rateado_total' => $acrescimoTotal, + 'imposto_rateado_total' => $impostoTotal, + 'total_receita' => (float) $documento->total_liquido, + 'total_custo_ref' => (float) $itens->sum('custo_total'), + 'total_margem' => (float) $itens->sum('margem'), + 'margem_percentual_total' => (float) ($documento->total_liquido > 0 ? round(($itens->sum('margem') / (float) $documento->total_liquido) * 100, 2) : 0), + ]; + } + + private function buildIndexQuery(Request $request) + { + $query = DocumentoComercial::query() + ->with(['cliente', 'vendedor', 'origem']) + ->orderByDesc('id'); + + if ($request->filled('tipo')) { + $query->where('tipo', $request->string('tipo')); + } + + if ($request->filled('status')) { + $query->where('status', $request->string('status')); + } + + if ($request->filled('cliente_id')) { + $query->where('cliente_id', (int) $request->integer('cliente_id')); + } + + if ($request->filled('numero')) { + $numero = trim((string) $request->string('numero')); + $query->where('numero', 'like', "%{$numero}%"); + } + + if ($request->filled('data_inicio')) { + $query->whereDate('data_emissao', '>=', $request->date('data_inicio')); + } + + if ($request->filled('data_fim')) { + $query->whereDate('data_emissao', '<=', $request->date('data_fim')); + } + + return $query; + } +} diff --git a/app/Http/Controllers/compras/CompraController.php b/app/Http/Controllers/compras/CompraController.php new file mode 100644 index 00000000..e9596219 --- /dev/null +++ b/app/Http/Controllers/compras/CompraController.php @@ -0,0 +1,143 @@ +buildIndexQuery($request); + + return view('content.compras.compras.index', [ + 'compras' => $query->paginate(20)->withQueryString(), + 'fornecedores' => Fornecedor::query()->orderBy('nome')->get(['id', 'nome']), + 'filtros' => $request->only(['status', 'fornecedor_id', 'data_inicio', 'data_fim']), + ]); + } + + public function exportCsv(Request $request) + { + $compras = $this->buildIndexQuery($request)->get(); + $fileName = 'compras_' . now()->format('Ymd_His') . '.csv'; + + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$fileName}\"", + ]; + + return response()->stream(function () use ($compras): void { + $out = fopen('php://output', 'w'); + fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); + + fputcsv($out, [ + 'ID', + 'Numero', + 'Fornecedor', + 'Data', + 'Status', + 'Valor Total', + 'Conta Pagar Status', + 'Conta Pagar Aberto', + ], ';'); + + foreach ($compras as $compra) { + fputcsv($out, [ + $compra->id, + $compra->numero, + $compra->fornecedor->nome ?? '', + optional($compra->data_compra)->format('Y-m-d H:i:s'), + $compra->status, + number_format((float) $compra->valor_total, 2, '.', ''), + $compra->contaPagar->status ?? '', + number_format((float) ($compra->contaPagar->valor_aberto ?? 0), 2, '.', ''), + ], ';'); + } + + fclose($out); + }, 200, $headers); + } + + public function create(): View + { + return view('content.compras.compras.create', [ + 'fornecedores' => Fornecedor::query()->where('ativo', true)->orderBy('nome')->get(['id', 'nome']), + 'filiais' => Filial::query()->where('ativa', true)->orderBy('nome')->get(['id', 'nome']), + 'produtos' => Produto::query()->where('ativo', true)->where('permite_compra', true)->orderBy('nome')->get(['id', 'nome', 'sku']), + ]); + } + + public function store(StoreCompraRequest $request): RedirectResponse + { + $compra = $this->service->create($request->validated(), $request->user()); + + return redirect()->route('compras.show', $compra)->with('success', 'Compra registrada com sucesso.'); + } + + public function show(Compra $compra): View + { + $compra->load(['fornecedor', 'usuario', 'filial', 'itens.produto', 'contaPagar']); + $movimentacoes = EstoqueMovimentacao::query() + ->with(['produto:id,nome,sku', 'lote:id,lote,serial']) + ->where('origem_tipo', 'COMPRA') + ->where('origem_id', $compra->id) + ->orderByDesc('id') + ->get(); + + $analitico = [ + 'itens_total' => $compra->itens->count(), + 'qtd_total' => (float) $compra->itens->sum('quantidade'), + 'ticket_medio_item' => $compra->itens->count() > 0 + ? round(((float) $compra->valor_total) / $compra->itens->count(), 2) + : 0, + 'movimentos_estoque' => $movimentacoes->count(), + 'qtd_entrada_estoque' => (float) $movimentacoes->sum('quantidade'), + ]; + + return view('content.compras.compras.show', [ + 'compra' => $compra, + 'movimentacoes' => $movimentacoes, + 'analitico' => $analitico, + ]); + } + + private function buildIndexQuery(Request $request) + { + $query = Compra::query() + ->with(['fornecedor', 'usuario', 'contaPagar']) + ->orderByDesc('id'); + + if ($request->filled('status')) { + $query->where('status', (string) $request->string('status')); + } + + if ($request->filled('fornecedor_id')) { + $query->where('fornecedor_id', (int) $request->integer('fornecedor_id')); + } + + if ($request->filled('data_inicio')) { + $query->whereDate('data_compra', '>=', $request->date('data_inicio')); + } + + if ($request->filled('data_fim')) { + $query->whereDate('data_compra', '<=', $request->date('data_fim')); + } + + return $query; + } +} diff --git a/app/Http/Controllers/compras/FornecedorController.php b/app/Http/Controllers/compras/FornecedorController.php new file mode 100644 index 00000000..cfdaddfa --- /dev/null +++ b/app/Http/Controllers/compras/FornecedorController.php @@ -0,0 +1,122 @@ +buildIndexQuery($request); + + return view('content.compras.fornecedores.index', [ + 'fornecedores' => $query->paginate(20)->withQueryString(), + 'filtros' => $request->only(['busca', 'ativo', 'tem_email', 'tem_telefone']), + ]); + } + + public function exportCsv(Request $request) + { + $fornecedores = $this->buildIndexQuery($request)->get(); + $fileName = 'fornecedores_' . now()->format('Ymd_His') . '.csv'; + + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$fileName}\"", + ]; + + return response()->stream(function () use ($fornecedores): void { + $out = fopen('php://output', 'w'); + fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); + + fputcsv($out, [ + 'ID', + 'Nome', + 'CNPJ', + 'Contato', + 'Telefone', + 'Email', + 'Status', + ], ';'); + + foreach ($fornecedores as $fornecedor) { + fputcsv($out, [ + $fornecedor->id, + $fornecedor->nome, + $fornecedor->cnpj ?? '', + $fornecedor->contato ?? '', + $fornecedor->telefone ?? '', + $fornecedor->email ?? '', + $fornecedor->ativo ? 'ATIVO' : 'INATIVO', + ], ';'); + } + + fclose($out); + }, 200, $headers); + } + + public function create(): View + { + return view('content.compras.fornecedores.create', ['fornecedor' => new Fornecedor(), 'isEdit' => false]); + } + + public function store(StoreFornecedorRequest $request): RedirectResponse + { + Fornecedor::create($request->validated()); + return redirect()->route('fornecedores.index')->with('success', 'Fornecedor cadastrado com sucesso.'); + } + + public function edit(Fornecedor $fornecedor): View + { + return view('content.compras.fornecedores.edit', compact('fornecedor') + ['isEdit' => true]); + } + + public function update(UpdateFornecedorRequest $request, Fornecedor $fornecedor): RedirectResponse + { + $fornecedor->update($request->validated()); + return redirect()->route('fornecedores.index')->with('success', 'Fornecedor atualizado com sucesso.'); + } + + public function destroy(Fornecedor $fornecedor): RedirectResponse + { + $fornecedor->delete(); + return redirect()->route('fornecedores.index')->with('success', 'Fornecedor removido.'); + } + + private function buildIndexQuery(Request $request) + { + $query = Fornecedor::query()->orderBy('nome'); + + if ($request->filled('busca')) { + $busca = trim((string) $request->string('busca')); + $query->where(function ($q) use ($busca) { + $q->where('nome', 'like', "%{$busca}%") + ->orWhere('cnpj', 'like', "%{$busca}%") + ->orWhere('email', 'like', "%{$busca}%") + ->orWhere('contato', 'like', "%{$busca}%") + ->orWhere('telefone', 'like', "%{$busca}%"); + }); + } + + if ($request->filled('ativo')) { + $query->where('ativo', ((int) $request->input('ativo')) === 1); + } + + if ($request->string('tem_email')->toString() === '1') { + $query->whereNotNull('email')->where('email', '!=', ''); + } + + if ($request->string('tem_telefone')->toString() === '1') { + $query->whereNotNull('telefone')->where('telefone', '!=', ''); + } + + return $query; + } +} diff --git a/app/Http/Controllers/estoque/AlertaEstoqueController.php b/app/Http/Controllers/estoque/AlertaEstoqueController.php new file mode 100644 index 00000000..c93d6343 --- /dev/null +++ b/app/Http/Controllers/estoque/AlertaEstoqueController.php @@ -0,0 +1,60 @@ +with(['produto.categoria']) + ->whereHas('produto', function (Builder $q) use ($request) { + $q->where('ativo', true); + + if ($request->filled('categoria_id')) { + $q->where('categoria_id', (int) $request->integer('categoria_id')); + } + + if ($request->filled('busca')) { + $busca = trim((string) $request->string('busca')); + $q->where(function (Builder $inner) use ($busca) { + $inner->where('nome', 'like', "%{$busca}%") + ->orWhere('sku', 'like', "%{$busca}%") + ->orWhere('codigo_barras', 'like', "%{$busca}%"); + }); + } + }); + + $tipoAlerta = (string) $request->string('tipo_alerta'); + if ($tipoAlerta === 'RUPTURA') { + $query->where('quantidade_atual', '<=', 0); + } elseif ($tipoAlerta === 'BAIXO') { + $query->whereColumn('quantidade_atual', '<=', 'estoque_minimo') + ->where('quantidade_atual', '>', 0); + } else { + $query->whereColumn('quantidade_atual', '<=', 'estoque_minimo'); + } + + $saldos = $query->orderBy('quantidade_atual')->paginate(25)->withQueryString(); + + return view('content.estoque.alertas.index', [ + 'saldos' => $saldos, + 'filialReferencia' => Filial::query()->where('ativa', true)->orderBy('id')->value('nome') ?? 'Matriz', + 'categorias' => CategoriaProduto::query()->where('ativo', true)->orderBy('nome')->get(['id', 'nome']), + 'filtros' => $request->only(['busca', 'categoria_id', 'tipo_alerta']), + 'cards' => [ + 'itens_monitorados' => (int) EstoqueSaldo::query()->count(), + 'baixo_estoque' => (int) EstoqueSaldo::query()->whereColumn('quantidade_atual', '<=', 'estoque_minimo')->where('quantidade_atual', '>', 0)->count(), + 'ruptura' => (int) EstoqueSaldo::query()->where('quantidade_atual', '<=', 0)->count(), + ], + ]); + } +} diff --git a/app/Http/Controllers/estoque/MovimentacaoEstoqueController.php b/app/Http/Controllers/estoque/MovimentacaoEstoqueController.php new file mode 100644 index 00000000..a028b7b8 --- /dev/null +++ b/app/Http/Controllers/estoque/MovimentacaoEstoqueController.php @@ -0,0 +1,143 @@ +with(['produto', 'lote']) + ->orderByDesc('id'); + + if ($request->filled('produto_id')) { + $query->where('produto_id', (int) $request->integer('produto_id')); + } + + if ($request->filled('tipo')) { + $query->where('tipo', (string) $request->string('tipo')); + } + + $movimentacoes = $query->paginate(20)->withQueryString(); + + return view('content.estoque.movimentacoes.index', [ + 'movimentacoes' => $movimentacoes, + 'produtos' => Produto::orderBy('nome')->get(['id', 'nome', 'sku']), + 'filtros' => $request->only(['produto_id', 'tipo']), + ]); + } + + public function create(): View + { + return view('content.estoque.movimentacoes.create', [ + 'produtos' => Produto::with('estoqueSaldo')->orderBy('nome')->get(), + 'tipos' => ['ENTRADA', 'SAIDA', 'AJUSTE'], + ]); + } + + public function store(StoreMovimentacaoEstoqueRequest $request): RedirectResponse + { + $data = $request->validated(); + + DB::transaction(function () use ($data, $request) { + $produto = Produto::lockForUpdate()->findOrFail((int) $data['produto_id']); + $saldo = EstoqueSaldo::lockForUpdate()->firstOrCreate( + ['produto_id' => $produto->id], + ['quantidade_atual' => 0, 'estoque_minimo' => 0, 'updated_at' => now()] + ); + + $tipoReal = $data['tipo'] === 'AJUSTE' ? $data['ajuste_direcao'] : $data['tipo']; + $quantidade = (float) $data['quantidade']; + $sinal = $tipoReal === 'SAIDA' ? -1 : 1; + + if ($produto->controla_lote && empty($data['lote'])) { + throw ValidationException::withMessages(['lote' => 'Este produto exige lote para movimentacao.']); + } + + $lote = null; + if (!empty($data['lote'])) { + $lote = EstoqueLote::lockForUpdate()->firstOrCreate( + [ + 'produto_id' => $produto->id, + 'lote' => $data['lote'], + 'serial' => $data['serial'] ?? null, + ], + [ + 'validade' => $data['validade'] ?? null, + 'quantidade_disponivel' => 0, + 'custo_unitario' => $data['custo_unitario'] ?? null, + ] + ); + } + + if ($sinal < 0) { + if ((float) $saldo->quantidade_atual < $quantidade) { + throw ValidationException::withMessages(['quantidade' => 'Saldo insuficiente para esta saida/ajuste.']); + } + + if ($lote && (float) $lote->quantidade_disponivel < $quantidade) { + throw ValidationException::withMessages(['quantidade' => 'Saldo insuficiente no lote informado.']); + } + } + + $novoSaldo = (float) $saldo->quantidade_atual + ($quantidade * $sinal); + $saldo->update([ + 'quantidade_atual' => $novoSaldo, + 'updated_at' => now(), + ]); + + if ($lote) { + $lote->update([ + 'quantidade_disponivel' => (float) $lote->quantidade_disponivel + ($quantidade * $sinal), + 'validade' => $data['validade'] ?? $lote->validade, + 'custo_unitario' => $data['custo_unitario'] ?? $lote->custo_unitario, + ]); + } + + EstoqueMovimentacao::create([ + 'produto_id' => $produto->id, + 'estoque_lote_id' => $lote?->id, + 'tipo' => $data['tipo'], + 'origem' => $data['origem'], + 'documento_ref' => $data['documento_ref'] ?: null, + 'quantidade' => $quantidade, + 'sinal' => $sinal, + 'saldo_apos' => $novoSaldo, + 'observacao' => $data['observacao'] ?? null, + 'user_id' => $request->user()?->id, + 'created_at' => now(), + ]); + }); + + return redirect()->route('movimentacoes-estoque.index')->with('success', 'Movimentacao registrada com sucesso.'); + } + + public function lotesPorProduto(Produto $produto): JsonResponse + { + $lotes = EstoqueLote::query() + ->where('produto_id', $produto->id) + ->where('quantidade_disponivel', '>', 0) + ->orderBy('validade') + ->orderBy('lote') + ->get(['id', 'lote', 'serial', 'validade', 'quantidade_disponivel']); + + return response()->json([ + 'controla_lote' => (bool) $produto->controla_lote, + 'controla_validade' => (bool) $produto->controla_validade, + 'lotes' => $lotes, + ]); + } +} diff --git a/app/Http/Controllers/financeiro/ContaPagarController.php b/app/Http/Controllers/financeiro/ContaPagarController.php new file mode 100644 index 00000000..fdba5c3d --- /dev/null +++ b/app/Http/Controllers/financeiro/ContaPagarController.php @@ -0,0 +1,291 @@ +buildIndexQuery($request); + + $contas = $query->paginate(20)->withQueryString(); + + $cards = [ + 'aberto_total' => (float) ContaPagar::whereIn('status', ['ABERTO', 'PARCIAL'])->sum('valor_aberto'), + 'atrasado_total' => (float) ContaPagar::whereIn('status', ['ABERTO', 'PARCIAL'])->whereDate('vencimento', '<', now()->toDateString())->sum('valor_aberto'), + 'pago_mes' => (float) ContaPagarMovimento::where('tipo', 'PAGAMENTO')->whereMonth('data_movimento', now()->month)->whereYear('data_movimento', now()->year)->sum('valor'), + ]; + + return view('content.financeiro.contas-pagar.index', [ + 'contas' => $contas, + 'fornecedores' => Fornecedor::query()->orderBy('nome')->get(['id', 'nome']), + 'cards' => $cards, + 'filtros' => $request->only(['status', 'fornecedor_id', 'vencimento_inicio', 'vencimento_fim', 'somente_atrasadas']), + ]); + } + + public function show(ContaPagar $conta): View + { + $conta->load([ + 'fornecedor:id,nome,cnpj,email,telefone', + 'compra:id,numero,data_compra,status,valor_total', + 'movimentos.usuario:id,name', + ]); + + return view('content.financeiro.contas-pagar.show', [ + 'conta' => $conta, + ]); + } + + public function exportExtratoCsv(ContaPagar $conta) + { + $request = request(); + $conta->load(['fornecedor:id,nome', 'movimentos.usuario:id,name']); + $fileName = 'conta_pagar_extrato_' . $conta->id . '_' . now()->format('Ymd_His') . '.csv'; + + AuditoriaLog::create([ + 'usuario_id' => $request->user()?->id, + 'acao' => 'CONTA_PAGAR_EXTRATO_EXPORT_CSV', + 'entidade_tipo' => 'CONTA_PAGAR', + 'entidade_id' => $conta->id, + 'dados_antes' => null, + 'dados_depois' => ['movimentos' => $conta->movimentos->count()], + 'ip' => $request->ip(), + 'user_agent' => mb_substr((string) $request->userAgent(), 0, 255), + ]); + + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$fileName}\"", + ]; + + return response()->stream(function () use ($conta): void { + $out = fopen('php://output', 'w'); + fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); + + fputcsv($out, ['Conta', 'Fornecedor', 'Status', 'Valor Original', 'Valor Aberto'], ';'); + fputcsv($out, [ + $conta->id, + $conta->fornecedor->nome ?? '', + $conta->status, + number_format((float) $conta->valor_original, 2, '.', ''), + number_format((float) $conta->valor_aberto, 2, '.', ''), + ], ';'); + fputcsv($out, [], ';'); + + fputcsv($out, ['Data', 'Tipo', 'Valor', 'Forma', 'Usuario', 'Observacao'], ';'); + foreach ($conta->movimentos->sortByDesc('data_movimento') as $mov) { + fputcsv($out, [ + optional($mov->data_movimento)->format('Y-m-d H:i:s'), + $mov->tipo, + number_format((float) $mov->valor, 2, '.', ''), + $mov->forma_pagamento ?? '', + $mov->usuario->name ?? 'Sistema', + $mov->observacao ?? '', + ], ';'); + } + + fclose($out); + }, 200, $headers); + } + + public function exportCsv(Request $request) + { + $contas = $this->buildIndexQuery($request)->get(); + $fileName = 'contas_pagar_' . now()->format('Ymd_His') . '.csv'; + + AuditoriaLog::create([ + 'usuario_id' => $request->user()?->id, + 'acao' => 'CONTAS_PAGAR_EXPORT_CSV', + 'entidade_tipo' => 'CONTA_PAGAR', + 'entidade_id' => null, + 'dados_antes' => null, + 'dados_depois' => ['quantidade' => $contas->count(), 'filtros' => $request->query()], + 'ip' => $request->ip(), + 'user_agent' => mb_substr((string) $request->userAgent(), 0, 255), + ]); + + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$fileName}\"", + ]; + + return response()->stream(function () use ($contas): void { + $out = fopen('php://output', 'w'); + fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); + + fputcsv($out, [ + 'ID', + 'Compra', + 'Fornecedor', + 'Vencimento', + 'Valor Original', + 'Valor Aberto', + 'Status', + ], ';'); + + foreach ($contas as $conta) { + fputcsv($out, [ + $conta->id, + $conta->compra->numero ?? '', + $conta->fornecedor->nome ?? '', + optional($conta->vencimento)->format('Y-m-d'), + number_format((float) $conta->valor_original, 2, '.', ''), + number_format((float) $conta->valor_aberto, 2, '.', ''), + $conta->status, + ], ';'); + } + + fclose($out); + }, 200, $headers); + } + + public function pagar(Request $request, ContaPagar $conta): RedirectResponse + { + $data = $request->validate([ + 'valor' => ['required', 'numeric', 'min:0.01'], + 'forma_pagamento' => ['nullable', 'string', 'max:50'], + 'observacao' => ['nullable', 'string', 'max:500'], + 'data_movimento' => ['nullable', 'date'], + ]); + + DB::transaction(function () use ($request, $conta, $data): void { + $valor = round((float) $data['valor'], 2); + $abertoAtual = round((float) $conta->valor_aberto, 2); + + if ($conta->status === 'CANCELADO') { + abort(422, 'Conta cancelada nao pode receber pagamento.'); + } + + if ($abertoAtual <= 0) { + abort(422, 'Conta ja quitada.'); + } + + if ($valor > $abertoAtual) { + abort(422, 'Valor informado excede o valor em aberto.'); + } + + $novoAberto = round($abertoAtual - $valor, 2); + $conta->update([ + 'valor_aberto' => $novoAberto, + 'status' => $novoAberto <= 0 ? 'QUITADO' : 'PARCIAL', + ]); + + ContaPagarMovimento::create([ + 'conta_pagar_id' => $conta->id, + 'usuario_id' => $request->user()?->id, + 'tipo' => 'PAGAMENTO', + 'valor' => $valor, + 'data_movimento' => $data['data_movimento'] ?? now(), + 'forma_pagamento' => $data['forma_pagamento'] ?? null, + 'observacao' => $data['observacao'] ?? null, + ]); + + AuditoriaLog::create([ + 'usuario_id' => $request->user()?->id, + 'acao' => 'CONTA_PAGAR_PAGAMENTO', + 'entidade_tipo' => 'CONTA_PAGAR', + 'entidade_id' => $conta->id, + 'dados_antes' => ['valor_aberto' => $abertoAtual, 'status' => $conta->getOriginal('status')], + 'dados_depois' => ['valor_aberto' => $novoAberto, 'status' => $conta->status, 'valor_pagamento' => $valor], + 'ip' => $request->ip(), + 'user_agent' => mb_substr((string) $request->userAgent(), 0, 255), + ]); + }); + + return back()->with('success', 'Pagamento registrado com sucesso.'); + } + + public function estornar(Request $request, ContaPagar $conta): RedirectResponse + { + $data = $request->validate([ + 'valor' => ['required', 'numeric', 'min:0.01'], + 'observacao' => ['nullable', 'string', 'max:500'], + 'data_movimento' => ['nullable', 'date'], + ]); + + DB::transaction(function () use ($request, $conta, $data): void { + $valor = round((float) $data['valor'], 2); + $abertoAtual = round((float) $conta->valor_aberto, 2); + $original = round((float) $conta->valor_original, 2); + + if ($conta->status === 'CANCELADO') { + abort(422, 'Conta cancelada nao pode ser estornada.'); + } + + if (($abertoAtual + $valor) > $original) { + abort(422, 'Estorno excede o valor original da conta.'); + } + + $novoAberto = round($abertoAtual + $valor, 2); + $conta->update([ + 'valor_aberto' => $novoAberto, + 'status' => $novoAberto <= 0 ? 'QUITADO' : 'ABERTO', + ]); + + ContaPagarMovimento::create([ + 'conta_pagar_id' => $conta->id, + 'usuario_id' => $request->user()?->id, + 'tipo' => 'ESTORNO', + 'valor' => $valor, + 'data_movimento' => $data['data_movimento'] ?? now(), + 'forma_pagamento' => null, + 'observacao' => $data['observacao'] ?? null, + ]); + + AuditoriaLog::create([ + 'usuario_id' => $request->user()?->id, + 'acao' => 'CONTA_PAGAR_ESTORNO', + 'entidade_tipo' => 'CONTA_PAGAR', + 'entidade_id' => $conta->id, + 'dados_antes' => ['valor_aberto' => $abertoAtual, 'status' => $conta->getOriginal('status')], + 'dados_depois' => ['valor_aberto' => $novoAberto, 'status' => $conta->status, 'valor_estorno' => $valor], + 'ip' => $request->ip(), + 'user_agent' => mb_substr((string) $request->userAgent(), 0, 255), + ]); + }); + + return back()->with('success', 'Estorno registrado com sucesso.'); + } + + private function buildIndexQuery(Request $request) + { + $query = ContaPagar::query() + ->with(['fornecedor:id,nome', 'compra:id,numero']) + ->orderBy('vencimento') + ->orderByDesc('id'); + + if ($request->filled('status')) { + $query->where('status', (string) $request->string('status')); + } + + if ($request->filled('fornecedor_id')) { + $query->where('fornecedor_id', (int) $request->integer('fornecedor_id')); + } + + if ($request->filled('vencimento_inicio')) { + $query->whereDate('vencimento', '>=', $request->date('vencimento_inicio')); + } + + if ($request->filled('vencimento_fim')) { + $query->whereDate('vencimento', '<=', $request->date('vencimento_fim')); + } + + if ($request->boolean('somente_atrasadas')) { + $query->whereIn('status', ['ABERTO', 'PARCIAL']) + ->whereDate('vencimento', '<', now()->toDateString()); + } + + return $query; + } +} diff --git a/app/Http/Controllers/financeiro/ContaReceberController.php b/app/Http/Controllers/financeiro/ContaReceberController.php new file mode 100644 index 00000000..d4a2dd04 --- /dev/null +++ b/app/Http/Controllers/financeiro/ContaReceberController.php @@ -0,0 +1,279 @@ +buildIndexQuery($request); + + return view('content.financeiro.contas-receber.index', [ + 'contas' => $query->paginate(20)->withQueryString(), + 'clientes' => Cliente::query()->orderBy('nome')->get(['id', 'nome']), + 'filtros' => $request->only(['status', 'cliente_id', 'vencimento_inicio', 'vencimento_fim', 'somente_atrasadas']), + 'cards' => [ + 'aberto_total' => (float) ContaReceber::query()->whereIn('status', ['ABERTO', 'PARCIAL'])->sum('valor_aberto'), + 'atrasado_total' => (float) ContaReceber::query()->whereIn('status', ['ABERTO', 'PARCIAL'])->whereDate('vencimento', '<', now()->toDateString())->sum('valor_aberto'), + 'recebido_mes' => (float) ContaReceberMovimento::query()->where('tipo', 'RECEBIMENTO')->whereMonth('data_movimento', now()->month)->sum('valor'), + ], + ]); + } + + public function show(ContaReceber $conta): View + { + $conta->load(['cliente', 'documento', 'movimentos.usuario']); + + return view('content.financeiro.contas-receber.show', [ + 'conta' => $conta, + ]); + } + + public function exportExtratoCsv(ContaReceber $conta) + { + $request = request(); + $conta->load(['cliente', 'documento', 'movimentos.usuario']); + $fileName = 'conta_receber_extrato_' . $conta->id . '_' . now()->format('Ymd_His') . '.csv'; + + AuditoriaLog::create([ + 'usuario_id' => $request->user()?->id, + 'acao' => 'CONTA_RECEBER_EXTRATO_EXPORT_CSV', + 'entidade_tipo' => 'CONTA_RECEBER', + 'entidade_id' => $conta->id, + 'dados_antes' => null, + 'dados_depois' => ['movimentos' => $conta->movimentos->count()], + 'ip' => $request->ip(), + 'user_agent' => mb_substr((string) $request->userAgent(), 0, 255), + ]); + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$fileName}\"", + ]; + + return response()->stream(function () use ($conta): void { + $out = fopen('php://output', 'w'); + fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); + + fputcsv($out, ['Conta', 'Documento', 'Cliente', 'Status', 'Valor Original', 'Valor Aberto'], ';'); + fputcsv($out, [ + $conta->id, + $conta->documento->numero ?? '', + $conta->cliente->nome ?? '', + $conta->status, + number_format((float) $conta->valor_original, 2, '.', ''), + number_format((float) $conta->valor_aberto, 2, '.', ''), + ], ';'); + fputcsv($out, [], ';'); + + fputcsv($out, ['Data', 'Tipo', 'Valor', 'Forma', 'Usuario', 'Observacao'], ';'); + foreach ($conta->movimentos->sortByDesc('data_movimento') as $mov) { + fputcsv($out, [ + optional($mov->data_movimento)->format('Y-m-d H:i:s'), + $mov->tipo, + number_format((float) $mov->valor, 2, '.', ''), + $mov->forma_pagamento ?? '', + $mov->usuario->name ?? 'Sistema', + $mov->observacao ?? '', + ], ';'); + } + + fclose($out); + }, 200, $headers); + } + + public function exportCsv(Request $request) + { + $contas = $this->buildIndexQuery($request)->get(); + $fileName = 'contas_receber_' . now()->format('Ymd_His') . '.csv'; + + AuditoriaLog::create([ + 'usuario_id' => $request->user()?->id, + 'acao' => 'CONTAS_RECEBER_EXPORT_CSV', + 'entidade_tipo' => 'CONTA_RECEBER', + 'entidade_id' => null, + 'dados_antes' => null, + 'dados_depois' => ['quantidade' => $contas->count(), 'filtros' => $request->query()], + 'ip' => $request->ip(), + 'user_agent' => mb_substr((string) $request->userAgent(), 0, 255), + ]); + + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$fileName}\"", + ]; + + return response()->stream(function () use ($contas): void { + $out = fopen('php://output', 'w'); + fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF)); + + fputcsv($out, [ + 'ID', + 'Documento', + 'Cliente', + 'Vencimento', + 'Valor Original', + 'Valor Aberto', + 'Status', + ], ';'); + + foreach ($contas as $conta) { + fputcsv($out, [ + $conta->id, + $conta->documento->numero ?? '', + $conta->cliente->nome ?? '', + optional($conta->vencimento)->format('Y-m-d'), + number_format((float) $conta->valor_original, 2, '.', ''), + number_format((float) $conta->valor_aberto, 2, '.', ''), + $conta->status, + ], ';'); + } + + fclose($out); + }, 200, $headers); + } + + public function baixar(BaixaContaReceberRequest $request, ContaReceber $conta): RedirectResponse + { + $dados = $request->validated(); + + DB::transaction(function () use ($conta, $dados, $request) { + $valorBaixa = (float) $dados['valor']; + $valorAbertoAtual = (float) $conta->valor_aberto; + + if ($conta->status === 'QUITADO') { + throw ValidationException::withMessages(['valor' => 'Conta ja esta quitada.']); + } + if ($valorBaixa > $valorAbertoAtual) { + throw ValidationException::withMessages(['valor' => 'Valor da baixa nao pode ser maior que o valor em aberto.']); + } + + $novoAberto = round(max(0, $valorAbertoAtual - $valorBaixa), 2); + $novoStatus = $novoAberto <= 0 ? 'QUITADO' : 'PARCIAL'; + + $conta->update([ + 'valor_aberto' => $novoAberto, + 'status' => $novoStatus, + ]); + + ContaReceberMovimento::create([ + 'conta_receber_id' => $conta->id, + 'usuario_id' => $request->user()->id, + 'tipo' => 'RECEBIMENTO', + 'valor' => $valorBaixa, + 'data_movimento' => $dados['data_movimento'], + 'forma_pagamento' => $dados['forma_pagamento'] ?? null, + 'observacao' => $dados['observacao'] ?? null, + ]); + + AuditoriaLog::create([ + 'usuario_id' => $request->user()->id, + 'acao' => 'CONTA_RECEBER_BAIXA', + 'entidade_tipo' => 'CONTA_RECEBER', + 'entidade_id' => $conta->id, + 'dados_antes' => ['valor_aberto' => $valorAbertoAtual, 'status' => $conta->getOriginal('status')], + 'dados_depois' => ['valor_aberto' => $novoAberto, 'status' => $novoStatus, 'valor_baixa' => $valorBaixa], + 'ip' => $request->ip(), + 'user_agent' => mb_substr((string) $request->userAgent(), 0, 255), + ]); + }); + + return back()->with('success', 'Baixa registrada com sucesso.'); + } + + public function estornar(EstornoContaReceberRequest $request, ContaReceber $conta): RedirectResponse + { + $this->assertAcessoGerencial($request->user()); + $dados = $request->validated(); + + DB::transaction(function () use ($conta, $dados, $request) { + $valorEstorno = (float) $dados['valor']; + $valorAbertoAtual = (float) $conta->valor_aberto; + $valorOriginal = (float) $conta->valor_original; + $valorPago = max(0, $valorOriginal - $valorAbertoAtual); + + if ($valorPago <= 0) { + throw ValidationException::withMessages(['valor' => 'Nao existe valor pago para estornar nesta conta.']); + } + if ($valorEstorno > $valorPago) { + throw ValidationException::withMessages(['valor' => 'Valor do estorno nao pode ser maior que o total pago.']); + } + + $novoAberto = round(min($valorOriginal, $valorAbertoAtual + $valorEstorno), 2); + $novoStatus = $novoAberto >= $valorOriginal ? 'ABERTO' : 'PARCIAL'; + + $conta->update([ + 'valor_aberto' => $novoAberto, + 'status' => $novoStatus, + ]); + + ContaReceberMovimento::create([ + 'conta_receber_id' => $conta->id, + 'usuario_id' => $request->user()->id, + 'tipo' => 'ESTORNO', + 'valor' => $valorEstorno, + 'data_movimento' => $dados['data_movimento'], + 'forma_pagamento' => null, + 'observacao' => $dados['observacao'], + ]); + + AuditoriaLog::create([ + 'usuario_id' => $request->user()->id, + 'acao' => 'CONTA_RECEBER_ESTORNO', + 'entidade_tipo' => 'CONTA_RECEBER', + 'entidade_id' => $conta->id, + 'dados_antes' => ['valor_aberto' => $valorAbertoAtual, 'status' => $conta->getOriginal('status')], + 'dados_depois' => ['valor_aberto' => $novoAberto, 'status' => $novoStatus, 'valor_estorno' => $valorEstorno], + 'ip' => $request->ip(), + 'user_agent' => mb_substr((string) $request->userAgent(), 0, 255), + ]); + }); + + return back()->with('success', 'Estorno registrado com sucesso.'); + } + + private function assertAcessoGerencial(?User $user): void + { + if (!$user || !$user->possuiAcessoGerencial()) { + abort(403, 'Apenas GERENTE/ADMIN podem estornar contas.'); + } + } + + private function buildIndexQuery(Request $request) + { + $query = ContaReceber::query() + ->with(['cliente', 'documento', 'movimentos.usuario']) + ->orderByDesc('vencimento'); + + if ($request->filled('status')) { + $query->where('status', (string) $request->string('status')); + } + if ($request->filled('cliente_id')) { + $query->where('cliente_id', (int) $request->integer('cliente_id')); + } + if ($request->filled('vencimento_inicio')) { + $query->whereDate('vencimento', '>=', (string) $request->string('vencimento_inicio')); + } + if ($request->filled('vencimento_fim')) { + $query->whereDate('vencimento', '<=', (string) $request->string('vencimento_fim')); + } + if ($request->boolean('somente_atrasadas')) { + $query->whereIn('status', ['ABERTO', 'PARCIAL'])->whereDate('vencimento', '<', now()->toDateString()); + } + + return $query; + } +} diff --git a/app/Http/Controllers/produtos/ProdutoController.php b/app/Http/Controllers/produtos/ProdutoController.php new file mode 100644 index 00000000..1da93c8c --- /dev/null +++ b/app/Http/Controllers/produtos/ProdutoController.php @@ -0,0 +1,704 @@ +buildIndexQuery($request); + + $produtos = $query->orderByDesc('id')->paginate(15)->withQueryString(); + $consumoMap = $this->consumoDiarioMap($produtos->getCollection()->pluck('id')->all()); + $produtos->getCollection()->transform(fn (Produto $produto) => $this->enriquecerIndicadores($produto, $consumoMap)); + + $cards = [ + 'total' => Produto::count(), + 'ativos' => Produto::where('ativo', true)->count(), + 'baixo_estoque' => EstoqueSaldo::whereColumn('quantidade_atual', '<=', 'estoque_minimo')->count(), + 'com_preco' => ProdutoPreco::where('ativo', true)->distinct('produto_id')->count('produto_id'), + 'margem_media_ref' => (float) ProdutoPreco::query() + ->where('ativo', true) + ->where('preco', '>', 0) + ->where(function (Builder $q) { + $q->whereNull('vigencia_fim')->orWhere('vigencia_fim', '>=', now()); + }) + ->avg(DB::raw('((preco - COALESCE(custo_referencia, 0)) / preco) * 100')) ?: 0, + 'cobertura_media_dias' => $this->coberturaMediaDiasGlobal(), + ]; + + return view('content.produtos.index', [ + 'produtos' => $produtos, + 'categorias' => CategoriaProduto::where('ativo', true)->orderBy('nome')->get(), + 'filtros' => $request->only(['busca', 'categoria_id', 'ativo', 'baixo_estoque']), + 'cards' => $cards, + ]); + } + + public function exportCsv(Request $request): StreamedResponse + { + $produtos = $this->buildIndexQuery($request)->orderByDesc('id')->get(); + $consumoMap = $this->consumoDiarioMap($produtos->pluck('id')->all()); + $filename = 'produtos_' . now()->format('Ymd_His') . '.csv'; + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$filename}\"", + ]; + + return response()->streamDownload(function () use ($produtos, $consumoMap): void { + $handle = fopen('php://output', 'w'); + fwrite($handle, "\xEF\xBB\xBF"); + + fputcsv($handle, [ + 'ID', + 'SKU', + 'Nome', + 'Categoria', + 'Unidade', + 'Preco Atual', + 'Custo Ref', + 'Margem Ref (%)', + 'Estoque Atual', + 'Estoque Minimo', + 'Consumo Diario 30d', + 'Cobertura (dias)', + 'Status', + ], ';'); + + foreach ($produtos as $produto) { + $produto = $this->enriquecerIndicadores($produto, $consumoMap); + $saldo = $produto->estoqueSaldo; + + fputcsv($handle, [ + $produto->id, + $produto->sku, + $produto->nome, + $produto->categoria?->nome ?? '', + $produto->unidadePrincipal?->sigla ?? '', + number_format((float) ($produto->preco_venda_atual ?? 0), 2, '.', ''), + number_format((float) ($produto->custo_ref_atual ?? 0), 2, '.', ''), + number_format((float) ($produto->margem_ref_percentual ?? 0), 2, '.', ''), + number_format((float) ($saldo->quantidade_atual ?? 0), 3, '.', ''), + number_format((float) ($saldo->estoque_minimo ?? 0), 3, '.', ''), + number_format((float) ($produto->consumo_diario_30 ?? 0), 3, '.', ''), + $produto->cobertura_dias !== null ? number_format((float) $produto->cobertura_dias, 1, '.', '') : '', + $produto->ativo ? 'ATIVO' : 'INATIVO', + ], ';'); + } + + fclose($handle); + }, $filename, $headers); + } + + public function create(): View + { + return view('content.produtos.create', [ + 'produto' => new Produto([ + 'ativo' => true, + 'permite_venda' => true, + 'permite_compra' => true, + 'controla_lote' => false, + 'controla_validade' => false, + ]), + 'categorias' => CategoriaProduto::where('ativo', true)->orderBy('nome')->get(), + 'unidades' => UnidadeMedida::where('ativo', true)->orderBy('sigla')->get(), + 'tabelasPreco' => TabelaPreco::where('ativo', true)->orderBy('prioridade')->orderBy('nome')->get(), + 'estoqueMinimo' => 0, + 'preco' => [ + 'tabela_preco_id' => TabelaPreco::where('codigo', 'VAREJO')->value('id'), + 'preco_custo' => 0, + 'preco_venda' => 0, + ], + ]); + } + + public function store(StoreProdutoRequest $request): RedirectResponse + { + $payload = $this->sanitizePayload($request->validated()); + + DB::transaction(function () use ($payload) { + $produto = Produto::create($payload['produto']); + + EstoqueSaldo::create([ + 'produto_id' => $produto->id, + 'quantidade_atual' => 0, + 'estoque_minimo' => $payload['estoque_minimo'], + 'updated_at' => now(), + ]); + + ProdutoPreco::create([ + 'produto_id' => $produto->id, + 'tabela_preco_id' => $payload['preco']['tabela_preco_id'], + 'preco' => $payload['preco']['preco_venda'], + 'custo_referencia' => $payload['preco']['preco_custo'], + 'margem_percentual' => $this->calcularMargem( + $payload['preco']['preco_custo'], + $payload['preco']['preco_venda'] + ), + 'vigencia_inicio' => now(), + 'ativo' => true, + ]); + }); + + return redirect()->route('produtos.index')->with('success', 'Produto cadastrado com sucesso.'); + } + + public function show(Produto $produto): View + { + $produto->load([ + 'categoria', + 'unidadePrincipal', + 'estoqueSaldo', + 'precos.tabelaPreco', + ]); + + return view('content.produtos.show', compact('produto')); + } + + public function edit(Produto $produto): View + { + $produto->load(['estoqueSaldo']); + + $precoAtual = ProdutoPreco::where('produto_id', $produto->id) + ->where('ativo', true) + ->where(function (Builder $q) { + $q->whereNull('vigencia_fim')->orWhere('vigencia_fim', '>=', now()); + }) + ->orderByDesc('vigencia_inicio') + ->first(); + + return view('content.produtos.edit', [ + 'produto' => $produto, + 'categorias' => CategoriaProduto::where('ativo', true)->orderBy('nome')->get(), + 'unidades' => UnidadeMedida::where('ativo', true)->orderBy('sigla')->get(), + 'tabelasPreco' => TabelaPreco::where('ativo', true)->orderBy('prioridade')->orderBy('nome')->get(), + 'estoqueMinimo' => (float) ($produto->estoqueSaldo->estoque_minimo ?? 0), + 'preco' => [ + 'tabela_preco_id' => $precoAtual?->tabela_preco_id ?: TabelaPreco::where('codigo', 'VAREJO')->value('id'), + 'preco_custo' => (float) ($precoAtual?->custo_referencia ?? 0), + 'preco_venda' => (float) ($precoAtual?->preco ?? 0), + ], + ]); + } + + public function update(UpdateProdutoRequest $request, Produto $produto): RedirectResponse + { + $payload = $this->sanitizePayload($request->validated()); + + DB::transaction(function () use ($produto, $payload) { + $produto->update($payload['produto']); + + EstoqueSaldo::updateOrCreate( + ['produto_id' => $produto->id], + [ + 'estoque_minimo' => $payload['estoque_minimo'], + 'updated_at' => now(), + ] + ); + + $precoAtual = ProdutoPreco::where('produto_id', $produto->id) + ->where('tabela_preco_id', $payload['preco']['tabela_preco_id']) + ->where('ativo', true) + ->whereNull('vigencia_fim') + ->orderByDesc('id') + ->first(); + + if ($precoAtual) { + $precoAtual->update([ + 'preco' => $payload['preco']['preco_venda'], + 'custo_referencia' => $payload['preco']['preco_custo'], + 'margem_percentual' => $this->calcularMargem( + $payload['preco']['preco_custo'], + $payload['preco']['preco_venda'] + ), + ]); + } else { + ProdutoPreco::create([ + 'produto_id' => $produto->id, + 'tabela_preco_id' => $payload['preco']['tabela_preco_id'], + 'preco' => $payload['preco']['preco_venda'], + 'custo_referencia' => $payload['preco']['preco_custo'], + 'margem_percentual' => $this->calcularMargem( + $payload['preco']['preco_custo'], + $payload['preco']['preco_venda'] + ), + 'vigencia_inicio' => now(), + 'ativo' => true, + ]); + } + }); + + return redirect()->route('produtos.show', $produto)->with('success', 'Produto atualizado com sucesso.'); + } + + public function destroy(Produto $produto): RedirectResponse + { + $produto->delete(); + + return redirect()->route('produtos.index')->with('success', 'Produto removido com sucesso.'); + } + + public function import(ImportProdutosRequest $request): RedirectResponse + { + $file = $request->file('arquivo'); + $rows = $this->parseImportRows($file); + + if (count($rows) === 0) { + return redirect()->route('produtos.index')->with('error', 'Arquivo sem dados para importacao.'); + } + + $categoriaId = (int) (CategoriaProduto::where('ativo', true)->value('id') ?: CategoriaProduto::create(['nome' => 'Geral', 'ativo' => true])->id); + $unidadeId = (int) (UnidadeMedida::where('ativo', true)->where('sigla', 'UN')->value('id') ?: UnidadeMedida::create([ + 'sigla' => 'UN', + 'nome' => 'Unidade', + 'casas_decimais' => 0, + 'ativo' => true, + ])->id); + $tabelaPrecoId = (int) (TabelaPreco::where('codigo', 'VAREJO')->value('id') ?: TabelaPreco::create([ + 'nome' => 'Tabela Varejo', + 'codigo' => 'VAREJO', + 'tipo' => 'VAREJO', + 'ativo' => true, + 'prioridade' => 0, + ])->id); + + $created = 0; + $updated = 0; + $ignored = 0; + + foreach ($rows as $index => $row) { + $nome = trim((string) ($row['nome'] ?? '')); + $ean = preg_replace('/\D/', '', (string) ($row['ean'] ?? '')); + $marca = trim((string) ($row['marca'] ?? '')); + $custo = $this->toDecimal($row['custo'] ?? 0); + $venda = $this->toDecimal($row['preco_venda'] ?? 0); + + if ($nome === '' || $venda < 0 || $custo < 0) { + $ignored++; + continue; + } + + if ($venda < $custo) { + $venda = $custo; + } + + DB::transaction(function () use ( + &$created, + &$updated, + $nome, + $ean, + $marca, + $custo, + $venda, + $categoriaId, + $unidadeId, + $tabelaPrecoId + ) { + $produto = null; + + if ($ean !== '') { + $produto = Produto::where('codigo_barras', $ean)->first(); + } + + if (!$produto) { + $produto = Produto::create([ + 'sku' => $this->generateImportSku($nome), + 'nome' => $nome, + 'descricao' => null, + 'codigo_barras' => $ean !== '' ? $ean : null, + 'categoria_id' => $categoriaId, + 'unidade_principal_id' => $unidadeId, + 'controla_lote' => false, + 'controla_validade' => false, + 'ativo' => true, + 'permite_venda' => true, + 'permite_compra' => true, + 'marca' => $marca !== '' ? $marca : null, + ]); + + EstoqueSaldo::create([ + 'produto_id' => $produto->id, + 'quantidade_atual' => 0, + 'estoque_minimo' => 0, + 'updated_at' => now(), + ]); + + $created++; + } else { + $produto->update([ + 'nome' => $nome, + 'marca' => $marca !== '' ? $marca : $produto->marca, + 'categoria_id' => $produto->categoria_id ?: $categoriaId, + 'unidade_principal_id' => $produto->unidade_principal_id ?: $unidadeId, + ]); + + EstoqueSaldo::firstOrCreate( + ['produto_id' => $produto->id], + ['quantidade_atual' => 0, 'estoque_minimo' => 0, 'updated_at' => now()] + ); + + $updated++; + } + + $precoAtual = ProdutoPreco::where('produto_id', $produto->id) + ->where('tabela_preco_id', $tabelaPrecoId) + ->where('ativo', true) + ->whereNull('vigencia_fim') + ->orderByDesc('id') + ->first(); + + if ($precoAtual) { + $precoAtual->update([ + 'preco' => $venda, + 'custo_referencia' => $custo, + 'margem_percentual' => $this->calcularMargem($custo, $venda), + ]); + } else { + ProdutoPreco::create([ + 'produto_id' => $produto->id, + 'tabela_preco_id' => $tabelaPrecoId, + 'preco' => $venda, + 'custo_referencia' => $custo, + 'margem_percentual' => $this->calcularMargem($custo, $venda), + 'vigencia_inicio' => now(), + 'ativo' => true, + ]); + } + }); + } + + return redirect()->route('produtos.index')->with( + 'success', + "Importacao concluida. Criados: {$created} | Atualizados: {$updated} | Ignorados: {$ignored}" + ); + } + + public function importTemplate(): StreamedResponse + { + $filename = 'template-importacao-produtos.csv'; + $headers = [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Content-Disposition' => "attachment; filename=\"{$filename}\"", + ]; + + return response()->streamDownload(function () { + $handle = fopen('php://output', 'w'); + + // BOM para abrir acentuacao corretamente no Excel + fwrite($handle, "\xEF\xBB\xBF"); + + fputcsv($handle, ['nome', 'ean', 'marca', 'custo', 'preco_venda'], ';'); + fputcsv($handle, ['Tinta Acrilica Fosca Branca 18L', '7891234567890', 'Marca Exemplo', '120.50', '169.90'], ';'); + + fclose($handle); + }, $filename, $headers); + } + + private function sanitizePayload(array $data): array + { + $nullableFields = [ + 'descricao', + 'codigo_barras', + 'marca', + 'ncm', + 'cest', + 'observacoes', + ]; + + foreach ($nullableFields as $field) { + if (array_key_exists($field, $data) && $data[$field] === '') { + $data[$field] = null; + } + } + + return [ + 'produto' => [ + 'sku' => $data['sku'], + 'nome' => $data['nome'], + 'descricao' => $data['descricao'] ?? null, + 'codigo_barras' => $data['codigo_barras'] ?? null, + 'categoria_id' => $data['categoria_id'], + 'unidade_principal_id' => $data['unidade_principal_id'], + 'controla_lote' => (bool) ($data['controla_lote'] ?? false), + 'controla_validade' => (bool) ($data['controla_validade'] ?? false), + 'ativo' => (bool) ($data['ativo'] ?? true), + 'permite_venda' => (bool) ($data['permite_venda'] ?? true), + 'permite_compra' => (bool) ($data['permite_compra'] ?? true), + 'ncm' => $data['ncm'] ?? null, + 'cest' => $data['cest'] ?? null, + 'marca' => $data['marca'] ?? null, + 'observacoes' => $data['observacoes'] ?? null, + ], + 'estoque_minimo' => (float) $data['estoque_minimo'], + 'preco' => [ + 'tabela_preco_id' => (int) $data['tabela_preco_id'], + 'preco_custo' => (float) $data['preco_custo'], + 'preco_venda' => (float) $data['preco_venda'], + ], + ]; + } + + private function buildIndexQuery(Request $request): Builder + { + $query = Produto::query() + ->with(['categoria', 'unidadePrincipal', 'estoqueSaldo']) + ->withMax(['precos as preco_venda_atual' => function (Builder $q) { + $q->where('ativo', true)->where(function (Builder $inner) { + $inner->whereNull('vigencia_fim')->orWhere('vigencia_fim', '>=', now()); + }); + }], 'preco') + ->withMax(['precos as custo_ref_atual' => function (Builder $q) { + $q->where('ativo', true)->where(function (Builder $inner) { + $inner->whereNull('vigencia_fim')->orWhere('vigencia_fim', '>=', now()); + }); + }], 'custo_referencia'); + + if ($request->filled('busca')) { + $busca = trim((string) $request->string('busca')); + $query->where(function (Builder $q) use ($busca) { + $q->where('nome', 'like', "%{$busca}%") + ->orWhere('sku', 'like', "%{$busca}%") + ->orWhere('codigo_barras', 'like', "%{$busca}%"); + }); + } + + if ($request->filled('categoria_id')) { + $query->where('categoria_id', (int) $request->integer('categoria_id')); + } + + if ($request->filled('ativo')) { + $query->where('ativo', (bool) $request->integer('ativo')); + } + + if ($request->filled('baixo_estoque') && $request->integer('baixo_estoque') === 1) { + $query->whereHas('estoqueSaldo', function (Builder $q) { + $q->whereColumn('quantidade_atual', '<=', 'estoque_minimo'); + }); + } + + return $query; + } + + private function consumoDiarioMap(array $produtoIds): array + { + if (empty($produtoIds)) { + return []; + } + + $inicio = now()->subDays(30); + + return DocumentoItem::query() + ->selectRaw('documento_itens.produto_id, SUM(documento_itens.quantidade) as total_qtd') + ->join('documentos_comerciais', 'documentos_comerciais.id', '=', 'documento_itens.documento_id') + ->whereIn('documento_itens.produto_id', $produtoIds) + ->where('documentos_comerciais.status', 'FATURADO') + ->whereDate('documentos_comerciais.data_emissao', '>=', $inicio->toDateString()) + ->groupBy('documento_itens.produto_id') + ->pluck('total_qtd', 'documento_itens.produto_id') + ->map(fn ($qtd) => round(((float) $qtd) / 30, 3)) + ->all(); + } + + private function enriquecerIndicadores(Produto $produto, array $consumoMap): Produto + { + $preco = (float) ($produto->preco_venda_atual ?? 0); + $custo = (float) ($produto->custo_ref_atual ?? 0); + $margem = $preco > 0 ? round((($preco - $custo) / $preco) * 100, 2) : 0; + + $estoqueAtual = (float) ($produto->estoqueSaldo->quantidade_atual ?? 0); + $consumoDiario = (float) ($consumoMap[$produto->id] ?? 0); + $cobertura = $consumoDiario > 0 ? round($estoqueAtual / $consumoDiario, 1) : null; + + $produto->setAttribute('margem_ref_percentual', $margem); + $produto->setAttribute('consumo_diario_30', $consumoDiario); + $produto->setAttribute('cobertura_dias', $cobertura); + + return $produto; + } + + private function coberturaMediaDiasGlobal(): float + { + $estoqueTotal = (float) EstoqueSaldo::query()->sum('quantidade_atual'); + $vendas30 = (float) DocumentoItem::query() + ->join('documentos_comerciais', 'documentos_comerciais.id', '=', 'documento_itens.documento_id') + ->where('documentos_comerciais.status', 'FATURADO') + ->whereDate('documentos_comerciais.data_emissao', '>=', now()->subDays(30)->toDateString()) + ->sum('documento_itens.quantidade'); + + if ($vendas30 <= 0) { + return 0; + } + + $consumoDiario = $vendas30 / 30; + return $consumoDiario > 0 ? round($estoqueTotal / $consumoDiario, 1) : 0; + } + + private function calcularMargem(float $custo, float $venda): ?float + { + if ($custo <= 0) { + return null; + } + + return round((($venda - $custo) / $custo) * 100, 4); + } + + /** + * @return array + */ + private function parseImportRows(UploadedFile $file): array + { + $extension = strtolower((string) $file->getClientOriginalExtension()); + + if ($extension === 'csv' || $extension === 'txt') { + return $this->parseCsv($file->getRealPath()); + } + + return $this->parseXlsx($file->getRealPath()); + } + + private function parseCsv(string $path): array + { + $peekHandle = fopen($path, 'r'); + $firstLine = $peekHandle ? (string) fgets($peekHandle) : ''; + if (is_resource($peekHandle)) { + fclose($peekHandle); + } + $delimiter = substr_count($firstLine, ';') > substr_count($firstLine, ',') ? ';' : ','; + + $handle = fopen($path, 'r'); + if ($handle === false) { + return []; + } + + $rows = []; + $headers = []; + $line = 0; + + while (($data = fgetcsv($handle, 0, $delimiter)) !== false) { + $line++; + if ($line === 1) { + $headers = $this->normalizeHeaders($data); + continue; + } + + $rows[] = $this->mapRowToFields($headers, $data); + } + + fclose($handle); + + return $rows; + } + + private function parseXlsx(string $path): array + { + $spreadsheet = IOFactory::load($path); + $sheet = $spreadsheet->getActiveSheet(); + $rowsRaw = $sheet->toArray(null, true, true, false); + + if (count($rowsRaw) <= 1) { + return []; + } + + $headers = $this->normalizeHeaders($rowsRaw[0]); + $rows = []; + + foreach (array_slice($rowsRaw, 1) as $row) { + $rows[] = $this->mapRowToFields($headers, $row); + } + + return $rows; + } + + private function normalizeHeaders(array $headers): array + { + return array_map(function ($header) { + $value = Str::of((string) $header) + ->lower() + ->ascii() + ->replace([' ', '-', '.'], '_') + ->replace(['(', ')'], '') + ->trim() + ->value(); + + return match ($value) { + 'codigo_barras', 'cod_barras', 'ean13', 'ean_13' => 'ean', + 'preco', 'preco_venda_r', 'preco_de_venda' => 'preco_venda', + default => $value, + }; + }, $headers); + } + + private function mapRowToFields(array $headers, array $row): array + { + $mapped = array_combine($headers, $row) ?: []; + + return [ + 'nome' => (string) ($mapped['nome'] ?? ''), + 'ean' => (string) ($mapped['ean'] ?? $mapped['codigo_barras'] ?? ''), + 'marca' => (string) ($mapped['marca'] ?? ''), + 'custo' => (string) ($mapped['custo'] ?? $mapped['preco_custo'] ?? '0'), + 'preco_venda' => (string) ($mapped['preco_venda'] ?? $mapped['preco'] ?? '0'), + ]; + } + + private function generateImportSku(string $nome): string + { + $prefix = Str::upper(Str::substr(preg_replace('/[^A-Za-z0-9]/', '', Str::ascii($nome)), 0, 6)); + if ($prefix === '') { + $prefix = 'PROD'; + } + + for ($i = 1; $i <= 999999; $i++) { + $sku = sprintf('IMP-%s-%06d', $prefix, $i); + if (!Produto::where('sku', $sku)->exists()) { + return $sku; + } + } + + return 'IMP-' . Str::upper(Str::random(10)); + } + + private function toDecimal(mixed $value): float + { + $raw = preg_replace('/[^\d,.-]/', '', (string) $value); + if ($raw === '' || $raw === null) { + return 0.0; + } + + $hasComma = str_contains($raw, ','); + $hasDot = str_contains($raw, '.'); + + if ($hasComma && $hasDot) { + $normalized = str_replace('.', '', $raw); + $normalized = str_replace(',', '.', $normalized); + return (float) $normalized; + } + + if ($hasComma) { + return (float) str_replace(',', '.', $raw); + } + + return (float) $raw; + } +} diff --git a/app/Http/Middleware/EnsurePermission.php b/app/Http/Middleware/EnsurePermission.php new file mode 100644 index 00000000..65dc4c91 --- /dev/null +++ b/app/Http/Middleware/EnsurePermission.php @@ -0,0 +1,20 @@ +user(); + if (!$user || !$user->hasPermission($permission)) { + abort(403, 'Você não tem permissão para acessar este recurso.'); + } + + return $next($request); + } +} diff --git a/app/Http/Requests/Auth/LoginRequest.php b/app/Http/Requests/Auth/LoginRequest.php new file mode 100644 index 00000000..711e0a16 --- /dev/null +++ b/app/Http/Requests/Auth/LoginRequest.php @@ -0,0 +1,86 @@ +|string> + */ + public function rules(): array + { + return [ + 'email' => ['required', 'string', 'email'], + 'password' => ['required', 'string'], + ]; + } + + /** + * Attempt to authenticate the request's credentials. + * + * @throws ValidationException + */ + public function authenticate(): void + { + $this->ensureIsNotRateLimited(); + + if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) { + RateLimiter::hit($this->throttleKey()); + + throw ValidationException::withMessages([ + 'email' => trans('auth.failed'), + ]); + } + + RateLimiter::clear($this->throttleKey()); + } + + /** + * Ensure the login request is not rate limited. + * + * @throws ValidationException + */ + public function ensureIsNotRateLimited(): void + { + if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) { + return; + } + + event(new Lockout($this)); + + $seconds = RateLimiter::availableIn($this->throttleKey()); + + throw ValidationException::withMessages([ + 'email' => trans('auth.throttle', [ + 'seconds' => $seconds, + 'minutes' => ceil($seconds / 60), + ]), + ]); + } + + /** + * Get the rate limiting throttle key for the request. + */ + public function throttleKey(): string + { + return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip()); + } +} diff --git a/app/Http/Requests/BaixaContaReceberRequest.php b/app/Http/Requests/BaixaContaReceberRequest.php new file mode 100644 index 00000000..49969e1c --- /dev/null +++ b/app/Http/Requests/BaixaContaReceberRequest.php @@ -0,0 +1,23 @@ + ['required', 'numeric', 'gt:0'], + 'data_movimento' => ['required', 'date'], + 'forma_pagamento' => ['nullable', 'string', 'max:50'], + 'observacao' => ['nullable', 'string', 'max:500'], + ]; + } +} diff --git a/app/Http/Requests/Concerns/ValidatesCpfCnpj.php b/app/Http/Requests/Concerns/ValidatesCpfCnpj.php new file mode 100644 index 00000000..413d93c9 --- /dev/null +++ b/app/Http/Requests/Concerns/ValidatesCpfCnpj.php @@ -0,0 +1,66 @@ +onlyDigits($cpf); + + if (strlen($cpf) !== 11 || preg_match('/(\d)\1{10}/', $cpf)) { + return false; + } + + for ($t = 9; $t < 11; $t++) { + $d = 0; + for ($c = 0; $c < $t; $c++) { + $d += ((int) $cpf[$c]) * (($t + 1) - $c); + } + $d = ((10 * $d) % 11) % 10; + + if ((int) $cpf[$c] !== $d) { + return false; + } + } + + return true; + } + + protected function isValidCnpj(string $cnpj): bool + { + $cnpj = $this->onlyDigits($cnpj); + + if (strlen($cnpj) !== 14 || preg_match('/(\d)\1{13}/', $cnpj)) { + return false; + } + + $weights1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; + $weights2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; + + $sum = 0; + for ($i = 0; $i < 12; $i++) { + $sum += ((int) $cnpj[$i]) * $weights1[$i]; + } + $rest = $sum % 11; + $digit1 = $rest < 2 ? 0 : 11 - $rest; + + if ((int) $cnpj[12] !== $digit1) { + return false; + } + + $sum = 0; + for ($i = 0; $i < 13; $i++) { + $sum += ((int) $cnpj[$i]) * $weights2[$i]; + } + $rest = $sum % 11; + $digit2 = $rest < 2 ? 0 : 11 - $rest; + + return (int) $cnpj[13] === $digit2; + } +} diff --git a/app/Http/Requests/EstornoContaReceberRequest.php b/app/Http/Requests/EstornoContaReceberRequest.php new file mode 100644 index 00000000..c9529b68 --- /dev/null +++ b/app/Http/Requests/EstornoContaReceberRequest.php @@ -0,0 +1,22 @@ + ['required', 'numeric', 'gt:0'], + 'data_movimento' => ['required', 'date'], + 'observacao' => ['required', 'string', 'min:5', 'max:500'], + ]; + } +} diff --git a/app/Http/Requests/ImportProdutosRequest.php b/app/Http/Requests/ImportProdutosRequest.php new file mode 100644 index 00000000..8ea07dea --- /dev/null +++ b/app/Http/Requests/ImportProdutosRequest.php @@ -0,0 +1,20 @@ + ['required', 'file', 'mimes:csv,txt,xlsx', 'max:10240'], + ]; + } +} diff --git a/app/Http/Requests/ImportVendasLegadoPdfRequest.php b/app/Http/Requests/ImportVendasLegadoPdfRequest.php new file mode 100644 index 00000000..c9fb45ae --- /dev/null +++ b/app/Http/Requests/ImportVendasLegadoPdfRequest.php @@ -0,0 +1,92 @@ + ['nullable', 'array'], + 'arquivos.*' => ['nullable', 'file', 'max:10240'], + 'pasta_arquivos' => ['nullable', 'array'], + 'pasta_arquivos.*' => ['nullable', 'file', 'max:10240'], + 'caminho_pasta' => ['nullable', 'string', 'max:1000'], + ]; + } + + public function withValidator(Validator $validator): void + { + $validator->after(function (Validator $validator): void { + $todosArquivos = $this->flattenFiles([ + $this->file('arquivos', []), + $this->file('pasta_arquivos', []), + ]); + + $pdfs = array_filter($todosArquivos, function ($arquivo): bool { + if (!$arquivo) { + return false; + } + + $mime = (string) $arquivo->getMimeType(); + $ext = strtolower((string) $arquivo->getClientOriginalExtension()); + + return $mime === 'application/pdf' || $ext === 'pdf'; + }); + + $caminhoPasta = trim((string) $this->input('caminho_pasta')); + $temCaminhoPasta = $caminhoPasta !== ''; + + if ($temCaminhoPasta && !is_dir($caminhoPasta)) { + $validator->errors()->add('caminho_pasta', 'Pasta local nao encontrada.'); + } + + if ($temCaminhoPasta && is_dir($caminhoPasta) && !$this->pastaContemPdf($caminhoPasta)) { + $validator->errors()->add('caminho_pasta', 'A pasta informada nao possui arquivos PDF.'); + } + + if (count($pdfs) === 0 && !$temCaminhoPasta) { + $validator->errors()->add('arquivos', 'Selecione ao menos um arquivo PDF valido para importacao.'); + } + }); + } + + public function messages(): array + { + return [ + 'arquivos.*.max' => 'Cada arquivo deve ter no maximo 10MB.', + 'pasta_arquivos.*.max' => 'Cada arquivo deve ter no maximo 10MB.', + ]; + } + + private function flattenFiles(array $files): array + { + $flat = Arr::flatten($files); + + return array_values(array_filter($flat, fn ($file) => is_object($file))); + } + + private function pastaContemPdf(string $path): bool + { + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS) + ); + + foreach ($iterator as $fileInfo) { + if ($fileInfo->isFile() && strtolower((string) $fileInfo->getExtension()) === 'pdf') { + return true; + } + } + + return false; + } +} diff --git a/app/Http/Requests/ProfileUpdateRequest.php b/app/Http/Requests/ProfileUpdateRequest.php new file mode 100644 index 00000000..e2202dd0 --- /dev/null +++ b/app/Http/Requests/ProfileUpdateRequest.php @@ -0,0 +1,31 @@ +|string> + */ + public function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:255'], + 'email' => [ + 'required', + 'string', + 'lowercase', + 'email', + 'max:255', + Rule::unique(User::class)->ignore($this->user()->id), + ], + ]; + } +} diff --git a/app/Http/Requests/StoreCategoriaProdutoRequest.php b/app/Http/Requests/StoreCategoriaProdutoRequest.php new file mode 100644 index 00000000..8df82546 --- /dev/null +++ b/app/Http/Requests/StoreCategoriaProdutoRequest.php @@ -0,0 +1,29 @@ +merge([ + 'nome' => trim((string) $this->input('nome')), + 'ativo' => $this->boolean('ativo', true), + ]); + } + + public function rules(): array + { + return [ + 'nome' => ['required', 'string', 'max:120', 'unique:categorias_produto,nome'], + 'ativo' => ['sometimes', 'boolean'], + ]; + } +} diff --git a/app/Http/Requests/StoreClienteRequest.php b/app/Http/Requests/StoreClienteRequest.php new file mode 100644 index 00000000..5e37c9cd --- /dev/null +++ b/app/Http/Requests/StoreClienteRequest.php @@ -0,0 +1,78 @@ +merge([ + 'tipo_pessoa' => strtoupper((string) $this->input('tipo_pessoa')), + 'cpf_cnpj' => $this->onlyDigits($this->input('cpf_cnpj')), + 'telefone' => $this->onlyDigits($this->input('telefone')), + 'celular' => $this->onlyDigits($this->input('celular')), + 'cep' => $this->onlyDigits($this->input('cep')), + 'uf' => strtoupper((string) $this->input('uf')), + 'sexo' => $this->input('sexo') ? strtoupper((string) $this->input('sexo')) : null, + 'ativo' => $this->boolean('ativo', true), + ]); + } + + public function rules(): array + { + return [ + 'codigo' => ['nullable', 'string', 'max:20', 'unique:clientes,codigo'], + 'tipo_pessoa' => ['required', Rule::in(['PF', 'PJ'])], + 'nome' => ['required', 'string', 'max:255'], + 'nome_fantasia' => ['nullable', 'string', 'max:255'], + 'cpf_cnpj' => ['required', 'string', 'min:11', 'max:14', 'unique:clientes,cpf_cnpj'], + 'rg_ie' => ['nullable', 'string', 'max:30'], + 'email' => ['nullable', 'email', 'max:255', 'unique:clientes,email'], + 'telefone' => ['nullable', 'string', 'max:20'], + 'celular' => ['nullable', 'string', 'max:20'], + 'contato_nome' => ['nullable', 'string', 'max:120'], + 'cep' => ['nullable', 'string', 'max:8'], + 'logradouro' => ['nullable', 'string', 'max:255'], + 'numero' => ['nullable', 'string', 'max:20'], + 'complemento' => ['nullable', 'string', 'max:120'], + 'bairro' => ['nullable', 'string', 'max:120'], + 'cidade' => ['nullable', 'string', 'max:120'], + 'uf' => ['nullable', 'string', 'size:2'], + 'codigo_ibge' => ['nullable', 'string', 'max:10'], + 'pais' => ['required', 'string', 'max:80'], + 'data_nascimento_fundacao' => ['nullable', 'date'], + 'sexo' => ['nullable', Rule::in(['M', 'F', 'N'])], + 'observacoes' => ['nullable', 'string'], + 'ativo' => ['sometimes', 'boolean'], + 'saldo_credito' => ['nullable', 'numeric', 'min:0'], + 'limite_prazo' => ['nullable', 'numeric', 'min:0'], + ]; + } + + public function withValidator($validator): void + { + $validator->after(function ($validator) { + $doc = (string) $this->input('cpf_cnpj'); + $tipo = $this->input('tipo_pessoa'); + + if ($tipo === 'PF' && !$this->isValidCpf($doc)) { + $validator->errors()->add('cpf_cnpj', 'CPF invalido.'); + } + + if ($tipo === 'PJ' && !$this->isValidCnpj($doc)) { + $validator->errors()->add('cpf_cnpj', 'CNPJ invalido.'); + } + }); + } +} diff --git a/app/Http/Requests/StoreCompraRequest.php b/app/Http/Requests/StoreCompraRequest.php new file mode 100644 index 00000000..f19c825d --- /dev/null +++ b/app/Http/Requests/StoreCompraRequest.php @@ -0,0 +1,39 @@ +merge([ + 'itens' => array_values((array) $this->input('itens', [])), + ]); + } + + public function rules(): array + { + return [ + 'fornecedor_id' => ['required', 'exists:fornecedores,id'], + 'filial_id' => ['nullable', 'exists:filiais,id'], + 'data_compra' => ['nullable', 'date'], + 'status' => ['nullable', Rule::in(['RASCUNHO', 'CONFIRMADA'])], + 'vencimento' => ['nullable', 'date'], + 'observacoes' => ['nullable', 'string'], + 'itens' => ['required', 'array', 'min:1'], + 'itens.*.produto_id' => ['required', 'exists:produtos,id'], + 'itens.*.quantidade' => ['required', 'numeric', 'gt:0'], + 'itens.*.preco_unitario' => ['required', 'numeric', 'min:0'], + 'itens.*.numero_lote' => ['nullable', 'string', 'max:80'], + 'itens.*.data_validade' => ['nullable', 'date'], + ]; + } +} diff --git a/app/Http/Requests/StoreDocumentoComercialRequest.php b/app/Http/Requests/StoreDocumentoComercialRequest.php new file mode 100644 index 00000000..8dd5f333 --- /dev/null +++ b/app/Http/Requests/StoreDocumentoComercialRequest.php @@ -0,0 +1,66 @@ +merge([ + 'desconto_total' => $this->input('desconto_total', 0), + 'acrescimo_total' => $this->input('acrescimo_total', 0), + 'impostos_total' => $this->input('impostos_total', 0), + 'itens' => array_values((array) $this->input('itens', [])), + ]); + } + + public function rules(): array + { + return [ + 'tipo' => ['required', Rule::in(['ORCAMENTO', 'PREVENDA', 'PEDIDO', 'VENDA'])], + 'cliente_id' => ['required', 'exists:clientes,id'], + 'filial_id' => ['nullable', 'exists:filiais,id'], + 'tabela_preco_id' => ['nullable', 'exists:tabelas_preco,id'], + 'data_emissao' => ['nullable', 'date'], + 'validade_orcamento' => ['nullable', 'date'], + 'status' => [ + 'nullable', + Rule::in([ + 'RASCUNHO', + 'PENDENTE', + 'AGUARDANDO_PAGAMENTO', + 'EM_SEPARACAO', + 'AGUARDANDO_FATURAMENTO', + 'CONCLUIDO', + 'FATURADO', + 'CANCELADO', + ]), + ], + 'desconto_total' => ['nullable', 'numeric', 'min:0'], + 'acrescimo_total' => ['nullable', 'numeric', 'min:0'], + 'impostos_total' => ['nullable', 'numeric', 'min:0'], + 'observacoes' => ['nullable', 'string'], + 'itens' => ['required', 'array', 'min:1'], + 'itens.*.produto_id' => ['required', 'exists:produtos,id'], + 'itens.*.quantidade' => ['required', 'numeric', 'gt:0'], + 'itens.*.preco_unitario' => ['nullable', 'numeric', 'min:0'], + ]; + } + + public function messages(): array + { + return [ + 'itens.required' => 'Adicione pelo menos um item no documento.', + 'itens.*.produto_id.required' => 'Selecione um produto para cada item.', + 'itens.*.quantidade.gt' => 'Quantidade deve ser maior que zero.', + ]; + } +} diff --git a/app/Http/Requests/StoreFornecedorRequest.php b/app/Http/Requests/StoreFornecedorRequest.php new file mode 100644 index 00000000..040e95cd --- /dev/null +++ b/app/Http/Requests/StoreFornecedorRequest.php @@ -0,0 +1,26 @@ + ['required', 'string', 'max:180'], + 'cnpj' => ['nullable', 'string', 'max:18', 'unique:fornecedores,cnpj'], + 'telefone' => ['nullable', 'string', 'max:30'], + 'email' => ['nullable', 'email', 'max:180'], + 'endereco' => ['nullable', 'string'], + 'contato' => ['nullable', 'string', 'max:120'], + 'ativo' => ['nullable', 'boolean'], + ]; + } +} diff --git a/app/Http/Requests/StoreMovimentacaoEstoqueRequest.php b/app/Http/Requests/StoreMovimentacaoEstoqueRequest.php new file mode 100644 index 00000000..e064c7ba --- /dev/null +++ b/app/Http/Requests/StoreMovimentacaoEstoqueRequest.php @@ -0,0 +1,52 @@ +merge([ + 'tipo' => strtoupper((string) $this->input('tipo')), + 'origem' => trim((string) $this->input('origem')), + 'documento_ref' => trim((string) $this->input('documento_ref')), + 'lote' => trim((string) $this->input('lote')), + 'serial' => trim((string) $this->input('serial')), + 'ajuste_direcao' => strtoupper((string) $this->input('ajuste_direcao')), + ]); + } + + public function rules(): array + { + return [ + 'produto_id' => ['required', Rule::exists('produtos', 'id')], + 'tipo' => ['required', Rule::in(['ENTRADA', 'SAIDA', 'AJUSTE'])], + 'origem' => ['required', 'string', 'max:40'], + 'documento_ref' => ['nullable', 'string', 'max:80'], + 'quantidade' => ['required', 'numeric', 'gt:0'], + 'lote' => ['nullable', 'string', 'max:80'], + 'serial' => ['nullable', 'string', 'max:120'], + 'validade' => ['nullable', 'date'], + 'custo_unitario' => ['nullable', 'numeric', 'min:0'], + 'observacao' => ['nullable', 'string'], + 'ajuste_direcao' => ['nullable', Rule::in(['ENTRADA', 'SAIDA'])], + ]; + } + + public function withValidator($validator): void + { + $validator->after(function ($validator) { + if ($this->input('tipo') === 'AJUSTE' && !$this->input('ajuste_direcao')) { + $validator->errors()->add('ajuste_direcao', 'Informe a direcao do ajuste.'); + } + }); + } +} diff --git a/app/Http/Requests/StoreProdutoRequest.php b/app/Http/Requests/StoreProdutoRequest.php new file mode 100644 index 00000000..c5cd9f9e --- /dev/null +++ b/app/Http/Requests/StoreProdutoRequest.php @@ -0,0 +1,64 @@ +merge([ + 'sku' => strtoupper(trim((string) $this->input('sku'))), + 'codigo_barras' => $this->input('codigo_barras') ? preg_replace('/\s+/', '', (string) $this->input('codigo_barras')) : null, + 'controla_lote' => $this->boolean('controla_lote', false), + 'controla_validade' => $this->boolean('controla_validade', false), + 'ativo' => $this->boolean('ativo', true), + 'permite_venda' => $this->boolean('permite_venda', true), + 'permite_compra' => $this->boolean('permite_compra', true), + ]); + } + + public function rules(): array + { + return [ + 'sku' => ['required', 'string', 'max:40', 'unique:produtos,sku'], + 'nome' => ['required', 'string', 'max:255'], + 'descricao' => ['nullable', 'string'], + 'codigo_barras' => ['nullable', 'string', 'max:50', 'unique:produtos,codigo_barras'], + 'categoria_id' => ['required', Rule::exists('categorias_produto', 'id')], + 'unidade_principal_id' => ['required', Rule::exists('unidades_medida', 'id')], + 'marca' => ['nullable', 'string', 'max:120'], + 'ncm' => ['nullable', 'string', 'max:20'], + 'cest' => ['nullable', 'string', 'max:20'], + 'observacoes' => ['nullable', 'string'], + 'controla_lote' => ['sometimes', 'boolean'], + 'controla_validade' => ['sometimes', 'boolean'], + 'ativo' => ['sometimes', 'boolean'], + 'permite_venda' => ['sometimes', 'boolean'], + 'permite_compra' => ['sometimes', 'boolean'], + 'estoque_minimo' => ['required', 'numeric', 'min:0'], + 'preco_custo' => ['required', 'numeric', 'min:0'], + 'preco_venda' => ['required', 'numeric', 'min:0'], + 'tabela_preco_id' => ['required', Rule::exists('tabelas_preco', 'id')], + ]; + } + + public function withValidator($validator): void + { + $validator->after(function ($validator) { + $precoCusto = (float) $this->input('preco_custo', 0); + $precoVenda = (float) $this->input('preco_venda', 0); + + if ($precoVenda < $precoCusto) { + $validator->errors()->add('preco_venda', 'Preco de venda nao pode ser menor que o preco de custo.'); + } + }); + } +} diff --git a/app/Http/Requests/StoreTabelaPrecoRequest.php b/app/Http/Requests/StoreTabelaPrecoRequest.php new file mode 100644 index 00000000..5ca0ce37 --- /dev/null +++ b/app/Http/Requests/StoreTabelaPrecoRequest.php @@ -0,0 +1,35 @@ +merge([ + 'nome' => trim((string) $this->input('nome')), + 'codigo' => strtoupper(trim((string) $this->input('codigo'))), + 'tipo' => strtoupper((string) $this->input('tipo')), + 'ativo' => $this->boolean('ativo', true), + ]); + } + + public function rules(): array + { + return [ + 'nome' => ['required', 'string', 'max:120', 'unique:tabelas_preco,nome'], + 'codigo' => ['required', 'string', 'max:40', 'unique:tabelas_preco,codigo'], + 'tipo' => ['required', Rule::in(['VAREJO', 'ATACADO', 'PROMOCAO', 'ESPECIAL'])], + 'prioridade' => ['required', 'integer', 'min:-999', 'max:999'], + 'ativo' => ['sometimes', 'boolean'], + ]; + } +} diff --git a/app/Http/Requests/StoreUnidadeMedidaRequest.php b/app/Http/Requests/StoreUnidadeMedidaRequest.php new file mode 100644 index 00000000..adfd4647 --- /dev/null +++ b/app/Http/Requests/StoreUnidadeMedidaRequest.php @@ -0,0 +1,32 @@ +merge([ + 'sigla' => strtoupper(trim((string) $this->input('sigla'))), + 'nome' => trim((string) $this->input('nome')), + 'ativo' => $this->boolean('ativo', true), + ]); + } + + public function rules(): array + { + return [ + 'sigla' => ['required', 'string', 'max:20', 'unique:unidades_medida,sigla'], + 'nome' => ['required', 'string', 'max:80'], + 'casas_decimais' => ['required', 'integer', 'min:0', 'max:6'], + 'ativo' => ['sometimes', 'boolean'], + ]; + } +} diff --git a/app/Http/Requests/UpdateCategoriaProdutoRequest.php b/app/Http/Requests/UpdateCategoriaProdutoRequest.php new file mode 100644 index 00000000..d4969071 --- /dev/null +++ b/app/Http/Requests/UpdateCategoriaProdutoRequest.php @@ -0,0 +1,32 @@ +merge([ + 'nome' => trim((string) $this->input('nome')), + 'ativo' => $this->boolean('ativo', true), + ]); + } + + public function rules(): array + { + $id = (int) $this->route('categoria_produto')->id; + + return [ + 'nome' => ['required', 'string', 'max:120', Rule::unique('categorias_produto', 'nome')->ignore($id)], + 'ativo' => ['sometimes', 'boolean'], + ]; + } +} diff --git a/app/Http/Requests/UpdateClienteRequest.php b/app/Http/Requests/UpdateClienteRequest.php new file mode 100644 index 00000000..6114270a --- /dev/null +++ b/app/Http/Requests/UpdateClienteRequest.php @@ -0,0 +1,80 @@ +merge([ + 'tipo_pessoa' => strtoupper((string) $this->input('tipo_pessoa')), + 'cpf_cnpj' => $this->onlyDigits($this->input('cpf_cnpj')), + 'telefone' => $this->onlyDigits($this->input('telefone')), + 'celular' => $this->onlyDigits($this->input('celular')), + 'cep' => $this->onlyDigits($this->input('cep')), + 'uf' => strtoupper((string) $this->input('uf')), + 'sexo' => $this->input('sexo') ? strtoupper((string) $this->input('sexo')) : null, + 'ativo' => $this->boolean('ativo', true), + ]); + } + + public function rules(): array + { + $clienteId = (int) $this->route('cliente')->id; + + return [ + 'codigo' => ['nullable', 'string', 'max:20', Rule::unique('clientes', 'codigo')->ignore($clienteId)], + 'tipo_pessoa' => ['required', Rule::in(['PF', 'PJ'])], + 'nome' => ['required', 'string', 'max:255'], + 'nome_fantasia' => ['nullable', 'string', 'max:255'], + 'cpf_cnpj' => ['required', 'string', 'min:11', 'max:14', Rule::unique('clientes', 'cpf_cnpj')->ignore($clienteId)], + 'rg_ie' => ['nullable', 'string', 'max:30'], + 'email' => ['nullable', 'email', 'max:255', Rule::unique('clientes', 'email')->ignore($clienteId)], + 'telefone' => ['nullable', 'string', 'max:20'], + 'celular' => ['nullable', 'string', 'max:20'], + 'contato_nome' => ['nullable', 'string', 'max:120'], + 'cep' => ['nullable', 'string', 'max:8'], + 'logradouro' => ['nullable', 'string', 'max:255'], + 'numero' => ['nullable', 'string', 'max:20'], + 'complemento' => ['nullable', 'string', 'max:120'], + 'bairro' => ['nullable', 'string', 'max:120'], + 'cidade' => ['nullable', 'string', 'max:120'], + 'uf' => ['nullable', 'string', 'size:2'], + 'codigo_ibge' => ['nullable', 'string', 'max:10'], + 'pais' => ['required', 'string', 'max:80'], + 'data_nascimento_fundacao' => ['nullable', 'date'], + 'sexo' => ['nullable', Rule::in(['M', 'F', 'N'])], + 'observacoes' => ['nullable', 'string'], + 'ativo' => ['sometimes', 'boolean'], + 'saldo_credito' => ['nullable', 'numeric', 'min:0'], + 'limite_prazo' => ['nullable', 'numeric', 'min:0'], + ]; + } + + public function withValidator($validator): void + { + $validator->after(function ($validator) { + $doc = (string) $this->input('cpf_cnpj'); + $tipo = $this->input('tipo_pessoa'); + + if ($tipo === 'PF' && !$this->isValidCpf($doc)) { + $validator->errors()->add('cpf_cnpj', 'CPF invalido.'); + } + + if ($tipo === 'PJ' && !$this->isValidCnpj($doc)) { + $validator->errors()->add('cpf_cnpj', 'CNPJ invalido.'); + } + }); + } +} diff --git a/app/Http/Requests/UpdateDocumentoComercialRequest.php b/app/Http/Requests/UpdateDocumentoComercialRequest.php new file mode 100644 index 00000000..11ec3830 --- /dev/null +++ b/app/Http/Requests/UpdateDocumentoComercialRequest.php @@ -0,0 +1,7 @@ +route('fornecedor')?->id; + + return [ + 'nome' => ['required', 'string', 'max:180'], + 'cnpj' => ['nullable', 'string', 'max:18', Rule::unique('fornecedores', 'cnpj')->ignore($fornecedorId)], + 'telefone' => ['nullable', 'string', 'max:30'], + 'email' => ['nullable', 'email', 'max:180'], + 'endereco' => ['nullable', 'string'], + 'contato' => ['nullable', 'string', 'max:120'], + 'ativo' => ['nullable', 'boolean'], + ]; + } +} diff --git a/app/Http/Requests/UpdateProdutoRequest.php b/app/Http/Requests/UpdateProdutoRequest.php new file mode 100644 index 00000000..caab4339 --- /dev/null +++ b/app/Http/Requests/UpdateProdutoRequest.php @@ -0,0 +1,66 @@ +merge([ + 'sku' => strtoupper(trim((string) $this->input('sku'))), + 'codigo_barras' => $this->input('codigo_barras') ? preg_replace('/\s+/', '', (string) $this->input('codigo_barras')) : null, + 'controla_lote' => $this->boolean('controla_lote', false), + 'controla_validade' => $this->boolean('controla_validade', false), + 'ativo' => $this->boolean('ativo', true), + 'permite_venda' => $this->boolean('permite_venda', true), + 'permite_compra' => $this->boolean('permite_compra', true), + ]); + } + + public function rules(): array + { + $produtoId = (int) $this->route('produto')->id; + + return [ + 'sku' => ['required', 'string', 'max:40', Rule::unique('produtos', 'sku')->ignore($produtoId)], + 'nome' => ['required', 'string', 'max:255'], + 'descricao' => ['nullable', 'string'], + 'codigo_barras' => ['nullable', 'string', 'max:50', Rule::unique('produtos', 'codigo_barras')->ignore($produtoId)], + 'categoria_id' => ['required', Rule::exists('categorias_produto', 'id')], + 'unidade_principal_id' => ['required', Rule::exists('unidades_medida', 'id')], + 'marca' => ['nullable', 'string', 'max:120'], + 'ncm' => ['nullable', 'string', 'max:20'], + 'cest' => ['nullable', 'string', 'max:20'], + 'observacoes' => ['nullable', 'string'], + 'controla_lote' => ['sometimes', 'boolean'], + 'controla_validade' => ['sometimes', 'boolean'], + 'ativo' => ['sometimes', 'boolean'], + 'permite_venda' => ['sometimes', 'boolean'], + 'permite_compra' => ['sometimes', 'boolean'], + 'estoque_minimo' => ['required', 'numeric', 'min:0'], + 'preco_custo' => ['required', 'numeric', 'min:0'], + 'preco_venda' => ['required', 'numeric', 'min:0'], + 'tabela_preco_id' => ['required', Rule::exists('tabelas_preco', 'id')], + ]; + } + + public function withValidator($validator): void + { + $validator->after(function ($validator) { + $precoCusto = (float) $this->input('preco_custo', 0); + $precoVenda = (float) $this->input('preco_venda', 0); + + if ($precoVenda < $precoCusto) { + $validator->errors()->add('preco_venda', 'Preco de venda nao pode ser menor que o preco de custo.'); + } + }); + } +} diff --git a/app/Http/Requests/UpdateTabelaPrecoRequest.php b/app/Http/Requests/UpdateTabelaPrecoRequest.php new file mode 100644 index 00000000..56774eec --- /dev/null +++ b/app/Http/Requests/UpdateTabelaPrecoRequest.php @@ -0,0 +1,37 @@ +merge([ + 'nome' => trim((string) $this->input('nome')), + 'codigo' => strtoupper(trim((string) $this->input('codigo'))), + 'tipo' => strtoupper((string) $this->input('tipo')), + 'ativo' => $this->boolean('ativo', true), + ]); + } + + public function rules(): array + { + $id = (int) $this->route('tabela_preco')->id; + + return [ + 'nome' => ['required', 'string', 'max:120', Rule::unique('tabelas_preco', 'nome')->ignore($id)], + 'codigo' => ['required', 'string', 'max:40', Rule::unique('tabelas_preco', 'codigo')->ignore($id)], + 'tipo' => ['required', Rule::in(['VAREJO', 'ATACADO', 'PROMOCAO', 'ESPECIAL'])], + 'prioridade' => ['required', 'integer', 'min:-999', 'max:999'], + 'ativo' => ['sometimes', 'boolean'], + ]; + } +} diff --git a/app/Http/Requests/UpdateUnidadeMedidaRequest.php b/app/Http/Requests/UpdateUnidadeMedidaRequest.php new file mode 100644 index 00000000..3463e501 --- /dev/null +++ b/app/Http/Requests/UpdateUnidadeMedidaRequest.php @@ -0,0 +1,35 @@ +merge([ + 'sigla' => strtoupper(trim((string) $this->input('sigla'))), + 'nome' => trim((string) $this->input('nome')), + 'ativo' => $this->boolean('ativo', true), + ]); + } + + public function rules(): array + { + $id = (int) $this->route('unidade_medida')->id; + + return [ + 'sigla' => ['required', 'string', 'max:20', Rule::unique('unidades_medida', 'sigla')->ignore($id)], + 'nome' => ['required', 'string', 'max:80'], + 'casas_decimais' => ['required', 'integer', 'min:0', 'max:6'], + 'ativo' => ['sometimes', 'boolean'], + ]; + } +} diff --git a/app/Http/Requests/UpdateUsuarioAcessoRequest.php b/app/Http/Requests/UpdateUsuarioAcessoRequest.php new file mode 100644 index 00000000..827a02e0 --- /dev/null +++ b/app/Http/Requests/UpdateUsuarioAcessoRequest.php @@ -0,0 +1,21 @@ + ['required', Rule::in(['OPERADOR', 'GERENTE', 'ADMIN'])], + ]; + } +} diff --git a/app/Models/AuditoriaLog.php b/app/Models/AuditoriaLog.php new file mode 100644 index 00000000..02483568 --- /dev/null +++ b/app/Models/AuditoriaLog.php @@ -0,0 +1,35 @@ + 'array', + 'dados_depois' => 'array', + ]; + + public function usuario(): BelongsTo + { + return $this->belongsTo(User::class, 'usuario_id'); + } +} diff --git a/app/Models/CategoriaProduto.php b/app/Models/CategoriaProduto.php new file mode 100644 index 00000000..270acac0 --- /dev/null +++ b/app/Models/CategoriaProduto.php @@ -0,0 +1,28 @@ + 'boolean', + ]; + + public function produtos(): HasMany + { + return $this->hasMany(Produto::class, 'categoria_id'); + } +} diff --git a/app/Models/Cliente.php b/app/Models/Cliente.php new file mode 100644 index 00000000..0a90af5c --- /dev/null +++ b/app/Models/Cliente.php @@ -0,0 +1,61 @@ + 'boolean', + 'saldo_credito' => 'decimal:2', + 'limite_prazo' => 'decimal:2', + 'data_nascimento_fundacao' => 'date', + ]; + + public function getDocumentoFormatadoAttribute(): string + { + $digits = preg_replace('/\D/', '', (string) $this->cpf_cnpj); + + if (strlen($digits) === 11) { + return preg_replace('/(\d{3})(\d{3})(\d{3})(\d{2})/', '$1.$2.$3-$4', $digits); + } + + if (strlen($digits) === 14) { + return preg_replace('/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/', '$1.$2.$3\/$4-$5', $digits); + } + + return (string) $this->cpf_cnpj; + } +} diff --git a/app/Models/Compra.php b/app/Models/Compra.php new file mode 100644 index 00000000..dc137c71 --- /dev/null +++ b/app/Models/Compra.php @@ -0,0 +1,57 @@ + 'datetime', + 'valor_total' => 'decimal:2', + ]; + + public function fornecedor(): BelongsTo + { + return $this->belongsTo(Fornecedor::class, 'fornecedor_id'); + } + + public function usuario(): BelongsTo + { + return $this->belongsTo(User::class, 'usuario_id'); + } + + public function filial(): BelongsTo + { + return $this->belongsTo(Filial::class, 'filial_id'); + } + + public function itens(): HasMany + { + return $this->hasMany(CompraItem::class, 'compra_id')->orderBy('sequencia'); + } + + public function contaPagar(): HasOne + { + return $this->hasOne(ContaPagar::class, 'compra_id'); + } +} diff --git a/app/Models/CompraItem.php b/app/Models/CompraItem.php new file mode 100644 index 00000000..554467be --- /dev/null +++ b/app/Models/CompraItem.php @@ -0,0 +1,42 @@ + 'decimal:3', + 'preco_unitario' => 'decimal:4', + 'subtotal' => 'decimal:2', + 'data_validade' => 'date', + ]; + + public function compra(): BelongsTo + { + return $this->belongsTo(Compra::class, 'compra_id'); + } + + public function produto(): BelongsTo + { + return $this->belongsTo(Produto::class, 'produto_id'); + } +} diff --git a/app/Models/ContaPagar.php b/app/Models/ContaPagar.php new file mode 100644 index 00000000..b3beae06 --- /dev/null +++ b/app/Models/ContaPagar.php @@ -0,0 +1,45 @@ + 'decimal:2', + 'valor_aberto' => 'decimal:2', + 'vencimento' => 'date', + ]; + + public function compra(): BelongsTo + { + return $this->belongsTo(Compra::class, 'compra_id'); + } + + public function fornecedor(): BelongsTo + { + return $this->belongsTo(Fornecedor::class, 'fornecedor_id'); + } + + public function movimentos(): HasMany + { + return $this->hasMany(ContaPagarMovimento::class, 'conta_pagar_id'); + } +} diff --git a/app/Models/ContaPagarMovimento.php b/app/Models/ContaPagarMovimento.php new file mode 100644 index 00000000..9d5a7255 --- /dev/null +++ b/app/Models/ContaPagarMovimento.php @@ -0,0 +1,40 @@ + 'decimal:2', + 'data_movimento' => 'datetime', + ]; + + public function contaPagar(): BelongsTo + { + return $this->belongsTo(ContaPagar::class, 'conta_pagar_id'); + } + + public function usuario(): BelongsTo + { + return $this->belongsTo(User::class, 'usuario_id'); + } +} + diff --git a/app/Models/ContaReceber.php b/app/Models/ContaReceber.php new file mode 100644 index 00000000..da64c444 --- /dev/null +++ b/app/Models/ContaReceber.php @@ -0,0 +1,45 @@ + 'decimal:2', + 'valor_aberto' => 'decimal:2', + 'vencimento' => 'date', + ]; + + public function documento(): BelongsTo + { + return $this->belongsTo(DocumentoComercial::class, 'documento_id'); + } + + public function cliente(): BelongsTo + { + return $this->belongsTo(Cliente::class, 'cliente_id'); + } + + public function movimentos(): HasMany + { + return $this->hasMany(ContaReceberMovimento::class, 'conta_receber_id')->orderByDesc('data_movimento'); + } +} diff --git a/app/Models/ContaReceberMovimento.php b/app/Models/ContaReceberMovimento.php new file mode 100644 index 00000000..c14a957b --- /dev/null +++ b/app/Models/ContaReceberMovimento.php @@ -0,0 +1,39 @@ + 'decimal:2', + 'data_movimento' => 'datetime', + ]; + + public function contaReceber(): BelongsTo + { + return $this->belongsTo(ContaReceber::class, 'conta_receber_id'); + } + + public function usuario(): BelongsTo + { + return $this->belongsTo(User::class, 'usuario_id'); + } +} diff --git a/app/Models/DocumentoComercial.php b/app/Models/DocumentoComercial.php new file mode 100644 index 00000000..4215a485 --- /dev/null +++ b/app/Models/DocumentoComercial.php @@ -0,0 +1,107 @@ + 'datetime', + 'validade_orcamento' => 'date', + 'subtotal' => 'decimal:2', + 'desconto_total' => 'decimal:2', + 'acrescimo_total' => 'decimal:2', + 'impostos_total' => 'decimal:2', + 'total_liquido' => 'decimal:2', + ]; + + public function cliente(): BelongsTo + { + return $this->belongsTo(Cliente::class, 'cliente_id'); + } + + public function vendedor(): BelongsTo + { + return $this->belongsTo(User::class, 'vendedor_id'); + } + + public function operador(): BelongsTo + { + return $this->belongsTo(User::class, 'operador_id'); + } + + public function filial(): BelongsTo + { + return $this->belongsTo(Filial::class, 'filial_id'); + } + + public function tabelaPreco(): BelongsTo + { + return $this->belongsTo(TabelaPreco::class, 'tabela_preco_id'); + } + + public function origem(): BelongsTo + { + return $this->belongsTo(self::class, 'documento_origem_id'); + } + + public function derivados(): HasMany + { + return $this->hasMany(self::class, 'documento_origem_id'); + } + + public function itens(): HasMany + { + return $this->hasMany(DocumentoItem::class, 'documento_id')->orderBy('sequencia'); + } + + public function eventos(): HasMany + { + return $this->hasMany(DocumentoEvento::class, 'documento_id')->orderByDesc('data_evento'); + } + + public function pagamentos(): HasMany + { + return $this->hasMany(DocumentoPagamento::class, 'documento_id'); + } + + public function faturamento(): HasOne + { + return $this->hasOne(Faturamento::class, 'documento_id'); + } + + public function contaReceber(): HasOne + { + return $this->hasOne(ContaReceber::class, 'documento_id'); + } +} diff --git a/app/Models/DocumentoEvento.php b/app/Models/DocumentoEvento.php new file mode 100644 index 00000000..d8aa1eac --- /dev/null +++ b/app/Models/DocumentoEvento.php @@ -0,0 +1,39 @@ + 'datetime', + 'detalhes' => 'array', + ]; + + public function documento(): BelongsTo + { + return $this->belongsTo(DocumentoComercial::class, 'documento_id'); + } + + public function usuario(): BelongsTo + { + return $this->belongsTo(User::class, 'usuario_id'); + } +} diff --git a/app/Models/DocumentoItem.php b/app/Models/DocumentoItem.php new file mode 100644 index 00000000..b41cca95 --- /dev/null +++ b/app/Models/DocumentoItem.php @@ -0,0 +1,53 @@ + 'decimal:3', + 'preco_tabela' => 'decimal:4', + 'preco_unitario' => 'decimal:4', + 'subtotal_bruto' => 'decimal:2', + 'subtotal_liquido' => 'decimal:2', + 'metadata' => 'array', + ]; + + public function documento(): BelongsTo + { + return $this->belongsTo(DocumentoComercial::class, 'documento_id'); + } + + public function produto(): BelongsTo + { + return $this->belongsTo(Produto::class, 'produto_id'); + } + + public function reserva(): HasOne + { + return $this->hasOne(EstoqueReserva::class, 'documento_item_id'); + } +} diff --git a/app/Models/DocumentoPagamento.php b/app/Models/DocumentoPagamento.php new file mode 100644 index 00000000..b033ec23 --- /dev/null +++ b/app/Models/DocumentoPagamento.php @@ -0,0 +1,36 @@ + 'decimal:2', + 'data_pagamento' => 'datetime', + 'metadata' => 'array', + ]; + + public function documento(): BelongsTo + { + return $this->belongsTo(DocumentoComercial::class, 'documento_id'); + } +} diff --git a/app/Models/EstoqueLote.php b/app/Models/EstoqueLote.php new file mode 100644 index 00000000..70e93e45 --- /dev/null +++ b/app/Models/EstoqueLote.php @@ -0,0 +1,40 @@ + 'date', + 'quantidade_disponivel' => 'decimal:3', + 'custo_unitario' => 'decimal:4', + ]; + + public function produto(): BelongsTo + { + return $this->belongsTo(Produto::class, 'produto_id'); + } + + public function movimentacoes(): HasMany + { + return $this->hasMany(EstoqueMovimentacao::class, 'estoque_lote_id'); + } +} diff --git a/app/Models/EstoqueMovimentacao.php b/app/Models/EstoqueMovimentacao.php new file mode 100644 index 00000000..4d13fbef --- /dev/null +++ b/app/Models/EstoqueMovimentacao.php @@ -0,0 +1,54 @@ + 'decimal:3', + 'saldo_apos' => 'decimal:3', + 'created_at' => 'datetime', + ]; + + public function produto(): BelongsTo + { + return $this->belongsTo(Produto::class, 'produto_id'); + } + + public function lote(): BelongsTo + { + return $this->belongsTo(EstoqueLote::class, 'estoque_lote_id'); + } + + public function reserva(): BelongsTo + { + return $this->belongsTo(EstoqueReserva::class, 'estoque_reserva_id'); + } +} diff --git a/app/Models/EstoqueReserva.php b/app/Models/EstoqueReserva.php new file mode 100644 index 00000000..49d8d673 --- /dev/null +++ b/app/Models/EstoqueReserva.php @@ -0,0 +1,39 @@ + 'decimal:3', + 'data_reserva' => 'datetime', + 'data_consumo' => 'datetime', + ]; + + public function item(): BelongsTo + { + return $this->belongsTo(DocumentoItem::class, 'documento_item_id'); + } + + public function produto(): BelongsTo + { + return $this->belongsTo(Produto::class, 'produto_id'); + } +} diff --git a/app/Models/EstoqueSaldo.php b/app/Models/EstoqueSaldo.php new file mode 100644 index 00000000..ae7a5dc0 --- /dev/null +++ b/app/Models/EstoqueSaldo.php @@ -0,0 +1,36 @@ + 'decimal:3', + 'quantidade_reservada' => 'decimal:3', + 'estoque_minimo' => 'decimal:3', + 'updated_at' => 'datetime', + ]; + + public function produto(): BelongsTo + { + return $this->belongsTo(Produto::class, 'produto_id'); + } +} diff --git a/app/Models/Faturamento.php b/app/Models/Faturamento.php new file mode 100644 index 00000000..23fcdd57 --- /dev/null +++ b/app/Models/Faturamento.php @@ -0,0 +1,34 @@ + 'datetime', + ]; + + public function documento(): BelongsTo + { + return $this->belongsTo(DocumentoComercial::class, 'documento_id'); + } +} diff --git a/app/Models/Filial.php b/app/Models/Filial.php new file mode 100644 index 00000000..787cb71c --- /dev/null +++ b/app/Models/Filial.php @@ -0,0 +1,23 @@ + 'boolean', + ]; +} diff --git a/app/Models/Fornecedor.php b/app/Models/Fornecedor.php new file mode 100644 index 00000000..73117f76 --- /dev/null +++ b/app/Models/Fornecedor.php @@ -0,0 +1,34 @@ + 'boolean', + ]; + + public function compras(): HasMany + { + return $this->hasMany(Compra::class, 'fornecedor_id'); + } +} diff --git a/app/Models/Produto.php b/app/Models/Produto.php new file mode 100644 index 00000000..e457ac0e --- /dev/null +++ b/app/Models/Produto.php @@ -0,0 +1,76 @@ + 'boolean', + 'controla_validade' => 'boolean', + 'ativo' => 'boolean', + 'permite_venda' => 'boolean', + 'permite_compra' => 'boolean', + ]; + + public function categoria(): BelongsTo + { + return $this->belongsTo(CategoriaProduto::class, 'categoria_id'); + } + + public function unidadePrincipal(): BelongsTo + { + return $this->belongsTo(UnidadeMedida::class, 'unidade_principal_id'); + } + + public function unidades(): HasMany + { + return $this->hasMany(ProdutoUnidade::class, 'produto_id'); + } + + public function estoqueSaldo(): HasOne + { + return $this->hasOne(EstoqueSaldo::class, 'produto_id'); + } + + public function movimentosEstoque(): HasMany + { + return $this->hasMany(EstoqueMovimentacao::class, 'produto_id'); + } + + public function precos(): HasMany + { + return $this->hasMany(ProdutoPreco::class, 'produto_id'); + } + + public function documentoItens(): HasMany + { + return $this->hasMany(DocumentoItem::class, 'produto_id'); + } +} diff --git a/app/Models/ProdutoPreco.php b/app/Models/ProdutoPreco.php new file mode 100644 index 00000000..252ee450 --- /dev/null +++ b/app/Models/ProdutoPreco.php @@ -0,0 +1,44 @@ + 'decimal:4', + 'custo_referencia' => 'decimal:4', + 'margem_percentual' => 'decimal:4', + 'vigencia_inicio' => 'datetime', + 'vigencia_fim' => 'datetime', + 'ativo' => 'boolean', + ]; + + public function produto(): BelongsTo + { + return $this->belongsTo(Produto::class, 'produto_id'); + } + + public function tabelaPreco(): BelongsTo + { + return $this->belongsTo(TabelaPreco::class, 'tabela_preco_id'); + } +} diff --git a/app/Models/ProdutoUnidade.php b/app/Models/ProdutoUnidade.php new file mode 100644 index 00000000..29a26914 --- /dev/null +++ b/app/Models/ProdutoUnidade.php @@ -0,0 +1,37 @@ + 'decimal:4', + 'ativo' => 'boolean', + ]; + + public function produto(): BelongsTo + { + return $this->belongsTo(Produto::class, 'produto_id'); + } + + public function unidade(): BelongsTo + { + return $this->belongsTo(UnidadeMedida::class, 'unidade_id'); + } +} diff --git a/app/Models/TabelaPreco.php b/app/Models/TabelaPreco.php new file mode 100644 index 00000000..144a04d3 --- /dev/null +++ b/app/Models/TabelaPreco.php @@ -0,0 +1,32 @@ + 'boolean', + 'prioridade' => 'integer', + ]; + + public function produtoPrecos(): HasMany + { + return $this->hasMany(ProdutoPreco::class, 'tabela_preco_id'); + } +} diff --git a/app/Models/UnidadeMedida.php b/app/Models/UnidadeMedida.php new file mode 100644 index 00000000..9d9501cc --- /dev/null +++ b/app/Models/UnidadeMedida.php @@ -0,0 +1,31 @@ + 'integer', + 'ativo' => 'boolean', + ]; + + public function produtos(): HasMany + { + return $this->hasMany(Produto::class, 'unidade_principal_id'); + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 749c7b77..76276662 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -20,6 +20,7 @@ class User extends Authenticatable protected $fillable = [ 'name', 'email', + 'nivel_acesso', 'password', ]; @@ -45,4 +46,26 @@ protected function casts(): array 'password' => 'hashed', ]; } + + public function possuiAcessoGerencial(): bool + { + return in_array($this->nivelAcesso(), ['GERENTE', 'ADMIN'], true); + } + + public function nivelAcesso(): string + { + $nivel = (string) ($this->nivel_acesso ?? 'OPERADOR'); + return in_array($nivel, ['OPERADOR', 'GERENTE', 'ADMIN'], true) ? $nivel : 'OPERADOR'; + } + + public function hasPermission(string $permission): bool + { + $permissions = config('rbac.permissions_by_role.' . $this->nivelAcesso(), []); + + if (in_array('*', $permissions, true)) { + return true; + } + + return in_array($permission, $permissions, true); + } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 337659b5..f9faa2ed 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,6 +2,7 @@ namespace App\Providers; +use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider @@ -19,6 +20,17 @@ public function register(): void */ public function boot(): void { - // + Blade::if('perm', function (string $permission): bool { + if (!auth()->check()) { + return false; + } + + $user = auth()->user(); + if (!$user || !method_exists($user, 'hasPermission')) { + return false; + } + + return (bool) $user->hasPermission($permission); + }); } -} \ No newline at end of file +} diff --git a/app/Providers/MenuServiceProvider.php b/app/Providers/MenuServiceProvider.php index 1cb13b8b..d7636ef1 100644 --- a/app/Providers/MenuServiceProvider.php +++ b/app/Providers/MenuServiceProvider.php @@ -3,9 +3,8 @@ namespace App\Providers; use Illuminate\Support\Facades\View; -use Illuminate\Routing\Route; - use Illuminate\Support\ServiceProvider; +use stdClass; class MenuServiceProvider extends ServiceProvider { @@ -22,10 +21,119 @@ public function register(): void */ public function boot(): void { - $verticalMenuJson = file_get_contents(base_path('resources/menu/verticalMenu.json')); - $verticalMenuData = json_decode($verticalMenuJson); + View::composer('*', function ($view): void { + $verticalMenuJson = file_get_contents(base_path('resources/menu/verticalMenu.json')); + $verticalMenuData = json_decode($verticalMenuJson); + + $verticalMenuData->menu = $this->normalizeMenuHeaders( + $this->filterMenuItems($verticalMenuData->menu ?? []) + ); + + $view->with('menuData', [$verticalMenuData]); + }); + } + + /** + * @param array $items + * @return array + */ + private function filterMenuItems(array $items): array + { + $filtered = []; + + foreach ($items as $item) { + if (!($item instanceof stdClass)) { + continue; + } + + if (!$this->passesVisibilityRule($item)) { + continue; + } + + if (isset($item->menuHeader)) { + $filtered[] = $item; + continue; + } + + if (isset($item->permission) && !$this->can($item->permission)) { + continue; + } + + if (isset($item->submenu) && is_array($item->submenu)) { + $item->submenu = $this->filterMenuItems($item->submenu); + if (count($item->submenu) === 0 && !isset($item->url)) { + continue; + } + } + + $filtered[] = $item; + } + + return $filtered; + } + + /** + * Remove menu headers that end up with no visible items. + * + * @param array $items + * @return array + */ + private function normalizeMenuHeaders(array $items): array + { + $normalized = []; + $previousWasHeader = false; + + foreach ($items as $item) { + if (isset($item->menuHeader)) { + if (count($normalized) === 0 || $previousWasHeader) { + continue; + } + + $previousWasHeader = true; + $normalized[] = $item; + continue; + } + + $previousWasHeader = false; + $normalized[] = $item; + } + + if (!empty($normalized)) { + $last = end($normalized); + if ($last instanceof stdClass && isset($last->menuHeader)) { + array_pop($normalized); + } + } + + return $normalized; + } + + private function passesVisibilityRule(stdClass $item): bool + { + if (!isset($item->auth)) { + return true; + } + + $isAuthenticated = auth()->check(); + + return match ($item->auth) { + 'guest' => !$isAuthenticated, + 'auth' => $isAuthenticated, + default => true, + }; + } + + private function can(string $permission): bool + { + if (!auth()->check()) { + return false; + } + + $user = auth()->user(); + if (!$user || !method_exists($user, 'hasPermission')) { + return false; + } - // Share all menuData to all the views - $this->app->make('view')->share('menuData', [$verticalMenuData]); + return (bool) $user->hasPermission($permission); } } diff --git a/app/Services/Comercial/DocumentoComercialService.php b/app/Services/Comercial/DocumentoComercialService.php new file mode 100644 index 00000000..e08fc379 --- /dev/null +++ b/app/Services/Comercial/DocumentoComercialService.php @@ -0,0 +1,756 @@ + ['RASCUNHO', 'PENDENTE', 'CONCLUIDO', 'CANCELADO'], + 'PREVENDA' => ['RASCUNHO', 'AGUARDANDO_PAGAMENTO', 'CONCLUIDO', 'CANCELADO'], + 'PEDIDO' => ['EM_SEPARACAO', 'AGUARDANDO_PAGAMENTO', 'AGUARDANDO_FATURAMENTO', 'CONCLUIDO', 'FATURADO', 'CANCELADO'], + 'VENDA' => ['AGUARDANDO_PAGAMENTO', 'AGUARDANDO_FATURAMENTO', 'FATURADO', 'CANCELADO'], + ]; + + private const TRANSICOES_STATUS = [ + 'RASCUNHO' => ['PENDENTE', 'AGUARDANDO_PAGAMENTO', 'CANCELADO'], + 'PENDENTE' => ['CONCLUIDO', 'CANCELADO', 'EM_SEPARACAO', 'AGUARDANDO_PAGAMENTO'], + 'AGUARDANDO_PAGAMENTO' => ['EM_SEPARACAO', 'AGUARDANDO_FATURAMENTO', 'CONCLUIDO', 'CANCELADO'], + 'EM_SEPARACAO' => ['AGUARDANDO_FATURAMENTO', 'CONCLUIDO', 'CANCELADO'], + 'AGUARDANDO_FATURAMENTO' => ['FATURADO', 'CANCELADO'], + 'CONCLUIDO' => ['FATURADO', 'CANCELADO'], + 'FATURADO' => [], + 'CANCELADO' => [], + ]; + + public function create(array $data, User $usuario): DocumentoComercial + { + return DB::transaction(function () use ($data, $usuario) { + $status = $data['status'] ?? $this->statusInicial($data['tipo']); + $this->validarStatusPorTipo($data['tipo'], $status); + + $documento = DocumentoComercial::create([ + 'numero' => $this->gerarNumero($data['tipo']), + 'tipo' => $data['tipo'], + 'status' => $status, + 'documento_origem_id' => $data['documento_origem_id'] ?? null, + 'cliente_id' => $data['cliente_id'], + 'vendedor_id' => $usuario->id, + 'operador_id' => $usuario->id, + 'filial_id' => $data['filial_id'] ?? Filial::query()->value('id'), + 'tabela_preco_id' => $data['tabela_preco_id'] ?? TabelaPreco::query()->where('codigo', 'VAREJO')->value('id'), + 'data_emissao' => $data['data_emissao'] ?? now(), + 'validade_orcamento' => $data['validade_orcamento'] ?? null, + 'subtotal' => 0, + 'desconto_total' => (float) ($data['desconto_total'] ?? 0), + 'acrescimo_total' => (float) ($data['acrescimo_total'] ?? 0), + 'impostos_total' => (float) ($data['impostos_total'] ?? 0), + 'total_liquido' => 0, + 'observacoes' => $data['observacoes'] ?? null, + ]); + + $this->syncItens( + $documento, + $data['itens'] ?? [], + true, + (bool) ($data['usar_preco_informado_itens'] ?? false) + ); + $this->recalcularTotais($documento); + $this->logEvento($documento, null, $documento->status, 'CRIADO', $usuario->id, [ + 'tipo' => $documento->tipo, + ]); + + $reservarEstoque = (bool) ($data['reservar_estoque'] ?? true); + if ($reservarEstoque && in_array($documento->tipo, ['PEDIDO', 'VENDA'], true)) { + $this->reservarEstoque($documento, $usuario->id); + } + + $this->registrarAuditoria( + 'DOCUMENTO_CRIADO', + $documento, + $usuario->id, + null, + $this->snapshotDocumento($documento) + ); + + return $documento->fresh(['itens.produto', 'cliente', 'vendedor', 'eventos']); + }); + } + + public function update(DocumentoComercial $documento, array $data, User $usuario): DocumentoComercial + { + $regrasEdicao = $this->regrasEdicao($documento); + if (!$regrasEdicao['pode_editar']) { + throw ValidationException::withMessages([ + 'status' => $regrasEdicao['motivo'] ?? 'Documento nao pode ser alterado nesta etapa.', + ]); + } + + if (!$regrasEdicao['permite_alterar_itens'] && $this->itensForamAlterados($documento, $data['itens'] ?? [])) { + throw ValidationException::withMessages([ + 'itens' => 'Nesta etapa nao e permitido alterar itens do documento.', + ]); + } + + return DB::transaction(function () use ($documento, $data, $usuario) { + $statusAnterior = $documento->status; + $statusNovo = (string) ($data['status'] ?? $documento->status); + $antes = $this->snapshotDocumento($documento); + $this->validarStatusPorTipo($documento->tipo, $statusNovo); + $this->validarTransicaoStatus($documento->tipo, $statusAnterior, $statusNovo); + + $documento->update([ + 'cliente_id' => $data['cliente_id'], + 'filial_id' => $data['filial_id'] ?? $documento->filial_id, + 'tabela_preco_id' => $data['tabela_preco_id'] ?? $documento->tabela_preco_id, + 'data_emissao' => $data['data_emissao'] ?? $documento->data_emissao, + 'validade_orcamento' => $data['validade_orcamento'] ?? null, + 'desconto_total' => (float) ($data['desconto_total'] ?? 0), + 'acrescimo_total' => (float) ($data['acrescimo_total'] ?? 0), + 'impostos_total' => (float) ($data['impostos_total'] ?? 0), + 'observacoes' => $data['observacoes'] ?? null, + 'status' => $statusNovo, + ]); + + $this->cancelarReservasAtivas($documento); + $this->syncItens( + $documento, + $data['itens'] ?? [], + false, + (bool) ($data['usar_preco_informado_itens'] ?? false) + ); + $this->recalcularTotais($documento); + + $usaReservaDaOrigem = $documento->tipo === 'VENDA' && $documento->documento_origem_id && $documento->origem?->tipo === 'PEDIDO'; + if (!$usaReservaDaOrigem && in_array($documento->tipo, ['PEDIDO', 'VENDA'], true) && $documento->status !== 'CANCELADO') { + $this->reservarEstoque($documento, $usuario->id); + } + + if ($statusAnterior !== $documento->status) { + $this->logEvento($documento, $statusAnterior, $documento->status, 'STATUS_ATUALIZADO', $usuario->id); + } + + $this->registrarAuditoria( + 'DOCUMENTO_ATUALIZADO', + $documento, + $usuario->id, + $antes, + $this->snapshotDocumento($documento) + ); + + return $documento->fresh(['itens.produto', 'cliente', 'vendedor', 'eventos']); + }); + } + + public function converterOrcamentoParaPedido(DocumentoComercial $orcamento, User $usuario): DocumentoComercial + { + if ($orcamento->tipo !== 'ORCAMENTO' || $orcamento->status !== 'PENDENTE') { + throw ValidationException::withMessages([ + 'tipo' => "Conversao bloqueada: documento {$orcamento->numero} esta em {$orcamento->tipo}/{$orcamento->status}. Esperado ORCAMENTO/PENDENTE.", + ]); + } + + $pedido = $this->create([ + 'tipo' => 'PEDIDO', + 'status' => 'EM_SEPARACAO', + 'documento_origem_id' => $orcamento->id, + 'cliente_id' => $orcamento->cliente_id, + 'filial_id' => $orcamento->filial_id, + 'tabela_preco_id' => $orcamento->tabela_preco_id, + 'desconto_total' => $orcamento->desconto_total, + 'acrescimo_total' => $orcamento->acrescimo_total, + 'impostos_total' => $orcamento->impostos_total, + 'observacoes' => $orcamento->observacoes, + 'itens' => $orcamento->itens->map(fn ($item) => [ + 'produto_id' => $item->produto_id, + 'quantidade' => $item->quantidade, + 'preco_unitario' => $item->preco_unitario, + ])->all(), + ], $usuario); + + $orcamento->update(['status' => 'CONCLUIDO']); + $this->logEvento($orcamento, 'PENDENTE', 'CONCLUIDO', 'CONVERTIDO_PEDIDO', $usuario->id, [ + 'pedido_id' => $pedido->id, + 'pedido_numero' => $pedido->numero, + ]); + $this->registrarAuditoria( + 'ORCAMENTO_CONVERTIDO_PEDIDO', + $orcamento, + $usuario->id, + ['status' => 'PENDENTE'], + ['status' => 'CONCLUIDO', 'pedido_id' => $pedido->id, 'pedido_numero' => $pedido->numero] + ); + + return $pedido; + } + + public function converterPedidoParaVenda(DocumentoComercial $pedido, User $usuario): DocumentoComercial + { + if ($pedido->tipo !== 'PEDIDO' || !in_array($pedido->status, ['EM_SEPARACAO', 'AGUARDANDO_PAGAMENTO'], true)) { + throw ValidationException::withMessages([ + 'tipo' => "Conversao bloqueada: documento {$pedido->numero} esta em {$pedido->tipo}/{$pedido->status}. Esperado PEDIDO/EM_SEPARACAO ou PEDIDO/AGUARDANDO_PAGAMENTO.", + ]); + } + + $venda = $this->create([ + 'tipo' => 'VENDA', + 'status' => 'AGUARDANDO_FATURAMENTO', + 'documento_origem_id' => $pedido->id, + 'cliente_id' => $pedido->cliente_id, + 'filial_id' => $pedido->filial_id, + 'tabela_preco_id' => $pedido->tabela_preco_id, + 'desconto_total' => $pedido->desconto_total, + 'acrescimo_total' => $pedido->acrescimo_total, + 'impostos_total' => $pedido->impostos_total, + 'observacoes' => $pedido->observacoes, + 'itens' => $pedido->itens->map(fn ($item) => [ + 'produto_id' => $item->produto_id, + 'quantidade' => $item->quantidade, + 'preco_unitario' => $item->preco_unitario, + ])->all(), + 'reservar_estoque' => false, + ], $usuario); + + $statusAnterior = $pedido->status; + $pedido->update(['status' => 'AGUARDANDO_FATURAMENTO']); + $this->logEvento($pedido, $statusAnterior, 'AGUARDANDO_FATURAMENTO', 'CONVERTIDO_VENDA', $usuario->id, [ + 'venda_id' => $venda->id, + 'venda_numero' => $venda->numero, + ]); + $this->registrarAuditoria( + 'PEDIDO_CONVERTIDO_VENDA', + $pedido, + $usuario->id, + ['status' => $statusAnterior], + ['status' => 'AGUARDANDO_FATURAMENTO', 'venda_id' => $venda->id, 'venda_numero' => $venda->numero] + ); + + return $venda; + } + + public function faturar(DocumentoComercial $documento, User $usuario): DocumentoComercial + { + if (!in_array($documento->tipo, ['PEDIDO', 'VENDA'], true)) { + throw ValidationException::withMessages([ + 'tipo' => "Faturamento bloqueado: {$documento->tipo} nao pode ser faturado.", + ]); + } + + if ($documento->status === 'FATURADO') { + return $documento; + } + + return DB::transaction(function () use ($documento, $usuario) { + $antes = $this->snapshotDocumento($documento); + $referenciaReserva = $documento; + if ($documento->tipo === 'VENDA' && $documento->origem?->tipo === 'PEDIDO') { + $referenciaReserva = $documento->origem; + } + + $referenciaReserva->loadMissing('itens.reserva'); + foreach ($referenciaReserva->itens as $item) { + $reserva = $item->reserva; + if (!$reserva || $reserva->status !== 'ATIVA') { + throw ValidationException::withMessages([ + 'estoque' => "Item {$item->descricao} sem reserva ativa para faturamento.", + ]); + } + + $saldo = EstoqueSaldo::lockForUpdate()->firstOrCreate( + ['produto_id' => $item->produto_id], + ['quantidade_atual' => 0, 'quantidade_reservada' => 0, 'estoque_minimo' => 0, 'updated_at' => now()] + ); + + $quantidade = (float) $reserva->quantidade_reservada; + if ((float) $saldo->quantidade_atual < $quantidade) { + throw ValidationException::withMessages([ + 'estoque' => "Estoque atual insuficiente para faturar {$item->descricao}.", + ]); + } + + $novoSaldoAtual = (float) $saldo->quantidade_atual - $quantidade; + $novoReservado = max(0, (float) $saldo->quantidade_reservada - $quantidade); + + $saldo->update([ + 'quantidade_atual' => $novoSaldoAtual, + 'quantidade_reservada' => $novoReservado, + 'updated_at' => now(), + ]); + + $reserva->update([ + 'status' => 'CONSUMIDA', + 'data_consumo' => now(), + ]); + + EstoqueMovimentacao::create([ + 'produto_id' => $item->produto_id, + 'estoque_lote_id' => null, + 'estoque_reserva_id' => $reserva->id, + 'tipo' => 'SAIDA', + 'origem' => 'FATURAMENTO', + 'origem_tipo' => 'DOCUMENTO_COMERCIAL', + 'origem_id' => $documento->id, + 'documento_ref' => $documento->numero, + 'quantidade' => $quantidade, + 'sinal' => -1, + 'saldo_apos' => $novoSaldoAtual, + 'observacao' => "Faturamento do documento {$documento->numero}", + 'user_id' => $usuario->id, + 'created_at' => now(), + ]); + } + + $statusAnterior = $documento->status; + $documento->update(['status' => 'FATURADO']); + if ($documento->origem && $documento->origem->tipo === 'PEDIDO') { + $documento->origem->update(['status' => 'FATURADO']); + } + + Faturamento::updateOrCreate( + ['documento_id' => $documento->id], + [ + 'numero_fiscal' => $this->gerarNumeroFiscal(), + 'status_fiscal' => 'AUTORIZADO', + 'data_faturamento' => now(), + ] + ); + + ContaReceber::updateOrCreate( + ['documento_id' => $documento->id], + [ + 'cliente_id' => $documento->cliente_id, + 'valor_original' => $documento->total_liquido, + 'valor_aberto' => $documento->total_liquido, + 'vencimento' => now()->toDateString(), + 'status' => ((float) $documento->total_liquido) > 0 ? 'ABERTO' : 'QUITADO', + ] + ); + + $this->logEvento($documento, $statusAnterior, 'FATURADO', 'FATURADO', $usuario->id); + $this->registrarAuditoria( + 'DOCUMENTO_FATURADO', + $documento, + $usuario->id, + $antes, + $this->snapshotDocumento($documento) + ); + + return $documento->fresh(['faturamento', 'itens.produto', 'cliente']); + }); + } + + public function acoesFluxoDisponiveis(DocumentoComercial $documento): array + { + return [ + 'converter_pedido' => [ + 'permitido' => $documento->tipo === 'ORCAMENTO' && $documento->status === 'PENDENTE', + 'motivo' => 'Disponivel apenas para ORCAMENTO em PENDENTE.', + ], + 'converter_venda' => [ + 'permitido' => $documento->tipo === 'PEDIDO' && in_array($documento->status, ['EM_SEPARACAO', 'AGUARDANDO_PAGAMENTO'], true), + 'motivo' => 'Disponivel apenas para PEDIDO em EM_SEPARACAO ou AGUARDANDO_PAGAMENTO.', + ], + 'faturar' => [ + 'permitido' => in_array($documento->tipo, ['PEDIDO', 'VENDA'], true) + && in_array($documento->status, ['AGUARDANDO_FATURAMENTO', 'CONCLUIDO', 'AGUARDANDO_PAGAMENTO', 'EM_SEPARACAO'], true), + 'motivo' => 'Disponivel apenas para PEDIDO/VENDA em etapa de fechamento.', + ], + ]; + } + + public function cancelar(DocumentoComercial $documento, User $usuario, string $motivoCancelamento): void + { + if ($documento->status === 'FATURADO') { + throw ValidationException::withMessages([ + 'status' => 'Documento faturado nao pode ser cancelado por esta rotina.', + ]); + } + + if ($documento->derivados()->whereNotIn('status', ['CANCELADO'])->exists()) { + throw ValidationException::withMessages([ + 'status' => 'Documento possui derivados ativos e nao pode ser cancelado.', + ]); + } + + DB::transaction(function () use ($documento, $usuario, $motivoCancelamento) { + $antes = $this->snapshotDocumento($documento); + $statusAnterior = $documento->status; + $this->cancelarReservasAtivas($documento); + $documento->update(['status' => 'CANCELADO']); + $this->logEvento($documento, $statusAnterior, 'CANCELADO', 'CANCELADO', $usuario->id, [ + 'motivo_cancelamento' => $motivoCancelamento, + 'total_itens' => $documento->itens()->count(), + 'total_liquido' => (float) $documento->total_liquido, + ]); + $this->registrarAuditoria( + 'DOCUMENTO_CANCELADO', + $documento, + $usuario->id, + $antes, + array_merge($this->snapshotDocumento($documento), ['motivo_cancelamento' => $motivoCancelamento]) + ); + }); + } + + public function reabrir(DocumentoComercial $documento, User $usuario, string $motivoReabertura): DocumentoComercial + { + if ($documento->status !== 'CANCELADO') { + throw ValidationException::withMessages([ + 'status' => 'Somente documento cancelado pode ser reaberto.', + ]); + } + + return DB::transaction(function () use ($documento, $usuario, $motivoReabertura) { + if ($documento->trashed()) { + $documento->restore(); + } + $antes = ['status' => 'CANCELADO']; + + $statusReaberto = $this->statusInicial($documento->tipo); + + $documento->update([ + 'status' => $statusReaberto, + ]); + + $this->logEvento($documento, 'CANCELADO', $statusReaberto, 'REABERTO', $usuario->id, [ + 'motivo_reabertura' => $motivoReabertura, + ]); + $this->registrarAuditoria( + 'DOCUMENTO_REABERTO', + $documento, + $usuario->id, + $antes, + array_merge($this->snapshotDocumento($documento), ['motivo_reabertura' => $motivoReabertura]) + ); + + return $documento->fresh(['itens', 'eventos', 'cliente']); + }); + } + + public function regrasEdicao(DocumentoComercial $documento): array + { + if (in_array($documento->status, ['FATURADO', 'CANCELADO'], true)) { + return [ + 'pode_editar' => false, + 'permite_alterar_itens' => false, + 'permite_alterar_cabecalho' => false, + 'motivo' => 'Documento finalizado.', + ]; + } + + return match ($documento->tipo) { + 'ORCAMENTO' => [ + 'pode_editar' => in_array($documento->status, ['RASCUNHO', 'PENDENTE'], true), + 'permite_alterar_itens' => true, + 'permite_alterar_cabecalho' => true, + 'motivo' => 'Orcamentos concluidos nao podem ser alterados.', + ], + 'PREVENDA' => [ + 'pode_editar' => in_array($documento->status, ['RASCUNHO', 'AGUARDANDO_PAGAMENTO'], true), + 'permite_alterar_itens' => true, + 'permite_alterar_cabecalho' => true, + 'motivo' => 'Prevenda concluida nao pode ser alterada.', + ], + 'PEDIDO' => [ + 'pode_editar' => in_array($documento->status, ['EM_SEPARACAO', 'AGUARDANDO_PAGAMENTO'], true), + 'permite_alterar_itens' => $documento->status === 'EM_SEPARACAO', + 'permite_alterar_cabecalho' => true, + 'motivo' => 'Pedido nesta etapa nao permite edicao.', + ], + 'VENDA' => [ + 'pode_editar' => in_array($documento->status, ['AGUARDANDO_PAGAMENTO', 'AGUARDANDO_FATURAMENTO'], true), + 'permite_alterar_itens' => false, + 'permite_alterar_cabecalho' => true, + 'motivo' => 'Venda nesta etapa nao permite edicao de itens.', + ], + default => [ + 'pode_editar' => false, + 'permite_alterar_itens' => false, + 'permite_alterar_cabecalho' => false, + 'motivo' => 'Tipo de documento sem regra de edicao.', + ], + }; + } + + private function syncItens(DocumentoComercial $documento, array $itens, bool $novo, bool $usarPrecoInformadoItens = false): void + { + if (!$novo) { + $documento->itens()->delete(); + } + + $documento->loadMissing('tabelaPreco'); + + foreach ($itens as $index => $item) { + $produto = Produto::findOrFail((int) $item['produto_id']); + $quantidade = (float) $item['quantidade']; + + $precoTabela = $this->precoTabela($produto->id, $documento->tabela_preco_id); + $precoUnitario = $precoTabela; + + if (($documento->tipo === 'ORCAMENTO' || $usarPrecoInformadoItens) && isset($item['preco_unitario'])) { + $precoUnitario = (float) $item['preco_unitario']; + } + + $subtotalBruto = round($precoUnitario * $quantidade, 2); + + $documento->itens()->create([ + 'sequencia' => $index + 1, + 'produto_id' => $produto->id, + 'descricao' => $produto->nome, + 'unidade_sigla' => $produto->unidadePrincipal?->sigla ?? 'UN', + 'quantidade' => $quantidade, + 'preco_tabela' => $precoTabela, + 'preco_unitario' => $precoUnitario, + 'subtotal_bruto' => $subtotalBruto, + 'subtotal_liquido' => $subtotalBruto, + 'metadata' => [ + 'produto_sku' => $produto->sku, + 'preco_editavel' => $documento->tipo === 'ORCAMENTO', + ], + ]); + } + } + + private function reservarEstoque(DocumentoComercial $documento, int $userId): void + { + $documento->loadMissing('itens'); + + foreach ($documento->itens as $item) { + $saldo = EstoqueSaldo::lockForUpdate()->firstOrCreate( + ['produto_id' => $item->produto_id], + ['quantidade_atual' => 0, 'quantidade_reservada' => 0, 'estoque_minimo' => 0, 'updated_at' => now()] + ); + + $quantidade = (float) $item->quantidade; + $disponivel = (float) $saldo->quantidade_atual - (float) $saldo->quantidade_reservada; + + if ($disponivel < $quantidade) { + throw ValidationException::withMessages([ + 'estoque' => "Estoque insuficiente para {$item->descricao}. Disponivel: {$disponivel}.", + ]); + } + + $saldo->update([ + 'quantidade_reservada' => (float) $saldo->quantidade_reservada + $quantidade, + 'updated_at' => now(), + ]); + + EstoqueReserva::updateOrCreate( + ['documento_item_id' => $item->id], + [ + 'produto_id' => $item->produto_id, + 'quantidade_reservada' => $quantidade, + 'status' => 'ATIVA', + 'data_reserva' => now(), + 'data_consumo' => null, + ] + ); + + $this->logEvento($documento, $documento->status, $documento->status, 'RESERVA_ESTOQUE', $userId, [ + 'item_id' => $item->id, + 'produto_id' => $item->produto_id, + 'quantidade' => $quantidade, + ]); + } + } + + private function cancelarReservasAtivas(DocumentoComercial $documento): void + { + $documento->loadMissing('itens.reserva'); + + foreach ($documento->itens as $item) { + $reserva = $item->reserva; + if (!$reserva || $reserva->status !== 'ATIVA') { + continue; + } + + $saldo = EstoqueSaldo::lockForUpdate()->firstOrCreate( + ['produto_id' => $item->produto_id], + ['quantidade_atual' => 0, 'quantidade_reservada' => 0, 'estoque_minimo' => 0, 'updated_at' => now()] + ); + + $saldo->update([ + 'quantidade_reservada' => max(0, (float) $saldo->quantidade_reservada - (float) $reserva->quantidade_reservada), + 'updated_at' => now(), + ]); + + $reserva->update([ + 'status' => 'CANCELADA', + 'data_consumo' => now(), + ]); + } + } + + private function recalcularTotais(DocumentoComercial $documento): void + { + $subtotal = (float) $documento->itens()->sum('subtotal_bruto'); + $totalLiquido = $subtotal + - (float) $documento->desconto_total + + (float) $documento->acrescimo_total + + (float) $documento->impostos_total; + + $documento->update([ + 'subtotal' => $subtotal, + 'total_liquido' => max(0, round($totalLiquido, 2)), + ]); + } + + private function statusInicial(string $tipo): string + { + return match ($tipo) { + 'ORCAMENTO' => 'PENDENTE', + 'PREVENDA' => 'AGUARDANDO_PAGAMENTO', + 'PEDIDO' => 'EM_SEPARACAO', + 'VENDA' => 'AGUARDANDO_FATURAMENTO', + default => 'RASCUNHO', + }; + } + + private function validarStatusPorTipo(string $tipo, string $status): void + { + $permitidos = self::STATUS_POR_TIPO[$tipo] ?? []; + if (!in_array($status, $permitidos, true)) { + throw ValidationException::withMessages([ + 'status' => "Status {$status} nao permitido para o tipo {$tipo}.", + ]); + } + } + + private function validarTransicaoStatus(string $tipo, string $statusAnterior, string $statusNovo): void + { + if ($statusAnterior === $statusNovo) { + return; + } + + $permitidas = self::TRANSICOES_STATUS[$statusAnterior] ?? []; + if (!in_array($statusNovo, $permitidas, true)) { + throw ValidationException::withMessages([ + 'status' => "Transicao de status invalida para {$tipo}: {$statusAnterior} -> {$statusNovo}.", + ]); + } + } + + private function precoTabela(int $produtoId, ?int $tabelaPrecoId): float + { + $query = ProdutoPreco::query() + ->where('produto_id', $produtoId) + ->where('ativo', true) + ->where(function ($q) { + $q->whereNull('vigencia_fim')->orWhere('vigencia_fim', '>=', now()); + }) + ->orderByDesc('vigencia_inicio'); + + if ($tabelaPrecoId) { + $registro = (clone $query)->where('tabela_preco_id', $tabelaPrecoId)->first(); + if ($registro) { + return (float) $registro->preco; + } + } + + return (float) ($query->first()?->preco ?? 0); + } + + private function gerarNumero(string $tipo): string + { + $prefixo = match ($tipo) { + 'ORCAMENTO' => 'ORC', + 'PREVENDA' => 'PVD', + 'PEDIDO' => 'PED', + 'VENDA' => 'VND', + default => 'DOC', + }; + + $ultimo = DocumentoComercial::query()->where('tipo', $tipo)->max('id') ?? 0; + + return sprintf('%s-%s-%06d', $prefixo, now()->format('Ymd'), $ultimo + 1); + } + + private function gerarNumeroFiscal(): string + { + return 'NF-' . now()->format('YmdHis') . '-' . random_int(100, 999); + } + + private function logEvento(DocumentoComercial $documento, ?string $statusAnterior, string $statusNovo, string $acao, ?int $usuarioId, array $detalhes = []): void + { + DocumentoEvento::create([ + 'documento_id' => $documento->id, + 'status_anterior' => $statusAnterior, + 'status_novo' => $statusNovo, + 'acao' => $acao, + 'usuario_id' => $usuarioId, + 'data_evento' => now(), + 'detalhes' => $detalhes, + ]); + } + + private function itensForamAlterados(DocumentoComercial $documento, array $itensPayload): bool + { + $atuais = $documento->itens() + ->orderBy('sequencia') + ->get(['produto_id', 'quantidade', 'preco_unitario']) + ->map(fn ($item) => [ + 'produto_id' => (int) $item->produto_id, + 'quantidade' => round((float) $item->quantidade, 3), + 'preco_unitario' => round((float) $item->preco_unitario, 4), + ]) + ->values() + ->all(); + + $novos = collect($itensPayload) + ->map(fn ($item) => [ + 'produto_id' => (int) ($item['produto_id'] ?? 0), + 'quantidade' => round((float) ($item['quantidade'] ?? 0), 3), + 'preco_unitario' => round((float) ($item['preco_unitario'] ?? 0), 4), + ]) + ->values() + ->all(); + + return $atuais !== $novos; + } + + private function snapshotDocumento(DocumentoComercial $documento): array + { + return [ + 'id' => $documento->id, + 'numero' => $documento->numero, + 'tipo' => $documento->tipo, + 'status' => $documento->status, + 'cliente_id' => $documento->cliente_id, + 'filial_id' => $documento->filial_id, + 'total_liquido' => (float) $documento->total_liquido, + 'subtotal' => (float) $documento->subtotal, + ]; + } + + private function registrarAuditoria( + string $acao, + DocumentoComercial $documento, + ?int $usuarioId, + ?array $dadosAntes, + ?array $dadosDepois + ): void { + AuditoriaLog::create([ + 'usuario_id' => $usuarioId, + 'acao' => $acao, + 'entidade_tipo' => 'DOCUMENTO_COMERCIAL', + 'entidade_id' => $documento->id, + 'dados_antes' => $dadosAntes, + 'dados_depois' => $dadosDepois, + ]); + } +} diff --git a/app/Services/Comercial/LegacyVendaImportService.php b/app/Services/Comercial/LegacyVendaImportService.php new file mode 100644 index 00000000..36f272c0 --- /dev/null +++ b/app/Services/Comercial/LegacyVendaImportService.php @@ -0,0 +1,267 @@ +resolverCliente($dados); + $filialId = (int) (Filial::query()->value('id') ?: Filial::create([ + 'nome' => 'Matriz', + 'codigo' => 'MAT', + 'ativa' => true, + ])->id); + $tabelaPrecoId = (int) (TabelaPreco::query()->where('codigo', 'VAREJO')->value('id') + ?: TabelaPreco::create([ + 'nome' => 'Tabela Varejo', + 'codigo' => 'VAREJO', + 'tipo' => 'VAREJO', + 'ativo' => true, + 'prioridade' => 0, + ])->id); + $numeroExterno = trim((string) ($dados['numero_externo'] ?? '')); + $numeroFiscal = $this->normalizarNumeroFiscal($numeroExterno ?: null); + $this->validarNaoDuplicado($numeroFiscal, $numeroExterno !== ''); + + $itens = []; + foreach ($dados['itens'] as $item) { + $produto = $this->resolverProduto($item, $tabelaPrecoId); + $itens[] = [ + 'produto_id' => $produto->id, + 'quantidade' => (float) $item['quantidade'], + 'preco_unitario' => (float) $item['preco_unitario'], + ]; + } + + $documento = $this->documentoService->create([ + 'tipo' => 'VENDA', + 'status' => 'FATURADO', + 'cliente_id' => $cliente->id, + 'filial_id' => $filialId, + 'tabela_preco_id' => $tabelaPrecoId, + 'data_emissao' => $dados['data_emissao'], + 'desconto_total' => (float) ($dados['desconto'] ?? 0), + 'acrescimo_total' => 0, + 'impostos_total' => 0, + 'observacoes' => $this->buildObservacoes($dados), + 'itens' => $itens, + 'reservar_estoque' => false, + 'usar_preco_informado_itens' => true, + ], $usuario); + + $this->ajustarTotaisImportados($documento, $dados); + + Faturamento::updateOrCreate( + ['documento_id' => $documento->id], + [ + 'numero_fiscal' => $numeroFiscal, + 'chave_acesso' => $dados['chave_acesso'] ?? null, + 'status_fiscal' => 'AUTORIZADO', + 'data_faturamento' => $dados['data_emissao'], + ] + ); + + ContaReceber::updateOrCreate( + ['documento_id' => $documento->id], + [ + 'cliente_id' => $cliente->id, + 'valor_original' => (float) ($dados['total'] ?? $documento->total_liquido), + 'valor_aberto' => 0, + 'vencimento' => now()->toDateString(), + 'status' => 'QUITADO', + ] + ); + + if (!empty($dados['forma_pagamento'])) { + DocumentoPagamento::create([ + 'documento_id' => $documento->id, + 'forma_pagamento' => Str::limit((string) $dados['forma_pagamento'], 50, ''), + 'valor' => (float) ($dados['total'] ?? $documento->total_liquido), + 'parcelas' => 1, + 'status' => 'AUTORIZADO', + 'data_pagamento' => $dados['data_emissao'], + 'metadata' => [ + 'origem' => 'PDF_LEGADO', + ], + ]); + } + + $documento->eventos()->create([ + 'status_anterior' => 'FATURADO', + 'status_novo' => 'FATURADO', + 'acao' => 'IMPORTACAO_PDF_LEGADO', + 'usuario_id' => $usuario->id, + 'data_evento' => now(), + 'detalhes' => [ + 'numero_externo' => $dados['numero_externo'] ?? null, + 'operador_legacy' => $dados['operador_nome'] ?? null, + ], + ]); + + return $documento->fresh(['cliente', 'itens', 'faturamento']); + }); + } + + private function resolverCliente(array $dados): Cliente + { + $doc = preg_replace('/\D/', '', (string) ($dados['cliente_cpf_cnpj'] ?? '')); + + if ($doc !== '') { + $clientePorDoc = Cliente::query()->whereRaw('REPLACE(REPLACE(REPLACE(cpf_cnpj, ".", ""), "-", ""), "/", "") = ?', [$doc])->first(); + if ($clientePorDoc) { + return $clientePorDoc; + } + } + + $clientePorNome = Cliente::query()->where('nome', trim((string) $dados['cliente_nome']))->first(); + if ($clientePorNome) { + return $clientePorNome; + } + + return Cliente::create([ + 'tipo_pessoa' => strlen($doc) === 14 ? 'PJ' : 'PF', + 'nome' => trim((string) $dados['cliente_nome']), + 'cpf_cnpj' => $doc !== '' ? $doc : (string) now()->format('YmdHisv'), + 'ativo' => true, + 'pais' => 'Brasil', + ]); + } + + private function resolverProduto(array $item, int $tabelaPrecoId): Produto + { + $ean = preg_replace('/\D/', '', (string) ($item['ean'] ?? '')); + $nome = trim((string) $item['nome']); + + if ($ean !== '') { + $porEan = Produto::query()->whereRaw('REPLACE(codigo_barras, " ", "") = ?', [$ean])->first(); + if ($porEan) { + return $porEan; + } + } + + $porNome = Produto::query()->where('nome', $nome)->first(); + if ($porNome) { + return $porNome; + } + + $categoriaId = (int) (CategoriaProduto::where('ativo', true)->value('id') ?: CategoriaProduto::create(['nome' => 'Geral', 'ativo' => true])->id); + $unidadeSigla = strtoupper((string) ($item['unidade'] ?? 'UN')); + $unidadeId = (int) (UnidadeMedida::where('sigla', $unidadeSigla)->value('id') ?: UnidadeMedida::create([ + 'sigla' => $unidadeSigla, + 'nome' => $unidadeSigla === 'UN' ? 'Unidade' : $unidadeSigla, + 'casas_decimais' => $unidadeSigla === 'UN' ? 0 : 3, + 'ativo' => true, + ])->id); + + $produto = Produto::create([ + 'sku' => 'LEG-' . Str::upper(Str::random(8)), + 'nome' => $nome, + 'descricao' => 'Importado de PDF legado', + 'codigo_barras' => $ean !== '' ? $ean : null, + 'categoria_id' => $categoriaId, + 'unidade_principal_id' => $unidadeId, + 'controla_lote' => false, + 'controla_validade' => false, + 'ativo' => true, + 'permite_venda' => true, + 'permite_compra' => true, + 'marca' => null, + ]); + + EstoqueSaldo::firstOrCreate( + ['produto_id' => $produto->id], + ['quantidade_atual' => 0, 'quantidade_reservada' => 0, 'estoque_minimo' => 0, 'updated_at' => now()] + ); + + ProdutoPreco::create([ + 'produto_id' => $produto->id, + 'tabela_preco_id' => $tabelaPrecoId, + 'preco' => (float) ($item['preco_unitario'] ?? 0), + 'custo_referencia' => 0, + 'margem_percentual' => null, + 'vigencia_inicio' => now(), + 'ativo' => true, + ]); + + return $produto; + } + + private function ajustarTotaisImportados(DocumentoComercial $documento, array $dados): void + { + $subtotal = (float) ($dados['subtotal'] ?? $documento->subtotal); + $desconto = (float) ($dados['desconto'] ?? 0); + $total = (float) ($dados['total'] ?? max(0, $subtotal - $desconto)); + + $documento->update([ + 'status' => 'FATURADO', + 'subtotal' => $subtotal, + 'desconto_total' => $desconto, + 'acrescimo_total' => 0, + 'impostos_total' => 0, + 'total_liquido' => $total, + ]); + } + + private function buildObservacoes(array $dados): string + { + $chunks = [ + 'Importado de PDF legado.', + ]; + + if (!empty($dados['numero_externo'])) { + $chunks[] = 'Numero externo: ' . $dados['numero_externo']; + } + + if (!empty($dados['operador_nome'])) { + $chunks[] = 'Operador legado: ' . $dados['operador_nome']; + } + + return implode(' ', $chunks); + } + + private function normalizarNumeroFiscal(?string $numeroExterno): string + { + $numeroExterno = trim((string) $numeroExterno); + if ($numeroExterno === '') { + return 'NF-LEG-' . now()->format('YmdHis') . '-' . random_int(100, 999); + } + + return Str::limit('NF-LEG-' . preg_replace('/[^A-Za-z0-9\-]/', '', $numeroExterno), 60, ''); + } + + private function validarNaoDuplicado(string $numeroFiscal, bool $possuiNumeroExterno): void + { + if (!$possuiNumeroExterno) { + return; + } + + if (Faturamento::query()->where('numero_fiscal', $numeroFiscal)->exists()) { + throw ValidationException::withMessages([ + 'arquivos' => "Venda legado ja importada para numero fiscal {$numeroFiscal}.", + ]); + } + } +} diff --git a/app/Services/Comercial/LegacyVendaPdfParser.php b/app/Services/Comercial/LegacyVendaPdfParser.php new file mode 100644 index 00000000..318d3784 --- /dev/null +++ b/app/Services/Comercial/LegacyVendaPdfParser.php @@ -0,0 +1,198 @@ +, + * texto:string + * } + */ + public function parse(UploadedFile $arquivo): array + { + $pdf = (new Parser())->parseFile($arquivo->getRealPath()); + $texto = preg_replace('/[ \t]+/', ' ', str_replace("\r", '', $pdf->getText() ?? '')); + $texto = preg_replace('/\n{2,}/', "\n", trim((string) $texto)); + + if ($texto === '') { + throw new RuntimeException('Nao foi possivel extrair texto do PDF.'); + } + + $linhas = array_values(array_filter(array_map('trim', explode("\n", $texto)), fn ($l) => $l !== '')); + + $dataEmissao = $this->extractDataEmissao($texto); + $numeroExterno = $this->extractNumeroExterno($texto); + $clienteNome = $this->extractByRegex($texto, '/Cliente:\s*(.+)/i'); + $clienteDoc = $this->onlyDigits($this->extractByRegex($texto, '/CPF\/?CNPJ:\s*([0-9\.\/-]+)/i')); + $operador = $this->extractByRegex($texto, '/Operador:\s*([^\(\n]+)/i'); + + if (!$clienteNome) { + throw new RuntimeException('Cliente nao identificado no PDF.'); + } + + [$itens, $subtotal, $desconto, $total, $formaPagamento] = $this->extractItensETotais($linhas, $texto); + + if (count($itens) === 0) { + throw new RuntimeException('Nenhum item foi identificado no PDF.'); + } + + return [ + 'numero_externo' => $numeroExterno, + 'data_emissao' => $dataEmissao, + 'cliente_nome' => $clienteNome, + 'cliente_cpf_cnpj' => $clienteDoc ?: null, + 'operador_nome' => $operador ?: null, + 'subtotal' => $subtotal, + 'desconto' => $desconto, + 'total' => $total, + 'forma_pagamento' => $formaPagamento, + 'itens' => $itens, + 'texto' => $texto, + ]; + } + + private function extractDataEmissao(string $texto): string + { + if (preg_match('/(\d{2}\/\d{2}\/\d{4})\s+(?:às|as)\s+(\d{2})h(\d{2})m/i', $texto, $m)) { + return Carbon::createFromFormat('d/m/Y H:i', "{$m[1]} {$m[2]}:{$m[3]}", 'America/Sao_Paulo') + ->setTimezone(config('app.timezone')) + ->format('Y-m-d H:i:s'); + } + + return now()->format('Y-m-d H:i:s'); + } + + private function extractNumeroExterno(string $texto): ?string + { + $numero = $this->extractByRegex($texto, '/N\.:\s*([^\n\r-]+(?:-[^\n\r]+)?)\s*-\s*\d{2}\/\d{2}\/\d{4}/i'); + if ($numero) { + return trim($numero); + } + + $prevenda = $this->extractByRegex($texto, '/PREVENDA\s+ID\/PDV:\s*([^\n\r]+)/i'); + return $prevenda ? trim($prevenda) : null; + } + + private function extractByRegex(string $texto, string $regex): ?string + { + return preg_match($regex, $texto, $m) ? trim((string) ($m[1] ?? '')) : null; + } + + /** + * @return array{0:array,1:float,2:float,3:float,4:string|null} + */ + private function extractItensETotais(array $linhas, string $texto): array + { + $inicio = null; + foreach ($linhas as $i => $linha) { + if (stripos($linha, 'Produto Qtd Valor Unit Sub-Total') !== false) { + $inicio = $i + 1; + break; + } + } + + if ($inicio === null) { + throw new RuntimeException('Secao de itens nao encontrada no PDF.'); + } + + $itens = []; + $atual = null; + + for ($i = $inicio; $i < count($linhas); $i++) { + $linha = trim($linhas[$i]); + + if (preg_match('/^Sub\s*Total\s+/i', $linha)) { + break; + } + + if (preg_match('/^\d+\s*-\s*(.+)$/', $linha, $m)) { + if ($atual && isset($atual['quantidade'])) { + $itens[] = $atual; + } + + $atual = [ + 'nome' => trim($m[1]), + 'ean' => null, + ]; + continue; + } + + if (!$atual) { + continue; + } + + if (preg_match('/^EAN:\s*([^\s]+)$/i', $linha, $m)) { + $atual['ean'] = $this->onlyDigits($m[1]); + continue; + } + + if (preg_match('/^(\d+(?:[\.,]\d+)?)\s+([A-Za-z]+)\s+(\d+[\.,]\d+)\s+(\d+[\.,]\d+)$/', $linha, $m)) { + $atual['quantidade'] = $this->toQuantidade($m[1]); + $atual['unidade'] = strtoupper($m[2]); + $atual['preco_unitario'] = $this->toFloat($m[3]); + $atual['subtotal'] = $this->toFloat($m[4]); + continue; + } + } + + if ($atual && isset($atual['quantidade'])) { + $itens[] = $atual; + } + + $subtotal = $this->toFloat($this->extractByRegex($texto, '/Sub\s*Total\s+([0-9\.,]+)/i') ?? '0'); + $desconto = $this->toFloat($this->extractByRegex($texto, '/Desconto\s*R\$\s*([0-9\.,]+)/i') ?? '0'); + $total = $this->toFloat($this->extractByRegex($texto, '/Total\s*R\$\s*([0-9\.,]+)/i') ?? '0'); + $forma = $this->extractByRegex($texto, '/Pagamento\(s\)\s*=>\s*([A-Za-z0-9\s\-\.]+)R\$/i'); + + return [$itens, $subtotal, $desconto, $total, $forma ? trim($forma) : null]; + } + + private function toFloat(string $valor): float + { + $valor = trim($valor); + + if (str_contains($valor, ',')) { + $valor = str_replace('.', '', $valor); + $valor = str_replace(',', '.', $valor); + return (float) $valor; + } + + if (substr_count($valor, '.') > 1) { + return (float) str_replace('.', '', $valor); + } + + return (float) $valor; + } + + private function toQuantidade(string $valor): float + { + $valor = trim($valor); + + if (!str_contains($valor, ',') && preg_match('/^\d+\.\d{3}$/', $valor)) { + return (float) $valor; + } + + return $this->toFloat($valor); + } + + private function onlyDigits(?string $value): string + { + return preg_replace('/\D/', '', (string) $value) ?: ''; + } +} diff --git a/app/Services/Compras/CompraService.php b/app/Services/Compras/CompraService.php new file mode 100644 index 00000000..ebe87721 --- /dev/null +++ b/app/Services/Compras/CompraService.php @@ -0,0 +1,134 @@ + $this->gerarNumero(), + 'fornecedor_id' => $data['fornecedor_id'], + 'usuario_id' => $usuario->id, + 'filial_id' => $data['filial_id'] ?? Filial::query()->value('id'), + 'data_compra' => $data['data_compra'] ?? now(), + 'status' => $data['status'] ?? 'CONFIRMADA', + 'valor_total' => 0, + 'observacoes' => $data['observacoes'] ?? null, + ]); + + $total = 0; + + foreach ($data['itens'] as $index => $item) { + $produto = Produto::findOrFail((int) $item['produto_id']); + $quantidade = (float) $item['quantidade']; + $precoUnitario = (float) $item['preco_unitario']; + $subtotal = round($quantidade * $precoUnitario, 2); + $total += $subtotal; + + $compraItem = $compra->itens()->create([ + 'sequencia' => $index + 1, + 'produto_id' => $produto->id, + 'quantidade' => $quantidade, + 'preco_unitario' => $precoUnitario, + 'subtotal' => $subtotal, + 'numero_lote' => $item['numero_lote'] ?? null, + 'data_validade' => $item['data_validade'] ?? null, + ]); + + if ($compra->status === 'CONFIRMADA') { + $this->entradaEstoque($compra, $compraItem->produto_id, $quantidade, $usuario->id, $item['numero_lote'] ?? null, $item['data_validade'] ?? null); + } + } + + $compra->update(['valor_total' => round($total, 2)]); + + ContaPagar::create([ + 'compra_id' => $compra->id, + 'fornecedor_id' => $compra->fornecedor_id, + 'valor_original' => round($total, 2), + 'valor_aberto' => round($total, 2), + 'vencimento' => $data['vencimento'] ?? now()->addDays(30)->toDateString(), + 'status' => round($total, 2) > 0 ? 'ABERTO' : 'QUITADO', + ]); + + AuditoriaLog::create([ + 'usuario_id' => $usuario->id, + 'acao' => 'COMPRA_CRIADA', + 'entidade_tipo' => 'COMPRA', + 'entidade_id' => $compra->id, + 'dados_antes' => null, + 'dados_depois' => [ + 'numero' => $compra->numero, + 'fornecedor_id' => $compra->fornecedor_id, + 'valor_total' => (float) $compra->valor_total, + 'status' => $compra->status, + ], + ]); + + return $compra->fresh(['fornecedor', 'itens.produto', 'contaPagar']); + }); + } + + private function entradaEstoque(Compra $compra, int $produtoId, float $quantidade, int $userId, ?string $numeroLote, ?string $dataValidade): void + { + $saldo = EstoqueSaldo::lockForUpdate()->firstOrCreate( + ['produto_id' => $produtoId], + ['quantidade_atual' => 0, 'quantidade_reservada' => 0, 'estoque_minimo' => 0, 'updated_at' => now()] + ); + + $novoSaldo = round((float) $saldo->quantidade_atual + $quantidade, 3); + $saldo->update([ + 'quantidade_atual' => $novoSaldo, + 'updated_at' => now(), + ]); + + $loteId = null; + if ($numeroLote || $dataValidade) { + $lote = EstoqueLote::create([ + 'produto_id' => $produtoId, + 'lote' => $numeroLote ?: 'SEM-LOTE', + 'serial' => null, + 'validade' => $dataValidade, + 'quantidade_disponivel' => $quantidade, + 'custo_unitario' => null, + ]); + $loteId = $lote->id; + } + + EstoqueMovimentacao::create([ + 'produto_id' => $produtoId, + 'estoque_lote_id' => $loteId, + 'estoque_reserva_id' => null, + 'tipo' => 'ENTRADA', + 'origem' => 'COMPRA', + 'origem_tipo' => 'COMPRA', + 'origem_id' => $compra->id, + 'documento_ref' => $compra->numero, + 'quantidade' => $quantidade, + 'sinal' => 1, + 'saldo_apos' => $novoSaldo, + 'observacao' => "Entrada por compra {$compra->numero}", + 'user_id' => $userId, + 'created_at' => now(), + ]); + } + + private function gerarNumero(): string + { + $ultimo = Compra::query()->max('id') ?? 0; + return sprintf('CMP-%s-%06d', now()->format('Ymd'), $ultimo + 1); + } +} diff --git a/app/View/Components/AppLayout.php b/app/View/Components/AppLayout.php new file mode 100644 index 00000000..de0d46f5 --- /dev/null +++ b/app/View/Components/AppLayout.php @@ -0,0 +1,17 @@ +withRouting( @@ -11,8 +12,10 @@ health: '/up', ) ->withMiddleware(function (Middleware $middleware) { - // + $middleware->alias([ + 'perm' => EnsurePermission::class, + ]); }) ->withExceptions(function (Exceptions $exceptions) { // - })->create(); \ No newline at end of file + })->create(); diff --git a/composer.json b/composer.json index d72197db..04b04115 100644 --- a/composer.json +++ b/composer.json @@ -11,10 +11,13 @@ "require": { "php": "^8.2", "laravel/framework": "^12.0", - "laravel/tinker": "^2.10.1" + "laravel/tinker": "^2.10.1", + "phpoffice/phpspreadsheet": "^5.5", + "smalot/pdfparser": "^2.12" }, "require-dev": { "fakerphp/faker": "^1.23", + "laravel/breeze": "^2.4", "laravel/pail": "^1.2.2", "laravel/pint": "^1.13", "laravel/sail": "^1.41", diff --git a/composer.lock b/composer.lock index ce47bbfd..e8c65913 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "88970a0117c062eed55fa8728fc43833", + "content-hash": "e7a7d582fef3a83b722f8e97ae484691", "packages": [ { "name": "brick/math", @@ -135,6 +135,85 @@ ], "time": "2024-02-09T16:56:22+00:00" }, + { + "name": "composer/pcre", + "version": "3.3.2", + "source": { + "type": "git", + "url": "https://github.com/composer/pcre.git", + "reference": "b2bed4734f0cc156ee1fe9c0da2550420d99a21e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/pcre/zipball/b2bed4734f0cc156ee1fe9c0da2550420d99a21e", + "reference": "b2bed4734f0cc156ee1fe9c0da2550420d99a21e", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0" + }, + "conflict": { + "phpstan/phpstan": "<1.11.10" + }, + "require-dev": { + "phpstan/phpstan": "^1.12 || ^2", + "phpstan/phpstan-strict-rules": "^1 || ^2", + "phpunit/phpunit": "^8 || ^9" + }, + "type": "library", + "extra": { + "phpstan": { + "includes": [ + "extension.neon" + ] + }, + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Pcre\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "keywords": [ + "PCRE", + "preg", + "regex", + "regular expression" + ], + "support": { + "issues": "https://github.com/composer/pcre/issues", + "source": "https://github.com/composer/pcre/tree/3.3.2" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2024-11-12T16:29:46+00:00" + }, { "name": "dflydev/dot-access-data", "version": "v3.0.3", @@ -2009,6 +2088,191 @@ ], "time": "2024-12-08T08:18:47+00:00" }, + { + "name": "maennchen/zipstream-php", + "version": "3.2.1", + "source": { + "type": "git", + "url": "https://github.com/maennchen/ZipStream-PHP.git", + "reference": "682f1098a8fddbaf43edac2306a691c7ad508ec5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/maennchen/ZipStream-PHP/zipball/682f1098a8fddbaf43edac2306a691c7ad508ec5", + "reference": "682f1098a8fddbaf43edac2306a691c7ad508ec5", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "ext-zlib": "*", + "php-64bit": "^8.3" + }, + "require-dev": { + "brianium/paratest": "^7.7", + "ext-zip": "*", + "friendsofphp/php-cs-fixer": "^3.86", + "guzzlehttp/guzzle": "^7.5", + "mikey179/vfsstream": "^1.6", + "php-coveralls/php-coveralls": "^2.5", + "phpunit/phpunit": "^12.0", + "vimeo/psalm": "^6.0" + }, + "suggest": { + "guzzlehttp/psr7": "^2.4", + "psr/http-message": "^2.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "ZipStream\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paul Duncan", + "email": "pabs@pablotron.org" + }, + { + "name": "Jonatan Männchen", + "email": "jonatan@maennchen.ch" + }, + { + "name": "Jesse Donat", + "email": "donatj@gmail.com" + }, + { + "name": "András Kolesár", + "email": "kolesar@kolesar.hu" + } + ], + "description": "ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server.", + "keywords": [ + "stream", + "zip" + ], + "support": { + "issues": "https://github.com/maennchen/ZipStream-PHP/issues", + "source": "https://github.com/maennchen/ZipStream-PHP/tree/3.2.1" + }, + "funding": [ + { + "url": "https://github.com/maennchen", + "type": "github" + } + ], + "time": "2025-12-10T09:58:31+00:00" + }, + { + "name": "markbaker/complex", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/MarkBaker/PHPComplex.git", + "reference": "95c56caa1cf5c766ad6d65b6344b807c1e8405b9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/MarkBaker/PHPComplex/zipball/95c56caa1cf5c766ad6d65b6344b807c1e8405b9", + "reference": "95c56caa1cf5c766ad6d65b6344b807c1e8405b9", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "dev-master", + "phpcompatibility/php-compatibility": "^9.3", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0", + "squizlabs/php_codesniffer": "^3.7" + }, + "type": "library", + "autoload": { + "psr-4": { + "Complex\\": "classes/src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mark Baker", + "email": "mark@lange.demon.co.uk" + } + ], + "description": "PHP Class for working with complex numbers", + "homepage": "https://github.com/MarkBaker/PHPComplex", + "keywords": [ + "complex", + "mathematics" + ], + "support": { + "issues": "https://github.com/MarkBaker/PHPComplex/issues", + "source": "https://github.com/MarkBaker/PHPComplex/tree/3.0.2" + }, + "time": "2022-12-06T16:21:08+00:00" + }, + { + "name": "markbaker/matrix", + "version": "3.0.1", + "source": { + "type": "git", + "url": "https://github.com/MarkBaker/PHPMatrix.git", + "reference": "728434227fe21be27ff6d86621a1b13107a2562c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/MarkBaker/PHPMatrix/zipball/728434227fe21be27ff6d86621a1b13107a2562c", + "reference": "728434227fe21be27ff6d86621a1b13107a2562c", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "dev-master", + "phpcompatibility/php-compatibility": "^9.3", + "phpdocumentor/phpdocumentor": "2.*", + "phploc/phploc": "^4.0", + "phpmd/phpmd": "2.*", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0", + "sebastian/phpcpd": "^4.0", + "squizlabs/php_codesniffer": "^3.7" + }, + "type": "library", + "autoload": { + "psr-4": { + "Matrix\\": "classes/src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mark Baker", + "email": "mark@demon-angel.eu" + } + ], + "description": "PHP Class for working with matrices", + "homepage": "https://github.com/MarkBaker/PHPMatrix", + "keywords": [ + "mathematics", + "matrix", + "vector" + ], + "support": { + "issues": "https://github.com/MarkBaker/PHPMatrix/issues", + "source": "https://github.com/MarkBaker/PHPMatrix/tree/3.0.1" + }, + "time": "2022-12-02T22:17:43+00:00" + }, { "name": "monolog/monolog", "version": "3.9.0", @@ -2513,6 +2777,115 @@ ], "time": "2025-05-08T08:14:37+00:00" }, + { + "name": "phpoffice/phpspreadsheet", + "version": "5.5.0", + "source": { + "type": "git", + "url": "https://github.com/PHPOffice/PhpSpreadsheet.git", + "reference": "eecd31b885a1c8192f12738130f85bbc6e8906ba" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/eecd31b885a1c8192f12738130f85bbc6e8906ba", + "reference": "eecd31b885a1c8192f12738130f85bbc6e8906ba", + "shasum": "" + }, + "require": { + "composer/pcre": "^1||^2||^3", + "ext-ctype": "*", + "ext-dom": "*", + "ext-fileinfo": "*", + "ext-filter": "*", + "ext-gd": "*", + "ext-iconv": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-simplexml": "*", + "ext-xml": "*", + "ext-xmlreader": "*", + "ext-xmlwriter": "*", + "ext-zip": "*", + "ext-zlib": "*", + "maennchen/zipstream-php": "^2.1 || ^3.0", + "markbaker/complex": "^3.0", + "markbaker/matrix": "^3.0", + "php": "^8.1", + "psr/simple-cache": "^1.0 || ^2.0 || ^3.0" + }, + "require-dev": { + "dealerdirect/phpcodesniffer-composer-installer": "dev-main", + "dompdf/dompdf": "^2.0 || ^3.0", + "ext-intl": "*", + "friendsofphp/php-cs-fixer": "^3.2", + "mitoteam/jpgraph": "^10.5", + "mpdf/mpdf": "^8.1.1", + "phpcompatibility/php-compatibility": "^9.3", + "phpstan/phpstan": "^1.1 || ^2.0", + "phpstan/phpstan-deprecation-rules": "^1.0 || ^2.0", + "phpstan/phpstan-phpunit": "^1.0 || ^2.0", + "phpunit/phpunit": "^10.5", + "squizlabs/php_codesniffer": "^3.7", + "tecnickcom/tcpdf": "^6.5" + }, + "suggest": { + "dompdf/dompdf": "Option for rendering PDF with PDF Writer", + "ext-intl": "PHP Internationalization Functions, required for NumberFormat Wizard and StringHelper::setLocale()", + "mitoteam/jpgraph": "Option for rendering charts, or including charts with PDF or HTML Writers", + "mpdf/mpdf": "Option for rendering PDF with PDF Writer", + "tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer" + }, + "type": "library", + "autoload": { + "psr-4": { + "PhpOffice\\PhpSpreadsheet\\": "src/PhpSpreadsheet" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Maarten Balliauw", + "homepage": "https://blog.maartenballiauw.be" + }, + { + "name": "Mark Baker", + "homepage": "https://markbakeruk.net" + }, + { + "name": "Franck Lefevre", + "homepage": "https://rootslabs.net" + }, + { + "name": "Erik Tilt" + }, + { + "name": "Adrien Crivelli" + }, + { + "name": "Owen Leibman" + } + ], + "description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine", + "homepage": "https://github.com/PHPOffice/PhpSpreadsheet", + "keywords": [ + "OpenXML", + "excel", + "gnumeric", + "ods", + "php", + "spreadsheet", + "xls", + "xlsx" + ], + "support": { + "issues": "https://github.com/PHPOffice/PhpSpreadsheet/issues", + "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/5.5.0" + }, + "time": "2026-03-01T00:58:56+00:00" + }, { "name": "phpoption/phpoption", "version": "1.9.4", @@ -3276,6 +3649,57 @@ }, "time": "2025-09-04T20:59:21+00:00" }, + { + "name": "smalot/pdfparser", + "version": "v2.12.4", + "source": { + "type": "git", + "url": "https://github.com/smalot/pdfparser.git", + "reference": "028d7cc0ceff323bc001d763caa2bbdf611866c4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/smalot/pdfparser/zipball/028d7cc0ceff323bc001d763caa2bbdf611866c4", + "reference": "028d7cc0ceff323bc001d763caa2bbdf611866c4", + "shasum": "" + }, + "require": { + "ext-iconv": "*", + "ext-zlib": "*", + "php": ">=7.1", + "symfony/polyfill-mbstring": "^1.18" + }, + "type": "library", + "autoload": { + "psr-0": { + "Smalot\\PdfParser\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0" + ], + "authors": [ + { + "name": "Sebastien MALOT", + "email": "sebastien@malot.fr" + } + ], + "description": "Pdf parser library. Can read and extract information from pdf file.", + "homepage": "https://www.pdfparser.org", + "keywords": [ + "extract", + "parse", + "parser", + "pdf", + "text" + ], + "support": { + "issues": "https://github.com/smalot/pdfparser/issues", + "source": "https://github.com/smalot/pdfparser/tree/v2.12.4" + }, + "time": "2026-03-10T15:39:47+00:00" + }, { "name": "symfony/clock", "version": "v7.3.0", @@ -6211,6 +6635,67 @@ }, "time": "2025-04-30T06:54:44+00:00" }, + { + "name": "laravel/breeze", + "version": "v2.4.1", + "source": { + "type": "git", + "url": "https://github.com/laravel/breeze.git", + "reference": "28cefeaf6af20177ddf5cc7b93e87e4ad79d533f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/breeze/zipball/28cefeaf6af20177ddf5cc7b93e87e4ad79d533f", + "reference": "28cefeaf6af20177ddf5cc7b93e87e4ad79d533f", + "shasum": "" + }, + "require": { + "illuminate/console": "^11.0|^12.0|^13.0", + "illuminate/filesystem": "^11.0|^12.0|^13.0", + "illuminate/support": "^11.0|^12.0|^13.0", + "illuminate/validation": "^11.0|^12.0|^13.0", + "php": "^8.2.0", + "symfony/console": "^7.0|^8.0" + }, + "require-dev": { + "laravel/framework": "^11.0|^12.0|^13.0", + "orchestra/testbench-core": "^9.0|^10.0|^11.0", + "phpstan/phpstan": "^2.0" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Laravel\\Breeze\\BreezeServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Laravel\\Breeze\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Minimal Laravel authentication scaffolding with Blade and Tailwind.", + "keywords": [ + "auth", + "laravel" + ], + "support": { + "issues": "https://github.com/laravel/breeze/issues", + "source": "https://github.com/laravel/breeze" + }, + "time": "2026-03-10T19:59:01+00:00" + }, { "name": "laravel/pail", "version": "v1.2.3", @@ -8390,12 +8875,12 @@ ], "aliases": [], "minimum-stability": "stable", - "stability-flags": [], + "stability-flags": {}, "prefer-stable": true, "prefer-lowest": false, "platform": { "php": "^8.2" }, - "platform-dev": [], - "plugin-api-version": "2.6.0" + "platform-dev": {}, + "plugin-api-version": "2.9.0" } diff --git a/config/brasil.php b/config/brasil.php new file mode 100644 index 00000000..a6e1b973 --- /dev/null +++ b/config/brasil.php @@ -0,0 +1,33 @@ + [ + 'AC' => 'Acre', + 'AL' => 'Alagoas', + 'AP' => 'Amapa', + 'AM' => 'Amazonas', + 'BA' => 'Bahia', + 'CE' => 'Ceara', + 'DF' => 'Distrito Federal', + 'ES' => 'Espirito Santo', + 'GO' => 'Goias', + 'MA' => 'Maranhao', + 'MT' => 'Mato Grosso', + 'MS' => 'Mato Grosso do Sul', + 'MG' => 'Minas Gerais', + 'PA' => 'Para', + 'PB' => 'Paraiba', + 'PR' => 'Parana', + 'PE' => 'Pernambuco', + 'PI' => 'Piaui', + 'RJ' => 'Rio de Janeiro', + 'RN' => 'Rio Grande do Norte', + 'RS' => 'Rio Grande do Sul', + 'RO' => 'Rondonia', + 'RR' => 'Roraima', + 'SC' => 'Santa Catarina', + 'SP' => 'Sao Paulo', + 'SE' => 'Sergipe', + 'TO' => 'Tocantins', + ], +]; diff --git a/config/rbac.php b/config/rbac.php new file mode 100644 index 00000000..800cc76d --- /dev/null +++ b/config/rbac.php @@ -0,0 +1,60 @@ + [ + 'OPERADOR' => [ + 'dashboard.view', + 'clientes.view', + 'clientes.manage', + 'produtos.view', + 'produtos.manage', + 'vendas.documentos.view', + 'vendas.documentos.manage', + 'vendas.documentos.converter', + 'vendas.pdv.use', + 'compras.fornecedores.view', + 'compras.compras.view', + 'estoque.movimentacoes.view', + 'estoque.movimentacoes.manage', + 'financeiro.contas_receber.view', + 'financeiro.contas_receber.baixar', + 'financeiro.contas_pagar.view', + 'financeiro.contas_pagar.pagar', + 'usuarios.view', + ], + 'GERENTE' => [ + 'dashboard.view', + 'clientes.view', + 'clientes.manage', + 'produtos.view', + 'produtos.manage', + 'vendas.documentos.view', + 'vendas.documentos.manage', + 'vendas.documentos.converter', + 'vendas.documentos.faturar', + 'vendas.documentos.cancelar', + 'vendas.documentos.importar_legado', + 'vendas.pdv.use', + 'estoque.movimentacoes.view', + 'estoque.movimentacoes.manage', + 'estoque.alertas.view', + 'cadastros_base.view', + 'cadastros_base.manage', + 'compras.fornecedores.view', + 'compras.fornecedores.manage', + 'compras.compras.view', + 'compras.compras.manage', + 'financeiro.contas_receber.view', + 'financeiro.contas_receber.baixar', + 'financeiro.contas_receber.estornar', + 'financeiro.contas_pagar.view', + 'financeiro.contas_pagar.pagar', + 'financeiro.contas_pagar.estornar', + 'usuarios.view', + 'auditoria.view', + ], + 'ADMIN' => [ + '*', + ], + ], +]; diff --git a/config/variables.php b/config/variables.php index 8b462090..1c3bcd19 100644 --- a/config/variables.php +++ b/config/variables.php @@ -3,8 +3,8 @@ return [ "creatorName" => "ThemeSelection", "creatorUrl" => "https://themeselection.com", - "templateName" => "sneat", - "templateSuffix" => "Sneat Bootstrap Dashboard FREE", + "templateName" => "JBTINTAS", + "templateSuffix" => "Painel Administrativo", "templateVersion" => "2.0.0", "templateFree" => true, "templateDescription" => "Most Powerful & Comprehensive Bootstrap 5 + Laravel HTML Admin Dashboard Template built for developers!", @@ -28,4 +28,4 @@ "githubUrl" => "https://github.com/themeselection", "dribbbleUrl" => "https://dribbble.com/themeselection", "instagramUrl" => "https://www.instagram.com/themeselection/" -]; \ No newline at end of file +]; diff --git a/database/migrations/2026_03_19_000003_create_clientes_table.php b/database/migrations/2026_03_19_000003_create_clientes_table.php new file mode 100644 index 00000000..21222635 --- /dev/null +++ b/database/migrations/2026_03_19_000003_create_clientes_table.php @@ -0,0 +1,45 @@ +id(); + $table->string('codigo', 20)->nullable()->unique(); + $table->enum('tipo_pessoa', ['PF', 'PJ'])->index(); + $table->string('nome'); + $table->string('nome_fantasia')->nullable(); + $table->string('cpf_cnpj', 18)->unique(); + $table->string('rg_ie', 30)->nullable(); + $table->string('email')->nullable()->unique(); + $table->string('telefone', 20)->nullable(); + $table->string('celular', 20)->nullable(); + $table->string('contato_nome', 120)->nullable(); + $table->string('cep', 9)->nullable()->index(); + $table->string('logradouro')->nullable(); + $table->string('numero', 20)->nullable(); + $table->string('complemento', 120)->nullable(); + $table->string('bairro', 120)->nullable(); + $table->string('cidade', 120)->nullable()->index(); + $table->char('uf', 2)->nullable()->index(); + $table->string('codigo_ibge', 10)->nullable(); + $table->string('pais', 80)->default('Brasil'); + $table->date('data_nascimento_fundacao')->nullable(); + $table->enum('sexo', ['M', 'F', 'N'])->nullable(); + $table->text('observacoes')->nullable(); + $table->boolean('ativo')->default(true)->index(); + $table->decimal('saldo_credito', 12, 2)->default(0); + $table->decimal('limite_prazo', 12, 2)->default(0); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('clientes'); + } +}; diff --git a/database/migrations/2026_03_19_000004_create_categorias_produto_table.php b/database/migrations/2026_03_19_000004_create_categorias_produto_table.php new file mode 100644 index 00000000..69a12890 --- /dev/null +++ b/database/migrations/2026_03_19_000004_create_categorias_produto_table.php @@ -0,0 +1,31 @@ +id(); + $table->string('nome', 120)->unique(); + $table->boolean('ativo')->default(true); + $table->timestamps(); + }); + + DB::table('categorias_produto')->insert([ + ['nome' => 'Tinta Acrilica', 'ativo' => true, 'created_at' => now(), 'updated_at' => now()], + ['nome' => 'Solvente', 'ativo' => true, 'created_at' => now(), 'updated_at' => now()], + ['nome' => 'Pincel', 'ativo' => true, 'created_at' => now(), 'updated_at' => now()], + ['nome' => 'Rolo', 'ativo' => true, 'created_at' => now(), 'updated_at' => now()], + ['nome' => 'Acessorio', 'ativo' => true, 'created_at' => now(), 'updated_at' => now()], + ]); + } + + public function down(): void + { + Schema::dropIfExists('categorias_produto'); + } +}; diff --git a/database/migrations/2026_03_19_000005_create_unidades_medida_table.php b/database/migrations/2026_03_19_000005_create_unidades_medida_table.php new file mode 100644 index 00000000..2d6631d4 --- /dev/null +++ b/database/migrations/2026_03_19_000005_create_unidades_medida_table.php @@ -0,0 +1,32 @@ +id(); + $table->string('sigla', 20)->unique(); + $table->string('nome', 80); + $table->unsignedTinyInteger('casas_decimais')->default(3); + $table->boolean('ativo')->default(true); + $table->timestamps(); + }); + + DB::table('unidades_medida')->insert([ + ['sigla' => 'UN', 'nome' => 'Unidade', 'casas_decimais' => 0, 'ativo' => true, 'created_at' => now(), 'updated_at' => now()], + ['sigla' => 'L', 'nome' => 'Litro', 'casas_decimais' => 3, 'ativo' => true, 'created_at' => now(), 'updated_at' => now()], + ['sigla' => 'GL3.6', 'nome' => 'Galao 3.6L', 'casas_decimais' => 3, 'ativo' => true, 'created_at' => now(), 'updated_at' => now()], + ['sigla' => 'LT18', 'nome' => 'Lata 18L', 'casas_decimais' => 3, 'ativo' => true, 'created_at' => now(), 'updated_at' => now()], + ]); + } + + public function down(): void + { + Schema::dropIfExists('unidades_medida'); + } +}; diff --git a/database/migrations/2026_03_19_000006_create_tabelas_preco_table.php b/database/migrations/2026_03_19_000006_create_tabelas_preco_table.php new file mode 100644 index 00000000..cd9cbdfa --- /dev/null +++ b/database/migrations/2026_03_19_000006_create_tabelas_preco_table.php @@ -0,0 +1,38 @@ +id(); + $table->string('nome', 120)->unique(); + $table->string('codigo', 40)->unique(); + $table->enum('tipo', ['VAREJO', 'ATACADO', 'PROMOCAO', 'ESPECIAL']); + $table->boolean('ativo')->default(true); + $table->smallInteger('prioridade')->default(0); + $table->timestamps(); + }); + + DB::table('tabelas_preco')->insert([ + [ + 'nome' => 'Tabela Varejo', + 'codigo' => 'VAREJO', + 'tipo' => 'VAREJO', + 'ativo' => true, + 'prioridade' => 0, + 'created_at' => now(), + 'updated_at' => now(), + ], + ]); + } + + public function down(): void + { + Schema::dropIfExists('tabelas_preco'); + } +}; diff --git a/database/migrations/2026_03_19_000007_create_produtos_table.php b/database/migrations/2026_03_19_000007_create_produtos_table.php new file mode 100644 index 00000000..48646c95 --- /dev/null +++ b/database/migrations/2026_03_19_000007_create_produtos_table.php @@ -0,0 +1,36 @@ +id(); + $table->string('sku', 40)->unique(); + $table->string('nome')->index(); + $table->text('descricao')->nullable(); + $table->string('codigo_barras', 50)->nullable()->unique(); + $table->foreignId('categoria_id')->constrained('categorias_produto'); + $table->foreignId('unidade_principal_id')->constrained('unidades_medida'); + $table->boolean('controla_lote')->default(false); + $table->boolean('controla_validade')->default(false); + $table->boolean('ativo')->default(true)->index(); + $table->boolean('permite_venda')->default(true); + $table->boolean('permite_compra')->default(true); + $table->string('ncm', 20)->nullable()->index(); + $table->string('cest', 20)->nullable()->index(); + $table->string('marca', 120)->nullable(); + $table->text('observacoes')->nullable(); + $table->timestamps(); + $table->softDeletes(); + }); + } + + public function down(): void + { + Schema::dropIfExists('produtos'); + } +}; diff --git a/database/migrations/2026_03_19_000008_create_produto_unidades_table.php b/database/migrations/2026_03_19_000008_create_produto_unidades_table.php new file mode 100644 index 00000000..a66d1ab6 --- /dev/null +++ b/database/migrations/2026_03_19_000008_create_produto_unidades_table.php @@ -0,0 +1,27 @@ +id(); + $table->foreignId('produto_id')->constrained('produtos')->cascadeOnDelete(); + $table->foreignId('unidade_id')->constrained('unidades_medida'); + $table->decimal('fator_conversao', 12, 4); + $table->string('codigo_barras', 50)->nullable()->unique(); + $table->boolean('ativo')->default(true); + $table->timestamps(); + + $table->unique(['produto_id', 'unidade_id']); + }); + } + + public function down(): void + { + Schema::dropIfExists('produto_unidades'); + } +}; diff --git a/database/migrations/2026_03_19_000009_create_estoque_saldos_table.php b/database/migrations/2026_03_19_000009_create_estoque_saldos_table.php new file mode 100644 index 00000000..e88a3598 --- /dev/null +++ b/database/migrations/2026_03_19_000009_create_estoque_saldos_table.php @@ -0,0 +1,23 @@ +id(); + $table->foreignId('produto_id')->unique()->constrained('produtos')->cascadeOnDelete(); + $table->decimal('quantidade_atual', 14, 3)->default(0); + $table->decimal('estoque_minimo', 14, 3)->default(0); + $table->timestamp('updated_at')->nullable(); + }); + } + + public function down(): void + { + Schema::dropIfExists('estoque_saldos'); + } +}; diff --git a/database/migrations/2026_03_19_000010_create_estoque_lotes_table.php b/database/migrations/2026_03_19_000010_create_estoque_lotes_table.php new file mode 100644 index 00000000..1c693ef2 --- /dev/null +++ b/database/migrations/2026_03_19_000010_create_estoque_lotes_table.php @@ -0,0 +1,29 @@ +id(); + $table->foreignId('produto_id')->constrained('produtos')->cascadeOnDelete(); + $table->string('lote', 80); + $table->string('serial', 120)->nullable(); + $table->date('validade')->nullable()->index(); + $table->decimal('quantidade_disponivel', 14, 3)->default(0); + $table->decimal('custo_unitario', 12, 4)->nullable(); + $table->timestamps(); + + $table->unique(['produto_id', 'lote', 'serial']); + $table->index(['produto_id', 'lote']); + }); + } + + public function down(): void + { + Schema::dropIfExists('estoque_lotes'); + } +}; diff --git a/database/migrations/2026_03_19_000011_create_estoque_movimentacoes_table.php b/database/migrations/2026_03_19_000011_create_estoque_movimentacoes_table.php new file mode 100644 index 00000000..dec54e08 --- /dev/null +++ b/database/migrations/2026_03_19_000011_create_estoque_movimentacoes_table.php @@ -0,0 +1,30 @@ +id(); + $table->foreignId('produto_id')->constrained('produtos')->cascadeOnDelete(); + $table->foreignId('estoque_lote_id')->nullable()->constrained('estoque_lotes')->nullOnDelete(); + $table->enum('tipo', ['ENTRADA', 'SAIDA', 'AJUSTE'])->index(); + $table->string('origem', 40); + $table->string('documento_ref', 80)->nullable()->index(); + $table->decimal('quantidade', 14, 3); + $table->smallInteger('sinal'); + $table->decimal('saldo_apos', 14, 3); + $table->text('observacao')->nullable(); + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->timestamp('created_at')->useCurrent(); + }); + } + + public function down(): void + { + Schema::dropIfExists('estoque_movimentacoes'); + } +}; diff --git a/database/migrations/2026_03_19_000012_create_produto_precos_table.php b/database/migrations/2026_03_19_000012_create_produto_precos_table.php new file mode 100644 index 00000000..601b499a --- /dev/null +++ b/database/migrations/2026_03_19_000012_create_produto_precos_table.php @@ -0,0 +1,31 @@ +id(); + $table->foreignId('produto_id')->constrained('produtos')->cascadeOnDelete(); + $table->foreignId('tabela_preco_id')->constrained('tabelas_preco'); + $table->decimal('preco', 12, 4); + $table->decimal('custo_referencia', 12, 4)->nullable(); + $table->decimal('margem_percentual', 7, 4)->nullable(); + $table->dateTime('vigencia_inicio')->nullable(); + $table->dateTime('vigencia_fim')->nullable(); + $table->boolean('ativo')->default(true); + $table->timestamps(); + + $table->unique(['produto_id', 'tabela_preco_id', 'vigencia_inicio'], 'produto_preco_vigencia_unique'); + $table->index(['produto_id', 'tabela_preco_id', 'ativo']); + }); + } + + public function down(): void + { + Schema::dropIfExists('produto_precos'); + } +}; diff --git a/database/migrations/2026_03_20_000013_create_filiais_table.php b/database/migrations/2026_03_20_000013_create_filiais_table.php new file mode 100644 index 00000000..bf7afaa0 --- /dev/null +++ b/database/migrations/2026_03_20_000013_create_filiais_table.php @@ -0,0 +1,32 @@ +id(); + $table->string('nome', 120); + $table->string('codigo', 30)->unique(); + $table->boolean('ativa')->default(true); + $table->timestamps(); + }); + + DB::table('filiais')->insert([ + 'nome' => 'Matriz', + 'codigo' => 'MAT', + 'ativa' => true, + 'created_at' => now(), + 'updated_at' => now(), + ]); + } + + public function down(): void + { + Schema::dropIfExists('filiais'); + } +}; diff --git a/database/migrations/2026_03_20_000014_create_documentos_comerciais_table.php b/database/migrations/2026_03_20_000014_create_documentos_comerciais_table.php new file mode 100644 index 00000000..b8434b84 --- /dev/null +++ b/database/migrations/2026_03_20_000014_create_documentos_comerciais_table.php @@ -0,0 +1,47 @@ +id(); + $table->string('numero', 30)->unique(); + $table->enum('tipo', ['ORCAMENTO', 'PREVENDA', 'PEDIDO', 'VENDA'])->index(); + $table->enum('status', [ + 'RASCUNHO', + 'PENDENTE', + 'AGUARDANDO_PAGAMENTO', + 'EM_SEPARACAO', + 'AGUARDANDO_FATURAMENTO', + 'CONCLUIDO', + 'FATURADO', + 'CANCELADO', + ])->index(); + $table->foreignId('documento_origem_id')->nullable()->constrained('documentos_comerciais')->nullOnDelete(); + $table->foreignId('cliente_id')->constrained('clientes'); + $table->foreignId('vendedor_id')->constrained('users'); + $table->foreignId('operador_id')->nullable()->constrained('users')->nullOnDelete(); + $table->foreignId('filial_id')->constrained('filiais'); + $table->foreignId('tabela_preco_id')->nullable()->constrained('tabelas_preco')->nullOnDelete(); + $table->dateTime('data_emissao'); + $table->date('validade_orcamento')->nullable(); + $table->decimal('subtotal', 14, 2)->default(0); + $table->decimal('desconto_total', 14, 2)->default(0); + $table->decimal('acrescimo_total', 14, 2)->default(0); + $table->decimal('impostos_total', 14, 2)->default(0); + $table->decimal('total_liquido', 14, 2)->default(0); + $table->text('observacoes')->nullable(); + $table->timestamps(); + $table->softDeletes(); + }); + } + + public function down(): void + { + Schema::dropIfExists('documentos_comerciais'); + } +}; diff --git a/database/migrations/2026_03_20_000015_create_documento_itens_table.php b/database/migrations/2026_03_20_000015_create_documento_itens_table.php new file mode 100644 index 00000000..d9038eea --- /dev/null +++ b/database/migrations/2026_03_20_000015_create_documento_itens_table.php @@ -0,0 +1,33 @@ +id(); + $table->foreignId('documento_id')->constrained('documentos_comerciais')->cascadeOnDelete(); + $table->unsignedInteger('sequencia'); + $table->foreignId('produto_id')->constrained('produtos'); + $table->string('descricao', 255); + $table->string('unidade_sigla', 20); + $table->decimal('quantidade', 14, 3); + $table->decimal('preco_tabela', 14, 4)->default(0); + $table->decimal('preco_unitario', 14, 4)->default(0); + $table->decimal('subtotal_bruto', 14, 2)->default(0); + $table->decimal('subtotal_liquido', 14, 2)->default(0); + $table->json('metadata')->nullable(); + $table->timestamps(); + + $table->index(['documento_id', 'sequencia']); + }); + } + + public function down(): void + { + Schema::dropIfExists('documento_itens'); + } +}; diff --git a/database/migrations/2026_03_20_000016_create_documento_eventos_table.php b/database/migrations/2026_03_20_000016_create_documento_eventos_table.php new file mode 100644 index 00000000..4f078e65 --- /dev/null +++ b/database/migrations/2026_03_20_000016_create_documento_eventos_table.php @@ -0,0 +1,27 @@ +id(); + $table->foreignId('documento_id')->constrained('documentos_comerciais')->cascadeOnDelete(); + $table->string('status_anterior', 50)->nullable(); + $table->string('status_novo', 50); + $table->string('acao', 60); + $table->foreignId('usuario_id')->nullable()->constrained('users')->nullOnDelete(); + $table->dateTime('data_evento'); + $table->json('detalhes')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('documento_eventos'); + } +}; diff --git a/database/migrations/2026_03_20_000017_create_documento_pagamentos_table.php b/database/migrations/2026_03_20_000017_create_documento_pagamentos_table.php new file mode 100644 index 00000000..3175c75d --- /dev/null +++ b/database/migrations/2026_03_20_000017_create_documento_pagamentos_table.php @@ -0,0 +1,28 @@ +id(); + $table->foreignId('documento_id')->constrained('documentos_comerciais')->cascadeOnDelete(); + $table->string('forma_pagamento', 50); + $table->decimal('valor', 14, 2); + $table->unsignedInteger('parcelas')->default(1); + $table->string('autorizacao', 80)->nullable(); + $table->enum('status', ['PENDENTE', 'AUTORIZADO', 'NEGADO', 'ESTORNADO'])->default('PENDENTE'); + $table->dateTime('data_pagamento')->nullable(); + $table->json('metadata')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('documento_pagamentos'); + } +}; diff --git a/database/migrations/2026_03_20_000018_create_contas_receber_table.php b/database/migrations/2026_03_20_000018_create_contas_receber_table.php new file mode 100644 index 00000000..85450167 --- /dev/null +++ b/database/migrations/2026_03_20_000018_create_contas_receber_table.php @@ -0,0 +1,26 @@ +id(); + $table->foreignId('documento_id')->constrained('documentos_comerciais')->cascadeOnDelete(); + $table->foreignId('cliente_id')->constrained('clientes'); + $table->decimal('valor_original', 14, 2)->default(0); + $table->decimal('valor_aberto', 14, 2)->default(0); + $table->date('vencimento'); + $table->enum('status', ['ABERTO', 'PARCIAL', 'QUITADO', 'CANCELADO'])->default('ABERTO'); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('contas_receber'); + } +}; diff --git a/database/migrations/2026_03_20_000019_create_faturamentos_table.php b/database/migrations/2026_03_20_000019_create_faturamentos_table.php new file mode 100644 index 00000000..3dbc31d8 --- /dev/null +++ b/database/migrations/2026_03_20_000019_create_faturamentos_table.php @@ -0,0 +1,28 @@ +id(); + $table->foreignId('documento_id')->unique()->constrained('documentos_comerciais')->cascadeOnDelete(); + $table->string('numero_fiscal', 60)->nullable()->unique(); + $table->string('chave_acesso', 60)->nullable()->unique(); + $table->enum('status_fiscal', ['PENDENTE', 'AUTORIZADO', 'REJEITADO', 'CANCELADO'])->default('PENDENTE'); + $table->string('xml_path', 255)->nullable(); + $table->string('pdf_path', 255)->nullable(); + $table->dateTime('data_faturamento'); + $table->text('erro_fiscal')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('faturamentos'); + } +}; diff --git a/database/migrations/2026_03_20_000020_create_estoque_reservas_table.php b/database/migrations/2026_03_20_000020_create_estoque_reservas_table.php new file mode 100644 index 00000000..c2360469 --- /dev/null +++ b/database/migrations/2026_03_20_000020_create_estoque_reservas_table.php @@ -0,0 +1,26 @@ +id(); + $table->foreignId('documento_item_id')->unique()->constrained('documento_itens')->cascadeOnDelete(); + $table->foreignId('produto_id')->constrained('produtos'); + $table->decimal('quantidade_reservada', 14, 3); + $table->enum('status', ['ATIVA', 'CONSUMIDA', 'CANCELADA'])->default('ATIVA'); + $table->dateTime('data_reserva'); + $table->dateTime('data_consumo')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('estoque_reservas'); + } +}; diff --git a/database/migrations/2026_03_20_000021_alter_estoque_tables_for_sales.php b/database/migrations/2026_03_20_000021_alter_estoque_tables_for_sales.php new file mode 100644 index 00000000..eaa25810 --- /dev/null +++ b/database/migrations/2026_03_20_000021_alter_estoque_tables_for_sales.php @@ -0,0 +1,32 @@ +decimal('quantidade_reservada', 14, 3)->default(0)->after('quantidade_atual'); + }); + + Schema::table('estoque_movimentacoes', function (Blueprint $table) { + $table->string('origem_tipo', 50)->nullable()->after('origem'); + $table->unsignedBigInteger('origem_id')->nullable()->after('origem_tipo'); + $table->foreignId('estoque_reserva_id')->nullable()->after('estoque_lote_id')->constrained('estoque_reservas')->nullOnDelete(); + }); + } + + public function down(): void + { + Schema::table('estoque_movimentacoes', function (Blueprint $table) { + $table->dropConstrainedForeignId('estoque_reserva_id'); + $table->dropColumn(['origem_tipo', 'origem_id']); + }); + + Schema::table('estoque_saldos', function (Blueprint $table) { + $table->dropColumn('quantidade_reservada'); + }); + } +}; diff --git a/database/migrations/2026_03_21_000022_add_nivel_acesso_to_users_table.php b/database/migrations/2026_03_21_000022_add_nivel_acesso_to_users_table.php new file mode 100644 index 00000000..f3342f48 --- /dev/null +++ b/database/migrations/2026_03_21_000022_add_nivel_acesso_to_users_table.php @@ -0,0 +1,26 @@ +enum('nivel_acesso', ['OPERADOR', 'GERENTE', 'ADMIN']) + ->default('ADMIN') + ->after('email'); + }); + + DB::table('users')->whereNull('nivel_acesso')->update(['nivel_acesso' => 'ADMIN']); + } + + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropColumn('nivel_acesso'); + }); + } +}; diff --git a/database/migrations/2026_03_21_000023_create_auditoria_logs_table.php b/database/migrations/2026_03_21_000023_create_auditoria_logs_table.php new file mode 100644 index 00000000..45a4d29f --- /dev/null +++ b/database/migrations/2026_03_21_000023_create_auditoria_logs_table.php @@ -0,0 +1,28 @@ +id(); + $table->foreignId('usuario_id')->nullable()->constrained('users')->nullOnDelete(); + $table->string('acao', 80)->index(); + $table->string('entidade_tipo', 80)->index(); + $table->unsignedBigInteger('entidade_id')->nullable()->index(); + $table->json('dados_antes')->nullable(); + $table->json('dados_depois')->nullable(); + $table->string('ip', 45)->nullable(); + $table->string('user_agent', 255)->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('auditoria_logs'); + } +}; diff --git a/database/migrations/2026_03_21_000024_create_contas_receber_movimentos_table.php b/database/migrations/2026_03_21_000024_create_contas_receber_movimentos_table.php new file mode 100644 index 00000000..df9a8ef0 --- /dev/null +++ b/database/migrations/2026_03_21_000024_create_contas_receber_movimentos_table.php @@ -0,0 +1,27 @@ +id(); + $table->foreignId('conta_receber_id')->constrained('contas_receber')->cascadeOnDelete(); + $table->foreignId('usuario_id')->nullable()->constrained('users')->nullOnDelete(); + $table->enum('tipo', ['RECEBIMENTO', 'ESTORNO'])->index(); + $table->decimal('valor', 14, 2); + $table->dateTime('data_movimento'); + $table->string('forma_pagamento', 50)->nullable(); + $table->text('observacao')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('contas_receber_movimentos'); + } +}; diff --git a/database/migrations/2026_03_21_000025_create_fornecedores_table.php b/database/migrations/2026_03_21_000025_create_fornecedores_table.php new file mode 100644 index 00000000..789d09b5 --- /dev/null +++ b/database/migrations/2026_03_21_000025_create_fornecedores_table.php @@ -0,0 +1,28 @@ +id(); + $table->string('nome', 180)->index(); + $table->string('cnpj', 18)->nullable()->unique(); + $table->string('telefone', 30)->nullable(); + $table->string('email', 180)->nullable(); + $table->text('endereco')->nullable(); + $table->string('contato', 120)->nullable(); + $table->boolean('ativo')->default(true)->index(); + $table->timestamps(); + $table->softDeletes(); + }); + } + + public function down(): void + { + Schema::dropIfExists('fornecedores'); + } +}; diff --git a/database/migrations/2026_03_21_000026_create_compras_table.php b/database/migrations/2026_03_21_000026_create_compras_table.php new file mode 100644 index 00000000..17d221b5 --- /dev/null +++ b/database/migrations/2026_03_21_000026_create_compras_table.php @@ -0,0 +1,28 @@ +id(); + $table->string('numero', 30)->unique(); + $table->foreignId('fornecedor_id')->constrained('fornecedores'); + $table->foreignId('usuario_id')->constrained('users'); + $table->foreignId('filial_id')->constrained('filiais'); + $table->dateTime('data_compra'); + $table->enum('status', ['RASCUNHO', 'CONFIRMADA', 'CANCELADA'])->default('CONFIRMADA')->index(); + $table->decimal('valor_total', 14, 2)->default(0); + $table->text('observacoes')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('compras'); + } +}; diff --git a/database/migrations/2026_03_21_000027_create_compra_itens_table.php b/database/migrations/2026_03_21_000027_create_compra_itens_table.php new file mode 100644 index 00000000..e76833ea --- /dev/null +++ b/database/migrations/2026_03_21_000027_create_compra_itens_table.php @@ -0,0 +1,30 @@ +id(); + $table->foreignId('compra_id')->constrained('compras')->cascadeOnDelete(); + $table->unsignedInteger('sequencia'); + $table->foreignId('produto_id')->constrained('produtos'); + $table->decimal('quantidade', 14, 3); + $table->decimal('preco_unitario', 14, 4); + $table->decimal('subtotal', 14, 2); + $table->string('numero_lote', 80)->nullable(); + $table->date('data_validade')->nullable(); + $table->timestamps(); + + $table->index(['compra_id', 'sequencia']); + }); + } + + public function down(): void + { + Schema::dropIfExists('compra_itens'); + } +}; diff --git a/database/migrations/2026_03_21_000028_create_contas_pagar_table.php b/database/migrations/2026_03_21_000028_create_contas_pagar_table.php new file mode 100644 index 00000000..39ad515f --- /dev/null +++ b/database/migrations/2026_03_21_000028_create_contas_pagar_table.php @@ -0,0 +1,26 @@ +id(); + $table->foreignId('compra_id')->constrained('compras')->cascadeOnDelete(); + $table->foreignId('fornecedor_id')->constrained('fornecedores'); + $table->decimal('valor_original', 14, 2)->default(0); + $table->decimal('valor_aberto', 14, 2)->default(0); + $table->date('vencimento'); + $table->enum('status', ['ABERTO', 'PARCIAL', 'QUITADO', 'CANCELADO'])->default('ABERTO')->index(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('contas_pagar'); + } +}; diff --git a/database/migrations/2026_03_21_000029_set_default_nivel_acesso_operador.php b/database/migrations/2026_03_21_000029_set_default_nivel_acesso_operador.php new file mode 100644 index 00000000..1b5f8641 --- /dev/null +++ b/database/migrations/2026_03_21_000029_set_default_nivel_acesso_operador.php @@ -0,0 +1,23 @@ +whereNull('nivel_acesso')->update(['nivel_acesso' => 'OPERADOR']); + + if (DB::getDriverName() === 'mysql') { + DB::statement("ALTER TABLE users MODIFY nivel_acesso ENUM('OPERADOR','GERENTE','ADMIN') NOT NULL DEFAULT 'OPERADOR'"); + } + } + + public function down(): void + { + if (DB::getDriverName() === 'mysql') { + DB::statement("ALTER TABLE users MODIFY nivel_acesso ENUM('OPERADOR','GERENTE','ADMIN') NOT NULL DEFAULT 'ADMIN'"); + } + } +}; + diff --git a/database/migrations/2026_03_21_000030_create_contas_pagar_movimentos_table.php b/database/migrations/2026_03_21_000030_create_contas_pagar_movimentos_table.php new file mode 100644 index 00000000..dc21f3aa --- /dev/null +++ b/database/migrations/2026_03_21_000030_create_contas_pagar_movimentos_table.php @@ -0,0 +1,28 @@ +id(); + $table->foreignId('conta_pagar_id')->constrained('contas_pagar')->cascadeOnDelete(); + $table->foreignId('usuario_id')->nullable()->constrained('users')->nullOnDelete(); + $table->enum('tipo', ['PAGAMENTO', 'ESTORNO'])->index(); + $table->decimal('valor', 14, 2); + $table->dateTime('data_movimento'); + $table->string('forma_pagamento', 50)->nullable(); + $table->text('observacao')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('contas_pagar_movimentos'); + } +}; + diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 30614acf..cca97fad 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -2,22 +2,18 @@ namespace Database\Seeders; -use App\Models\User; // use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { - /** - * Seed the application's database. - */ - public function run(): void - { - // User::factory(10)->create(); - - User::factory()->create([ - 'name' => 'Test User', - 'email' => 'test@example.com', + /** + * Seed the application's database. + */ + public function run(): void + { + $this->call([ + UserAccessSeeder::class, ]); } -} \ No newline at end of file +} diff --git a/database/seeders/UserAccessSeeder.php b/database/seeders/UserAccessSeeder.php new file mode 100644 index 00000000..4d975532 --- /dev/null +++ b/database/seeders/UserAccessSeeder.php @@ -0,0 +1,32 @@ + 'Administrador', 'email' => 'admin@jbtintas.local', 'nivel_acesso' => 'ADMIN'], + ['name' => 'Gerente', 'email' => 'gerente@jbtintas.local', 'nivel_acesso' => 'GERENTE'], + ['name' => 'Operador', 'email' => 'operador@jbtintas.local', 'nivel_acesso' => 'OPERADOR'], + ]; + + foreach ($usuarios as $dados) { + User::updateOrCreate( + ['email' => $dados['email']], + [ + 'name' => $dados['name'], + 'nivel_acesso' => $dados['nivel_acesso'], + 'password' => Hash::make('12345678'), + 'email_verified_at' => now(), + ] + ); + } + } +} + diff --git a/package.json b/package.json index 11289f09..2249c8b6 100644 --- a/package.json +++ b/package.json @@ -1,102 +1,105 @@ { - "name": "sneat-bootstrap-html-laravel-admin-template-free", - "version": "2.0.0", - "private": true, - "type": "module", - "license": "MIT", - "scripts": { - "dev": "vite", - "build": "vite build" - }, - "devDependencies": { - "@babel/core": "~7.26.10", - "@babel/plugin-transform-destructuring": "~7.23.3", - "@babel/plugin-transform-object-rest-spread": "7.23.4", - "@babel/plugin-transform-template-literals": "~7.23.3", - "@babel/preset-env": "~7.26.9", - "@prettier/plugin-php": "0.22.4", - "@rollup/plugin-html": "^1.1.0", - "@stylistic/stylelint-config": "^1.0.1", - "@stylistic/stylelint-plugin": "^2.1.3", - "ajv": "^8.17.1", - "autoprefixer": "^10.4.21", - "axios": "^1.12.2", - "babel-loader": "~9.1.3", - "browser-sync": "^3.0.4", - "concurrently": "^9.2.1", - "cross-env": "^7.0.3", - "glob": "^10.4.5", - "eslint": "~9.16.0", - "eslint-config-airbnb-base": "^15.0.0", - "eslint-config-prettier": "^9.1.2", - "eslint-plugin-import": "^2.32.0", - "eslint-plugin-prettier": "^5.5.4", - "lodash": "^4.17.21", - "postcss": "^8.5.6", - "prettier": "^3.6.2", - "resolve-url-loader": "5.0.0", - "sass": "1.76.0", - "sass-loader": "~14.0.0", - "source-map-resolve": "0.6.0", - "vite": "^6.3.6" - }, - "overrides": { - "prop-types": "15.8.1", - "sass": "1.76.0" - }, - "resolutions": { - "prop-types": "15.8.1", - "sass": "1.76.0" - }, - "browserslist": [ - ">= 1%", - "last 2 versions", - "not dead", - "Chrome >= 45", - "Firefox >= 38", - "Edge >= 12", - "Explorer >= 10", - "iOS >= 9", - "Safari >= 9", - "Android >= 4.4", - "Opera >= 30" - ], - "babel": { - "presets": [ - [ - "@babel/env", - { - "targets": { - "browsers": [ - ">= 1%", - "last 2 versions", - "not dead", - "Chrome >= 45", - "Firefox >= 38", - "Edge >= 12", - "Explorer >= 10", - "iOS >= 9", - "Safari >= 9", - "Android >= 4.4", - "Opera >= 30" + "name": "sneat-bootstrap-html-laravel-admin-template-free", + "version": "2.0.0", + "private": true, + "type": "module", + "license": "MIT", + "scripts": { + "dev": "vite", + "build": "vite build" + }, + "devDependencies": { + "@babel/core": "~7.26.10", + "@babel/plugin-transform-destructuring": "~7.23.3", + "@babel/plugin-transform-object-rest-spread": "7.23.4", + "@babel/plugin-transform-template-literals": "~7.23.3", + "@babel/preset-env": "~7.26.9", + "@prettier/plugin-php": "0.22.4", + "@rollup/plugin-html": "^1.1.0", + "@stylistic/stylelint-config": "^1.0.1", + "@stylistic/stylelint-plugin": "^2.1.3", + "@tailwindcss/forms": "^0.5.2", + "ajv": "^8.17.1", + "alpinejs": "^3.4.2", + "autoprefixer": "^10.4.2", + "axios": "^1.12.2", + "babel-loader": "~9.1.3", + "browser-sync": "^3.0.4", + "concurrently": "^9.2.1", + "cross-env": "^7.0.3", + "eslint": "~9.16.0", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-config-prettier": "^9.1.2", + "eslint-plugin-import": "^2.32.0", + "eslint-plugin-prettier": "^5.5.4", + "glob": "^10.4.5", + "lodash": "^4.17.21", + "postcss": "^8.4.31", + "prettier": "^3.6.2", + "resolve-url-loader": "5.0.0", + "sass": "1.76.0", + "sass-loader": "~14.0.0", + "source-map-resolve": "0.6.0", + "tailwindcss": "^3.1.0", + "vite": "^6.3.6" + }, + "overrides": { + "prop-types": "15.8.1", + "sass": "1.76.0" + }, + "resolutions": { + "prop-types": "15.8.1", + "sass": "1.76.0" + }, + "browserslist": [ + ">= 1%", + "last 2 versions", + "not dead", + "Chrome >= 45", + "Firefox >= 38", + "Edge >= 12", + "Explorer >= 10", + "iOS >= 9", + "Safari >= 9", + "Android >= 4.4", + "Opera >= 30" + ], + "babel": { + "presets": [ + [ + "@babel/env", + { + "targets": { + "browsers": [ + ">= 1%", + "last 2 versions", + "not dead", + "Chrome >= 45", + "Firefox >= 38", + "Edge >= 12", + "Explorer >= 10", + "iOS >= 9", + "Safari >= 9", + "Android >= 4.4", + "Opera >= 30" + ] + } + } ] - } - } - ] - ] - }, - "dependencies": { - "@popperjs/core": "^2.11.8", - "apexcharts": "~4.2.0", - "bootstrap": "~5.3.3", - "highlight.js": "~11.10.0", - "@iconify/json": "^2.2.392", - "@iconify/tools": "^4.1.4", - "@iconify/types": "^2.0.0", - "@iconify/utils": "^2.3.0", - "jquery": "~3.7.1", - "masonry-layout": "~4.2.2", - "perfect-scrollbar": "~1.5.6", - "laravel-vite-plugin": "1.0.6" - } -} \ No newline at end of file + ] + }, + "dependencies": { + "@popperjs/core": "^2.11.8", + "apexcharts": "~4.2.0", + "bootstrap": "~5.3.3", + "highlight.js": "~11.10.0", + "@iconify/json": "^2.2.392", + "@iconify/tools": "^4.1.4", + "@iconify/types": "^2.0.0", + "@iconify/utils": "^2.3.0", + "jquery": "~3.7.1", + "masonry-layout": "~4.2.2", + "perfect-scrollbar": "~1.5.6", + "laravel-vite-plugin": "1.0.6" + } +} diff --git a/postcss.config.js b/postcss.config.js new file mode 100644 index 00000000..49c0612d --- /dev/null +++ b/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; diff --git a/public/build/assets/_commonjsHelpers-CqkleIqs.js b/public/build/assets/_commonjsHelpers-CqkleIqs.js new file mode 100644 index 00000000..dbbfc19b --- /dev/null +++ b/public/build/assets/_commonjsHelpers-CqkleIqs.js @@ -0,0 +1 @@ +function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}export{e as g}; diff --git a/public/build/assets/apex-charts-BSEhqGnV.css b/public/build/assets/apex-charts-BSEhqGnV.css new file mode 100644 index 00000000..1ac23ded --- /dev/null +++ b/public/build/assets/apex-charts-BSEhqGnV.css @@ -0,0 +1 @@ +@-webkit-keyframes opaque{0%{opacity:0}to{opacity:1}}@keyframes opaque{0%{opacity:0}to{opacity:1}}@-webkit-keyframes resizeanim{0%,to{opacity:0}}@keyframes resizeanim{0%,to{opacity:0}}.apexcharts-canvas{position:relative;direction:ltr!important;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.apexcharts-canvas ::-webkit-scrollbar{-webkit-appearance:none;width:6px}.apexcharts-canvas ::-webkit-scrollbar-thumb{border-radius:4px;background-color:#00000080;box-shadow:0 0 1px #ffffff80;-webkit-box-shadow:0 0 1px rgba(255,255,255,.5)}.apexcharts-inner{position:relative}.apexcharts-text tspan{font-family:inherit}rect.legend-mouseover-inactive,.legend-mouseover-inactive rect,.legend-mouseover-inactive path,.legend-mouseover-inactive circle,.legend-mouseover-inactive line,.legend-mouseover-inactive text.apexcharts-yaxis-title-text,.legend-mouseover-inactive text.apexcharts-yaxis-label{transition:.15s ease all;opacity:.2}.apexcharts-legend-text{padding-left:15px;margin-left:-15px}.apexcharts-series-collapsed{opacity:0}.apexcharts-tooltip{border-radius:5px;box-shadow:2px 2px 6px -4px #999;cursor:default;font-size:14px;left:62px;opacity:0;pointer-events:none;position:absolute;top:20px;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;overflow:hidden;white-space:nowrap;z-index:12;transition:.15s ease all}.apexcharts-tooltip.apexcharts-active{opacity:1;transition:.15s ease all}.apexcharts-tooltip.apexcharts-theme-light{border:1px solid #e3e3e3;background:#fffffff5}.apexcharts-tooltip.apexcharts-theme-dark{color:#fff;background:#1e1e1ecc}.apexcharts-tooltip *{font-family:inherit}.apexcharts-tooltip-title{padding:6px;font-size:15px;margin-bottom:4px}.apexcharts-tooltip.apexcharts-theme-light .apexcharts-tooltip-title{background:#eceff1;border-bottom:1px solid #ddd}.apexcharts-tooltip.apexcharts-theme-dark .apexcharts-tooltip-title{background:#000000b3;border-bottom:1px solid #333}.apexcharts-tooltip-text-goals-value,.apexcharts-tooltip-text-y-value,.apexcharts-tooltip-text-z-value{display:inline-block;margin-left:5px;font-weight:600}.apexcharts-tooltip-text-goals-label:empty,.apexcharts-tooltip-text-goals-value:empty,.apexcharts-tooltip-text-y-label:empty,.apexcharts-tooltip-text-y-value:empty,.apexcharts-tooltip-text-z-value:empty,.apexcharts-tooltip-title:empty{display:none}.apexcharts-tooltip-text-goals-label,.apexcharts-tooltip-text-goals-value{padding:6px 0 5px}.apexcharts-tooltip-goals-group,.apexcharts-tooltip-text-goals-label,.apexcharts-tooltip-text-goals-value{display:-ms-flexbox;display:flex}.apexcharts-tooltip-text-goals-label:not(:empty),.apexcharts-tooltip-text-goals-value:not(:empty){margin-top:-6px}.apexcharts-tooltip-marker{width:12px;height:12px;position:relative;top:0;margin-right:10px;border-radius:50%}.apexcharts-tooltip-series-group{padding:0 10px;display:none;text-align:left;-ms-flex-pack:left;justify-content:left;-ms-flex-align:center;align-items:center}.apexcharts-tooltip-series-group.apexcharts-active .apexcharts-tooltip-marker{opacity:1}.apexcharts-tooltip-series-group.apexcharts-active,.apexcharts-tooltip-series-group:last-child{padding-bottom:4px}.apexcharts-tooltip-y-group{padding:6px 0 5px}.apexcharts-custom-tooltip,.apexcharts-tooltip-box{padding:4px 8px}.apexcharts-tooltip-boxPlot{display:-ms-flexbox;display:flex;-ms-flex-direction:column-reverse;flex-direction:column-reverse}.apexcharts-tooltip-box>div{margin:4px 0}.apexcharts-tooltip-box span.value{font-weight:700}.apexcharts-tooltip-rangebar{padding:5px 8px}.apexcharts-tooltip-rangebar .category{font-weight:600;color:#777}.apexcharts-tooltip-rangebar .series-name{font-weight:700;display:block;margin-bottom:5px}.apexcharts-xaxistooltip,.apexcharts-yaxistooltip{opacity:0;pointer-events:none;color:#373d3f;font-size:13px;text-align:center;border-radius:2px;position:absolute;z-index:10;background:#eceff1;border:1px solid #90a4ae}.apexcharts-xaxistooltip{padding:9px 10px;transition:.15s ease all}.apexcharts-xaxistooltip.apexcharts-theme-dark{background:#000000b3;border:1px solid rgba(0,0,0,.5);color:#fff}.apexcharts-xaxistooltip:after,.apexcharts-xaxistooltip:before{left:50%;border:solid transparent;content:" ";height:0;width:0;position:absolute;pointer-events:none}.apexcharts-xaxistooltip:after{border-color:transparent;border-width:6px;margin-left:-6px}.apexcharts-xaxistooltip:before{border-color:transparent;border-width:7px;margin-left:-7px}.apexcharts-xaxistooltip-bottom:after,.apexcharts-xaxistooltip-bottom:before{bottom:100%}.apexcharts-xaxistooltip-top:after,.apexcharts-xaxistooltip-top:before{top:100%}.apexcharts-xaxistooltip-bottom:after{border-bottom-color:#eceff1}.apexcharts-xaxistooltip-bottom:before{border-bottom-color:#90a4ae}.apexcharts-xaxistooltip-bottom.apexcharts-theme-dark:after,.apexcharts-xaxistooltip-bottom.apexcharts-theme-dark:before{border-bottom-color:#00000080}.apexcharts-xaxistooltip-top:after{border-top-color:#eceff1}.apexcharts-xaxistooltip-top:before{border-top-color:#90a4ae}.apexcharts-xaxistooltip-top.apexcharts-theme-dark:after,.apexcharts-xaxistooltip-top.apexcharts-theme-dark:before{border-top-color:#00000080}.apexcharts-xaxistooltip.apexcharts-active{opacity:1;transition:.15s ease all}.apexcharts-yaxistooltip{padding:4px 10px}.apexcharts-yaxistooltip.apexcharts-theme-dark{background:#000000b3;border:1px solid rgba(0,0,0,.5);color:#fff}.apexcharts-yaxistooltip:after,.apexcharts-yaxistooltip:before{top:50%;border:solid transparent;content:" ";height:0;width:0;position:absolute;pointer-events:none}.apexcharts-yaxistooltip:after{border-color:transparent;border-width:6px;margin-top:-6px}.apexcharts-yaxistooltip:before{border-color:transparent;border-width:7px;margin-top:-7px}.apexcharts-yaxistooltip-left:after,.apexcharts-yaxistooltip-left:before{left:100%}.apexcharts-yaxistooltip-right:after,.apexcharts-yaxistooltip-right:before{right:100%}.apexcharts-yaxistooltip-left:after{border-left-color:#eceff1}.apexcharts-yaxistooltip-left:before{border-left-color:#90a4ae}.apexcharts-yaxistooltip-left.apexcharts-theme-dark:after,.apexcharts-yaxistooltip-left.apexcharts-theme-dark:before{border-left-color:#00000080}.apexcharts-yaxistooltip-right:after{border-right-color:#eceff1}.apexcharts-yaxistooltip-right:before{border-right-color:#90a4ae}.apexcharts-yaxistooltip-right.apexcharts-theme-dark:after,.apexcharts-yaxistooltip-right.apexcharts-theme-dark:before{border-right-color:#00000080}.apexcharts-yaxistooltip.apexcharts-active{opacity:1}.apexcharts-yaxistooltip-hidden{display:none}.apexcharts-xcrosshairs,.apexcharts-ycrosshairs{pointer-events:none;opacity:0;transition:.15s ease all}.apexcharts-xcrosshairs.apexcharts-active,.apexcharts-ycrosshairs.apexcharts-active{opacity:1;transition:.15s ease all}.apexcharts-ycrosshairs-hidden{opacity:0}.apexcharts-selection-rect{cursor:move}.svg_select_shape{stroke-width:1;stroke-dasharray:10 10;stroke:#000;stroke-opacity:.1;pointer-events:none;fill:none}.svg_select_handle{stroke-width:3;stroke:#000;fill:none}.svg_select_handle_r{cursor:e-resize}.svg_select_handle_l{cursor:w-resize}.apexcharts-svg.apexcharts-zoomable.hovering-zoom{cursor:crosshair}.apexcharts-svg.apexcharts-zoomable.hovering-pan{cursor:move}.apexcharts-menu-icon,.apexcharts-pan-icon,.apexcharts-reset-icon,.apexcharts-selection-icon,.apexcharts-toolbar-custom-icon,.apexcharts-zoom-icon,.apexcharts-zoomin-icon,.apexcharts-zoomout-icon{cursor:pointer;width:20px;height:20px;line-height:24px;color:#6e8192;text-align:center}.apexcharts-menu-icon svg,.apexcharts-reset-icon svg,.apexcharts-zoom-icon svg,.apexcharts-zoomin-icon svg,.apexcharts-zoomout-icon svg{fill:#6e8192}.apexcharts-selection-icon svg{fill:#444;-webkit-transform:scale(.76);transform:scale(.76)}.apexcharts-theme-dark .apexcharts-menu-icon svg,.apexcharts-theme-dark .apexcharts-pan-icon svg,.apexcharts-theme-dark .apexcharts-reset-icon svg,.apexcharts-theme-dark .apexcharts-selection-icon svg,.apexcharts-theme-dark .apexcharts-toolbar-custom-icon svg,.apexcharts-theme-dark .apexcharts-zoom-icon svg,.apexcharts-theme-dark .apexcharts-zoomin-icon svg,.apexcharts-theme-dark .apexcharts-zoomout-icon svg{fill:#f3f4f5}.apexcharts-canvas .apexcharts-reset-zoom-icon.apexcharts-selected svg,.apexcharts-canvas .apexcharts-selection-icon.apexcharts-selected svg,.apexcharts-canvas .apexcharts-zoom-icon.apexcharts-selected svg{fill:#008ffb}.apexcharts-theme-light .apexcharts-menu-icon:hover svg,.apexcharts-theme-light .apexcharts-reset-icon:hover svg,.apexcharts-theme-light .apexcharts-selection-icon:not(.apexcharts-selected):hover svg,.apexcharts-theme-light .apexcharts-zoom-icon:not(.apexcharts-selected):hover svg,.apexcharts-theme-light .apexcharts-zoomin-icon:hover svg,.apexcharts-theme-light .apexcharts-zoomout-icon:hover svg{fill:#333}.apexcharts-menu-icon,.apexcharts-selection-icon{position:relative}.apexcharts-reset-icon{margin-left:5px}.apexcharts-menu-icon,.apexcharts-reset-icon,.apexcharts-zoom-icon{-webkit-transform:scale(.85);transform:scale(.85)}.apexcharts-zoomin-icon,.apexcharts-zoomout-icon{-webkit-transform:scale(.7);transform:scale(.7)}.apexcharts-zoomout-icon{margin-right:3px}.apexcharts-pan-icon{-webkit-transform:scale(.62);transform:scale(.62);position:relative;left:1px;top:0}.apexcharts-pan-icon svg{fill:#fff;stroke:#6e8192;stroke-width:2}.apexcharts-pan-icon.apexcharts-selected svg{stroke:#008ffb}.apexcharts-pan-icon:not(.apexcharts-selected):hover svg{stroke:#333}.apexcharts-toolbar{position:absolute;z-index:11;max-width:176px;text-align:right;border-radius:3px;padding:0 6px 2px;display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;-ms-flex-align:center;align-items:center}.apexcharts-menu{background:#fff;position:absolute;top:100%;border:1px solid #ddd;border-radius:3px;padding:3px;right:10px;opacity:0;min-width:110px;transition:.15s ease all;pointer-events:none}.apexcharts-menu.apexcharts-menu-open{opacity:1;pointer-events:all;transition:.15s ease all}.apexcharts-menu-item{padding:6px 7px;font-size:12px;cursor:pointer}.apexcharts-theme-light .apexcharts-menu-item:hover{background:#eee}.apexcharts-theme-dark .apexcharts-menu{background:#000000b3;color:#fff}@media screen and (min-width: 768px){.apexcharts-canvas:hover .apexcharts-toolbar{opacity:1}}.apexcharts-canvas .apexcharts-element-hidden,.apexcharts-datalabel.apexcharts-element-hidden,.apexcharts-hide .apexcharts-series-points{opacity:0}.apexcharts-hidden-element-shown{opacity:1;transition:.25s ease all}.apexcharts-datalabel,.apexcharts-datalabel-label,.apexcharts-datalabel-value,.apexcharts-datalabels,.apexcharts-pie-label{cursor:default;pointer-events:none}.apexcharts-pie-label-delay{opacity:0;-webkit-animation-name:opaque;animation-name:opaque;-webkit-animation-duration:.3s;animation-duration:.3s;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards;-webkit-animation-timing-function:ease;animation-timing-function:ease}.apexcharts-radialbar-label{cursor:pointer}.apexcharts-annotation-rect,.apexcharts-area-series .apexcharts-area,.apexcharts-gridline,.apexcharts-line,.apexcharts-point-annotation-label,.apexcharts-radar-series path:not(.apexcharts-marker),.apexcharts-radar-series polygon,.apexcharts-toolbar svg,.apexcharts-tooltip .apexcharts-marker,.apexcharts-xaxis-annotation-label,.apexcharts-yaxis-annotation-label,.apexcharts-zoom-rect,.no-pointer-events{pointer-events:none}.apexcharts-tooltip-active .apexcharts-marker{transition:.15s ease all}.resize-triggers{-webkit-animation:1ms resizeanim;animation:1ms resizeanim;visibility:hidden;opacity:0;height:100%;width:100%;overflow:hidden}.contract-trigger:before,.resize-triggers,.resize-triggers>div{content:" ";display:block;position:absolute;top:0;left:0}.resize-triggers>div{height:100%;width:100%;background:#eee;overflow:auto}.contract-trigger:before{overflow:hidden;width:200%;height:200%}.apexcharts-bar-goals-markers,.apexcharts-bar-shadows,.apexcharts-rangebar-goals-markers{pointer-events:none}.apexcharts-canvas .apexcharts-tooltip{box-shadow:var(--bs-box-shadow)}.apexcharts-canvas .apexcharts-tooltip.apexcharts-theme-light{border-color:var(--bs-border-color);background:var(--bs-paper-bg);color:var(--bs-heading-color)}.apexcharts-canvas .apexcharts-tooltip.apexcharts-theme-light .apexcharts-tooltip-title{background:var(--bs-paper-bg);border-block-end-color:var(--bs-border-color);font-family:var(--bs-font-sans-serif)!important;font-weight:500}.apexcharts-canvas .apexcharts-tooltip.apexcharts-theme-dark{background:transparent}.apexcharts-canvas .apexcharts-xaxistooltip,.apexcharts-canvas .apexcharts-yaxistooltip{border-color:var(--bs-border-color);background:var(--bs-paper-bg);color:var(--bs-heading-color)}.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-xaxistooltip-bottom:after,.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-yaxistooltip-bottom:after,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-xaxistooltip-bottom:after,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-yaxistooltip-bottom:after{border-block-end-color:var(--bs-paper-bg)}.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-xaxistooltip-bottom:before,.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-yaxistooltip-bottom:before,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-xaxistooltip-bottom:before,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-yaxistooltip-bottom:before{border-block-end-color:var(--bs-border-color)}.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-xaxistooltip-left:after,.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-yaxistooltip-left:after,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-xaxistooltip-left:after,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-yaxistooltip-left:after{border-inline-start-color:var(--bs-paper-bg)}.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-xaxistooltip-left:before,.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-yaxistooltip-left:before,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-xaxistooltip-left:before,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-yaxistooltip-left:before{border-inline-start-color:var(--bs-border-color)}.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-xaxistooltip-right:after,.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-yaxistooltip-right:after,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-xaxistooltip-right:after,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-yaxistooltip-right:after{border-inline-end-color:var(--bs-paper-bg)}.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-xaxistooltip-right:before,.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-yaxistooltip-right:before,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-xaxistooltip-right:before,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-yaxistooltip-right:before{border-inline-end-color:var(--bs-border-color)}.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-xaxistooltip-top:after,.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-yaxistooltip-top:after,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-xaxistooltip-top:after,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-yaxistooltip-top:after{border-block-start-color:var(--bs-paper-bg)}.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-xaxistooltip-top:before,.apexcharts-canvas .apexcharts-xaxistooltip.apexcharts-yaxistooltip-top:before,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-xaxistooltip-top:before,.apexcharts-canvas .apexcharts-yaxistooltip.apexcharts-yaxistooltip-top:before{border-block-start-color:var(--bs-border-color)}.apexcharts-canvas .apexcharts-tooltip-text{font-family:var(--bs-font-sans-serif)!important}.apexcharts-canvas .apexcharts-legend-marker,.apexcharts-canvas .apexcharts-tooltip-marker{margin-inline:0 .5rem}@media (min-width: 1400px) and (max-width: 1550px){.total-revenue,.profile-report{inline-size:100%!important}.profile-report .payments,.profile-report .transactions{inline-size:25%!important}.profile-report .profile-report{inline-size:50%!important}} diff --git a/public/build/assets/apexcharts-DrruP4Np.js b/public/build/assets/apexcharts-DrruP4Np.js new file mode 100644 index 00000000..5b4b9b00 --- /dev/null +++ b/public/build/assets/apexcharts-DrruP4Np.js @@ -0,0 +1,850 @@ +import{g as dr}from"./_commonjsHelpers-CqkleIqs.js";/*! + * ApexCharts v4.2.0 + * (c) 2018-2024 ApexCharts + * Released under the MIT License. + */var Yi,Za;function ur(){if(Za)return Yi;Za=1;function At(o,e){(e==null||e>o.length)&&(e=o.length);for(var t=0,i=Array(e);t=o.length?{done:!0}:{done:!1,value:o[i++]}},e:function(l){throw l},f:a}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,r=!0,n=!1;return{s:function(){t=t.call(o)},n:function(){var l=t.next();return r=l.done,l},e:function(l){n=!0,s=l},f:function(){try{r||t.return==null||t.return()}finally{if(n)throw s}}}}function lt(o){var e=Fi();return function(){var t,i=St(o);if(e){var a=St(this).constructor;t=Reflect.construct(i,arguments,a)}else t=i.apply(this,arguments);return(function(s,r){if(r&&(typeof r=="object"||typeof r=="function"))return r;if(r!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Hi(s)})(this,t)}}function Ct(o,e,t){return(e=Wi(e))in o?Object.defineProperty(o,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):o[e]=t,o}function St(o){return St=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},St(o)}function ht(o,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(e&&e.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),Object.defineProperty(o,"prototype",{writable:!1}),e&&Dt(o,e)}function Fi(){try{var o=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(Fi=function(){return!!o})()}function Di(o,e){var t=Object.keys(o);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(o);e&&(i=i.filter((function(a){return Object.getOwnPropertyDescriptor(o,a).enumerable}))),t.push.apply(t,i)}return t}function R(o){for(var e=1;e>16,n=i>>8&255,l=255&i;return"#"+(16777216+65536*(Math.round((a-r)*s)+r)+256*(Math.round((a-n)*s)+n)+(Math.round((a-l)*s)+l)).toString(16).slice(1)}},{key:"shadeColor",value:function(e,t){return o.isColorHex(t)?this.shadeHexColor(e,t):this.shadeRGBColor(e,t)}}],[{key:"bind",value:function(e,t){return function(){return e.apply(t,arguments)}}},{key:"isObject",value:function(e){return e&&Ze(e)==="object"&&!Array.isArray(e)&&e!=null}},{key:"is",value:function(e,t){return Object.prototype.toString.call(t)==="[object "+e+"]"}},{key:"listToArray",value:function(e){var t,i=[];for(t=0;t1&&arguments[1]!==void 0?arguments[1]:2;return Number.isInteger(e)?e:parseFloat(e.toPrecision(t))}},{key:"randomId",value:function(){return(Math.random()+1).toString(36).substring(4)}},{key:"noExponents",value:function(e){var t=String(e).split(/[eE]/);if(t.length===1)return t[0];var i="",a=e<0?"-":"",s=t[0].replace(".",""),r=Number(t[1])+1;if(r<0){for(i=a+"0.";r++;)i+="0";return i+s.replace(/^-/,"")}for(r-=s.length;r--;)i+="0";return s+i}},{key:"elementExists",value:function(e){return!(!e||!e.isConnected)}},{key:"getDimensions",value:function(e){var t=getComputedStyle(e,null),i=e.clientHeight,a=e.clientWidth;return i-=parseFloat(t.paddingTop)+parseFloat(t.paddingBottom),[a-=parseFloat(t.paddingLeft)+parseFloat(t.paddingRight),i]}},{key:"getBoundingClientRect",value:function(e){var t=e.getBoundingClientRect();return{top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:e.clientWidth,height:e.clientHeight,x:t.left,y:t.top}}},{key:"getLargestStringFromArr",value:function(e){return e.reduce((function(t,i){return Array.isArray(i)&&(i=i.reduce((function(a,s){return a.length>s.length?a:s}))),t.length>i.length?t:i}),0)}},{key:"hexToRgba",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"#999999",t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.6;e.substring(0,1)!=="#"&&(e="#999999");var i=e.replace("#","");i=i.match(new RegExp("(.{"+i.length/3+"})","g"));for(var a=0;a1&&arguments[1]!==void 0?arguments[1]:"x",i=e.toString().slice();return i=i.replace(/[` ~!@#$%^&*()|+\=?;:'",.<>{}[\]\\/]/gi,t)}},{key:"negToZero",value:function(e){return e<0?0:e}},{key:"moveIndexInArray",value:function(e,t,i){if(i>=e.length)for(var a=i-e.length+1;a--;)e.push(void 0);return e.splice(i,0,e.splice(t,1)[0]),e}},{key:"extractNumber",value:function(e){return parseFloat(e.replace(/[^\d.]*/g,""))}},{key:"findAncestor",value:function(e,t){for(;(e=e.parentElement)&&!e.classList.contains(t););return e}},{key:"setELstyles",value:function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e.style.key=t[i])}},{key:"preciseAddition",value:function(e,t){var i=(String(e).split(".")[1]||"").length,a=(String(t).split(".")[1]||"").length,s=Math.pow(10,Math.max(i,a));return(Math.round(e*s)+Math.round(t*s))/s}},{key:"isNumber",value:function(e){return!isNaN(e)&&parseFloat(Number(e))===e&&!isNaN(parseInt(e,10))}},{key:"isFloat",value:function(e){return Number(e)===e&&e%1!=0}},{key:"isMsEdge",value:function(){var e=window.navigator.userAgent,t=e.indexOf("Edge/");return t>0&&parseInt(e.substring(t+5,e.indexOf(".",t)),10)}},{key:"getGCD",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:7,a=Math.pow(10,i-Math.floor(Math.log10(Math.max(e,t))));for(e=Math.round(Math.abs(e)*a),t=Math.round(Math.abs(t)*a);t;){var s=t;t=e%t,e=s}return e/a}},{key:"getPrimeFactors",value:function(e){for(var t=[],i=2;e>=2;)e%i==0?(t.push(i),e/=i):i++;return t}},{key:"mod",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:7,a=Math.pow(10,i-Math.floor(Math.log10(Math.max(e,t))));return(e=Math.round(Math.abs(e)*a))%(t=Math.round(Math.abs(t)*a))/a}}]),o})(),$e=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"animateLine",value:function(e,t,i,a){e.attr(t).animate(a).attr(i)}},{key:"animateMarker",value:function(e,t,i,a){e.attr({opacity:0}).animate(t).attr({opacity:1}).after((function(){a()}))}},{key:"animateRect",value:function(e,t,i,a,s){e.attr(t).animate(a).attr(i).after((function(){return s()}))}},{key:"animatePathsGradually",value:function(e){var t=e.el,i=e.realIndex,a=e.j,s=e.fill,r=e.pathFrom,n=e.pathTo,l=e.speed,h=e.delay,d=this.w,c=0;d.config.chart.animations.animateGradually.enabled&&(c=d.config.chart.animations.animateGradually.delay),d.config.chart.animations.dynamicAnimation.enabled&&d.globals.dataChanged&&d.config.chart.type!=="bar"&&(c=0),this.morphSVG(t,i,a,d.config.chart.type!=="line"||d.globals.comboCharts?s:"stroke",r,n,l,h*c)}},{key:"showDelayedElements",value:function(){this.w.globals.delayedElements.forEach((function(e){var t=e.el;t.classList.remove("apexcharts-element-hidden"),t.classList.add("apexcharts-hidden-element-shown")}))}},{key:"animationCompleted",value:function(e){var t=this.w;t.globals.animationEnded||(t.globals.animationEnded=!0,this.showDelayedElements(),typeof t.config.chart.events.animationEnd=="function"&&t.config.chart.events.animationEnd(this.ctx,{el:e,w:t}))}},{key:"morphSVG",value:function(e,t,i,a,s,r,n,l){var h=this,d=this.w;s||(s=e.attr("pathFrom")),r||(r=e.attr("pathTo"));var c=function(u){return d.config.chart.type==="radar"&&(n=1),"M 0 ".concat(d.globals.gridHeight)};(!s||s.indexOf("undefined")>-1||s.indexOf("NaN")>-1)&&(s=c()),(!r.trim()||r.indexOf("undefined")>-1||r.indexOf("NaN")>-1)&&(r=c()),d.globals.shouldAnimate||(n=1),e.plot(s).animate(1,l).plot(s).animate(n,l).plot(r).after((function(){L.isNumber(i)?i===d.globals.series[d.globals.maxValsInArrayIndex].length-2&&d.globals.shouldAnimate&&h.animationCompleted(e):a!=="none"&&d.globals.shouldAnimate&&(!d.globals.comboCharts&&t===d.globals.series.length-1||d.globals.comboCharts)&&h.animationCompleted(e),h.showDelayedElements()}))}}]),o})();const Wt={},_i=[];function U(o,e){if(Array.isArray(o))for(const t of o)U(t,e);else if(typeof o!="object")Bi(Object.getOwnPropertyNames(e)),Wt[o]=Object.assign(Wt[o]||{},e);else for(const t in o)U(t,o[t])}function ye(o){return Wt[o]||{}}function Bi(o){_i.push(...o)}function _t(o,e){let t;const i=o.length,a=[];for(t=0;t$a.has(o.nodeName),Gi=(o,e,t={})=>{const i={...e};for(const a in i)i[a].valueOf()===t[a]&&delete i[a];Object.keys(i).length?o.node.setAttribute("data-svgjs",JSON.stringify(i)):(o.node.removeAttribute("data-svgjs"),o.node.removeAttribute("svgjs:data"))},Vt="http://www.w3.org/2000/svg",Ut="http://www.w3.org/2000/xmlns/",Ke="http://www.w3.org/1999/xlink",q={window:typeof window>"u"?null:window,document:typeof document>"u"?null:document};function ct(){return q.window}let qt=class{};const De={},Zt="___SYMBOL___ROOT___";function dt(o,e=Vt){return q.document.createElementNS(e,o)}function be(o,e=!1){if(o instanceof qt)return o;if(typeof o=="object")return $t(o);if(o==null)return new De[Zt];if(typeof o=="string"&&o.charAt(0)!=="<")return $t(q.document.querySelector(o));const t=e?q.document.createElement("div"):dt("svg");return t.innerHTML=o,o=$t(t.firstChild),t.removeChild(t.firstChild),o}function ie(o,e){return e&&(e instanceof q.window.Node||e.ownerDocument&&e instanceof e.ownerDocument.defaultView.Node)?e:dt(o)}function Ae(o){if(!o)return null;if(o.instance instanceof qt)return o.instance;if(o.nodeName==="#document-fragment")return new De.Fragment(o);let e=Je(o.nodeName||"Dom");return e==="LinearGradient"||e==="RadialGradient"?e="Gradient":De[e]||(e="Dom"),new De[e](o)}let $t=Ae;function Z(o,e=o.name,t=!1){return De[e]=o,t&&(De[Zt]=o),Bi(Object.getOwnPropertyNames(o.prototype)),o}let Ja=1e3;function ji(o){return"Svgjs"+Je(o)+Ja++}function Vi(o){for(let e=o.children.length-1;e>=0;e--)Vi(o.children[e]);return o.id&&(o.id=ji(o.nodeName)),o}function N(o,e){let t,i;for(i=(o=Array.isArray(o)?o:[o]).length-1;i>=0;i--)for(t in e)o[i].prototype[t]=e[t]}function ae(o){return function(...e){const t=e[e.length-1];return!t||t.constructor!==Object||t instanceof Array?o.apply(this,e):o.apply(this,e.slice(0,-1)).attr(t)}}U("Dom",{siblings:function(){return this.parent().children()},position:function(){return this.parent().index(this)},next:function(){return this.siblings()[this.position()+1]},prev:function(){return this.siblings()[this.position()-1]},forward:function(){const o=this.position();return this.parent().add(this.remove(),o+1),this},backward:function(){const o=this.position();return this.parent().add(this.remove(),o?o-1:0),this},front:function(){return this.parent().add(this.remove()),this},back:function(){return this.parent().add(this.remove(),0),this},before:function(o){(o=be(o)).remove();const e=this.position();return this.parent().add(o,e),this},after:function(o){(o=be(o)).remove();const e=this.position();return this.parent().add(o,e+1),this},insertBefore:function(o){return(o=be(o)).before(this),this},insertAfter:function(o){return(o=be(o)).after(this),this}});const Ui=/^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i,Qa=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,Ka=/rgb\((\d+),(\d+),(\d+)\)/,es=/(#[a-z_][a-z0-9\-_]*)/i,ts=/\)\s*,?\s*/,is=/\s/g,qi=/^#[a-f0-9]{3}$|^#[a-f0-9]{6}$/i,Zi=/^rgb\(/,$i=/^(\s+)?$/,Ji=/^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,as=/\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i,ze=/[\s,]+/,Jt=/[MLHVCSQTAZ]/i;function ss(o){const e=Math.round(o),t=Math.max(0,Math.min(255,e)).toString(16);return t.length===1?"0"+t:t}function et(o,e){for(let t=e.length;t--;)if(o[e[t]]==null)return!1;return!0}function Qt(o,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?o+6*(e-o)*t:t<.5?e:t<2/3?o+(e-o)*(2/3-t)*6:o}U("Dom",{classes:function(){const o=this.attr("class");return o==null?[]:o.trim().split(ze)},hasClass:function(o){return this.classes().indexOf(o)!==-1},addClass:function(o){if(!this.hasClass(o)){const e=this.classes();e.push(o),this.attr("class",e.join(" "))}return this},removeClass:function(o){return this.hasClass(o)&&this.attr("class",this.classes().filter((function(e){return e!==o})).join(" ")),this},toggleClass:function(o){return this.hasClass(o)?this.removeClass(o):this.addClass(o)}}),U("Dom",{css:function(o,e){const t={};if(arguments.length===0)return this.node.style.cssText.split(/\s*;\s*/).filter((function(i){return!!i.length})).forEach((function(i){const a=i.split(/\s*:\s*/);t[a[0]]=a[1]})),t;if(arguments.length<2){if(Array.isArray(o)){for(const i of o){const a=i;t[i]=this.node.style.getPropertyValue(a)}return t}if(typeof o=="string")return this.node.style.getPropertyValue(o);if(typeof o=="object")for(const i in o)this.node.style.setProperty(i,o[i]==null||$i.test(o[i])?"":o[i])}return arguments.length===2&&this.node.style.setProperty(o,e==null||$i.test(e)?"":e),this},show:function(){return this.css("display","")},hide:function(){return this.css("display","none")},visible:function(){return this.css("display")!=="none"}}),U("Dom",{data:function(o,e,t){if(o==null)return this.data(_t((function(i,a){let s;const r=i.length,n=[];for(s=0;si.nodeName.indexOf("data-")===0)),(i=>i.nodeName.slice(5))));if(o instanceof Array){const i={};for(const a of o)i[a]=this.data(a);return i}if(typeof o=="object")for(e in o)this.data(e,o[e]);else if(arguments.length<2)try{return JSON.parse(this.attr("data-"+o))}catch{return this.attr("data-"+o)}else this.attr("data-"+o,e===null?null:t===!0||typeof e=="string"||typeof e=="number"?e:JSON.stringify(e));return this}}),U("Dom",{remember:function(o,e){if(typeof arguments[0]=="object")for(const t in o)this.remember(t,o[t]);else{if(arguments.length===1)return this.memory()[o];this.memory()[o]=e}return this},forget:function(){if(arguments.length===0)this._memory={};else for(let o=arguments.length-1;o>=0;o--)delete this.memory()[arguments[o]];return this},memory:function(){return this._memory=this._memory||{}}});class ee{constructor(...e){this.init(...e)}static isColor(e){return e&&(e instanceof ee||this.isRgb(e)||this.test(e))}static isRgb(e){return e&&typeof e.r=="number"&&typeof e.g=="number"&&typeof e.b=="number"}static random(e="vibrant",t){const{random:i,round:a,sin:s,PI:r}=Math;if(e==="vibrant"){const n=24*i()+57,l=38*i()+45,h=360*i();return new ee(n,l,h,"lch")}if(e==="sine"){const n=a(80*s(2*r*(t=t??i())/.5+.01)+150),l=a(50*s(2*r*t/.5+4.6)+200),h=a(100*s(2*r*t/.5+2.3)+150);return new ee(n,l,h)}if(e==="pastel"){const n=8*i()+86,l=17*i()+9,h=360*i();return new ee(n,l,h,"lch")}if(e==="dark"){const n=10+10*i(),l=50*i()+86,h=360*i();return new ee(n,l,h,"lch")}if(e==="rgb"){const n=255*i(),l=255*i(),h=255*i();return new ee(n,l,h)}if(e==="lab"){const n=100*i(),l=256*i()-128,h=256*i()-128;return new ee(n,l,h,"lab")}if(e==="grey"){const n=255*i();return new ee(n,n,n)}throw new Error("Unsupported random color mode")}static test(e){return typeof e=="string"&&(qi.test(e)||Zi.test(e))}cmyk(){const{_a:e,_b:t,_c:i}=this.rgb(),[a,s,r]=[e,t,i].map((l=>l/255)),n=Math.min(1-a,1-s,1-r);return n===1?new ee(0,0,0,1,"cmyk"):new ee((1-a-n)/(1-n),(1-s-n)/(1-n),(1-r-n)/(1-n),n,"cmyk")}hsl(){const{_a:e,_b:t,_c:i}=this.rgb(),[a,s,r]=[e,t,i].map((u=>u/255)),n=Math.max(a,s,r),l=Math.min(a,s,r),h=(n+l)/2,d=n===l,c=n-l;return new ee(360*(d?0:n===a?((s-r)/c+(s.5?c/(2-n-l):c/(n+l)),100*h,"hsl")}init(e=0,t=0,i=0,a=0,s="rgb"){if(e=e||0,this.space)for(const c in this.space)delete this[this.space[c]];if(typeof e=="number")s=typeof a=="string"?a:s,a=typeof a=="string"?0:a,Object.assign(this,{_a:e,_b:t,_c:i,_d:a,space:s});else if(e instanceof Array)this.space=t||(typeof e[3]=="string"?e[3]:e[4])||"rgb",Object.assign(this,{_a:e[0],_b:e[1],_c:e[2],_d:e[3]||0});else if(e instanceof Object){const c=(function(u,g){const p=et(u,"rgb")?{_a:u.r,_b:u.g,_c:u.b,_d:0,space:"rgb"}:et(u,"xyz")?{_a:u.x,_b:u.y,_c:u.z,_d:0,space:"xyz"}:et(u,"hsl")?{_a:u.h,_b:u.s,_c:u.l,_d:0,space:"hsl"}:et(u,"lab")?{_a:u.l,_b:u.a,_c:u.b,_d:0,space:"lab"}:et(u,"lch")?{_a:u.l,_b:u.c,_c:u.h,_d:0,space:"lch"}:et(u,"cmyk")?{_a:u.c,_b:u.m,_c:u.y,_d:u.k,space:"cmyk"}:{_a:0,_b:0,_c:0,space:"rgb"};return p.space=g||p.space,p})(e,t);Object.assign(this,c)}else if(typeof e=="string")if(Zi.test(e)){const c=e.replace(is,""),[u,g,p]=Ka.exec(c).slice(1,4).map((f=>parseInt(f)));Object.assign(this,{_a:u,_b:g,_c:p,_d:0,space:"rgb"})}else{if(!qi.test(e))throw Error("Unsupported string format, can't construct Color");{const c=f=>parseInt(f,16),[,u,g,p]=Qa.exec((function(f){return f.length===4?["#",f.substring(1,2),f.substring(1,2),f.substring(2,3),f.substring(2,3),f.substring(3,4),f.substring(3,4)].join(""):f})(e)).map(c);Object.assign(this,{_a:u,_b:g,_c:p,_d:0,space:"rgb"})}}const{_a:r,_b:n,_c:l,_d:h}=this,d=this.space==="rgb"?{r,g:n,b:l}:this.space==="xyz"?{x:r,y:n,z:l}:this.space==="hsl"?{h:r,s:n,l}:this.space==="lab"?{l:r,a:n,b:l}:this.space==="lch"?{l:r,c:n,h:l}:this.space==="cmyk"?{c:r,m:n,y:l,k:h}:{};Object.assign(this,d)}lab(){const{x:e,y:t,z:i}=this.xyz();return new ee(116*t-16,500*(e-t),200*(t-i),"lab")}lch(){const{l:e,a:t,b:i}=this.lab(),a=Math.sqrt(t**2+i**2);let s=180*Math.atan2(i,t)/Math.PI;return s<0&&(s*=-1,s=360-s),new ee(e,a,s,"lch")}rgb(){if(this.space==="rgb")return this;if((e=this.space)==="lab"||e==="xyz"||e==="lch"){let{x:t,y:i,z:a}=this;if(this.space==="lab"||this.space==="lch"){let{l:g,a:p,b:f}=this;if(this.space==="lch"){const{c:C,h:w}=this,A=Math.PI/180;p=C*Math.cos(A*w),f=C*Math.sin(A*w)}const x=(g+16)/116,b=p/500+x,m=x-f/200,v=16/116,k=.008856,y=7.787;t=.95047*(b**3>k?b**3:(b-v)/y),i=1*(x**3>k?x**3:(x-v)/y),a=1.08883*(m**3>k?m**3:(m-v)/y)}const s=3.2406*t+-1.5372*i+-.4986*a,r=-.9689*t+1.8758*i+.0415*a,n=.0557*t+-.204*i+1.057*a,l=Math.pow,h=.0031308,d=s>h?1.055*l(s,1/2.4)-.055:12.92*s,c=r>h?1.055*l(r,1/2.4)-.055:12.92*r,u=n>h?1.055*l(n,1/2.4)-.055:12.92*n;return new ee(255*d,255*c,255*u)}if(this.space==="hsl"){let{h:t,s:i,l:a}=this;if(t/=360,i/=100,a/=100,i===0)return a*=255,new ee(a,a,a);const s=a<.5?a*(1+i):a+i-a*i,r=2*a-s,n=255*Qt(r,s,t+1/3),l=255*Qt(r,s,t),h=255*Qt(r,s,t-1/3);return new ee(n,l,h)}if(this.space==="cmyk"){const{c:t,m:i,y:a,k:s}=this,r=255*(1-Math.min(1,t*(1-s)+s)),n=255*(1-Math.min(1,i*(1-s)+s)),l=255*(1-Math.min(1,a*(1-s)+s));return new ee(r,n,l)}return this;var e}toArray(){const{_a:e,_b:t,_c:i,_d:a,space:s}=this;return[e,t,i,a,s]}toHex(){const[e,t,i]=this._clamped().map(ss);return`#${e}${t}${i}`}toRgb(){const[e,t,i]=this._clamped();return`rgb(${e},${t},${i})`}toString(){return this.toHex()}xyz(){const{_a:e,_b:t,_c:i}=this.rgb(),[a,s,r]=[e,t,i].map((x=>x/255)),n=a>.04045?Math.pow((a+.055)/1.055,2.4):a/12.92,l=s>.04045?Math.pow((s+.055)/1.055,2.4):s/12.92,h=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92,d=(.4124*n+.3576*l+.1805*h)/.95047,c=(.2126*n+.7152*l+.0722*h)/1,u=(.0193*n+.1192*l+.9505*h)/1.08883,g=d>.008856?Math.pow(d,1/3):7.787*d+16/116,p=c>.008856?Math.pow(c,1/3):7.787*c+16/116,f=u>.008856?Math.pow(u,1/3):7.787*u+16/116;return new ee(g,p,f,"xyz")}_clamped(){const{_a:e,_b:t,_c:i}=this.rgb(),{max:a,min:s,round:r}=Math;return[e,t,i].map((n=>a(0,s(r(n),255))))}}class Q{constructor(...e){this.init(...e)}clone(){return new Q(this)}init(e,t){const s=Array.isArray(e)?{x:e[0],y:e[1]}:typeof e=="object"?{x:e.x,y:e.y}:{x:e,y:t};return this.x=s.x==null?0:s.x,this.y=s.y==null?0:s.y,this}toArray(){return[this.x,this.y]}transform(e){return this.clone().transformO(e)}transformO(e){D.isMatrixLike(e)||(e=new D(e));const{x:t,y:i}=this;return this.x=e.a*t+e.c*i+e.e,this.y=e.b*t+e.d*i+e.f,this}}function tt(o,e,t){return Math.abs(e-o)<1e-6}class D{constructor(...e){this.init(...e)}static formatTransforms(e){const t=e.flip==="both"||e.flip===!0,i=e.flip&&(t||e.flip==="x")?-1:1,a=e.flip&&(t||e.flip==="y")?-1:1,s=e.skew&&e.skew.length?e.skew[0]:isFinite(e.skew)?e.skew:isFinite(e.skewX)?e.skewX:0,r=e.skew&&e.skew.length?e.skew[1]:isFinite(e.skew)?e.skew:isFinite(e.skewY)?e.skewY:0,n=e.scale&&e.scale.length?e.scale[0]*i:isFinite(e.scale)?e.scale*i:isFinite(e.scaleX)?e.scaleX*i:i,l=e.scale&&e.scale.length?e.scale[1]*a:isFinite(e.scale)?e.scale*a:isFinite(e.scaleY)?e.scaleY*a:a,h=e.shear||0,d=e.rotate||e.theta||0,c=new Q(e.origin||e.around||e.ox||e.originX,e.oy||e.originY),u=c.x,g=c.y,p=new Q(e.position||e.px||e.positionX||NaN,e.py||e.positionY||NaN),f=p.x,x=p.y,b=new Q(e.translate||e.tx||e.translateX,e.ty||e.translateY),m=b.x,v=b.y,k=new Q(e.relative||e.rx||e.relativeX,e.ry||e.relativeY);return{scaleX:n,scaleY:l,skewX:s,skewY:r,shear:h,theta:d,rx:k.x,ry:k.y,tx:m,ty:v,ox:u,oy:g,px:f,py:x}}static fromArray(e){return{a:e[0],b:e[1],c:e[2],d:e[3],e:e[4],f:e[5]}}static isMatrixLike(e){return e.a!=null||e.b!=null||e.c!=null||e.d!=null||e.e!=null||e.f!=null}static matrixMultiply(e,t,i){const a=e.a*t.a+e.c*t.b,s=e.b*t.a+e.d*t.b,r=e.a*t.c+e.c*t.d,n=e.b*t.c+e.d*t.d,l=e.e+e.a*t.e+e.c*t.f,h=e.f+e.b*t.e+e.d*t.f;return i.a=a,i.b=s,i.c=r,i.d=n,i.e=l,i.f=h,i}around(e,t,i){return this.clone().aroundO(e,t,i)}aroundO(e,t,i){const a=e||0,s=t||0;return this.translateO(-a,-s).lmultiplyO(i).translateO(a,s)}clone(){return new D(this)}decompose(e=0,t=0){const i=this.a,a=this.b,s=this.c,r=this.d,n=this.e,l=this.f,h=i*r-a*s,d=h>0?1:-1,c=d*Math.sqrt(i*i+a*a),u=Math.atan2(d*a,d*i),g=180/Math.PI*u,p=Math.cos(u),f=Math.sin(u),x=(i*s+a*r)/h,b=s*c/(x*i-a)||r*c/(x*a+i);return{scaleX:c,scaleY:b,shear:x,rotate:g,translateX:n-e+e*p*c+t*(x*p*c-f*b),translateY:l-t+e*f*c+t*(x*f*c+p*b),originX:e,originY:t,a:this.a,b:this.b,c:this.c,d:this.d,e:this.e,f:this.f}}equals(e){if(e===this)return!0;const t=new D(e);return tt(this.a,t.a)&&tt(this.b,t.b)&&tt(this.c,t.c)&&tt(this.d,t.d)&&tt(this.e,t.e)&&tt(this.f,t.f)}flip(e,t){return this.clone().flipO(e,t)}flipO(e,t){return e==="x"?this.scaleO(-1,1,t,0):e==="y"?this.scaleO(1,-1,0,t):this.scaleO(-1,-1,e,t||e)}init(e){const t=D.fromArray([1,0,0,1,0,0]);return e=e instanceof de?e.matrixify():typeof e=="string"?D.fromArray(e.split(ze).map(parseFloat)):Array.isArray(e)?D.fromArray(e):typeof e=="object"&&D.isMatrixLike(e)?e:typeof e=="object"?new D().transform(e):arguments.length===6?D.fromArray([].slice.call(arguments)):t,this.a=e.a!=null?e.a:t.a,this.b=e.b!=null?e.b:t.b,this.c=e.c!=null?e.c:t.c,this.d=e.d!=null?e.d:t.d,this.e=e.e!=null?e.e:t.e,this.f=e.f!=null?e.f:t.f,this}inverse(){return this.clone().inverseO()}inverseO(){const e=this.a,t=this.b,i=this.c,a=this.d,s=this.e,r=this.f,n=e*a-t*i;if(!n)throw new Error("Cannot invert "+this);const l=a/n,h=-t/n,d=-i/n,c=e/n,u=-(l*s+d*r),g=-(h*s+c*r);return this.a=l,this.b=h,this.c=d,this.d=c,this.e=u,this.f=g,this}lmultiply(e){return this.clone().lmultiplyO(e)}lmultiplyO(e){const t=e instanceof D?e:new D(e);return D.matrixMultiply(t,this,this)}multiply(e){return this.clone().multiplyO(e)}multiplyO(e){const t=e instanceof D?e:new D(e);return D.matrixMultiply(this,t,this)}rotate(e,t,i){return this.clone().rotateO(e,t,i)}rotateO(e,t=0,i=0){e=Bt(e);const a=Math.cos(e),s=Math.sin(e),{a:r,b:n,c:l,d:h,e:d,f:c}=this;return this.a=r*a-n*s,this.b=n*a+r*s,this.c=l*a-h*s,this.d=h*a+l*s,this.e=d*a-c*s+i*s-t*a+t,this.f=c*a+d*s-t*s-i*a+i,this}scale(){return this.clone().scaleO(...arguments)}scaleO(e,t=e,i=0,a=0){arguments.length===3&&(a=i,i=t,t=e);const{a:s,b:r,c:n,d:l,e:h,f:d}=this;return this.a=s*e,this.b=r*t,this.c=n*e,this.d=l*t,this.e=h*e-i*e+i,this.f=d*t-a*t+a,this}shear(e,t,i){return this.clone().shearO(e,t,i)}shearO(e,t=0,i=0){const{a,b:s,c:r,d:n,e:l,f:h}=this;return this.a=a+s*e,this.c=r+n*e,this.e=l+h*e-i*e,this}skew(){return this.clone().skewO(...arguments)}skewO(e,t=e,i=0,a=0){arguments.length===3&&(a=i,i=t,t=e),e=Bt(e),t=Bt(t);const s=Math.tan(e),r=Math.tan(t),{a:n,b:l,c:h,d,e:c,f:u}=this;return this.a=n+l*s,this.b=l+n*r,this.c=h+d*s,this.d=d+h*r,this.e=c+u*s-a*s,this.f=u+c*r-i*r,this}skewX(e,t,i){return this.skew(e,0,t,i)}skewY(e,t,i){return this.skew(0,e,t,i)}toArray(){return[this.a,this.b,this.c,this.d,this.e,this.f]}toString(){return"matrix("+this.a+","+this.b+","+this.c+","+this.d+","+this.e+","+this.f+")"}transform(e){if(D.isMatrixLike(e))return new D(e).multiplyO(this);const t=D.formatTransforms(e),{x:i,y:a}=new Q(t.ox,t.oy).transform(this),s=new D().translateO(t.rx,t.ry).lmultiplyO(this).translateO(-i,-a).scaleO(t.scaleX,t.scaleY).skewO(t.skewX,t.skewY).shearO(t.shear).rotateO(t.theta).translateO(i,a);if(isFinite(t.px)||isFinite(t.py)){const r=new Q(i,a).transform(s),n=isFinite(t.px)?t.px-r.x:0,l=isFinite(t.py)?t.py-r.y:0;s.translateO(n,l)}return s.translateO(t.tx,t.ty),s}translate(e,t){return this.clone().translateO(e,t)}translateO(e,t){return this.e+=e||0,this.f+=t||0,this}valueOf(){return{a:this.a,b:this.b,c:this.c,d:this.d,e:this.e,f:this.f}}}function Ee(){if(!Ee.nodes){const o=be().size(2,0);o.node.style.cssText=["opacity: 0","position: absolute","left: -100%","top: -100%","overflow: hidden"].join(";"),o.attr("focusable","false"),o.attr("aria-hidden","true");const e=o.path().node;Ee.nodes={svg:o,path:e}}if(!Ee.nodes.svg.node.parentNode){const o=q.document.body||q.document.documentElement;Ee.nodes.svg.addTo(o)}return Ee.nodes}function Qi(o){return!(o.width||o.height||o.x||o.y)}Z(D,"Matrix");class le{constructor(...e){this.init(...e)}addOffset(){return this.x+=q.window.pageXOffset,this.y+=q.window.pageYOffset,new le(this)}init(e){return e=typeof e=="string"?e.split(ze).map(parseFloat):Array.isArray(e)?e:typeof e=="object"?[e.left!=null?e.left:e.x,e.top!=null?e.top:e.y,e.width,e.height]:arguments.length===4?[].slice.call(arguments):[0,0,0,0],this.x=e[0]||0,this.y=e[1]||0,this.width=this.w=e[2]||0,this.height=this.h=e[3]||0,this.x2=this.x+this.w,this.y2=this.y+this.h,this.cx=this.x+this.w/2,this.cy=this.y+this.h/2,this}isNulled(){return Qi(this)}merge(e){const t=Math.min(this.x,e.x),i=Math.min(this.y,e.y),a=Math.max(this.x+this.width,e.x+e.width)-t,s=Math.max(this.y+this.height,e.y+e.height)-i;return new le(t,i,a,s)}toArray(){return[this.x,this.y,this.width,this.height]}toString(){return this.x+" "+this.y+" "+this.width+" "+this.height}transform(e){e instanceof D||(e=new D(e));let t=1/0,i=-1/0,a=1/0,s=-1/0;return[new Q(this.x,this.y),new Q(this.x2,this.y),new Q(this.x,this.y2),new Q(this.x2,this.y2)].forEach((function(r){r=r.transform(e),t=Math.min(t,r.x),i=Math.max(i,r.x),a=Math.min(a,r.y),s=Math.max(s,r.y)})),new le(t,a,i-t,s-a)}}function Ki(o,e,t){let i;try{if(i=e(o.node),Qi(i)&&(a=o.node)!==q.document&&!(q.document.documentElement.contains||function(s){for(;s.parentNode;)s=s.parentNode;return s===q.document}).call(q.document.documentElement,a))throw new Error("Element not in the dom")}catch{i=t(o)}var a;return i}U({viewbox:{viewbox(o,e,t,i){return o==null?new le(this.attr("viewBox")):this.attr("viewBox",new le(o,e,t,i))},zoom(o,e){let{width:t,height:i}=this.attr(["width","height"]);if((t||i)&&typeof t!="string"&&typeof i!="string"||(t=this.node.clientWidth,i=this.node.clientHeight),!t||!i)throw new Error("Impossible to get absolute width and height. Please provide an absolute width and height attribute on the zooming element");const a=this.viewbox(),s=t/a.width,r=i/a.height,n=Math.min(s,r);if(o==null)return n;let l=n/o;l===1/0&&(l=Number.MAX_SAFE_INTEGER/100),e=e||new Q(t/2/s+a.x,i/2/r+a.y);const h=new le(a).transform(new D({scale:l,origin:e}));return this.viewbox(h)}}}),Z(le,"Box");class Ne extends Array{constructor(e=[],...t){if(super(e,...t),typeof e=="number")return this;this.length=0,this.push(...e)}}N([Ne],{each(o,...e){return typeof o=="function"?this.map(((t,i,a)=>o.call(t,t,i,a))):this.map((t=>t[o](...e)))},toArray(){return Array.prototype.concat.apply([],this)}});const rs=["toArray","constructor","each"];function We(o,e){return new Ne(_t((e||q.document).querySelectorAll(o),(function(t){return Ae(t)})))}Ne.extend=function(o){o=o.reduce(((e,t)=>(rs.includes(t)||t[0]==="_"||(t in Array.prototype&&(e["$"+t]=Array.prototype[t]),e[t]=function(...i){return this.each(t,...i)}),e)),{}),N([Ne],o)};let ns=0;const ea={};function ta(o){let e=o.getEventHolder();return e===q.window&&(e=ea),e.events||(e.events={}),e.events}function Kt(o){return o.getEventTarget()}function Xe(o,e,t,i,a){const s=t.bind(i||o),r=be(o),n=ta(r),l=Kt(r);e=Array.isArray(e)?e:e.split(ze),t._svgjsListenerId||(t._svgjsListenerId=++ns),e.forEach((function(h){const d=h.split(".")[0],c=h.split(".")[1]||"*";n[d]=n[d]||{},n[d][c]=n[d][c]||{},n[d][c][t._svgjsListenerId]=s,l.addEventListener(d,s,a||!1)}))}function Ce(o,e,t,i){const a=be(o),s=ta(a),r=Kt(a);(typeof t!="function"||(t=t._svgjsListenerId))&&(e=Array.isArray(e)?e:(e||"").split(ze)).forEach((function(n){const l=n&&n.split(".")[0],h=n&&n.split(".")[1];let d,c;if(t)s[l]&&s[l][h||"*"]&&(r.removeEventListener(l,s[l][h||"*"][t],i||!1),delete s[l][h||"*"][t]);else if(l&&h){if(s[l]&&s[l][h]){for(c in s[l][h])Ce(r,[l,h].join("."),c);delete s[l][h]}}else if(h)for(n in s)for(d in s[n])h===d&&Ce(r,[n,h].join("."));else if(l){if(s[l]){for(d in s[l])Ce(r,[l,d].join("."));delete s[l]}}else{for(n in s)Ce(r,n);(function(u){let g=u.getEventHolder();g===q.window&&(g=ea),g.events&&(g.events={})})(a)}}))}class ut extends qt{addEventListener(){}dispatch(e,t,i){return(function(a,s,r,n){const l=Kt(a);return s instanceof q.window.Event||(s=new q.window.CustomEvent(s,{detail:r,cancelable:!0,...n})),l.dispatchEvent(s),s})(this,e,t,i)}dispatchEvent(e){const t=this.getEventHolder().events;if(!t)return!0;const i=t[e.type];for(const a in i)for(const s in i[a])i[a][s](e);return!e.defaultPrevented}fire(e,t,i){return this.dispatch(e,t,i),this}getEventHolder(){return this}getEventTarget(){return this}off(e,t,i){return Ce(this,e,t,i),this}on(e,t,i,a){return Xe(this,e,t,i,a),this}removeEventListener(){}}function ia(){}Z(ut,"EventTarget");const ei=400,os=">",ls=0,hs={"fill-opacity":1,"stroke-opacity":1,"stroke-width":0,"stroke-linejoin":"miter","stroke-linecap":"butt",fill:"#000000",stroke:"#000000",opacity:1,x:0,y:0,cx:0,cy:0,width:0,height:0,r:0,rx:0,ry:0,offset:0,"stop-opacity":1,"stop-color":"#000000","text-anchor":"start"};class _e extends Array{constructor(...e){super(...e),this.init(...e)}clone(){return new this.constructor(this)}init(e){return typeof e=="number"||(this.length=0,this.push(...this.parse(e))),this}parse(e=[]){return e instanceof Array?e:e.trim().split(ze).map(parseFloat)}toArray(){return Array.prototype.concat.apply([],this)}toSet(){return new Set(this)}toString(){return this.join(" ")}valueOf(){const e=[];return e.push(...this),e}}class V{constructor(...e){this.init(...e)}convert(e){return new V(this.value,e)}divide(e){return e=new V(e),new V(this/e,this.unit||e.unit)}init(e,t){return t=Array.isArray(e)?e[1]:t,e=Array.isArray(e)?e[0]:e,this.value=0,this.unit=t||"",typeof e=="number"?this.value=isNaN(e)?0:isFinite(e)?e:e<0?-34e37:34e37:typeof e=="string"?(t=e.match(Ui))&&(this.value=parseFloat(t[1]),t[5]==="%"?this.value/=100:t[5]==="s"&&(this.value*=1e3),this.unit=t[5]):e instanceof V&&(this.value=e.valueOf(),this.unit=e.unit),this}minus(e){return e=new V(e),new V(this-e,this.unit||e.unit)}plus(e){return e=new V(e),new V(this+e,this.unit||e.unit)}times(e){return e=new V(e),new V(this*e,this.unit||e.unit)}toArray(){return[this.value,this.unit]}toJSON(){return this.toString()}toString(){return(this.unit==="%"?~~(1e8*this.value)/1e6:this.unit==="s"?this.value/1e3:this.value)+this.unit}valueOf(){return this.value}}const cs=new Set(["fill","stroke","color","bgcolor","stop-color","flood-color","lighting-color"]),aa=[];class Ye extends ut{constructor(e,t){super(),this.node=e,this.type=e.nodeName,t&&e!==t&&this.attr(t)}add(e,t){return(e=be(e)).removeNamespace&&this.node instanceof q.window.SVGElement&&e.removeNamespace(),t==null?this.node.appendChild(e.node):e.node!==this.node.childNodes[t]&&this.node.insertBefore(e.node,this.node.childNodes[t]),this}addTo(e,t){return be(e).put(this,t)}children(){return new Ne(_t(this.node.children,(function(e){return Ae(e)})))}clear(){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return this}clone(e=!0,t=!0){this.writeDataToDom();let i=this.node.cloneNode(e);return t&&(i=Vi(i)),new this.constructor(i)}each(e,t){const i=this.children();let a,s;for(a=0,s=i.length;a=0}html(e,t){return this.xml(e,t,"http://www.w3.org/1999/xhtml")}id(e){return e!==void 0||this.node.id||(this.node.id=ji(this.type)),this.attr("id",e)}index(e){return[].slice.call(this.node.childNodes).indexOf(e.node)}last(){return Ae(this.node.lastChild)}matches(e){const t=this.node,i=t.matches||t.matchesSelector||t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||t.oMatchesSelector||null;return i&&i.call(t,e)}parent(e){let t=this;if(!t.node.parentNode)return null;if(t=Ae(t.node.parentNode),!e)return t;do if(typeof e=="string"?t.matches(e):t instanceof e)return t;while(t=Ae(t.node.parentNode));return t}put(e,t){return e=be(e),this.add(e,t),e}putIn(e,t){return be(e).add(this,t)}remove(){return this.parent()&&this.parent().removeElement(this),this}removeElement(e){return this.node.removeChild(e.node),this}replace(e){return e=be(e),this.node.parentNode&&this.node.parentNode.replaceChild(e.node,this.node),e}round(e=2,t=null){const i=10**e,a=this.attr(t);for(const s in a)typeof a[s]=="number"&&(a[s]=Math.round(a[s]*i)/i);return this.attr(a),this}svg(e,t){return this.xml(e,t,Vt)}toString(){return this.id()}words(e){return this.node.textContent=e,this}wrap(e){const t=this.parent();if(!t)return this.addTo(e);const i=t.index(this);return t.put(e,i).put(this)}writeDataToDom(){return this.each((function(){this.writeDataToDom()})),this}xml(e,t,i){if(typeof e=="boolean"&&(i=t,t=e,e=null),e==null||typeof e=="function"){t=t==null||t,this.writeDataToDom();let n=this;if(e!=null){if(n=Ae(n.node.cloneNode(!0)),t){const l=e(n);if(n=l||n,l===!1)return""}n.each((function(){const l=e(this),h=l||this;l===!1?this.remove():l&&this!==h&&this.replace(h)}),!0)}return t?n.node.outerHTML:n.node.innerHTML}t=t!=null&&t;const a=dt("wrapper",i),s=q.document.createDocumentFragment();a.innerHTML=e;for(let n=a.children.length;n--;)s.appendChild(a.firstElementChild);const r=this.parent();return t?this.replace(s)&&r:this.add(s)}}N(Ye,{attr:function(o,e,t){if(o==null){o={},e=this.node.attributes;for(const i of e)o[i.nodeName]=Ji.test(i.nodeValue)?parseFloat(i.nodeValue):i.nodeValue;return o}if(o instanceof Array)return o.reduce(((i,a)=>(i[a]=this.attr(a),i)),{});if(typeof o=="object"&&o.constructor===Object)for(e in o)this.attr(e,o[e]);else if(e===null)this.node.removeAttribute(o);else{if(e==null)return(e=this.node.getAttribute(o))==null?hs[o]:Ji.test(e)?parseFloat(e):e;typeof(e=aa.reduce(((i,a)=>a(o,i,this)),e))=="number"?e=new V(e):cs.has(o)&&ee.isColor(e)?e=new ee(e):e.constructor===Array&&(e=new _e(e)),o==="leading"?this.leading&&this.leading(e):typeof t=="string"?this.node.setAttributeNS(t,o,e.toString()):this.node.setAttribute(o,e.toString()),!this.rebuild||o!=="font-size"&&o!=="x"||this.rebuild()}return this},find:function(o){return We(o,this.node)},findOne:function(o){return Ae(this.node.querySelector(o))}}),Z(Ye,"Dom");class de extends Ye{constructor(e,t){super(e,t),this.dom={},this.node.instance=this,(e.hasAttribute("data-svgjs")||e.hasAttribute("svgjs:data"))&&this.setData(JSON.parse(e.getAttribute("data-svgjs"))??JSON.parse(e.getAttribute("svgjs:data"))??{})}center(e,t){return this.cx(e).cy(t)}cx(e){return e==null?this.x()+this.width()/2:this.x(e-this.width()/2)}cy(e){return e==null?this.y()+this.height()/2:this.y(e-this.height()/2)}defs(){const e=this.root();return e&&e.defs()}dmove(e,t){return this.dx(e).dy(t)}dx(e=0){return this.x(new V(e).plus(this.x()))}dy(e=0){return this.y(new V(e).plus(this.y()))}getEventHolder(){return this}height(e){return this.attr("height",e)}move(e,t){return this.x(e).y(t)}parents(e=this.root()){const t=typeof e=="string";t||(e=be(e));const i=new Ne;let a=this;for(;(a=a.parent())&&a.node!==q.document&&a.nodeName!=="#document-fragment"&&(i.push(a),t||a.node!==e.node)&&(!t||!a.matches(e));)if(a.node===this.root().node)return null;return i}reference(e){if(!(e=this.attr(e)))return null;const t=(e+"").match(es);return t?be(t[1]):null}root(){const e=this.parent((function(t){return De[t]})(Zt));return e&&e.root()}setData(e){return this.dom=e,this}size(e,t){const i=Qe(this,e,t);return this.width(new V(i.width)).height(new V(i.height))}width(e){return this.attr("width",e)}writeDataToDom(){return Gi(this,this.dom),super.writeDataToDom()}x(e){return this.attr("x",e)}y(e){return this.attr("y",e)}}N(de,{bbox:function(){const o=Ki(this,(e=>e.getBBox()),(e=>{try{const t=e.clone().addTo(Ee().svg).show(),i=t.node.getBBox();return t.remove(),i}catch(t){throw new Error(`Getting bbox of element "${e.node.nodeName}" is not possible: ${t.toString()}`)}}));return new le(o)},rbox:function(o){const e=Ki(this,(i=>i.getBoundingClientRect()),(i=>{throw new Error(`Getting rbox of element "${i.node.nodeName}" is not possible`)})),t=new le(e);return o?t.transform(o.screenCTM().inverseO()):t.addOffset()},inside:function(o,e){const t=this.bbox();return o>t.x&&e>t.y&&o=0;t--)i[gt[o][t]]!=null&&this.attr(gt.prefix(o,gt[o][t]),i[gt[o][t]]);return this},U(["Element","Runner"],e)})),U(["Element","Runner"],{matrix:function(o,e,t,i,a,s){return o==null?new D(this):this.attr("transform",new D(o,e,t,i,a,s))},rotate:function(o,e,t){return this.transform({rotate:o,ox:e,oy:t},!0)},skew:function(o,e,t,i){return arguments.length===1||arguments.length===3?this.transform({skew:o,ox:e,oy:t},!0):this.transform({skew:[o,e],ox:t,oy:i},!0)},shear:function(o,e,t){return this.transform({shear:o,ox:e,oy:t},!0)},scale:function(o,e,t,i){return arguments.length===1||arguments.length===3?this.transform({scale:o,ox:e,oy:t},!0):this.transform({scale:[o,e],ox:t,oy:i},!0)},translate:function(o,e){return this.transform({translate:[o,e]},!0)},relative:function(o,e){return this.transform({relative:[o,e]},!0)},flip:function(o="both",e="center"){return"xybothtrue".indexOf(o)===-1&&(e=o,o="both"),this.transform({flip:o,origin:e},!0)},opacity:function(o){return this.attr("opacity",o)}}),U("radius",{radius:function(o,e=o){return(this._element||this).type==="radialGradient"?this.attr("r",new V(o)):this.rx(o).ry(e)}}),U("Path",{length:function(){return this.node.getTotalLength()},pointAt:function(o){return new Q(this.node.getPointAtLength(o))}}),U(["Element","Runner"],{font:function(o,e){if(typeof o=="object"){for(e in o)this.font(e,o[e]);return this}return o==="leading"?this.leading(e):o==="anchor"?this.attr("text-anchor",e):o==="size"||o==="family"||o==="weight"||o==="stretch"||o==="variant"||o==="style"?this.attr("font-"+o,e):this.attr(o,e)}}),U("Element",["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","touchstart","touchmove","touchleave","touchend","touchcancel","contextmenu","wheel","pointerdown","pointermove","pointerup","pointerleave","pointercancel"].reduce((function(o,e){return o[e]=function(t){return t===null?this.off(e):this.on(e,t),this},o}),{})),U("Element",{untransform:function(){return this.attr("transform",null)},matrixify:function(){return(this.attr("transform")||"").split(ts).slice(0,-1).map((function(e){const t=e.trim().split("(");return[t[0],t[1].split(ze).map((function(i){return parseFloat(i)}))]})).reverse().reduce((function(e,t){return t[0]==="matrix"?e.lmultiply(D.fromArray(t[1])):e[t[0]].apply(e,t[1])}),new D)},toParent:function(o,e){if(this===o)return this;if(jt(this.node))return this.addTo(o,e);const t=this.screenCTM(),i=o.screenCTM().inverse();return this.addTo(o,e).untransform().transform(i.multiply(t)),this},toRoot:function(o){return this.toParent(this.root(),o)},transform:function(o,e){if(o==null||typeof o=="string"){const i=new D(this).decompose();return o==null?i:i[o]}D.isMatrixLike(o)||(o={...o,origin:Gt(o,this)});const t=new D(e===!0?this:e||!1).transform(o);return this.attr("transform",t)}});class me extends de{flatten(){return this.each((function(){if(this instanceof me)return this.flatten().ungroup()})),this}ungroup(e=this.parent(),t=e.index(this)){return t=t===-1?e.children().length:t,this.each((function(i,a){return a[a.length-i-1].toParent(e,t)})),this.remove()}}Z(me,"Container");class Lt extends me{constructor(e,t=e){super(ie("defs",e),t)}flatten(){return this}ungroup(){return this}}Z(Lt,"Defs");class we extends de{}function ti(o){return this.attr("rx",o)}function ii(o){return this.attr("ry",o)}function sa(o){return o==null?this.cx()-this.rx():this.cx(o+this.rx())}function ra(o){return o==null?this.cy()-this.ry():this.cy(o+this.ry())}function na(o){return this.attr("cx",o)}function oa(o){return this.attr("cy",o)}function la(o){return o==null?2*this.rx():this.rx(new V(o).divide(2))}function ha(o){return o==null?2*this.ry():this.ry(new V(o).divide(2))}Z(we,"Shape");var ds=Object.freeze({__proto__:null,cx:na,cy:oa,height:ha,rx:ti,ry:ii,width:la,x:sa,y:ra});class Mt extends we{constructor(e,t=e){super(ie("ellipse",e),t)}size(e,t){const i=Qe(this,e,t);return this.rx(new V(i.width).divide(2)).ry(new V(i.height).divide(2))}}N(Mt,ds),U("Container",{ellipse:ae((function(o=0,e=o){return this.put(new Mt).size(o,e).move(0,0)}))}),Z(Mt,"Ellipse");class ca extends Ye{constructor(e=q.document.createDocumentFragment()){super(e)}xml(e,t,i){if(typeof e=="boolean"&&(i=t,t=e,e=null),e==null||typeof e=="function"){const a=new Ye(dt("wrapper",i));return a.add(this.node.cloneNode(!0)),a.xml(!1,i)}return super.xml(e,!1,i)}}function da(o,e){return(this._element||this).type==="radialGradient"?this.attr({fx:new V(o),fy:new V(e)}):this.attr({x1:new V(o),y1:new V(e)})}function ua(o,e){return(this._element||this).type==="radialGradient"?this.attr({cx:new V(o),cy:new V(e)}):this.attr({x2:new V(o),y2:new V(e)})}Z(ca,"Fragment");var us=Object.freeze({__proto__:null,from:da,to:ua});class ft extends me{constructor(e,t){super(ie(e+"Gradient",typeof e=="string"?null:e),t)}attr(e,t,i){return e==="transform"&&(e="gradientTransform"),super.attr(e,t,i)}bbox(){return new le}targets(){return We("svg [fill*="+this.id()+"]")}toString(){return this.url()}update(e){return this.clear(),typeof e=="function"&&e.call(this,this),this}url(){return"url(#"+this.id()+")"}}N(ft,us),U({Container:{gradient(...o){return this.defs().gradient(...o)}},Defs:{gradient:ae((function(o,e){return this.put(new ft(o)).update(e)}))}}),Z(ft,"Gradient");class pt extends me{constructor(e,t=e){super(ie("pattern",e),t)}attr(e,t,i){return e==="transform"&&(e="patternTransform"),super.attr(e,t,i)}bbox(){return new le}targets(){return We("svg [fill*="+this.id()+"]")}toString(){return this.url()}update(e){return this.clear(),typeof e=="function"&&e.call(this,this),this}url(){return"url(#"+this.id()+")"}}U({Container:{pattern(...o){return this.defs().pattern(...o)}},Defs:{pattern:ae((function(o,e,t){return this.put(new pt).update(t).attr({x:0,y:0,width:o,height:e,patternUnits:"userSpaceOnUse"})}))}}),Z(pt,"Pattern");let Pt=class extends we{constructor(o,e=o){super(ie("image",o),e)}load(o,e){if(!o)return this;const t=new q.window.Image;return Xe(t,"load",(function(i){const a=this.parent(pt);this.width()===0&&this.height()===0&&this.size(t.width,t.height),a instanceof pt&&a.width()===0&&a.height()===0&&a.size(this.width(),this.height()),typeof e=="function"&&e.call(this,i)}),this),Xe(t,"load error",(function(){Ce(t)})),this.attr("href",t.src=o,Ke)}};var ga;ga=function(o,e,t){return o!=="fill"&&o!=="stroke"||as.test(e)&&(e=t.root().defs().image(e)),e instanceof Pt&&(e=t.root().defs().pattern(0,0,(i=>{i.add(e)}))),e},aa.push(ga),U({Container:{image:ae((function(o,e){return this.put(new Pt).size(0,0).load(o,e)}))}}),Z(Pt,"Image");class He extends _e{bbox(){let e=-1/0,t=-1/0,i=1/0,a=1/0;return this.forEach((function(s){e=Math.max(s[0],e),t=Math.max(s[1],t),i=Math.min(s[0],i),a=Math.min(s[1],a)})),new le(i,a,e-i,t-a)}move(e,t){const i=this.bbox();if(e-=i.x,t-=i.y,!isNaN(e)&&!isNaN(t))for(let a=this.length-1;a>=0;a--)this[a]=[this[a][0]+e,this[a][1]+t];return this}parse(e=[0,0]){const t=[];(e=e instanceof Array?Array.prototype.concat.apply([],e):e.trim().split(ze).map(parseFloat)).length%2!=0&&e.pop();for(let i=0,a=e.length;i=0;i--)a.width&&(this[i][0]=(this[i][0]-a.x)*e/a.width+a.x),a.height&&(this[i][1]=(this[i][1]-a.y)*t/a.height+a.y);return this}toLine(){return{x1:this[0][0],y1:this[0][1],x2:this[1][0],y2:this[1][1]}}toString(){const e=[];for(let t=0,i=this.length;t":function(o){return-Math.cos(o*Math.PI)/2+.5},">":function(o){return Math.sin(o*Math.PI/2)},"<":function(o){return 1-Math.cos(o*Math.PI/2)},bezier:function(o,e,t,i){return function(a){return a<0?o>0?e/o*a:t>0?i/t*a:0:a>1?t<1?(1-i)/(1-t)*a+(i-t)/(1-t):o<1?(1-e)/(1-o)*a+(e-o)/(1-o):1:3*a*(1-a)**2*e+3*a**2*(1-a)*i+a**3}},steps:function(o,e="end"){e=e.split("-").reverse()[0];let t=o;return e==="none"?--t:e==="both"&&++t,(i,a=!1)=>{let s=Math.floor(i*o);const r=i*s%1==0;return e!=="start"&&e!=="both"||++s,a&&r&&--s,i>=0&&s<0&&(s=0),i<=1&&s>t&&(s=t),s/t}}};class si{done(){return!1}}class ri extends si{constructor(e=os){super(),this.ease=gs[e]||e}step(e,t,i){return typeof e!="number"?i<1?e:t:e+(t-e)*this.ease(i)}}class Tt extends si{constructor(e){super(),this.stepper=e}done(e){return e.done}step(e,t,i,a){return this.stepper(e,t,i,a)}}function fa(){const o=(this._duration||500)/1e3,e=this._overshoot||0,t=Math.PI,i=Math.log(e/100+1e-10),a=-i/Math.sqrt(t*t+i*i),s=3.9/(a*o);this.d=2*a*s,this.k=s*s}N(class extends Tt{constructor(o=500,e=0){super(),this.duration(o).overshoot(e)}step(o,e,t,i){if(typeof o=="string")return o;if(i.done=t===1/0,t===1/0)return e;if(t===0)return o;t>100&&(t=16),t/=1e3;const a=i.velocity||0,s=-this.d*a-this.k*(o-e),r=o+a*t+s*t*t/2;return i.velocity=a+s*t,i.done=Math.abs(e-r)+Math.abs(a)<.002,i.done?e:r}},{duration:it("_duration",fa),overshoot:it("_overshoot",fa)}),N(class extends Tt{constructor(o=.1,e=.01,t=0,i=1e3){super(),this.p(o).i(e).d(t).windup(i)}step(o,e,t,i){if(typeof o=="string")return o;if(i.done=t===1/0,t===1/0)return e;if(t===0)return o;const a=e-o;let s=(i.integral||0)+a*t;const r=(a-(i.error||0))/t,n=this._windup;return n!==!1&&(s=Math.max(-n,Math.min(s,n))),i.error=a,i.integral=s,i.done=Math.abs(a)<.001,i.done?e:o+(this.P*a+this.I*s+this.D*r)}},{windup:it("_windup"),p:it("P"),i:it("I"),d:it("D")});const fs={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},ni={M:function(o,e,t){return e.x=t.x=o[0],e.y=t.y=o[1],["M",e.x,e.y]},L:function(o,e){return e.x=o[0],e.y=o[1],["L",o[0],o[1]]},H:function(o,e){return e.x=o[0],["H",o[0]]},V:function(o,e){return e.y=o[0],["V",o[0]]},C:function(o,e){return e.x=o[4],e.y=o[5],["C",o[0],o[1],o[2],o[3],o[4],o[5]]},S:function(o,e){return e.x=o[2],e.y=o[3],["S",o[0],o[1],o[2],o[3]]},Q:function(o,e){return e.x=o[2],e.y=o[3],["Q",o[0],o[1],o[2],o[3]]},T:function(o,e){return e.x=o[0],e.y=o[1],["T",o[0],o[1]]},Z:function(o,e,t){return e.x=t.x,e.y=t.y,["Z"]},A:function(o,e){return e.x=o[5],e.y=o[6],["A",o[0],o[1],o[2],o[3],o[4],o[5],o[6]]}},oi="mlhvqtcsaz".split("");for(let o=0,e=oi.length;o=0;s--)a=this[s][0],a==="M"||a==="L"||a==="T"?(this[s][1]+=e,this[s][2]+=t):a==="H"?this[s][1]+=e:a==="V"?this[s][1]+=t:a==="C"||a==="S"||a==="Q"?(this[s][1]+=e,this[s][2]+=t,this[s][3]+=e,this[s][4]+=t,a==="C"&&(this[s][5]+=e,this[s][6]+=t)):a==="A"&&(this[s][6]+=e,this[s][7]+=t);return this}parse(e="M0 0"){return Array.isArray(e)&&(e=Array.prototype.concat.apply([],e).toString()),(function(t,i=!0){let a=0,s="";const r={segment:[],inNumber:!1,number:"",lastToken:"",inSegment:!1,segments:[],pointSeen:!1,hasExponent:!1,absolute:i,p0:new Q,p:new Q};for(;r.lastToken=s,s=t.charAt(a++);)if(r.inSegment||!ps(r,s))if(s!==".")if(isNaN(parseInt(s)))if(ms.has(s))r.inNumber&&Ge(r,!1);else if(s!=="-"&&s!=="+")if(s.toUpperCase()!=="E"){if(Jt.test(s)){if(r.inNumber)Ge(r,!1);else{if(!li(r))throw new Error("parser Error");hi(r)}--a}}else r.number+=s,r.hasExponent=!0;else{if(r.inNumber&&!bs(r)){Ge(r,!1),--a;continue}r.number+=s,r.inNumber=!0}else{if(r.number==="0"||xs(r)){r.inNumber=!0,r.number=s,Ge(r,!0);continue}r.inNumber=!0,r.number+=s}else{if(r.pointSeen||r.hasExponent){Ge(r,!1),--a;continue}r.inNumber=!0,r.pointSeen=!0,r.number+=s}return r.inNumber&&Ge(r,!1),r.inSegment&&li(r)&&hi(r),r.segments})(e)}size(e,t){const i=this.bbox();let a,s;for(i.width=i.width===0?1:i.width,i.height=i.height===0?1:i.height,a=this.length-1;a>=0;a--)s=this[a][0],s==="M"||s==="L"||s==="T"?(this[a][1]=(this[a][1]-i.x)*e/i.width+i.x,this[a][2]=(this[a][2]-i.y)*t/i.height+i.y):s==="H"?this[a][1]=(this[a][1]-i.x)*e/i.width+i.x:s==="V"?this[a][1]=(this[a][1]-i.y)*t/i.height+i.y:s==="C"||s==="S"||s==="Q"?(this[a][1]=(this[a][1]-i.x)*e/i.width+i.x,this[a][2]=(this[a][2]-i.y)*t/i.height+i.y,this[a][3]=(this[a][3]-i.x)*e/i.width+i.x,this[a][4]=(this[a][4]-i.y)*t/i.height+i.y,s==="C"&&(this[a][5]=(this[a][5]-i.x)*e/i.width+i.x,this[a][6]=(this[a][6]-i.y)*t/i.height+i.y)):s==="A"&&(this[a][1]=this[a][1]*e/i.width,this[a][2]=this[a][2]*t/i.height,this[a][6]=(this[a][6]-i.x)*e/i.width+i.x,this[a][7]=(this[a][7]-i.y)*t/i.height+i.y);return this}toString(){return(function(e){let t="";for(let i=0,a=e.length;i{const e=typeof o;return e==="number"?V:e==="string"?ee.isColor(o)?ee:ze.test(o)?Jt.test(o)?Me:_e:Ui.test(o)?V:ci:di.indexOf(o.constructor)>-1?o.constructor:Array.isArray(o)?_e:e==="object"?bt:ci};class je{constructor(e){this._stepper=e||new ri("-"),this._from=null,this._to=null,this._type=null,this._context=null,this._morphObj=null}at(e){return this._morphObj.morph(this._from,this._to,e,this._stepper,this._context)}done(){return this._context.map(this._stepper.done).reduce((function(e,t){return e&&t}),!0)}from(e){return e==null?this._from:(this._from=this._set(e),this)}stepper(e){return e==null?this._stepper:(this._stepper=e,this)}to(e){return e==null?this._to:(this._to=this._set(e),this)}type(e){return e==null?this._type:(this._type=e,this)}_set(e){this._type||this.type(pa(e));let t=new this._type(e);return this._type===ee&&(t=this._to?t[this._to[4]]():this._from?t[this._from[4]]():t),this._type===bt&&(t=this._to?t.align(this._to):this._from?t.align(this._from):t),t=t.toConsumable(),this._morphObj=this._morphObj||new this._type,this._context=this._context||Array.apply(null,Array(t.length)).map(Object).map((function(i){return i.done=!0,i})),t}}class ci{constructor(...e){this.init(...e)}init(e){return e=Array.isArray(e)?e[0]:e,this.value=e,this}toArray(){return[this.value]}valueOf(){return this.value}}class xt{constructor(...e){this.init(...e)}init(e){return Array.isArray(e)&&(e={scaleX:e[0],scaleY:e[1],shear:e[2],rotate:e[3],translateX:e[4],translateY:e[5],originX:e[6],originY:e[7]}),Object.assign(this,xt.defaults,e),this}toArray(){const e=this;return[e.scaleX,e.scaleY,e.shear,e.rotate,e.translateX,e.translateY,e.originX,e.originY]}}xt.defaults={scaleX:1,scaleY:1,shear:0,rotate:0,translateX:0,translateY:0,originX:0,originY:0};const vs=(o,e)=>o[0]e[0]?1:0;class bt{constructor(...e){this.init(...e)}align(e){const t=this.values;for(let i=0,a=t.length;ii.concat(a)),[]),this}toArray(){return this.values}valueOf(){const e={},t=this.values;for(;t.length;){const i=t.shift(),a=t.shift(),s=t.shift(),r=t.splice(0,s);e[i]=new a(r)}return e}}const di=[ci,xt,bt];class at extends we{constructor(e,t=e){super(ie("path",e),t)}array(){return this._array||(this._array=new Me(this.attr("d")))}clear(){return delete this._array,this}height(e){return e==null?this.bbox().height:this.size(this.bbox().width,e)}move(e,t){return this.attr("d",this.array().move(e,t))}plot(e){return e==null?this.array():this.clear().attr("d",typeof e=="string"?e:this._array=new Me(e))}size(e,t){const i=Qe(this,e,t);return this.attr("d",this.array().size(i.width,i.height))}width(e){return e==null?this.bbox().width:this.size(e,this.bbox().height)}x(e){return e==null?this.bbox().x:this.move(e,this.bbox().y)}y(e){return e==null?this.bbox().y:this.move(this.bbox().x,e)}}at.prototype.MorphArray=Me,U({Container:{path:ae((function(o){return this.put(new at).plot(o||new Me)}))}}),Z(at,"Path");var xa=Object.freeze({__proto__:null,array:function(){return this._array||(this._array=new He(this.attr("points")))},clear:function(){return delete this._array,this},move:function(o,e){return this.attr("points",this.array().move(o,e))},plot:function(o){return o==null?this.array():this.clear().attr("points",typeof o=="string"?o:this._array=new He(o))},size:function(o,e){const t=Qe(this,o,e);return this.attr("points",this.array().size(t.width,t.height))}});class Ve extends we{constructor(e,t=e){super(ie("polygon",e),t)}}U({Container:{polygon:ae((function(o){return this.put(new Ve).plot(o||new He)}))}}),N(Ve,ai),N(Ve,xa),Z(Ve,"Polygon");class Ue extends we{constructor(e,t=e){super(ie("polyline",e),t)}}U({Container:{polyline:ae((function(o){return this.put(new Ue).plot(o||new He)}))}}),N(Ue,ai),N(Ue,xa),Z(Ue,"Polyline");class zt extends we{constructor(e,t=e){super(ie("rect",e),t)}}N(zt,{rx:ti,ry:ii}),U({Container:{rect:ae((function(o,e){return this.put(new zt).size(o,e)}))}}),Z(zt,"Rect");class ui{constructor(){this._first=null,this._last=null}first(){return this._first&&this._first.value}last(){return this._last&&this._last.value}push(e){const t=e.next!==void 0?e:{value:e,next:null,prev:null};return this._last?(t.prev=this._last,this._last.next=t,this._last=t):(this._last=t,this._first=t),t}remove(e){e.prev&&(e.prev.next=e.next),e.next&&(e.next.prev=e.prev),e===this._last&&(this._last=e.prev),e===this._first&&(this._first=e.next),e.prev=null,e.next=null}shift(){const e=this._first;return e?(this._first=e.next,this._first&&(this._first.prev=null),this._last=this._first?this._last:null,e.value):null}}const K={nextDraw:null,frames:new ui,timeouts:new ui,immediates:new ui,timer:()=>q.window.performance||q.window.Date,transforms:[],frame(o){const e=K.frames.push({run:o});return K.nextDraw===null&&(K.nextDraw=q.window.requestAnimationFrame(K._draw)),e},timeout(o,e){e=e||0;const t=K.timer().now()+e,i=K.timeouts.push({run:o,time:t});return K.nextDraw===null&&(K.nextDraw=q.window.requestAnimationFrame(K._draw)),i},immediate(o){const e=K.immediates.push(o);return K.nextDraw===null&&(K.nextDraw=q.window.requestAnimationFrame(K._draw)),e},cancelFrame(o){o!=null&&K.frames.remove(o)},clearTimeout(o){o!=null&&K.timeouts.remove(o)},cancelImmediate(o){o!=null&&K.immediates.remove(o)},_draw(o){let e=null;const t=K.timeouts.last();for(;(e=K.timeouts.shift())&&(o>=e.time?e.run():K.timeouts.push(e),e!==t););let i=null;const a=K.frames.last();for(;i!==a&&(i=K.frames.shift());)i.run(o);let s=null;for(;s=K.immediates.shift();)s();K.nextDraw=K.timeouts.first()||K.frames.first()?q.window.requestAnimationFrame(K._draw):null}},ys=function(o){const e=o.start,t=o.runner.duration();return{start:e,duration:t,end:e+t,runner:o.runner}},ws=function(){const o=q.window;return(o.performance||o.Date).now()};class ba extends ut{constructor(e=ws){super(),this._timeSource=e,this.terminate()}active(){return!!this._nextFrame}finish(){return this.time(this.getEndTimeOfTimeline()+1),this.pause()}getEndTime(){const e=this.getLastRunnerInfo(),t=e?e.runner.duration():0;return(e?e.start:this._time)+t}getEndTimeOfTimeline(){const e=this._runners.map((t=>t.start+t.runner.duration()));return Math.max(0,...e)}getLastRunnerInfo(){return this.getRunnerInfoById(this._lastRunnerId)}getRunnerInfoById(e){return this._runners[this._runnerIds.indexOf(e)]||null}pause(){return this._paused=!0,this._continue()}persist(e){return e==null?this._persist:(this._persist=e,this)}play(){return this._paused=!1,this.updateTime()._continue()}reverse(e){const t=this.speed();if(e==null)return this.speed(-t);const i=Math.abs(t);return this.speed(e?-i:i)}schedule(e,t,i){if(e==null)return this._runners.map(ys);let a=0;const s=this.getEndTime();if(t=t||0,i==null||i==="last"||i==="after")a=s;else if(i==="absolute"||i==="start")a=t,t=0;else if(i==="now")a=this._time;else if(i==="relative"){const l=this.getRunnerInfoById(e.id);l&&(a=l.start+t,t=0)}else{if(i!=="with-last")throw new Error('Invalid value for the "when" parameter');{const l=this.getLastRunnerInfo();a=l?l.start:this._time}}e.unschedule(),e.timeline(this);const r=e.persist(),n={persist:r===null?this._persist:r,start:a+t,runner:e};return this._lastRunnerId=e.id,this._runners.push(n),this._runners.sort(((l,h)=>l.start-h.start)),this._runnerIds=this._runners.map((l=>l.runner.id)),this.updateTime()._continue(),this}seek(e){return this.time(this._time+e)}source(e){return e==null?this._timeSource:(this._timeSource=e,this)}speed(e){return e==null?this._speed:(this._speed=e,this)}stop(){return this.time(0),this.pause()}time(e){return e==null?this._time:(this._time=e,this._continue(!0))}unschedule(e){const t=this._runnerIds.indexOf(e.id);return t<0||(this._runners.splice(t,1),this._runnerIds.splice(t,1),e.timeline(null)),this}updateTime(){return this.active()||(this._lastSourceTime=this._timeSource()),this}_continue(e=!1){return K.cancelFrame(this._nextFrame),this._nextFrame=null,e?this._stepImmediate():(this._paused||(this._nextFrame=K.frame(this._step)),this)}_stepFn(e=!1){const t=this._timeSource();let i=t-this._lastSourceTime;e&&(i=0);const a=this._speed*i+(this._time-this._lastStepTime);this._lastSourceTime=t,e||(this._time+=a,this._time=this._time<0?0:this._time),this._lastStepTime=this._time,this.fire("time",this._time);for(let r=this._runners.length;r--;){const n=this._runners[r],l=n.runner;this._time-n.start<=0&&l.reset()}let s=!1;for(let r=0,n=this._runners.length;r0?this._continue():(this.pause(),this.fire("finished")),this}terminate(){this._startTime=0,this._speed=1,this._persist=0,this._nextFrame=null,this._paused=!0,this._runners=[],this._runnerIds=[],this._lastRunnerId=-1,this._time=0,this._lastSourceTime=0,this._lastStepTime=0,this._step=this._stepFn.bind(this,!1),this._stepImmediate=this._stepFn.bind(this,!0)}}U({Element:{timeline:function(o){return o==null?(this._timeline=this._timeline||new ba,this._timeline):(this._timeline=o,this)}}});class ke extends ut{constructor(e){super(),this.id=ke.id++,e=typeof(e=e??ei)=="function"?new Tt(e):e,this._element=null,this._timeline=null,this.done=!1,this._queue=[],this._duration=typeof e=="number"&&e,this._isDeclarative=e instanceof Tt,this._stepper=this._isDeclarative?e:new ri,this._history={},this.enabled=!0,this._time=0,this._lastTime=0,this._reseted=!0,this.transforms=new D,this.transformId=1,this._haveReversed=!1,this._reverse=!1,this._loopsDone=0,this._swing=!1,this._wait=0,this._times=1,this._frameId=null,this._persist=!!this._isDeclarative||null}static sanitise(e,t,i){let a=1,s=!1,r=0;return t=t??ls,i=i||"last",typeof(e=e??ei)!="object"||e instanceof si||(t=e.delay??t,i=e.when??i,s=e.swing||s,a=e.times??a,r=e.wait??r,e=e.duration??ei),{duration:e,delay:t,swing:s,times:a,wait:r,when:i}}active(e){return e==null?this.enabled:(this.enabled=e,this)}addTransform(e){return this.transforms.lmultiplyO(e),this}after(e){return this.on("finished",e)}animate(e,t,i){const a=ke.sanitise(e,t,i),s=new ke(a.duration);return this._timeline&&s.timeline(this._timeline),this._element&&s.element(this._element),s.loop(a).schedule(a.delay,a.when)}clearTransform(){return this.transforms=new D,this}clearTransformsFromQueue(){this.done&&this._timeline&&this._timeline._runnerIds.includes(this.id)||(this._queue=this._queue.filter((e=>!e.isTransform)))}delay(e){return this.animate(0,e)}duration(){return this._times*(this._wait+this._duration)-this._wait}during(e){return this.queue(null,e)}ease(e){return this._stepper=new ri(e),this}element(e){return e==null?this._element:(this._element=e,e._prepareRunner(),this)}finish(){return this.step(1/0)}loop(e,t,i){return typeof e=="object"&&(t=e.swing,i=e.wait,e=e.times),this._times=e||1/0,this._swing=t||!1,this._wait=i||0,this._times===!0&&(this._times=1/0),this}loops(e){const t=this._duration+this._wait;if(e==null){const s=Math.floor(this._time/t),r=(this._time-s*t)/this._duration;return Math.min(s+r,this._times)}const i=e%1,a=t*Math.floor(e)+this._duration*i;return this.time(a)}persist(e){return e==null?this._persist:(this._persist=e,this)}position(e){const t=this._time,i=this._duration,a=this._wait,s=this._times,r=this._swing,n=this._reverse;let l;if(e==null){const c=function(g){const p=r*Math.floor(g%(2*(a+i))/(a+i)),f=p&&!n||!p&&n,x=Math.pow(-1,f)*(g%(a+i))/i+f;return Math.max(Math.min(x,1),0)},u=s*(a+i)-a;return l=t<=0?Math.round(c(1e-5)):t=0;this._lastPosition=t;const a=this.duration(),s=this._lastTime<=0&&this._time>0,r=this._lastTime=a;this._lastTime=this._time,s&&this.fire("start",this);const n=this._isDeclarative;this.done=!n&&!r&&this._time>=a,this._reseted=!1;let l=!1;return(i||n)&&(this._initialise(i),this.transforms=new D,l=this._run(n?e:t),this.fire("step",this)),this.done=this.done||l&&n,r&&this.fire("finished",this),this}time(e){if(e==null)return this._time;const t=e-this._time;return this.step(t),this}timeline(e){return e===void 0?this._timeline:(this._timeline=e,this)}unschedule(){const e=this.timeline();return e&&e.unschedule(this),this}_initialise(e){if(e||this._isDeclarative)for(let t=0,i=this._queue.length;to.lmultiplyO(e),va=o=>o.transforms;function ks(){const o=this._transformationRunners.runners.map(va).reduce(ma,new D);this.transform(o),this._transformationRunners.merge(),this._transformationRunners.length()===1&&(this._frameId=null)}class As{constructor(){this.runners=[],this.ids=[]}add(e){if(this.runners.includes(e))return;const t=e.id+1;return this.runners.push(e),this.ids.push(t),this}clearBefore(e){const t=this.ids.indexOf(e+1)||1;return this.ids.splice(0,t,0),this.runners.splice(0,t,new Xt).forEach((i=>i.clearTransformsFromQueue())),this}edit(e,t){const i=this.ids.indexOf(e+1);return this.ids.splice(i,1,e+1),this.runners.splice(i,1,t),this}getByID(e){return this.runners[this.ids.indexOf(e+1)]}length(){return this.ids.length}merge(){let e=null;for(let t=0;te.id<=o.id)).map(va).reduce(ma,new D)},_addRunner(o){this._transformationRunners.add(o),K.cancelImmediate(this._frameId),this._frameId=K.immediate(ks.bind(this))},_prepareRunner(){this._frameId==null&&(this._transformationRunners=new As().add(new Xt(new D(this))))}}}),N(ke,{attr(o,e){return this.styleAttr("attr",o,e)},css(o,e){return this.styleAttr("css",o,e)},styleAttr(o,e,t){if(typeof e=="string")return this.styleAttr(o,{[e]:t});let i=e;if(this._tryRetarget(o,i))return this;let a=new je(this._stepper).to(i),s=Object.keys(i);return this.queue((function(){a=a.from(this.element()[o](s))}),(function(r){return this.element()[o](a.at(r).valueOf()),a.done()}),(function(r){const n=Object.keys(r),l=(h=s,n.filter((c=>!h.includes(c))));var h;if(l.length){const c=this.element()[o](l),u=new bt(a.from()).valueOf();Object.assign(u,c),a.from(u)}const d=new bt(a.to()).valueOf();Object.assign(d,r),a.to(d),s=n,i=r})),this._rememberMorpher(o,a),this},zoom(o,e){if(this._tryRetarget("zoom",o,e))return this;let t=new je(this._stepper).to(new V(o));return this.queue((function(){t=t.from(this.element().zoom())}),(function(i){return this.element().zoom(t.at(i),e),t.done()}),(function(i,a){e=a,t.to(i)})),this._rememberMorpher("zoom",t),this},transform(o,e,t){if(e=o.relative||e,this._isDeclarative&&!e&&this._tryRetarget("transform",o))return this;const i=D.isMatrixLike(o);t=o.affine!=null?o.affine:t??!i;const a=new je(this._stepper).type(t?xt:D);let s,r,n,l,h;return this.queue((function(){r=r||this.element(),s=s||Gt(o,r),h=new D(e?void 0:r),r._addRunner(this),e||r._clearTransformRunnersBefore(this)}),(function(d){e||this.clearTransform();const{x:c,y:u}=new Q(s).transform(r._currentTransform(this));let g=new D({...o,origin:[c,u]}),p=this._isDeclarative&&n?n:h;if(t){g=g.decompose(c,u),p=p.decompose(c,u);const x=g.rotate,b=p.rotate,m=[x-360,x,x+360],v=m.map((C=>Math.abs(C-b))),k=Math.min(...v),y=v.indexOf(k);g.rotate=m[y]}e&&(i||(g.rotate=o.rotate||0),this._isDeclarative&&l&&(p.rotate=l)),a.from(p),a.to(g);const f=a.at(d);return l=f.rotate,n=new D(f),this.addTransform(n),r._addRunner(this),a.done()}),(function(d){(d.origin||"center").toString()!==(o.origin||"center").toString()&&(s=Gt(d,r)),o={...d,origin:s}}),!0),this._isDeclarative&&this._rememberMorpher("transform",a),this},x(o){return this._queueNumber("x",o)},y(o){return this._queueNumber("y",o)},ax(o){return this._queueNumber("ax",o)},ay(o){return this._queueNumber("ay",o)},dx(o=0){return this._queueNumberDelta("x",o)},dy(o=0){return this._queueNumberDelta("y",o)},dmove(o,e){return this.dx(o).dy(e)},_queueNumberDelta(o,e){if(e=new V(e),this._tryRetarget(o,e))return this;const t=new je(this._stepper).to(e);let i=null;return this.queue((function(){i=this.element()[o](),t.from(i),t.to(i+e)}),(function(a){return this.element()[o](t.at(a)),t.done()}),(function(a){t.to(i+new V(a))})),this._rememberMorpher(o,t),this},_queueObject(o,e){if(this._tryRetarget(o,e))return this;const t=new je(this._stepper).to(e);return this.queue((function(){t.from(this.element()[o]())}),(function(i){return this.element()[o](t.at(i)),t.done()})),this._rememberMorpher(o,t),this},_queueNumber(o,e){return this._queueObject(o,new V(e))},cx(o){return this._queueNumber("cx",o)},cy(o){return this._queueNumber("cy",o)},move(o,e){return this.x(o).y(e)},amove(o,e){return this.ax(o).ay(e)},center(o,e){return this.cx(o).cy(e)},size(o,e){let t;return o&&e||(t=this._element.bbox()),o||(o=t.width/t.height*e),e||(e=t.height/t.width*o),this.width(o).height(e)},width(o){return this._queueNumber("width",o)},height(o){return this._queueNumber("height",o)},plot(o,e,t,i){if(arguments.length===4)return this.plot([o,e,t,i]);if(this._tryRetarget("plot",o))return this;const a=new je(this._stepper).type(this._element.MorphArray).to(o);return this.queue((function(){a.from(this._element.array())}),(function(s){return this._element.plot(a.at(s)),a.done()})),this._rememberMorpher("plot",a),this},leading(o){return this._queueNumber("leading",o)},viewbox(o,e,t,i){return this._queueObject("viewbox",new le(o,e,t,i))},update(o){return typeof o!="object"?this.update({offset:arguments[0],color:arguments[1],opacity:arguments[2]}):(o.opacity!=null&&this.attr("stop-opacity",o.opacity),o.color!=null&&this.attr("stop-color",o.color),o.offset!=null&&this.attr("offset",o.offset),this)}}),N(ke,{rx:ti,ry:ii,from:da,to:ua}),Z(ke,"Runner");class gi extends me{constructor(e,t=e){super(ie("svg",e),t),this.namespace()}defs(){return this.isRoot()?Ae(this.node.querySelector("defs"))||this.put(new Lt):this.root().defs()}isRoot(){return!this.node.parentNode||!(this.node.parentNode instanceof q.window.SVGElement)&&this.node.parentNode.nodeName!=="#document-fragment"}namespace(){return this.isRoot()?this.attr({xmlns:Vt,version:"1.1"}).attr("xmlns:xlink",Ke,Ut):this.root().namespace()}removeNamespace(){return this.attr({xmlns:null,version:null}).attr("xmlns:xlink",null,Ut).attr("xmlns:svgjs",null,Ut)}root(){return this.isRoot()?this:super.root()}}U({Container:{nested:ae((function(){return this.put(new gi)}))}}),Z(gi,"Svg",!0);let fi=class extends me{constructor(o,e=o){super(ie("symbol",o),e)}};U({Container:{symbol:ae((function(){return this.put(new fi)}))}}),Z(fi,"Symbol");var ya=Object.freeze({__proto__:null,amove:function(o,e){return this.ax(o).ay(e)},ax:function(o){return this.attr("x",o)},ay:function(o){return this.attr("y",o)},build:function(o){return this._build=!!o,this},center:function(o,e,t=this.bbox()){return this.cx(o,t).cy(e,t)},cx:function(o,e=this.bbox()){return o==null?e.cx:this.attr("x",this.attr("x")+o-e.cx)},cy:function(o,e=this.bbox()){return o==null?e.cy:this.attr("y",this.attr("y")+o-e.cy)},length:function(){return this.node.getComputedTextLength()},move:function(o,e,t=this.bbox()){return this.x(o,t).y(e,t)},plain:function(o){return this._build===!1&&this.clear(),this.node.appendChild(q.document.createTextNode(o)),this},x:function(o,e=this.bbox()){return o==null?e.x:this.attr("x",this.attr("x")+o-e.x)},y:function(o,e=this.bbox()){return o==null?e.y:this.attr("y",this.attr("y")+o-e.y)}});class Pe extends we{constructor(e,t=e){super(ie("text",e),t),this.dom.leading=this.dom.leading??new V(1.3),this._rebuild=!0,this._build=!1}leading(e){return e==null?this.dom.leading:(this.dom.leading=new V(e),this.rebuild())}rebuild(e){if(typeof e=="boolean"&&(this._rebuild=e),this._rebuild){const t=this;let i=0;const a=this.dom.leading;this.each((function(s){if(jt(this.node))return;const r=q.window.getComputedStyle(this.node).getPropertyValue("font-size"),n=a*new V(r);this.dom.newLined&&(this.attr("x",t.attr("x")),this.text()===` +`?i+=n:(this.attr("dy",s?n+i:0),i=0))})),this.fire("rebuild")}return this}setData(e){return this.dom=e,this.dom.leading=new V(e.leading||1.3),this}writeDataToDom(){return Gi(this,this.dom,{leading:1.3}),this}text(e){if(e===void 0){const t=this.node.childNodes;let i=0;e="";for(let a=0,s=t.length;a{let i;try{i=t.node instanceof ct().SVGSVGElement?new le(t.attr(["x","y","width","height"])):t.bbox()}catch{return}const a=new D(t),s=a.translate(o,e).transform(a.inverse()),r=new Q(i.x,i.y).transform(s);t.move(r.x,r.y)})),this},dx:function(o){return this.dmove(o,0)},dy:function(o){return this.dmove(0,o)},height:function(o,e=this.bbox()){return o==null?e.height:this.size(e.width,o,e)},move:function(o=0,e=0,t=this.bbox()){const i=o-t.x,a=e-t.y;return this.dmove(i,a)},size:function(o,e,t=this.bbox()){const i=Qe(this,o,e,t),a=i.width/t.width,s=i.height/t.height;return this.children().forEach((r=>{const n=new Q(t).transform(new D(r).inverse());r.scale(a,s,n.x,n.y)})),this},width:function(o,e=this.bbox()){return o==null?e.width:this.size(o,e.height,e)},x:function(o,e=this.bbox()){return o==null?e.x:this.move(o,e.y,e)},y:function(o,e=this.bbox()){return o==null?e.y:this.move(e.x,o,e)}});class Oe extends me{constructor(e,t=e){super(ie("g",e),t)}}N(Oe,ka),U({Container:{group:ae((function(){return this.put(new Oe)}))}}),Z(Oe,"G");class Et extends me{constructor(e,t=e){super(ie("a",e),t)}target(e){return this.attr("target",e)}to(e){return this.attr("href",e,Ke)}}N(Et,ka),U({Container:{link:ae((function(o){return this.put(new Et).to(o)}))},Element:{unlink(){const o=this.linker();if(!o)return this;const e=o.parent();if(!e)return this.remove();const t=e.index(o);return e.add(this,t),o.remove(),this},linkTo(o){let e=this.linker();return e||(e=new Et,this.wrap(e)),typeof o=="function"?o.call(e,e):e.to(o),this},linker(){const o=this.parent();return o&&o.node.nodeName.toLowerCase()==="a"?o:null}}}),Z(Et,"A");class bi extends me{constructor(e,t=e){super(ie("mask",e),t)}remove(){return this.targets().forEach((function(e){e.unmask()})),super.remove()}targets(){return We("svg [mask*="+this.id()+"]")}}U({Container:{mask:ae((function(){return this.defs().put(new bi)}))},Element:{masker(){return this.reference("mask")},maskWith(o){const e=o instanceof bi?o:this.parent().mask().add(o);return this.attr("mask","url(#"+e.id()+")")},unmask(){return this.attr("mask",null)}}}),Z(bi,"Mask");class Aa extends de{constructor(e,t=e){super(ie("stop",e),t)}update(e){return(typeof e=="number"||e instanceof V)&&(e={offset:arguments[0],color:arguments[1],opacity:arguments[2]}),e.opacity!=null&&this.attr("stop-opacity",e.opacity),e.color!=null&&this.attr("stop-color",e.color),e.offset!=null&&this.attr("offset",new V(e.offset)),this}}U({Gradient:{stop:function(o,e,t){return this.put(new Aa).update(o,e,t)}}}),Z(Aa,"Stop");class mi extends de{constructor(e,t=e){super(ie("style",e),t)}addText(e=""){return this.node.textContent+=e,this}font(e,t,i={}){return this.rule("@font-face",{fontFamily:e,src:t,...i})}rule(e,t){return this.addText((function(i,a){if(!i)return"";if(!a)return i;let s=i+"{";for(const r in a)s+=r.replace(/([A-Z])/g,(function(n,l){return"-"+l.toLowerCase()}))+":"+a[r]+";";return s+="}",s})(e,t))}}U("Dom",{style(o,e){return this.put(new mi).rule(o,e)},fontface(o,e,t){return this.put(new mi).font(o,e,t)}}),Z(mi,"Style");class vi extends Pe{constructor(e,t=e){super(ie("textPath",e),t)}array(){const e=this.track();return e?e.array():null}plot(e){const t=this.track();let i=null;return t&&(i=t.plot(e)),e==null?i:this}track(){return this.reference("href")}}U({Container:{textPath:ae((function(o,e){return o instanceof Pe||(o=this.text(o)),o.path(e)}))},Text:{path:ae((function(o,e=!0){const t=new vi;let i;if(o instanceof at||(o=this.defs().path(o)),t.attr("href","#"+o,Ke),e)for(;i=this.node.firstChild;)t.node.appendChild(i);return this.put(t)})),textPath(){return this.findOne("textPath")}},Path:{text:ae((function(o){return o instanceof Pe||(o=new Pe().addTo(this.parent()).text(o)),o.path(this)})),targets(){return We("svg textPath").filter((o=>(o.attr("href")||"").includes(this.id())))}}}),vi.prototype.MorphArray=Me,Z(vi,"TextPath");class Ca extends we{constructor(e,t=e){super(ie("use",e),t)}use(e,t){return this.attr("href",(t||"")+"#"+e,Ke)}}U({Container:{use:ae((function(o,e){return this.put(new Ca).use(o,e)}))}}),Z(Ca,"Use");const Cs=be;N([gi,fi,Pt,pt,It],ye("viewbox")),N([Be,Ue,Ve,at],ye("marker")),N(Pe,ye("Text")),N(at,ye("Path")),N(Lt,ye("Defs")),N([Pe,Rt],ye("Tspan")),N([zt,Mt,ft,ke],ye("radius")),N(ut,ye("EventTarget")),N(Ye,ye("Dom")),N(de,ye("Element")),N(we,ye("Shape")),N([me,ca],ye("Container")),N(ft,ye("Gradient")),N(ke,ye("Runner")),Ne.extend([...new Set(_i)]),(function(o=[]){di.push(...[].concat(o))})([V,ee,le,D,_e,He,Me,Q]),N(di,{to(o){return new je().type(this.constructor).from(this.toArray()).to(o)},fromArray(o){return this.init(o),this},toConsumable(){return this.toArray()},morph(o,e,t,i,a){return this.fromArray(o.map((function(s,r){return i.step(s,e[r],t,a[r],a)})))}});class re extends de{constructor(e){super(ie("filter",e),e),this.$source="SourceGraphic",this.$sourceAlpha="SourceAlpha",this.$background="BackgroundImage",this.$backgroundAlpha="BackgroundAlpha",this.$fill="FillPaint",this.$stroke="StrokePaint",this.$autoSetIn=!0}put(e,t){return!(e=super.put(e,t)).attr("in")&&this.$autoSetIn&&e.attr("in",this.$source),e.attr("result")||e.attr("result",e.id()),e}remove(){return this.targets().each("unfilter"),super.remove()}targets(){return We('svg [filter*="'+this.id()+'"]')}toString(){return"url(#"+this.id()+")"}}class yi extends de{constructor(e,t){super(e,t),this.result(this.id())}in(e){if(e==null){const t=this.attr("in");return this.parent()&&this.parent().find(`[result="${t}"]`)[0]||t}return this.attr("in",e)}result(e){return this.attr("result",e)}toString(){return this.result()}}const Se=o=>function(...e){for(let t=o.length;t--;)e[t]!=null&&this.attr(o[t],e[t])},Ss={blend:Se(["in","in2","mode"]),colorMatrix:Se(["type","values"]),composite:Se(["in","in2","operator"]),convolveMatrix:function(o){o=new _e(o).toString(),this.attr({order:Math.sqrt(o.split(" ").length),kernelMatrix:o})},diffuseLighting:Se(["surfaceScale","lightingColor","diffuseConstant","kernelUnitLength"]),displacementMap:Se(["in","in2","scale","xChannelSelector","yChannelSelector"]),dropShadow:Se(["in","dx","dy","stdDeviation"]),flood:Se(["flood-color","flood-opacity"]),gaussianBlur:function(o=0,e=o){this.attr("stdDeviation",o+" "+e)},image:function(o){this.attr("href",o,Ke)},morphology:Se(["operator","radius"]),offset:Se(["dx","dy"]),specularLighting:Se(["surfaceScale","lightingColor","diffuseConstant","specularExponent","kernelUnitLength"]),tile:Se([]),turbulence:Se(["baseFrequency","numOctaves","seed","stitchTiles","type"])};["blend","colorMatrix","componentTransfer","composite","convolveMatrix","diffuseLighting","displacementMap","dropShadow","flood","gaussianBlur","image","merge","morphology","offset","specularLighting","tile","turbulence"].forEach((o=>{const e=Je(o),t=Ss[o];re[e+"Effect"]=class extends yi{constructor(i){super(ie("fe"+e,i),i)}update(i){return t.apply(this,i),this}},re.prototype[o]=ae((function(i,...a){const s=new re[e+"Effect"];return i==null?this.put(s):(typeof i=="function"?i.call(s,s):a.unshift(i),this.put(s).update(a))}))})),N(re,{merge(o){const e=this.put(new re.MergeEffect);return typeof o=="function"?(o.call(e,e),e):((o instanceof Array?o:[...arguments]).forEach((t=>{t instanceof re.MergeNode?e.put(t):e.mergeNode(t)})),e)},componentTransfer(o={}){const e=this.put(new re.ComponentTransferEffect);if(typeof o=="function")return o.call(e,e),e;o.r||o.g||o.b||o.a||(o={r:o,g:o,b:o,a:o});for(const t in o)e.add(new re["Func"+t.toUpperCase()](o[t]));return e}}),["distantLight","pointLight","spotLight","mergeNode","FuncR","FuncG","FuncB","FuncA"].forEach((o=>{const e=Je(o);re[e]=class extends yi{constructor(t){super(ie("fe"+e,t),t)}}})),["funcR","funcG","funcB","funcA"].forEach((function(o){const e=re[Je(o)],t=ae((function(){return this.put(new e)}));re.ComponentTransferEffect.prototype[o]=t})),["distantLight","pointLight","spotLight"].forEach((o=>{const e=re[Je(o)],t=ae((function(){return this.put(new e)}));re.DiffuseLightingEffect.prototype[o]=t,re.SpecularLightingEffect.prototype[o]=t})),N(re.MergeEffect,{mergeNode(o){return this.put(new re.MergeNode).attr("in",o)}}),N(Lt,{filter:function(o){const e=this.put(new re);return typeof o=="function"&&o.call(e,e),e}}),N(me,{filter:function(o){return this.defs().filter(o)}}),N(de,{filterWith:function(o){const e=o instanceof re?o:this.defs().filter(o);return this.attr("filter",e)},unfilter:function(o){return this.attr("filter",null)},filterer(){return this.reference("filter")}}),N(yi,{blend:function(o,e){return this.parent()&&this.parent().blend(this,o,e)},colorMatrix:function(o,e){return this.parent()&&this.parent().colorMatrix(o,e).in(this)},componentTransfer:function(o){return this.parent()&&this.parent().componentTransfer(o).in(this)},composite:function(o,e){return this.parent()&&this.parent().composite(this,o,e)},convolveMatrix:function(o){return this.parent()&&this.parent().convolveMatrix(o).in(this)},diffuseLighting:function(o,e,t,i){return this.parent()&&this.parent().diffuseLighting(o,t,i).in(this)},displacementMap:function(o,e,t,i){return this.parent()&&this.parent().displacementMap(this,o,e,t,i)},dropShadow:function(o,e,t){return this.parent()&&this.parent().dropShadow(this,o,e,t).in(this)},flood:function(o,e){return this.parent()&&this.parent().flood(o,e)},gaussianBlur:function(o,e){return this.parent()&&this.parent().gaussianBlur(o,e).in(this)},image:function(o){return this.parent()&&this.parent().image(o)},merge:function(o){return o=o instanceof Array?o:[...o],this.parent()&&this.parent().merge(this,...o)},morphology:function(o,e){return this.parent()&&this.parent().morphology(o,e).in(this)},offset:function(o,e){return this.parent()&&this.parent().offset(o,e).in(this)},specularLighting:function(o,e,t,i,a){return this.parent()&&this.parent().specularLighting(o,t,i,a).in(this)},tile:function(){return this.parent()&&this.parent().tile().in(this)},turbulence:function(o,e,t,i,a){return this.parent()&&this.parent().turbulence(o,e,t,i,a).in(this)}}),N(re.MergeEffect,{in:function(o){return o instanceof re.MergeNode?this.add(o,0):this.add(new re.MergeNode().in(o),0),this}}),N([re.CompositeEffect,re.BlendEffect,re.DisplacementMapEffect],{in2:function(o){if(o==null){const e=this.attr("in2");return this.parent()&&this.parent().find(`[result="${e}"]`)[0]||e}return this.attr("in2",o)}}),re.filter={sepiatone:[.343,.669,.119,0,0,.249,.626,.13,0,0,.172,.334,.111,0,0,0,0,0,1,0]};var ue=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"getDefaultFilter",value:function(e,t){var i=this.w;e.unfilter(!0),new re().size("120%","180%","-5%","-40%"),i.config.chart.dropShadow.enabled&&this.dropShadow(e,i.config.chart.dropShadow,t)}},{key:"applyFilter",value:function(e,t,i){var a,s=this,r=this.w;if(e.unfilter(!0),i!=="none"){var n,l,h=r.config.chart.dropShadow,d=i==="lighten"?2:.3;e.filterWith((function(c){c.colorMatrix({type:"matrix",values:` + `.concat(d,` 0 0 0 0 + 0 `).concat(d,` 0 0 0 + 0 0 `).concat(d,` 0 0 + 0 0 0 1 0 + `),in:"SourceGraphic",result:"brightness"}),h.enabled&&s.addShadow(c,t,h,"brightness")})),!h.noUserSpaceOnUse&&((n=e.filterer())===null||n===void 0||(l=n.node)===null||l===void 0||l.setAttribute("filterUnits","userSpaceOnUse")),this._scaleFilterSize((a=e.filterer())===null||a===void 0?void 0:a.node)}else this.getDefaultFilter(e,t)}},{key:"addShadow",value:function(e,t,i,a){var s,r=this.w,n=i.blur,l=i.top,h=i.left,d=i.color,c=i.opacity;if(d=Array.isArray(d)?d[t]:d,((s=r.config.chart.dropShadow.enabledOnSeries)===null||s===void 0?void 0:s.length)>0&&r.config.chart.dropShadow.enabledOnSeries.indexOf(t)===-1)return e;e.offset({in:a,dx:h,dy:l,result:"offset"}),e.gaussianBlur({in:"offset",stdDeviation:n,result:"blur"}),e.flood({"flood-color":d,"flood-opacity":c,result:"flood"}),e.composite({in:"flood",in2:"blur",operator:"in",result:"shadow"}),e.merge(["shadow",a])}},{key:"dropShadow",value:function(e,t){var i,a,s,r,n,l=this,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,d=this.w;return e.unfilter(!0),L.isMsEdge()&&d.config.chart.type==="radialBar"||((i=d.config.chart.dropShadow.enabledOnSeries)===null||i===void 0?void 0:i.length)>0&&((s=d.config.chart.dropShadow.enabledOnSeries)===null||s===void 0?void 0:s.indexOf(h))===-1?e:(e.filterWith((function(c){l.addShadow(c,h,t,"SourceGraphic")})),t.noUserSpaceOnUse||(r=e.filterer())===null||r===void 0||(n=r.node)===null||n===void 0||n.setAttribute("filterUnits","userSpaceOnUse"),this._scaleFilterSize((a=e.filterer())===null||a===void 0?void 0:a.node),e)}},{key:"setSelectionFilter",value:function(e,t,i){var a=this.w;if(a.globals.selectedDataPoints[t]!==void 0&&a.globals.selectedDataPoints[t].indexOf(i)>-1){e.node.setAttribute("selected",!0);var s=a.config.states.active.filter;s!=="none"&&this.applyFilter(e,t,s.type)}}},{key:"_scaleFilterSize",value:function(e){e&&(function(t){for(var i in t)t.hasOwnProperty(i)&&e.setAttribute(i,t[i])})({width:"200%",height:"200%",x:"-50%",y:"-50%"})}}]),o})(),X=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"roundPathCorners",value:function(e,t){function i(A,S,M){var P=S.x-A.x,I=S.y-A.y,T=Math.sqrt(P*P+I*I);return a(A,S,Math.min(1,M/T))}function a(A,S,M){return{x:A.x+(S.x-A.x)*M,y:A.y+(S.y-A.y)*M}}function s(A,S){A.length>2&&(A[A.length-2]=S.x,A[A.length-1]=S.y)}function r(A){return{x:parseFloat(A[A.length-2]),y:parseFloat(A[A.length-1])}}e.indexOf("NaN")>-1&&(e="");var n=e.split(/[,\s]/).reduce((function(A,S){var M=S.match("([a-zA-Z])(.+)");return M?(A.push(M[1]),A.push(M[2])):A.push(S),A}),[]).reduce((function(A,S){return parseFloat(S)==S&&A.length?A[A.length-1].push(S):A.push([S]),A}),[]),l=[];if(n.length>1){var h=r(n[0]),d=null;n[n.length-1][0]=="Z"&&n[0].length>2&&(d=["L",h.x,h.y],n[n.length-1]=d),l.push(n[0]);for(var c=1;c2&&g[0]=="L"&&p.length>2&&p[0]=="L"){var f,x,b=r(u),m=r(g),v=r(p);f=i(m,b,t),x=i(m,v,t),s(g,f),g.origPoint=m,l.push(g);var k=a(f,m,.5),y=a(m,x,.5),C=["C",k.x,k.y,y.x,y.y,x.x,x.y];C.origPoint=m,l.push(C)}else l.push(g)}if(d){var w=r(l[l.length-1]);l.push(["Z"]),s(l[0],w)}}else l=n;return l.reduce((function(A,S){return A+S.join(" ")+" "}),"")}},{key:"drawLine",value:function(e,t,i,a){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"#a8a8a8",r=arguments.length>5&&arguments[5]!==void 0?arguments[5]:0,n=arguments.length>6&&arguments[6]!==void 0?arguments[6]:null,l=arguments.length>7&&arguments[7]!==void 0?arguments[7]:"butt";return this.w.globals.dom.Paper.line().attr({x1:e,y1:t,x2:i,y2:a,stroke:s,"stroke-dasharray":r,"stroke-width":n,"stroke-linecap":l})}},{key:"drawRect",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0,r=arguments.length>5&&arguments[5]!==void 0?arguments[5]:"#fefefe",n=arguments.length>6&&arguments[6]!==void 0?arguments[6]:1,l=arguments.length>7&&arguments[7]!==void 0?arguments[7]:null,h=arguments.length>8&&arguments[8]!==void 0?arguments[8]:null,d=arguments.length>9&&arguments[9]!==void 0?arguments[9]:0,c=this.w.globals.dom.Paper.rect();return c.attr({x:e,y:t,width:i>0?i:0,height:a>0?a:0,rx:s,ry:s,opacity:n,"stroke-width":l!==null?l:0,stroke:h!==null?h:"none","stroke-dasharray":d}),c.node.setAttribute("fill",r),c}},{key:"drawPolygon",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#e1e1e1",i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"none";return this.w.globals.dom.Paper.polygon(e).attr({fill:a,stroke:t,"stroke-width":i})}},{key:"drawCircle",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;e<0&&(e=0);var i=this.w.globals.dom.Paper.circle(2*e);return t!==null&&i.attr(t),i}},{key:"drawPath",value:function(e){var t=e.d,i=t===void 0?"":t,a=e.stroke,s=a===void 0?"#a8a8a8":a,r=e.strokeWidth,n=r===void 0?1:r,l=e.fill,h=e.fillOpacity,d=h===void 0?1:h,c=e.strokeOpacity,u=c===void 0?1:c,g=e.classes,p=e.strokeLinecap,f=p===void 0?null:p,x=e.strokeDashArray,b=x===void 0?0:x,m=this.w;return f===null&&(f=m.config.stroke.lineCap),(i.indexOf("undefined")>-1||i.indexOf("NaN")>-1)&&(i="M 0 ".concat(m.globals.gridHeight)),m.globals.dom.Paper.path(i).attr({fill:l,"fill-opacity":d,stroke:s,"stroke-opacity":u,"stroke-linecap":f,"stroke-width":n,"stroke-dasharray":b,class:g})}},{key:"group",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,t=this.w.globals.dom.Paper.group();return e!==null&&t.attr(e),t}},{key:"move",value:function(e,t){var i=["M",e,t].join(" ");return i}},{key:"line",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=null;return i===null?a=[" L",e,t].join(" "):i==="H"?a=[" H",e].join(" "):i==="V"&&(a=[" V",t].join(" ")),a}},{key:"curve",value:function(e,t,i,a,s,r){var n=["C",e,t,i,a,s,r].join(" ");return n}},{key:"quadraticCurve",value:function(e,t,i,a){return["Q",e,t,i,a].join(" ")}},{key:"arc",value:function(e,t,i,a,s,r,n){var l="A";arguments.length>7&&arguments[7]!==void 0&&arguments[7]&&(l="a");var h=[l,e,t,i,a,s,r,n].join(" ");return h}},{key:"renderPaths",value:function(e){var t,i=e.j,a=e.realIndex,s=e.pathFrom,r=e.pathTo,n=e.stroke,l=e.strokeWidth,h=e.strokeLinecap,d=e.fill,c=e.animationDelay,u=e.initialSpeed,g=e.dataChangeSpeed,p=e.className,f=e.chartType,x=e.shouldClipToGrid,b=x===void 0||x,m=e.bindEventsOnPaths,v=m===void 0||m,k=e.drawShadow,y=k===void 0||k,C=this.w,w=new ue(this.ctx),A=new $e(this.ctx),S=this.w.config.chart.animations.enabled,M=S&&this.w.config.chart.animations.dynamicAnimation.enabled,P=!!(S&&!C.globals.resized||M&&C.globals.dataChanged&&C.globals.shouldAnimate);P?t=s:(t=r,C.globals.animationEnded=!0);var I=C.config.stroke.dashArray,T=0;T=Array.isArray(I)?I[a]:C.config.stroke.dashArray;var z=this.drawPath({d:t,stroke:n,strokeWidth:l,fill:d,fillOpacity:1,classes:p,strokeLinecap:h,strokeDashArray:T});z.attr("index",a),b&&(f==="bar"&&!C.globals.isHorizontal||C.globals.comboCharts?z.attr({"clip-path":"url(#gridRectBarMask".concat(C.globals.cuid,")")}):z.attr({"clip-path":"url(#gridRectMask".concat(C.globals.cuid,")")})),C.config.chart.dropShadow.enabled&&y&&w.dropShadow(z,C.config.chart.dropShadow,a),v&&(z.node.addEventListener("mouseenter",this.pathMouseEnter.bind(this,z)),z.node.addEventListener("mouseleave",this.pathMouseLeave.bind(this,z)),z.node.addEventListener("mousedown",this.pathMouseDown.bind(this,z))),z.attr({pathTo:r,pathFrom:s});var E={el:z,j:i,realIndex:a,pathFrom:s,pathTo:r,fill:d,strokeWidth:l,delay:c};return!S||C.globals.resized||C.globals.dataChanged?!C.globals.resized&&C.globals.dataChanged||A.showDelayedElements():A.animatePathsGradually(R(R({},E),{},{speed:u})),C.globals.dataChanged&&M&&P&&A.animatePathsGradually(R(R({},E),{},{speed:g})),z}},{key:"drawPattern",value:function(e,t,i){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"#a8a8a8",s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;return this.w.globals.dom.Paper.pattern(t,i,(function(r){e==="horizontalLines"?r.line(0,0,i,0).stroke({color:a,width:s+1}):e==="verticalLines"?r.line(0,0,0,t).stroke({color:a,width:s+1}):e==="slantedLines"?r.line(0,0,t,i).stroke({color:a,width:s}):e==="squares"?r.rect(t,i).fill("none").stroke({color:a,width:s}):e==="circles"&&r.circle(t).fill("none").stroke({color:a,width:s})}))}},{key:"drawGradient",value:function(e,t,i,a,s){var r,n=arguments.length>5&&arguments[5]!==void 0?arguments[5]:null,l=arguments.length>6&&arguments[6]!==void 0?arguments[6]:null,h=arguments.length>7&&arguments[7]!==void 0?arguments[7]:[],d=arguments.length>8&&arguments[8]!==void 0?arguments[8]:0,c=this.w;t.length<9&&t.indexOf("#")===0&&(t=L.hexToRgba(t,a)),i.length<9&&i.indexOf("#")===0&&(i=L.hexToRgba(i,s));var u=0,g=1,p=1,f=null;l!==null&&(u=l[0]!==void 0?l[0]/100:0,g=l[1]!==void 0?l[1]/100:1,p=l[2]!==void 0?l[2]/100:1,f=l[3]!==void 0?l[3]/100:null);var x=!(c.config.chart.type!=="donut"&&c.config.chart.type!=="pie"&&c.config.chart.type!=="polarArea"&&c.config.chart.type!=="bubble");if(r=h&&h.length!==0?c.globals.dom.Paper.gradient(x?"radial":"linear",(function(v){(Array.isArray(h[d])?h[d]:h).forEach((function(k){v.stop(k.offset/100,k.color,k.opacity)}))})):c.globals.dom.Paper.gradient(x?"radial":"linear",(function(v){v.stop(u,t,a),v.stop(g,i,s),v.stop(p,i,s),f!==null&&v.stop(f,t,a)})),x){var b=c.globals.gridWidth/2,m=c.globals.gridHeight/2;c.config.chart.type!=="bubble"?r.attr({gradientUnits:"userSpaceOnUse",cx:b,cy:m,r:n}):r.attr({cx:.5,cy:.5,r:.8,fx:.2,fy:.2})}else e==="vertical"?r.from(0,0).to(0,1):e==="diagonal"?r.from(0,0).to(1,1):e==="horizontal"?r.from(0,1).to(1,1):e==="diagonal2"&&r.from(1,0).to(0,1);return r}},{key:"getTextBasedOnMaxWidth",value:function(e){var t=e.text,i=e.maxWidth,a=e.fontSize,s=e.fontFamily,r=this.getTextRects(t,a,s),n=r.width/t.length,l=Math.floor(i/n);return i-1){var l=i.globals.selectedDataPoints[s].indexOf(r);i.globals.selectedDataPoints[s].splice(l,1)}}else{if(!i.config.states.active.allowMultipleDataPointsSelection&&i.globals.selectedDataPoints.length>0){i.globals.selectedDataPoints=[];var h=i.globals.dom.Paper.find(".apexcharts-series path:not(.apexcharts-decoration-element)"),d=i.globals.dom.Paper.find(".apexcharts-series circle:not(.apexcharts-decoration-element), .apexcharts-series rect:not(.apexcharts-decoration-element)"),c=function(p){Array.prototype.forEach.call(p,(function(f){f.node.setAttribute("selected","false"),a.getDefaultFilter(f,s)}))};c(h),c(d)}e.node.setAttribute("selected","true"),n="true",i.globals.selectedDataPoints[s]===void 0&&(i.globals.selectedDataPoints[s]=[]),i.globals.selectedDataPoints[s].push(r)}if(n==="true"){var u=i.config.states.active.filter;if(u!=="none")a.applyFilter(e,s,u.type);else if(i.config.states.hover.filter!=="none"&&!i.globals.isTouchDevice){var g=i.config.states.hover.filter;a.applyFilter(e,s,g.type)}}else i.config.states.active.filter.type!=="none"&&(i.config.states.hover.filter.type==="none"||i.globals.isTouchDevice?a.getDefaultFilter(e,s):(g=i.config.states.hover.filter,a.applyFilter(e,s,g.type)));typeof i.config.chart.events.dataPointSelection=="function"&&i.config.chart.events.dataPointSelection(t,this.ctx,{selectedDataPoints:i.globals.selectedDataPoints,seriesIndex:s,dataPointIndex:r,w:i}),t&&this.ctx.events.fireEvent("dataPointSelection",[t,this.ctx,{selectedDataPoints:i.globals.selectedDataPoints,seriesIndex:s,dataPointIndex:r,w:i}])}},{key:"rotateAroundCenter",value:function(e){var t={};return e&&typeof e.getBBox=="function"&&(t=e.getBBox()),{x:t.x+t.width/2,y:t.y+t.height/2}}},{key:"getTextRects",value:function(e,t,i,a){var s=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],r=this.w,n=this.drawText({x:-200,y:-200,text:e,textAnchor:"start",fontSize:t,fontFamily:i,foreColor:"#fff",opacity:0});a&&n.attr("transform",a),r.globals.dom.Paper.add(n);var l=n.bbox();return s||(l=n.node.getBoundingClientRect()),n.remove(),{width:l.width,height:l.height}}},{key:"placeTextWithEllipsis",value:function(e,t,i){if(typeof e.getComputedTextLength=="function"&&(e.textContent=t,t.length>0&&e.getComputedTextLength()>=i/1.1)){for(var a=t.length-3;a>0;a-=3)if(e.getSubStringLength(0,a)<=i/1.1)return void(e.textContent=t.substring(0,a)+"...");e.textContent="."}}}],[{key:"setAttrs",value:function(e,t){for(var i in t)t.hasOwnProperty(i)&&e.setAttribute(i,t[i])}}]),o})(),he=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"getStackedSeriesTotals",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=this.w,i=[];if(t.globals.series.length===0)return i;for(var a=0;a0&&arguments[0]!==void 0?arguments[0]:null;return e===null?this.w.config.series.reduce((function(t,i){return t+i}),0):this.w.globals.series[e].reduce((function(t,i){return t+i}),0)}},{key:"getStackedSeriesTotalsByGroups",value:function(){var e=this,t=this.w,i=[];return t.globals.seriesGroups.forEach((function(a){var s=[];t.config.series.forEach((function(n,l){a.indexOf(t.globals.seriesNames[l])>-1&&s.push(l)}));var r=t.globals.series.map((function(n,l){return s.indexOf(l)===-1?l:-1})).filter((function(n){return n!==-1}));i.push(e.getStackedSeriesTotals(r))})),i}},{key:"setSeriesYAxisMappings",value:function(){var e=this.w.globals,t=this.w.config,i=[],a=[],s=[],r=e.series.length>t.yaxis.length||t.yaxis.some((function(c){return Array.isArray(c.seriesName)}));t.series.forEach((function(c,u){s.push(u),a.push(null)})),t.yaxis.forEach((function(c,u){i[u]=[]}));var n=[];t.yaxis.forEach((function(c,u){var g=!1;if(c.seriesName){var p=[];Array.isArray(c.seriesName)?p=c.seriesName:p.push(c.seriesName),p.forEach((function(f){t.series.forEach((function(x,b){if(x.name===f){var m=b;u===b||r?!r||s.indexOf(b)>-1?i[u].push([u,b]):console.warn("Series '"+x.name+"' referenced more than once in what looks like the new style. That is, when using either seriesName: [], or when there are more series than yaxes."):(i[b].push([b,u]),m=u),g=!0,(m=s.indexOf(m))!==-1&&s.splice(m,1)}}))}))}g||n.push(u)})),i=i.map((function(c,u){var g=[];return c.forEach((function(p){a[p[1]]=p[0],g.push(p[1])})),g}));for(var l=t.yaxis.length-1,h=0;h0&&arguments[0]!==void 0?arguments[0]:null;return(e===null?this.w.config.series.filter((function(t){return t!==null})):this.w.config.series[e].data.filter((function(t){return t!==null}))).length===0}},{key:"seriesHaveSameValues",value:function(e){return this.w.globals.series[e].every((function(t,i,a){return t===a[0]}))}},{key:"getCategoryLabels",value:function(e){var t=this.w,i=e.slice();return t.config.xaxis.convertedCatToNumeric&&(i=e.map((function(a,s){return t.config.xaxis.labels.formatter(a-t.globals.minX+1)}))),i}},{key:"getLargestSeries",value:function(){var e=this.w;e.globals.maxValsInArrayIndex=e.globals.series.map((function(t){return t.length})).indexOf(Math.max.apply(Math,e.globals.series.map((function(t){return t.length}))))}},{key:"getLargestMarkerSize",value:function(){var e=this.w,t=0;return e.globals.markers.size.forEach((function(i){t=Math.max(t,i)})),e.config.markers.discrete&&e.config.markers.discrete.length&&e.config.markers.discrete.forEach((function(i){t=Math.max(t,i.size)})),t>0&&(e.config.markers.hover.size>0?t=e.config.markers.hover.size:t+=e.config.markers.hover.sizeOffset),e.globals.markers.largestSize=t,t}},{key:"getSeriesTotals",value:function(){var e=this.w;e.globals.seriesTotals=e.globals.series.map((function(t,i){var a=0;if(Array.isArray(t))for(var s=0;se&&i.globals.seriesX[s][n]0){var p=function(x,b){var m=s.config.yaxis[s.globals.seriesYAxisReverseMap[b]],v=x<0?-1:1;return x=Math.abs(x),m.logarithmic&&(x=a.getBaseLog(m.logBase,x)),-v*x/n[b]};if(r.isMultipleYAxis){h=[];for(var f=0;f0&&t.forEach((function(n){var l=[],h=[];e.i.forEach((function(d,c){s.config.series[d].group===n&&(l.push(e.series[c]),h.push(d))})),l.length>0&&r.push(a.draw(l,i,h))})),r}}],[{key:"checkComboSeries",value:function(e,t){var i=!1,a=0,s=0;return t===void 0&&(t="line"),e.length&&e[0].type!==void 0&&e.forEach((function(r){r.type!=="bar"&&r.type!=="column"&&r.type!=="candlestick"&&r.type!=="boxPlot"||a++,r.type!==void 0&&r.type!==t&&s++})),s>0&&(i=!0),{comboBarCount:a,comboCharts:i}}},{key:"extendArrayProps",value:function(e,t,i){var a,s,r,n,l,h;return(a=t)!==null&&a!==void 0&&a.yaxis&&(t=e.extendYAxis(t,i)),(s=t)!==null&&s!==void 0&&s.annotations&&(t.annotations.yaxis&&(t=e.extendYAxisAnnotations(t)),(r=t)!==null&&r!==void 0&&(n=r.annotations)!==null&&n!==void 0&&n.xaxis&&(t=e.extendXAxisAnnotations(t)),(l=t)!==null&&l!==void 0&&(h=l.annotations)!==null&&h!==void 0&&h.points&&(t=e.extendPointAnnotations(t))),t}}]),o})(),Yt=(function(){function o(e){H(this,o),this.w=e.w,this.annoCtx=e}return O(o,[{key:"setOrientations",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,i=this.w;if(e.label.orientation==="vertical"){var a=t!==null?t:0,s=i.globals.dom.baseEl.querySelector(".apexcharts-xaxis-annotations .apexcharts-xaxis-annotation-label[rel='".concat(a,"']"));if(s!==null){var r=s.getBoundingClientRect();s.setAttribute("x",parseFloat(s.getAttribute("x"))-r.height+4);var n=e.label.position==="top"?r.width:-r.width;s.setAttribute("y",parseFloat(s.getAttribute("y"))+n);var l=this.annoCtx.graphics.rotateAroundCenter(s),h=l.x,d=l.y;s.setAttribute("transform","rotate(-90 ".concat(h," ").concat(d,")"))}}}},{key:"addBackgroundToAnno",value:function(e,t){var i=this.w;if(!e||!t.label.text||!String(t.label.text).trim())return null;var a=i.globals.dom.baseEl.querySelector(".apexcharts-grid").getBoundingClientRect(),s=e.getBoundingClientRect(),r=t.label.style.padding,n=r.left,l=r.right,h=r.top,d=r.bottom;if(t.label.orientation==="vertical"){var c=[n,l,h,d];h=c[0],d=c[1],n=c[2],l=c[3]}var u=s.left-a.left-n,g=s.top-a.top-h,p=this.annoCtx.graphics.drawRect(u-i.globals.barPadForNumericAxis,g,s.width+n+l,s.height+h+d,t.label.borderRadius,t.label.style.background,1,t.label.borderWidth,t.label.borderColor,0);return t.id&&p.node.classList.add(t.id),p}},{key:"annotationsBackground",value:function(){var e=this,t=this.w,i=function(a,s,r){var n=t.globals.dom.baseEl.querySelector(".apexcharts-".concat(r,"-annotations .apexcharts-").concat(r,"-annotation-label[rel='").concat(s,"']"));if(n){var l=n.parentNode,h=e.addBackgroundToAnno(n,a);h&&(l.insertBefore(h.node,n),a.label.mouseEnter&&h.node.addEventListener("mouseenter",a.label.mouseEnter.bind(e,a)),a.label.mouseLeave&&h.node.addEventListener("mouseleave",a.label.mouseLeave.bind(e,a)),a.label.click&&h.node.addEventListener("click",a.label.click.bind(e,a)))}};t.config.annotations.xaxis.forEach((function(a,s){return i(a,s,"xaxis")})),t.config.annotations.yaxis.forEach((function(a,s){return i(a,s,"yaxis")})),t.config.annotations.points.forEach((function(a,s){return i(a,s,"point")}))}},{key:"getY1Y2",value:function(e,t){var i,a=this.w,s=e==="y1"?t.y:t.y2,r=!1;if(this.annoCtx.invertAxis){var n=a.config.xaxis.convertedCatToNumeric?a.globals.categoryLabels:a.globals.labels,l=n.indexOf(s),h=a.globals.dom.baseEl.querySelector(".apexcharts-yaxis-texts-g text:nth-child(".concat(l+1,")"));i=h?parseFloat(h.getAttribute("y")):(a.globals.gridHeight/n.length-1)*(l+1)-a.globals.barHeight,t.seriesIndex!==void 0&&a.globals.barHeight&&(i-=a.globals.barHeight/2*(a.globals.series.length-1)-a.globals.barHeight*t.seriesIndex)}else{var d,c=a.globals.seriesYAxisMap[t.yAxisIndex][0],u=a.config.yaxis[t.yAxisIndex].logarithmic?new he(this.annoCtx.ctx).getLogVal(a.config.yaxis[t.yAxisIndex].logBase,s,c)/a.globals.yLogRatio[c]:(s-a.globals.minYArr[c])/(a.globals.yRange[c]/a.globals.gridHeight);i=a.globals.gridHeight-Math.min(Math.max(u,0),a.globals.gridHeight),r=u>a.globals.gridHeight||u<0,!t.marker||t.y!==void 0&&t.y!==null||(i=0),(d=a.config.yaxis[t.yAxisIndex])!==null&&d!==void 0&&d.reversed&&(i=u)}return typeof s=="string"&&s.includes("px")&&(i=parseFloat(s)),{yP:i,clipped:r}}},{key:"getX1X2",value:function(e,t){var i=this.w,a=e==="x1"?t.x:t.x2,s=this.annoCtx.invertAxis?i.globals.minY:i.globals.minX,r=this.annoCtx.invertAxis?i.globals.maxY:i.globals.maxX,n=this.annoCtx.invertAxis?i.globals.yRange[0]:i.globals.xRange,l=!1,h=this.annoCtx.inversedReversedAxis?(r-a)/(n/i.globals.gridWidth):(a-s)/(n/i.globals.gridWidth);return i.config.xaxis.type!=="category"&&!i.config.xaxis.convertedCatToNumeric||this.annoCtx.invertAxis||i.globals.dataFormatXNumeric||i.config.chart.sparkline.enabled||(h=this.getStringX(a)),typeof a=="string"&&a.includes("px")&&(h=parseFloat(a)),a==null&&t.marker&&(h=i.globals.gridWidth),t.seriesIndex!==void 0&&i.globals.barWidth&&!this.annoCtx.invertAxis&&(h-=i.globals.barWidth/2*(i.globals.series.length-1)-i.globals.barWidth*t.seriesIndex),h>i.globals.gridWidth?(h=i.globals.gridWidth,l=!0):h<0&&(h=0,l=!0),{x:h,clipped:l}}},{key:"getStringX",value:function(e){var t=this.w,i=e;t.config.xaxis.convertedCatToNumeric&&t.globals.categoryLabels.length&&(e=t.globals.categoryLabels.indexOf(e)+1);var a=t.globals.labels.map((function(r){return Array.isArray(r)?r.join(" "):r})).indexOf(e),s=t.globals.dom.baseEl.querySelector(".apexcharts-xaxis-texts-g text:nth-child(".concat(a+1,")"));return s&&(i=parseFloat(s.getAttribute("x"))),i}}]),o})(),Ls=(function(){function o(e){H(this,o),this.w=e.w,this.annoCtx=e,this.invertAxis=this.annoCtx.invertAxis,this.helpers=new Yt(this.annoCtx)}return O(o,[{key:"addXaxisAnnotation",value:function(e,t,i){var a,s=this.w,r=this.helpers.getX1X2("x1",e),n=r.x,l=r.clipped,h=!0,d=e.label.text,c=e.strokeDashArray;if(L.isNumber(n)){if(e.x2===null||e.x2===void 0){if(!l){var u=this.annoCtx.graphics.drawLine(n+e.offsetX,0+e.offsetY,n+e.offsetX,s.globals.gridHeight+e.offsetY,e.borderColor,c,e.borderWidth);t.appendChild(u.node),e.id&&u.node.classList.add(e.id)}}else{var g=this.helpers.getX1X2("x2",e);if(a=g.x,h=g.clipped,!l||!h){if(a12?g-12:g===0?12:g;t=(t=(t=(t=t.replace(/(^|[^\\])HH+/g,"$1"+h(g))).replace(/(^|[^\\])H/g,"$1"+g)).replace(/(^|[^\\])hh+/g,"$1"+h(p))).replace(/(^|[^\\])h/g,"$1"+p);var f=a?e.getUTCMinutes():e.getMinutes();t=(t=t.replace(/(^|[^\\])mm+/g,"$1"+h(f))).replace(/(^|[^\\])m/g,"$1"+f);var x=a?e.getUTCSeconds():e.getSeconds();t=(t=t.replace(/(^|[^\\])ss+/g,"$1"+h(x))).replace(/(^|[^\\])s/g,"$1"+x);var b=a?e.getUTCMilliseconds():e.getMilliseconds();t=t.replace(/(^|[^\\])fff+/g,"$1"+h(b,3)),b=Math.round(b/10),t=t.replace(/(^|[^\\])ff/g,"$1"+h(b)),b=Math.round(b/10);var m=g<12?"AM":"PM";t=(t=(t=t.replace(/(^|[^\\])f/g,"$1"+b)).replace(/(^|[^\\])TT+/g,"$1"+m)).replace(/(^|[^\\])T/g,"$1"+m.charAt(0));var v=m.toLowerCase();t=(t=t.replace(/(^|[^\\])tt+/g,"$1"+v)).replace(/(^|[^\\])t/g,"$1"+v.charAt(0));var k=-e.getTimezoneOffset(),y=a||!k?"Z":k>0?"+":"-";if(!a){var C=(k=Math.abs(k))%60;y+=h(Math.floor(k/60))+":"+h(C)}t=t.replace(/(^|[^\\])K/g,"$1"+y);var w=(a?e.getUTCDay():e.getDay())+1;return t=(t=(t=(t=(t=t.replace(new RegExp(n[0],"g"),n[w])).replace(new RegExp(l[0],"g"),l[w])).replace(new RegExp(s[0],"g"),s[c])).replace(new RegExp(r[0],"g"),r[c])).replace(/\\(.)/g,"$1")}},{key:"getTimeUnitsfromTimestamp",value:function(e,t,i){var a=this.w;a.config.xaxis.min!==void 0&&(e=a.config.xaxis.min),a.config.xaxis.max!==void 0&&(t=a.config.xaxis.max);var s=this.getDate(e),r=this.getDate(t),n=this.formatDate(s,"yyyy MM dd HH mm ss fff").split(" "),l=this.formatDate(r,"yyyy MM dd HH mm ss fff").split(" ");return{minMillisecond:parseInt(n[6],10),maxMillisecond:parseInt(l[6],10),minSecond:parseInt(n[5],10),maxSecond:parseInt(l[5],10),minMinute:parseInt(n[4],10),maxMinute:parseInt(l[4],10),minHour:parseInt(n[3],10),maxHour:parseInt(l[3],10),minDate:parseInt(n[2],10),maxDate:parseInt(l[2],10),minMonth:parseInt(n[1],10)-1,maxMonth:parseInt(l[1],10)-1,minYear:parseInt(n[0],10),maxYear:parseInt(l[0],10)}}},{key:"isLeapYear",value:function(e){return e%4==0&&e%100!=0||e%400==0}},{key:"calculcateLastDaysOfMonth",value:function(e,t,i){return this.determineDaysOfMonths(e,t)-i}},{key:"determineDaysOfYear",value:function(e){var t=365;return this.isLeapYear(e)&&(t=366),t}},{key:"determineRemainingDaysOfYear",value:function(e,t,i){var a=this.daysCntOfYear[t]+i;return t>1&&this.isLeapYear()&&a++,a}},{key:"determineDaysOfMonths",value:function(e,t){var i=30;switch(e=L.monthMod(e),!0){case this.months30.indexOf(e)>-1:e===2&&(i=this.isLeapYear(t)?29:28);break;case this.months31.indexOf(e)>-1:default:i=31}return i}}]),o})(),mt=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w,this.tooltipKeyFormat="dd MMM"}return O(o,[{key:"xLabelFormat",value:function(e,t,i,a){var s=this.w;if(s.config.xaxis.type==="datetime"&&s.config.xaxis.labels.formatter===void 0&&s.config.tooltip.x.formatter===void 0){var r=new ge(this.ctx);return r.formatDate(r.getDate(t),s.config.tooltip.x.format)}return e(t,i,a)}},{key:"defaultGeneralFormatter",value:function(e){return Array.isArray(e)?e.map((function(t){return t})):e}},{key:"defaultYFormatter",value:function(e,t,i){var a=this.w;if(L.isNumber(e))if(a.globals.yValueDecimal!==0)e=e.toFixed(t.decimalsInFloat!==void 0?t.decimalsInFloat:a.globals.yValueDecimal);else{var s=e.toFixed(0);e=e==s?s:e.toFixed(1)}return e}},{key:"setLabelFormatters",value:function(){var e=this,t=this.w;return t.globals.xaxisTooltipFormatter=function(i){return e.defaultGeneralFormatter(i)},t.globals.ttKeyFormatter=function(i){return e.defaultGeneralFormatter(i)},t.globals.ttZFormatter=function(i){return i},t.globals.legendFormatter=function(i){return e.defaultGeneralFormatter(i)},t.config.xaxis.labels.formatter!==void 0?t.globals.xLabelFormatter=t.config.xaxis.labels.formatter:t.globals.xLabelFormatter=function(i){if(L.isNumber(i)){if(!t.config.xaxis.convertedCatToNumeric&&t.config.xaxis.type==="numeric"){if(L.isNumber(t.config.xaxis.decimalsInFloat))return i.toFixed(t.config.xaxis.decimalsInFloat);var a=t.globals.maxX-t.globals.minX;return a>0&&a<100?i.toFixed(1):i.toFixed(0)}return t.globals.isBarHorizontal&&t.globals.maxY-t.globals.minYArr<4?i.toFixed(1):i.toFixed(0)}return i},typeof t.config.tooltip.x.formatter=="function"?t.globals.ttKeyFormatter=t.config.tooltip.x.formatter:t.globals.ttKeyFormatter=t.globals.xLabelFormatter,typeof t.config.xaxis.tooltip.formatter=="function"&&(t.globals.xaxisTooltipFormatter=t.config.xaxis.tooltip.formatter),(Array.isArray(t.config.tooltip.y)||t.config.tooltip.y.formatter!==void 0)&&(t.globals.ttVal=t.config.tooltip.y),t.config.tooltip.z.formatter!==void 0&&(t.globals.ttZFormatter=t.config.tooltip.z.formatter),t.config.legend.formatter!==void 0&&(t.globals.legendFormatter=t.config.legend.formatter),t.config.yaxis.forEach((function(i,a){i.labels.formatter!==void 0?t.globals.yLabelFormatters[a]=i.labels.formatter:t.globals.yLabelFormatters[a]=function(s){return t.globals.xyCharts?Array.isArray(s)?s.map((function(r){return e.defaultYFormatter(r,i,a)})):e.defaultYFormatter(s,i,a):s}})),t.globals}},{key:"heatmapLabelFormatters",value:function(){var e=this.w;if(e.config.chart.type==="heatmap"){e.globals.yAxisScale[0].result=e.globals.seriesNames.slice();var t=e.globals.seriesNames.reduce((function(i,a){return i.length>a.length?i:a}),0);e.globals.yAxisScale[0].niceMax=t,e.globals.yAxisScale[0].niceMin=t}}}]),o})(),Fe=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"getLabel",value:function(e,t,i,a){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:[],r=arguments.length>5&&arguments[5]!==void 0?arguments[5]:"12px",n=!(arguments.length>6&&arguments[6]!==void 0)||arguments[6],l=this.w,h=e[a]===void 0?"":e[a],d=h,c=l.globals.xLabelFormatter,u=l.config.xaxis.labels.formatter,g=!1,p=new mt(this.ctx),f=h;n&&(d=p.xLabelFormat(c,h,f,{i:a,dateFormatter:new ge(this.ctx).formatDate,w:l}),u!==void 0&&(d=u(h,e[a],{i:a,dateFormatter:new ge(this.ctx).formatDate,w:l})));var x,b;t.length>0?(x=t[a].unit,b=null,t.forEach((function(y){y.unit==="month"?b="year":y.unit==="day"?b="month":y.unit==="hour"?b="day":y.unit==="minute"&&(b="hour")})),g=b===x,i=t[a].position,d=t[a].value):l.config.xaxis.type==="datetime"&&u===void 0&&(d=""),d===void 0&&(d=""),d=Array.isArray(d)?d:d.toString();var m=new X(this.ctx),v={};v=l.globals.rotateXLabels&&n?m.getTextRects(d,parseInt(r,10),null,"rotate(".concat(l.config.xaxis.labels.rotate," 0 0)"),!1):m.getTextRects(d,parseInt(r,10));var k=!l.config.xaxis.labels.showDuplicates&&this.ctx.timeScale;return!Array.isArray(d)&&(String(d)==="NaN"||s.indexOf(d)>=0&&k)&&(d=""),{x:i,text:d,textRect:v,isBold:g}}},{key:"checkLabelBasedOnTickamount",value:function(e,t,i){var a=this.w,s=a.config.xaxis.tickAmount;return s==="dataPoints"&&(s=Math.round(a.globals.gridWidth/120)),s>i||e%Math.round(i/(s+1))==0||(t.text=""),t}},{key:"checkForOverflowingLabels",value:function(e,t,i,a,s){var r=this.w;if(e===0&&r.globals.skipFirstTimelinelabel&&(t.text=""),e===i-1&&r.globals.skipLastTimelinelabel&&(t.text=""),r.config.xaxis.labels.hideOverlappingLabels&&a.length>0){var n=s[s.length-1];t.xa.length||a.some((function(s){return Array.isArray(s.seriesName)}))?e:i.seriesYAxisReverseMap[e]}},{key:"isYAxisHidden",value:function(e){var t=this.w,i=t.config.yaxis[e];if(!i.show||this.yAxisAllSeriesCollapsed(e))return!0;if(!i.showForNullSeries){var a=t.globals.seriesYAxisMap[e],s=new he(this.ctx);return a.every((function(r){return s.isSeriesNull(r)}))}return!1}},{key:"getYAxisForeColor",value:function(e,t){var i=this.w;return Array.isArray(e)&&i.globals.yAxisScale[t]&&this.ctx.theme.pushExtraColors(e,i.globals.yAxisScale[t].result.length,!1),e}},{key:"drawYAxisTicks",value:function(e,t,i,a,s,r,n){var l=this.w,h=new X(this.ctx),d=l.globals.translateY+l.config.yaxis[s].labels.offsetY;if(l.globals.isBarHorizontal?d=0:l.config.chart.type==="heatmap"&&(d+=r/2),a.show&&t>0){l.config.yaxis[s].opposite===!0&&(e+=a.width);for(var c=t;c>=0;c--){var u=h.drawLine(e+i.offsetX-a.width+a.offsetX,d+a.offsetY,e+i.offsetX+a.offsetX,d+a.offsetY,a.color);n.add(u),d+=r}}}}]),o})(),Ms=(function(){function o(e){H(this,o),this.w=e.w,this.annoCtx=e,this.helpers=new Yt(this.annoCtx),this.axesUtils=new Fe(this.annoCtx)}return O(o,[{key:"addYaxisAnnotation",value:function(e,t,i){var a,s=this.w,r=e.strokeDashArray,n=this.helpers.getY1Y2("y1",e),l=n.yP,h=n.clipped,d=!0,c=!1,u=e.label.text;if(e.y2===null||e.y2===void 0){if(!h){c=!0;var g=this.annoCtx.graphics.drawLine(0+e.offsetX,l+e.offsetY,this._getYAxisAnnotationWidth(e),l+e.offsetY,e.borderColor,r,e.borderWidth);t.appendChild(g.node),e.id&&g.node.classList.add(e.id)}}else{if(a=(n=this.helpers.getY1Y2("y2",e)).yP,d=n.clipped,a>l){var p=l;l=a,a=p}if(!h||!d){c=!0;var f=this.annoCtx.graphics.drawRect(0+e.offsetX,a+e.offsetY,this._getYAxisAnnotationWidth(e),l-a,0,e.fillColor,e.opacity,1,e.borderColor,r);f.node.classList.add("apexcharts-annotation-rect"),f.attr("clip-path","url(#gridRectMask".concat(s.globals.cuid,")")),t.appendChild(f.node),e.id&&f.node.classList.add(e.id)}}if(c){var x=e.label.position==="right"?s.globals.gridWidth:e.label.position==="center"?s.globals.gridWidth/2:0,b=this.annoCtx.graphics.drawText({x:x+e.label.offsetX,y:(a??l)+e.label.offsetY-3,text:u,textAnchor:e.label.textAnchor,fontSize:e.label.style.fontSize,fontFamily:e.label.style.fontFamily,fontWeight:e.label.style.fontWeight,foreColor:e.label.style.color,cssClass:"apexcharts-yaxis-annotation-label ".concat(e.label.style.cssClass," ").concat(e.id?e.id:"")});b.attr({rel:i}),t.appendChild(b.node)}}},{key:"_getYAxisAnnotationWidth",value:function(e){var t=this.w;return t.globals.gridWidth,(e.width.indexOf("%")>-1?t.globals.gridWidth*parseInt(e.width,10)/100:parseInt(e.width,10))+e.offsetX}},{key:"drawYAxisAnnotations",value:function(){var e=this,t=this.w,i=this.annoCtx.graphics.group({class:"apexcharts-yaxis-annotations"});return t.config.annotations.yaxis.forEach((function(a,s){a.yAxisIndex=e.axesUtils.translateYAxisIndex(a.yAxisIndex),e.axesUtils.isYAxisHidden(a.yAxisIndex)&&e.axesUtils.yAxisAllSeriesCollapsed(a.yAxisIndex)||e.addYaxisAnnotation(a,i.node,s)})),i}}]),o})(),Ps=(function(){function o(e){H(this,o),this.w=e.w,this.annoCtx=e,this.helpers=new Yt(this.annoCtx)}return O(o,[{key:"addPointAnnotation",value:function(e,t,i){if(!(this.w.globals.collapsedSeriesIndices.indexOf(e.seriesIndex)>-1)){var a=this.helpers.getX1X2("x1",e),s=a.x,r=a.clipped,n=(a=this.helpers.getY1Y2("y1",e)).yP,l=a.clipped;if(L.isNumber(s)&&!l&&!r){var h={pSize:e.marker.size,pointStrokeWidth:e.marker.strokeWidth,pointFillColor:e.marker.fillColor,pointStrokeColor:e.marker.strokeColor,shape:e.marker.shape,pRadius:e.marker.radius,class:"apexcharts-point-annotation-marker ".concat(e.marker.cssClass," ").concat(e.id?e.id:"")},d=this.annoCtx.graphics.drawMarker(s+e.marker.offsetX,n+e.marker.offsetY,h);t.appendChild(d.node);var c=e.label.text?e.label.text:"",u=this.annoCtx.graphics.drawText({x:s+e.label.offsetX,y:n+e.label.offsetY-e.marker.size-parseFloat(e.label.style.fontSize)/1.6,text:c,textAnchor:e.label.textAnchor,fontSize:e.label.style.fontSize,fontFamily:e.label.style.fontFamily,fontWeight:e.label.style.fontWeight,foreColor:e.label.style.color,cssClass:"apexcharts-point-annotation-label ".concat(e.label.style.cssClass," ").concat(e.id?e.id:"")});if(u.attr({rel:i}),t.appendChild(u.node),e.customSVG.SVG){var g=this.annoCtx.graphics.group({class:"apexcharts-point-annotations-custom-svg "+e.customSVG.cssClass});g.attr({transform:"translate(".concat(s+e.customSVG.offsetX,", ").concat(n+e.customSVG.offsetY,")")}),g.node.innerHTML=e.customSVG.SVG,t.appendChild(g.node)}if(e.image.path){var p=e.image.width?e.image.width:20,f=e.image.height?e.image.height:20;d=this.annoCtx.addImage({x:s+e.image.offsetX-p/2,y:n+e.image.offsetY-f/2,width:p,height:f,path:e.image.path,appendTo:".apexcharts-point-annotations"})}e.mouseEnter&&d.node.addEventListener("mouseenter",e.mouseEnter.bind(this,e)),e.mouseLeave&&d.node.addEventListener("mouseleave",e.mouseLeave.bind(this,e)),e.click&&d.node.addEventListener("click",e.click.bind(this,e))}}}},{key:"drawPointAnnotations",value:function(){var e=this,t=this.w,i=this.annoCtx.graphics.group({class:"apexcharts-point-annotations"});return t.config.annotations.points.map((function(a,s){e.addPointAnnotation(a,i.node,s)})),i}}]),o})(),Sa={name:"en",options:{months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],toolbar:{exportToSVG:"Download SVG",exportToPNG:"Download PNG",exportToCSV:"Download CSV",menu:"Menu",selection:"Selection",selectionZoom:"Selection Zoom",zoomIn:"Zoom In",zoomOut:"Zoom Out",pan:"Panning",reset:"Reset Zoom"}}},qe=(function(){function o(){H(this,o),this.yAxis={show:!0,showAlways:!1,showForNullSeries:!0,seriesName:void 0,opposite:!1,reversed:!1,logarithmic:!1,logBase:10,tickAmount:void 0,stepSize:void 0,forceNiceScale:!1,max:void 0,min:void 0,floating:!1,decimalsInFloat:void 0,labels:{show:!0,showDuplicates:!1,minWidth:0,maxWidth:160,offsetX:0,offsetY:0,align:void 0,rotate:0,padding:20,style:{colors:[],fontSize:"11px",fontWeight:400,fontFamily:void 0,cssClass:""},formatter:void 0},axisBorder:{show:!1,color:"#e0e0e0",width:1,offsetX:0,offsetY:0},axisTicks:{show:!1,color:"#e0e0e0",width:6,offsetX:0,offsetY:0},title:{text:void 0,rotate:-90,offsetY:0,offsetX:0,style:{color:void 0,fontSize:"11px",fontWeight:900,fontFamily:void 0,cssClass:""}},tooltip:{enabled:!1,offsetX:0},crosshairs:{show:!0,position:"front",stroke:{color:"#b6b6b6",width:1,dashArray:0}}},this.pointAnnotation={id:void 0,x:0,y:null,yAxisIndex:0,seriesIndex:void 0,mouseEnter:void 0,mouseLeave:void 0,click:void 0,marker:{size:4,fillColor:"#fff",strokeWidth:2,strokeColor:"#333",shape:"circle",offsetX:0,offsetY:0,cssClass:""},label:{borderColor:"#c2c2c2",borderWidth:1,borderRadius:2,text:void 0,textAnchor:"middle",offsetX:0,offsetY:0,mouseEnter:void 0,mouseLeave:void 0,click:void 0,style:{background:"#fff",color:void 0,fontSize:"11px",fontFamily:void 0,fontWeight:400,cssClass:"",padding:{left:5,right:5,top:2,bottom:2}}},customSVG:{SVG:void 0,cssClass:void 0,offsetX:0,offsetY:0},image:{path:void 0,width:20,height:20,offsetX:0,offsetY:0}},this.yAxisAnnotation={id:void 0,y:0,y2:null,strokeDashArray:1,fillColor:"#c2c2c2",borderColor:"#c2c2c2",borderWidth:1,opacity:.3,offsetX:0,offsetY:0,width:"100%",yAxisIndex:0,label:{borderColor:"#c2c2c2",borderWidth:1,borderRadius:2,text:void 0,textAnchor:"end",position:"right",offsetX:0,offsetY:-3,mouseEnter:void 0,mouseLeave:void 0,click:void 0,style:{background:"#fff",color:void 0,fontSize:"11px",fontFamily:void 0,fontWeight:400,cssClass:"",padding:{left:5,right:5,top:2,bottom:2}}}},this.xAxisAnnotation={id:void 0,x:0,x2:null,strokeDashArray:1,fillColor:"#c2c2c2",borderColor:"#c2c2c2",borderWidth:1,opacity:.3,offsetX:0,offsetY:0,label:{borderColor:"#c2c2c2",borderWidth:1,borderRadius:2,text:void 0,textAnchor:"middle",orientation:"vertical",position:"top",offsetX:0,offsetY:0,mouseEnter:void 0,mouseLeave:void 0,click:void 0,style:{background:"#fff",color:void 0,fontSize:"11px",fontFamily:void 0,fontWeight:400,cssClass:"",padding:{left:5,right:5,top:2,bottom:2}}}},this.text={x:0,y:0,text:"",textAnchor:"start",foreColor:void 0,fontSize:"13px",fontFamily:void 0,fontWeight:400,appendTo:".apexcharts-annotations",backgroundColor:"transparent",borderColor:"#c2c2c2",borderRadius:0,borderWidth:0,paddingLeft:4,paddingRight:4,paddingTop:2,paddingBottom:2}}return O(o,[{key:"init",value:function(){return{annotations:{yaxis:[this.yAxisAnnotation],xaxis:[this.xAxisAnnotation],points:[this.pointAnnotation],texts:[],images:[],shapes:[]},chart:{animations:{enabled:!0,speed:800,animateGradually:{delay:150,enabled:!0},dynamicAnimation:{enabled:!0,speed:350}},background:"",locales:[Sa],defaultLocale:"en",dropShadow:{enabled:!1,enabledOnSeries:void 0,top:2,left:2,blur:4,color:"#000",opacity:.7},events:{animationEnd:void 0,beforeMount:void 0,mounted:void 0,updated:void 0,click:void 0,mouseMove:void 0,mouseLeave:void 0,xAxisLabelClick:void 0,legendClick:void 0,markerClick:void 0,selection:void 0,dataPointSelection:void 0,dataPointMouseEnter:void 0,dataPointMouseLeave:void 0,beforeZoom:void 0,beforeResetZoom:void 0,zoomed:void 0,scrolled:void 0,brushScrolled:void 0},foreColor:"#373d3f",fontFamily:"Helvetica, Arial, sans-serif",height:"auto",parentHeightOffset:15,redrawOnParentResize:!0,redrawOnWindowResize:!0,id:void 0,group:void 0,nonce:void 0,offsetX:0,offsetY:0,selection:{enabled:!1,type:"x",fill:{color:"#24292e",opacity:.1},stroke:{width:1,color:"#24292e",opacity:.4,dashArray:3},xaxis:{min:void 0,max:void 0},yaxis:{min:void 0,max:void 0}},sparkline:{enabled:!1},brush:{enabled:!1,autoScaleYaxis:!0,target:void 0,targets:void 0},stacked:!1,stackOnlyBar:!0,stackType:"normal",toolbar:{show:!0,offsetX:0,offsetY:0,tools:{download:!0,selection:!0,zoom:!0,zoomin:!0,zoomout:!0,pan:!0,reset:!0,customIcons:[]},export:{csv:{filename:void 0,columnDelimiter:",",headerCategory:"category",headerValue:"value",categoryFormatter:void 0,valueFormatter:void 0},png:{filename:void 0},svg:{filename:void 0},scale:void 0,width:void 0},autoSelected:"zoom"},type:"line",width:"100%",zoom:{enabled:!0,type:"x",autoScaleYaxis:!1,allowMouseWheelZoom:!0,zoomedArea:{fill:{color:"#90CAF9",opacity:.4},stroke:{color:"#0D47A1",opacity:.4,width:1}}}},plotOptions:{line:{isSlopeChart:!1,colors:{threshold:0,colorAboveThreshold:void 0,colorBelowThreshold:void 0}},area:{fillTo:"origin"},bar:{horizontal:!1,columnWidth:"70%",barHeight:"70%",distributed:!1,borderRadius:0,borderRadiusApplication:"around",borderRadiusWhenStacked:"last",rangeBarOverlap:!0,rangeBarGroupRows:!1,hideZeroBarsWhenGrouped:!1,isDumbbell:!1,dumbbellColors:void 0,isFunnel:!1,isFunnel3d:!0,colors:{ranges:[],backgroundBarColors:[],backgroundBarOpacity:1,backgroundBarRadius:0},dataLabels:{position:"top",maxItems:100,hideOverflowingLabels:!0,orientation:"horizontal",total:{enabled:!1,formatter:void 0,offsetX:0,offsetY:0,style:{color:"#373d3f",fontSize:"12px",fontFamily:void 0,fontWeight:600}}}},bubble:{zScaling:!0,minBubbleRadius:void 0,maxBubbleRadius:void 0},candlestick:{colors:{upward:"#00B746",downward:"#EF403C"},wick:{useFillColor:!0}},boxPlot:{colors:{upper:"#00E396",lower:"#008FFB"}},heatmap:{radius:2,enableShades:!0,shadeIntensity:.5,reverseNegativeShade:!1,distributed:!1,useFillColorAsStroke:!1,colorScale:{inverse:!1,ranges:[],min:void 0,max:void 0}},treemap:{enableShades:!0,shadeIntensity:.5,distributed:!1,reverseNegativeShade:!1,useFillColorAsStroke:!1,borderRadius:4,dataLabels:{format:"scale"},colorScale:{inverse:!1,ranges:[],min:void 0,max:void 0}},radialBar:{inverseOrder:!1,startAngle:0,endAngle:360,offsetX:0,offsetY:0,hollow:{margin:5,size:"50%",background:"transparent",image:void 0,imageWidth:150,imageHeight:150,imageOffsetX:0,imageOffsetY:0,imageClipped:!0,position:"front",dropShadow:{enabled:!1,top:0,left:0,blur:3,color:"#000",opacity:.5}},track:{show:!0,startAngle:void 0,endAngle:void 0,background:"#f2f2f2",strokeWidth:"97%",opacity:1,margin:5,dropShadow:{enabled:!1,top:0,left:0,blur:3,color:"#000",opacity:.5}},dataLabels:{show:!0,name:{show:!0,fontSize:"16px",fontFamily:void 0,fontWeight:600,color:void 0,offsetY:0,formatter:function(e){return e}},value:{show:!0,fontSize:"14px",fontFamily:void 0,fontWeight:400,color:void 0,offsetY:16,formatter:function(e){return e+"%"}},total:{show:!1,label:"Total",fontSize:"16px",fontWeight:600,fontFamily:void 0,color:void 0,formatter:function(e){return e.globals.seriesTotals.reduce((function(t,i){return t+i}),0)/e.globals.series.length+"%"}}},barLabels:{enabled:!1,offsetX:0,offsetY:0,useSeriesColors:!0,fontFamily:void 0,fontWeight:600,fontSize:"16px",formatter:function(e){return e},onClick:void 0}},pie:{customScale:1,offsetX:0,offsetY:0,startAngle:0,endAngle:360,expandOnClick:!0,dataLabels:{offset:0,minAngleToShowLabel:10},donut:{size:"65%",background:"transparent",labels:{show:!1,name:{show:!0,fontSize:"16px",fontFamily:void 0,fontWeight:600,color:void 0,offsetY:-10,formatter:function(e){return e}},value:{show:!0,fontSize:"20px",fontFamily:void 0,fontWeight:400,color:void 0,offsetY:10,formatter:function(e){return e}},total:{show:!1,showAlways:!1,label:"Total",fontSize:"16px",fontWeight:400,fontFamily:void 0,color:void 0,formatter:function(e){return e.globals.seriesTotals.reduce((function(t,i){return t+i}),0)}}}}},polarArea:{rings:{strokeWidth:1,strokeColor:"#e8e8e8"},spokes:{strokeWidth:1,connectorColors:"#e8e8e8"}},radar:{size:void 0,offsetX:0,offsetY:0,polygons:{strokeWidth:1,strokeColors:"#e8e8e8",connectorColors:"#e8e8e8",fill:{colors:void 0}}}},colors:void 0,dataLabels:{enabled:!0,enabledOnSeries:void 0,formatter:function(e){return e!==null?e:""},textAnchor:"middle",distributed:!1,offsetX:0,offsetY:0,style:{fontSize:"12px",fontFamily:void 0,fontWeight:600,colors:void 0},background:{enabled:!0,foreColor:"#fff",borderRadius:2,padding:4,opacity:.9,borderWidth:1,borderColor:"#fff",dropShadow:{enabled:!1,top:1,left:1,blur:1,color:"#000",opacity:.8}},dropShadow:{enabled:!1,top:1,left:1,blur:1,color:"#000",opacity:.8}},fill:{type:"solid",colors:void 0,opacity:.85,gradient:{shade:"dark",type:"horizontal",shadeIntensity:.5,gradientToColors:void 0,inverseColors:!0,opacityFrom:1,opacityTo:1,stops:[0,50,100],colorStops:[]},image:{src:[],width:void 0,height:void 0},pattern:{style:"squares",width:6,height:6,strokeWidth:2}},forecastDataPoints:{count:0,fillOpacity:.5,strokeWidth:void 0,dashArray:4},grid:{show:!0,borderColor:"#e0e0e0",strokeDashArray:0,position:"back",xaxis:{lines:{show:!1}},yaxis:{lines:{show:!0}},row:{colors:void 0,opacity:.5},column:{colors:void 0,opacity:.5},padding:{top:0,right:10,bottom:0,left:12}},labels:[],legend:{show:!0,showForSingleSeries:!1,showForNullSeries:!0,showForZeroSeries:!0,floating:!1,position:"bottom",horizontalAlign:"center",inverseOrder:!1,fontSize:"12px",fontFamily:void 0,fontWeight:400,width:void 0,height:void 0,formatter:void 0,tooltipHoverFormatter:void 0,offsetX:-20,offsetY:4,customLegendItems:[],clusterGroupedSeries:!0,clusterGroupedSeriesOrientation:"vertical",labels:{colors:void 0,useSeriesColors:!1},markers:{size:7,fillColors:void 0,strokeWidth:1,shape:void 0,offsetX:0,offsetY:0,customHTML:void 0,onClick:void 0},itemMargin:{horizontal:5,vertical:4},onItemClick:{toggleDataSeries:!0},onItemHover:{highlightDataSeries:!0}},markers:{discrete:[],size:0,colors:void 0,strokeColors:"#fff",strokeWidth:2,strokeOpacity:.9,strokeDashArray:0,fillOpacity:1,shape:"circle",offsetX:0,offsetY:0,showNullDataPoints:!0,onClick:void 0,onDblClick:void 0,hover:{size:void 0,sizeOffset:3}},noData:{text:void 0,align:"center",verticalAlign:"middle",offsetX:0,offsetY:0,style:{color:void 0,fontSize:"14px",fontFamily:void 0}},responsive:[],series:void 0,states:{hover:{filter:{type:"lighten"}},active:{allowMultipleDataPointsSelection:!1,filter:{type:"darken"}}},title:{text:void 0,align:"left",margin:5,offsetX:0,offsetY:0,floating:!1,style:{fontSize:"14px",fontWeight:900,fontFamily:void 0,color:void 0}},subtitle:{text:void 0,align:"left",margin:5,offsetX:0,offsetY:30,floating:!1,style:{fontSize:"12px",fontWeight:400,fontFamily:void 0,color:void 0}},stroke:{show:!0,curve:"smooth",lineCap:"butt",width:2,colors:void 0,dashArray:0,fill:{type:"solid",colors:void 0,opacity:.85,gradient:{shade:"dark",type:"horizontal",shadeIntensity:.5,gradientToColors:void 0,inverseColors:!0,opacityFrom:1,opacityTo:1,stops:[0,50,100],colorStops:[]}}},tooltip:{enabled:!0,enabledOnSeries:void 0,shared:!0,hideEmptySeries:!1,followCursor:!1,intersect:!1,inverseOrder:!1,custom:void 0,fillSeriesColor:!1,theme:"light",cssClass:"",style:{fontSize:"12px",fontFamily:void 0},onDatasetHover:{highlightDataSeries:!1},x:{show:!0,format:"dd MMM",formatter:void 0},y:{formatter:void 0,title:{formatter:function(e){return e?e+": ":""}}},z:{formatter:void 0,title:"Size: "},marker:{show:!0,fillColors:void 0},items:{display:"flex"},fixed:{enabled:!1,position:"topRight",offsetX:0,offsetY:0}},xaxis:{type:"category",categories:[],convertedCatToNumeric:!1,offsetX:0,offsetY:0,overwriteCategories:void 0,labels:{show:!0,rotate:-45,rotateAlways:!1,hideOverlappingLabels:!0,trim:!1,minHeight:void 0,maxHeight:120,showDuplicates:!0,style:{colors:[],fontSize:"12px",fontWeight:400,fontFamily:void 0,cssClass:""},offsetX:0,offsetY:0,format:void 0,formatter:void 0,datetimeUTC:!0,datetimeFormatter:{year:"yyyy",month:"MMM 'yy",day:"dd MMM",hour:"HH:mm",minute:"HH:mm:ss",second:"HH:mm:ss"}},group:{groups:[],style:{colors:[],fontSize:"12px",fontWeight:400,fontFamily:void 0,cssClass:""}},axisBorder:{show:!0,color:"#e0e0e0",width:"100%",height:1,offsetX:0,offsetY:0},axisTicks:{show:!0,color:"#e0e0e0",height:6,offsetX:0,offsetY:0},stepSize:void 0,tickAmount:void 0,tickPlacement:"on",min:void 0,max:void 0,range:void 0,floating:!1,decimalsInFloat:void 0,position:"bottom",title:{text:void 0,offsetX:0,offsetY:0,style:{color:void 0,fontSize:"12px",fontWeight:900,fontFamily:void 0,cssClass:""}},crosshairs:{show:!0,width:1,position:"back",opacity:.9,stroke:{color:"#b6b6b6",width:1,dashArray:3},fill:{type:"solid",color:"#B1B9C4",gradient:{colorFrom:"#D8E3F0",colorTo:"#BED1E6",stops:[0,100],opacityFrom:.4,opacityTo:.5}},dropShadow:{enabled:!1,left:0,top:0,blur:1,opacity:.8}},tooltip:{enabled:!0,offsetY:0,formatter:void 0,style:{fontSize:"12px",fontFamily:void 0}}},yaxis:this.yAxis,theme:{mode:"",palette:"palette1",monochrome:{enabled:!1,color:"#008FFB",shadeTo:"light",shadeIntensity:.65}}}}}]),o})(),Is=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w,this.graphics=new X(this.ctx),this.w.globals.isBarHorizontal&&(this.invertAxis=!0),this.helpers=new Yt(this),this.xAxisAnnotations=new Ls(this),this.yAxisAnnotations=new Ms(this),this.pointsAnnotations=new Ps(this),this.w.globals.isBarHorizontal&&this.w.config.yaxis[0].reversed&&(this.inversedReversedAxis=!0),this.xDivision=this.w.globals.gridWidth/this.w.globals.dataPoints}return O(o,[{key:"drawAxesAnnotations",value:function(){var e=this.w;if(e.globals.axisCharts&&e.globals.dataPoints){for(var t=this.yAxisAnnotations.drawYAxisAnnotations(),i=this.xAxisAnnotations.drawXAxisAnnotations(),a=this.pointsAnnotations.drawPointAnnotations(),s=e.config.chart.animations.enabled,r=[t,i,a],n=[i.node,t.node,a.node],l=0;l<3;l++)e.globals.dom.elGraphical.add(r[l]),!s||e.globals.resized||e.globals.dataChanged||e.config.chart.type!=="scatter"&&e.config.chart.type!=="bubble"&&e.globals.dataPoints>1&&n[l].classList.add("apexcharts-element-hidden"),e.globals.delayedElements.push({el:n[l],index:0});this.helpers.annotationsBackground()}}},{key:"drawImageAnnos",value:function(){var e=this;this.w.config.annotations.images.map((function(t,i){e.addImage(t,i)}))}},{key:"drawTextAnnos",value:function(){var e=this;this.w.config.annotations.texts.map((function(t,i){e.addText(t,i)}))}},{key:"addXaxisAnnotation",value:function(e,t,i){this.xAxisAnnotations.addXaxisAnnotation(e,t,i)}},{key:"addYaxisAnnotation",value:function(e,t,i){this.yAxisAnnotations.addYaxisAnnotation(e,t,i)}},{key:"addPointAnnotation",value:function(e,t,i){this.pointsAnnotations.addPointAnnotation(e,t,i)}},{key:"addText",value:function(e,t){var i=e.x,a=e.y,s=e.text,r=e.textAnchor,n=e.foreColor,l=e.fontSize,h=e.fontFamily,d=e.fontWeight,c=e.cssClass,u=e.backgroundColor,g=e.borderWidth,p=e.strokeDashArray,f=e.borderRadius,x=e.borderColor,b=e.appendTo,m=b===void 0?".apexcharts-svg":b,v=e.paddingLeft,k=v===void 0?4:v,y=e.paddingRight,C=y===void 0?4:y,w=e.paddingBottom,A=w===void 0?2:w,S=e.paddingTop,M=S===void 0?2:S,P=this.w,I=this.graphics.drawText({x:i,y:a,text:s,textAnchor:r||"start",fontSize:l||"12px",fontWeight:d||"regular",fontFamily:h||P.config.chart.fontFamily,foreColor:n||P.config.chart.foreColor,cssClass:c}),T=P.globals.dom.baseEl.querySelector(m);T&&T.appendChild(I.node);var z=I.bbox();if(s){var E=this.graphics.drawRect(z.x-k,z.y-M,z.width+k+C,z.height+A+M,f,u||"transparent",1,g,x,p);T.insertBefore(E.node,I.node)}}},{key:"addImage",value:function(e,t){var i=this.w,a=e.path,s=e.x,r=s===void 0?0:s,n=e.y,l=n===void 0?0:n,h=e.width,d=h===void 0?20:h,c=e.height,u=c===void 0?20:c,g=e.appendTo,p=g===void 0?".apexcharts-svg":g,f=i.globals.dom.Paper.image(a);f.size(d,u).move(r,l);var x=i.globals.dom.baseEl.querySelector(p);return x&&x.appendChild(f.node),f}},{key:"addXaxisAnnotationExternal",value:function(e,t,i){return this.addAnnotationExternal({params:e,pushToMemory:t,context:i,type:"xaxis",contextMethod:i.addXaxisAnnotation}),i}},{key:"addYaxisAnnotationExternal",value:function(e,t,i){return this.addAnnotationExternal({params:e,pushToMemory:t,context:i,type:"yaxis",contextMethod:i.addYaxisAnnotation}),i}},{key:"addPointAnnotationExternal",value:function(e,t,i){return this.invertAxis===void 0&&(this.invertAxis=i.w.globals.isBarHorizontal),this.addAnnotationExternal({params:e,pushToMemory:t,context:i,type:"point",contextMethod:i.addPointAnnotation}),i}},{key:"addAnnotationExternal",value:function(e){var t=e.params,i=e.pushToMemory,a=e.context,s=e.type,r=e.contextMethod,n=a,l=n.w,h=l.globals.dom.baseEl.querySelector(".apexcharts-".concat(s,"-annotations")),d=h.childNodes.length+1,c=new qe,u=Object.assign({},s==="xaxis"?c.xAxisAnnotation:s==="yaxis"?c.yAxisAnnotation:c.pointAnnotation),g=L.extend(u,t);switch(s){case"xaxis":this.addXaxisAnnotation(g,h,d);break;case"yaxis":this.addYaxisAnnotation(g,h,d);break;case"point":this.addPointAnnotation(g,h,d)}var p=l.globals.dom.baseEl.querySelector(".apexcharts-".concat(s,"-annotations .apexcharts-").concat(s,"-annotation-label[rel='").concat(d,"']")),f=this.helpers.addBackgroundToAnno(p,g);return f&&h.insertBefore(f.node,p),i&&l.globals.memory.methodsToExec.push({context:n,id:g.id?g.id:L.randomId(),method:r,label:"addAnnotation",params:t}),a}},{key:"clearAnnotations",value:function(e){for(var t=e.w,i=t.globals.dom.baseEl.querySelectorAll(".apexcharts-yaxis-annotations, .apexcharts-xaxis-annotations, .apexcharts-point-annotations"),a=t.globals.memory.methodsToExec.length-1;a>=0;a--)t.globals.memory.methodsToExec[a].label!=="addText"&&t.globals.memory.methodsToExec[a].label!=="addAnnotation"||t.globals.memory.methodsToExec.splice(a,1);i=L.listToArray(i),Array.prototype.forEach.call(i,(function(s){for(;s.firstChild;)s.removeChild(s.firstChild)}))}},{key:"removeAnnotation",value:function(e,t){var i=e.w,a=i.globals.dom.baseEl.querySelectorAll(".".concat(t));a&&(i.globals.memory.methodsToExec.map((function(s,r){s.id===t&&i.globals.memory.methodsToExec.splice(r,1)})),Array.prototype.forEach.call(a,(function(s){s.parentElement.removeChild(s)})))}}]),o})(),wi=function(o){var e,t=o.isTimeline,i=o.ctx,a=o.seriesIndex,s=o.dataPointIndex,r=o.y1,n=o.y2,l=o.w,h=l.globals.seriesRangeStart[a][s],d=l.globals.seriesRangeEnd[a][s],c=l.globals.labels[s],u=l.config.series[a].name?l.config.series[a].name:"",g=l.globals.ttKeyFormatter,p=l.config.tooltip.y.title.formatter,f={w:l,seriesIndex:a,dataPointIndex:s,start:h,end:d};typeof p=="function"&&(u=p(u,f)),(e=l.config.series[a].data[s])!==null&&e!==void 0&&e.x&&(c=l.config.series[a].data[s].x),t||l.config.xaxis.type==="datetime"&&(c=new mt(i).xLabelFormat(l.globals.ttKeyFormatter,c,c,{i:void 0,dateFormatter:new ge(i).formatDate,w:l})),typeof g=="function"&&(c=g(c,f)),Number.isFinite(r)&&Number.isFinite(n)&&(h=r,d=n);var x="",b="",m=l.globals.colors[a];if(l.config.tooltip.x.formatter===void 0)if(l.config.xaxis.type==="datetime"){var v=new ge(i);x=v.formatDate(v.getDate(h),l.config.tooltip.x.format),b=v.formatDate(v.getDate(d),l.config.tooltip.x.format)}else x=h,b=d;else x=l.config.tooltip.x.formatter(h),b=l.config.tooltip.x.formatter(d);return{start:h,end:d,startVal:x,endVal:b,ylabel:c,color:m,seriesName:u}},ki=function(o){var e=o.color,t=o.seriesName,i=o.ylabel,a=o.start,s=o.end,r=o.seriesIndex,n=o.dataPointIndex,l=o.ctx.tooltip.tooltipLabels.getFormatters(r);a=l.yLbFormatter(a),s=l.yLbFormatter(s);var h=l.yLbFormatter(o.w.globals.series[r][n]),d=` + `.concat(a,` + - + `).concat(s,` + `);return'
'+(t||"")+'
'+i+": "+(o.w.globals.comboCharts?o.w.config.series[r].type==="rangeArea"||o.w.config.series[r].type==="rangeBar"?d:"".concat(h,""):d)+"
"},vt=(function(){function o(e){H(this,o),this.opts=e}return O(o,[{key:"hideYAxis",value:function(){this.opts.yaxis[0].show=!1,this.opts.yaxis[0].title.text="",this.opts.yaxis[0].axisBorder.show=!1,this.opts.yaxis[0].axisTicks.show=!1,this.opts.yaxis[0].floating=!0}},{key:"line",value:function(){return{dataLabels:{enabled:!1},stroke:{width:5,curve:"straight"},markers:{size:0,hover:{sizeOffset:6}},xaxis:{crosshairs:{width:1}}}}},{key:"sparkline",value:function(e){return this.hideYAxis(),L.extend(e,{grid:{show:!1,padding:{left:0,right:0,top:0,bottom:0}},legend:{show:!1},xaxis:{labels:{show:!1},tooltip:{enabled:!1},axisBorder:{show:!1},axisTicks:{show:!1}},chart:{toolbar:{show:!1},zoom:{enabled:!1}},dataLabels:{enabled:!1}})}},{key:"slope",value:function(){return this.hideYAxis(),{chart:{toolbar:{show:!1},zoom:{enabled:!1}},dataLabels:{enabled:!0,formatter:function(e,t){var i=t.w.config.series[t.seriesIndex].name;return e!==null?i+": "+e:""},background:{enabled:!1},offsetX:-5},grid:{xaxis:{lines:{show:!0}},yaxis:{lines:{show:!1}}},xaxis:{position:"top",labels:{style:{fontSize:14,fontWeight:900}},tooltip:{enabled:!1},crosshairs:{show:!1}},markers:{size:8,hover:{sizeOffset:1}},legend:{show:!1},tooltip:{shared:!1,intersect:!0,followCursor:!0},stroke:{width:5,curve:"straight"}}}},{key:"bar",value:function(){return{chart:{stacked:!1},plotOptions:{bar:{dataLabels:{position:"center"}}},dataLabels:{style:{colors:["#fff"]},background:{enabled:!1}},stroke:{width:0,lineCap:"round"},fill:{opacity:.85},legend:{markers:{shape:"square"}},tooltip:{shared:!1,intersect:!0},xaxis:{tooltip:{enabled:!1},tickPlacement:"between",crosshairs:{width:"barWidth",position:"back",fill:{type:"gradient"},dropShadow:{enabled:!1},stroke:{width:0}}}}}},{key:"funnel",value:function(){return this.hideYAxis(),R(R({},this.bar()),{},{chart:{animations:{speed:800,animateGradually:{enabled:!1}}},plotOptions:{bar:{horizontal:!0,borderRadiusApplication:"around",borderRadius:0,dataLabels:{position:"center"}}},grid:{show:!1,padding:{left:0,right:0}},xaxis:{labels:{show:!1},tooltip:{enabled:!1},axisBorder:{show:!1},axisTicks:{show:!1}}})}},{key:"candlestick",value:function(){var e=this;return{stroke:{width:1,colors:["#333"]},fill:{opacity:1},dataLabels:{enabled:!1},tooltip:{shared:!0,custom:function(t){var i=t.seriesIndex,a=t.dataPointIndex,s=t.w;return e._getBoxTooltip(s,i,a,["Open","High","","Low","Close"],"candlestick")}},states:{active:{filter:{type:"none"}}},xaxis:{crosshairs:{width:1}}}}},{key:"boxPlot",value:function(){var e=this;return{chart:{animations:{dynamicAnimation:{enabled:!1}}},stroke:{width:1,colors:["#24292e"]},dataLabels:{enabled:!1},tooltip:{shared:!0,custom:function(t){var i=t.seriesIndex,a=t.dataPointIndex,s=t.w;return e._getBoxTooltip(s,i,a,["Minimum","Q1","Median","Q3","Maximum"],"boxPlot")}},markers:{size:7,strokeWidth:1,strokeColors:"#111"},xaxis:{crosshairs:{width:1}}}}},{key:"rangeBar",value:function(){return{chart:{animations:{animateGradually:!1}},stroke:{width:0,lineCap:"square"},plotOptions:{bar:{borderRadius:0,dataLabels:{position:"center"}}},dataLabels:{enabled:!1,formatter:function(e,t){t.ctx;var i=t.seriesIndex,a=t.dataPointIndex,s=t.w,r=function(){var n=s.globals.seriesRangeStart[i][a];return s.globals.seriesRangeEnd[i][a]-n};return s.globals.comboCharts?s.config.series[i].type==="rangeBar"||s.config.series[i].type==="rangeArea"?r():e:r()},background:{enabled:!1},style:{colors:["#fff"]}},markers:{size:10},tooltip:{shared:!1,followCursor:!0,custom:function(e){return e.w.config.plotOptions&&e.w.config.plotOptions.bar&&e.w.config.plotOptions.bar.horizontal?(function(t){var i=wi(R(R({},t),{},{isTimeline:!0})),a=i.color,s=i.seriesName,r=i.ylabel,n=i.startVal,l=i.endVal;return ki(R(R({},t),{},{color:a,seriesName:s,ylabel:r,start:n,end:l}))})(e):(function(t){var i=wi(t),a=i.color,s=i.seriesName,r=i.ylabel,n=i.start,l=i.end;return ki(R(R({},t),{},{color:a,seriesName:s,ylabel:r,start:n,end:l}))})(e)}},xaxis:{tickPlacement:"between",tooltip:{enabled:!1},crosshairs:{stroke:{width:0}}}}}},{key:"dumbbell",value:function(e){var t,i;return(t=e.plotOptions.bar)!==null&&t!==void 0&&t.barHeight||(e.plotOptions.bar.barHeight=2),(i=e.plotOptions.bar)!==null&&i!==void 0&&i.columnWidth||(e.plotOptions.bar.columnWidth=2),e}},{key:"area",value:function(){return{stroke:{width:4,fill:{type:"solid",gradient:{inverseColors:!1,shade:"light",type:"vertical",opacityFrom:.65,opacityTo:.5,stops:[0,100,100]}}},fill:{type:"gradient",gradient:{inverseColors:!1,shade:"light",type:"vertical",opacityFrom:.65,opacityTo:.5,stops:[0,100,100]}},markers:{size:0,hover:{sizeOffset:6}},tooltip:{followCursor:!1}}}},{key:"rangeArea",value:function(){return{stroke:{curve:"straight",width:0},fill:{type:"solid",opacity:.6},markers:{size:0},states:{hover:{filter:{type:"none"}},active:{filter:{type:"none"}}},tooltip:{intersect:!1,shared:!0,followCursor:!0,custom:function(e){return(function(t){var i=wi(t),a=i.color,s=i.seriesName,r=i.ylabel,n=i.start,l=i.end;return ki(R(R({},t),{},{color:a,seriesName:s,ylabel:r,start:n,end:l}))})(e)}}}}},{key:"brush",value:function(e){return L.extend(e,{chart:{toolbar:{autoSelected:"selection",show:!1},zoom:{enabled:!1}},dataLabels:{enabled:!1},stroke:{width:1},tooltip:{enabled:!1},xaxis:{tooltip:{enabled:!1}}})}},{key:"stacked100",value:function(e){e.dataLabels=e.dataLabels||{},e.dataLabels.formatter=e.dataLabels.formatter||void 0;var t=e.dataLabels.formatter;return e.yaxis.forEach((function(i,a){e.yaxis[a].min=0,e.yaxis[a].max=100})),e.chart.type==="bar"&&(e.dataLabels.formatter=t||function(i){return typeof i=="number"&&i?i.toFixed(0)+"%":i}),e}},{key:"stackedBars",value:function(){var e=this.bar();return R(R({},e),{},{plotOptions:R(R({},e.plotOptions),{},{bar:R(R({},e.plotOptions.bar),{},{borderRadiusApplication:"end",borderRadiusWhenStacked:"last"})})})}},{key:"convertCatToNumeric",value:function(e){return e.xaxis.convertedCatToNumeric=!0,e}},{key:"convertCatToNumericXaxis",value:function(e,t,i){e.xaxis.type="numeric",e.xaxis.labels=e.xaxis.labels||{},e.xaxis.labels.formatter=e.xaxis.labels.formatter||function(r){return L.isNumber(r)?Math.floor(r):r};var a=e.xaxis.labels.formatter,s=e.xaxis.categories&&e.xaxis.categories.length?e.xaxis.categories:e.labels;return i&&i.length&&(s=i.map((function(r){return Array.isArray(r)?r:String(r)}))),s&&s.length&&(e.xaxis.labels.formatter=function(r){return L.isNumber(r)?a(s[Math.floor(r)-1]):a(r)}),e.xaxis.categories=[],e.labels=[],e.xaxis.tickAmount=e.xaxis.tickAmount||"dataPoints",e}},{key:"bubble",value:function(){return{dataLabels:{style:{colors:["#fff"]}},tooltip:{shared:!1,intersect:!0},xaxis:{crosshairs:{width:0}},fill:{type:"solid",gradient:{shade:"light",inverse:!0,shadeIntensity:.55,opacityFrom:.4,opacityTo:.8}}}}},{key:"scatter",value:function(){return{dataLabels:{enabled:!1},tooltip:{shared:!1,intersect:!0},markers:{size:6,strokeWidth:1,hover:{sizeOffset:2}}}}},{key:"heatmap",value:function(){return{chart:{stacked:!1},fill:{opacity:1},dataLabels:{style:{colors:["#fff"]}},stroke:{colors:["#fff"]},tooltip:{followCursor:!0,marker:{show:!1},x:{show:!1}},legend:{position:"top",markers:{shape:"square"}},grid:{padding:{right:20}}}}},{key:"treemap",value:function(){return{chart:{zoom:{enabled:!1}},dataLabels:{style:{fontSize:14,fontWeight:600,colors:["#fff"]}},stroke:{show:!0,width:2,colors:["#fff"]},legend:{show:!1},fill:{opacity:1,gradient:{stops:[0,100]}},tooltip:{followCursor:!0,x:{show:!1}},grid:{padding:{left:0,right:0}},xaxis:{crosshairs:{show:!1},tooltip:{enabled:!1}}}}},{key:"pie",value:function(){return{chart:{toolbar:{show:!1}},plotOptions:{pie:{donut:{labels:{show:!1}}}},dataLabels:{formatter:function(e){return e.toFixed(1)+"%"},style:{colors:["#fff"]},background:{enabled:!1},dropShadow:{enabled:!0}},stroke:{colors:["#fff"]},fill:{opacity:1,gradient:{shade:"light",stops:[0,100]}},tooltip:{theme:"dark",fillSeriesColor:!0},legend:{position:"right"},grid:{padding:{left:0,right:0,top:0,bottom:0}}}}},{key:"donut",value:function(){return{chart:{toolbar:{show:!1}},dataLabels:{formatter:function(e){return e.toFixed(1)+"%"},style:{colors:["#fff"]},background:{enabled:!1},dropShadow:{enabled:!0}},stroke:{colors:["#fff"]},fill:{opacity:1,gradient:{shade:"light",shadeIntensity:.35,stops:[80,100],opacityFrom:1,opacityTo:1}},tooltip:{theme:"dark",fillSeriesColor:!0},legend:{position:"right"},grid:{padding:{left:0,right:0,top:0,bottom:0}}}}},{key:"polarArea",value:function(){return{chart:{toolbar:{show:!1}},dataLabels:{formatter:function(e){return e.toFixed(1)+"%"},enabled:!1},stroke:{show:!0,width:2},fill:{opacity:.7},tooltip:{theme:"dark",fillSeriesColor:!0},legend:{position:"right"},grid:{padding:{left:0,right:0,top:0,bottom:0}}}}},{key:"radar",value:function(){return this.opts.yaxis[0].labels.offsetY=this.opts.yaxis[0].labels.offsetY?this.opts.yaxis[0].labels.offsetY:6,{dataLabels:{enabled:!1,style:{fontSize:"11px"}},stroke:{width:2},markers:{size:5,strokeWidth:1,strokeOpacity:1},fill:{opacity:.2},tooltip:{shared:!1,intersect:!0,followCursor:!0},grid:{show:!1,padding:{left:0,right:0,top:0,bottom:0}},xaxis:{labels:{formatter:function(e){return e},style:{colors:["#a8a8a8"],fontSize:"11px"}},tooltip:{enabled:!1},crosshairs:{show:!1}}}}},{key:"radialBar",value:function(){return{chart:{animations:{dynamicAnimation:{enabled:!0,speed:800}},toolbar:{show:!1}},fill:{gradient:{shade:"dark",shadeIntensity:.4,inverseColors:!1,type:"diagonal2",opacityFrom:1,opacityTo:1,stops:[70,98,100]}},legend:{show:!1,position:"right"},tooltip:{enabled:!1,fillSeriesColor:!0},grid:{padding:{left:0,right:0,top:0,bottom:0}}}}},{key:"_getBoxTooltip",value:function(e,t,i,a,s){var r=e.globals.seriesCandleO[t][i],n=e.globals.seriesCandleH[t][i],l=e.globals.seriesCandleM[t][i],h=e.globals.seriesCandleL[t][i],d=e.globals.seriesCandleC[t][i];return e.config.series[t].type&&e.config.series[t].type!==s?`
+ `.concat(e.config.series[t].name?e.config.series[t].name:"series-"+(t+1),": ").concat(e.globals.series[t][i],` +
`):'
')+"
".concat(a[0],': ')+r+"
"+"
".concat(a[1],': ')+n+"
"+(l?"
".concat(a[2],': ')+l+"
":"")+"
".concat(a[3],': ')+h+"
"+"
".concat(a[4],': ')+d+"
"}}]),o})(),yt=(function(){function o(e){H(this,o),this.opts=e}return O(o,[{key:"init",value:function(e){var t=e.responsiveOverride,i=this.opts,a=new qe,s=new vt(i);this.chartType=i.chart.type,i=this.extendYAxis(i),i=this.extendAnnotations(i);var r=a.init(),n={};if(i&&Ze(i)==="object"){var l,h,d,c,u,g,p,f,x,b,m={};m=["line","area","bar","candlestick","boxPlot","rangeBar","rangeArea","bubble","scatter","heatmap","treemap","pie","polarArea","donut","radar","radialBar"].indexOf(i.chart.type)!==-1?s[i.chart.type]():s.line(),(l=i.plotOptions)!==null&&l!==void 0&&(h=l.bar)!==null&&h!==void 0&&h.isFunnel&&(m=s.funnel()),i.chart.stacked&&i.chart.type==="bar"&&(m=s.stackedBars()),(d=i.chart.brush)!==null&&d!==void 0&&d.enabled&&(m=s.brush(m)),(c=i.plotOptions)!==null&&c!==void 0&&(u=c.line)!==null&&u!==void 0&&u.isSlopeChart&&(m=s.slope()),i.chart.stacked&&i.chart.stackType==="100%"&&(i=s.stacked100(i)),(g=i.plotOptions)!==null&&g!==void 0&&(p=g.bar)!==null&&p!==void 0&&p.isDumbbell&&(i=s.dumbbell(i)),this.checkForDarkTheme(window.Apex),this.checkForDarkTheme(i),i.xaxis=i.xaxis||window.Apex.xaxis||{},t||(i.xaxis.convertedCatToNumeric=!1),((f=(i=this.checkForCatToNumericXAxis(this.chartType,m,i)).chart.sparkline)!==null&&f!==void 0&&f.enabled||(x=window.Apex.chart)!==null&&x!==void 0&&(b=x.sparkline)!==null&&b!==void 0&&b.enabled)&&(m=s.sparkline(m)),n=L.extend(r,m)}var v=L.extend(n,window.Apex);return r=L.extend(v,i),r=this.handleUserInputErrors(r)}},{key:"checkForCatToNumericXAxis",value:function(e,t,i){var a,s,r=new vt(i),n=(e==="bar"||e==="boxPlot")&&((a=i.plotOptions)===null||a===void 0||(s=a.bar)===null||s===void 0?void 0:s.horizontal),l=e==="pie"||e==="polarArea"||e==="donut"||e==="radar"||e==="radialBar"||e==="heatmap",h=i.xaxis.type!=="datetime"&&i.xaxis.type!=="numeric",d=i.xaxis.tickPlacement?i.xaxis.tickPlacement:t.xaxis&&t.xaxis.tickPlacement;return n||l||!h||d==="between"||(i=r.convertCatToNumeric(i)),i}},{key:"extendYAxis",value:function(e,t){var i=new qe;(e.yaxis===void 0||!e.yaxis||Array.isArray(e.yaxis)&&e.yaxis.length===0)&&(e.yaxis={}),e.yaxis.constructor!==Array&&window.Apex.yaxis&&window.Apex.yaxis.constructor!==Array&&(e.yaxis=L.extend(e.yaxis,window.Apex.yaxis)),e.yaxis.constructor!==Array?e.yaxis=[L.extend(i.yAxis,e.yaxis)]:e.yaxis=L.extendArray(e.yaxis,i.yAxis);var a=!1;e.yaxis.forEach((function(r){r.logarithmic&&(a=!0)}));var s=e.series;return t&&!s&&(s=t.config.series),a&&s.length!==e.yaxis.length&&s.length&&(e.yaxis=s.map((function(r,n){if(r.name||(s[n].name="series-".concat(n+1)),e.yaxis[n])return e.yaxis[n].seriesName=s[n].name,e.yaxis[n];var l=L.extend(i.yAxis,e.yaxis[0]);return l.show=!1,l}))),a&&s.length>1&&s.length!==e.yaxis.length&&console.warn("A multi-series logarithmic chart should have equal number of series and y-axes"),e}},{key:"extendAnnotations",value:function(e){return e.annotations===void 0&&(e.annotations={},e.annotations.yaxis=[],e.annotations.xaxis=[],e.annotations.points=[]),e=this.extendYAxisAnnotations(e),e=this.extendXAxisAnnotations(e),e=this.extendPointAnnotations(e)}},{key:"extendYAxisAnnotations",value:function(e){var t=new qe;return e.annotations.yaxis=L.extendArray(e.annotations.yaxis!==void 0?e.annotations.yaxis:[],t.yAxisAnnotation),e}},{key:"extendXAxisAnnotations",value:function(e){var t=new qe;return e.annotations.xaxis=L.extendArray(e.annotations.xaxis!==void 0?e.annotations.xaxis:[],t.xAxisAnnotation),e}},{key:"extendPointAnnotations",value:function(e){var t=new qe;return e.annotations.points=L.extendArray(e.annotations.points!==void 0?e.annotations.points:[],t.pointAnnotation),e}},{key:"checkForDarkTheme",value:function(e){e.theme&&e.theme.mode==="dark"&&(e.tooltip||(e.tooltip={}),e.tooltip.theme!=="light"&&(e.tooltip.theme="dark"),e.chart.foreColor||(e.chart.foreColor="#f6f7f8"),e.theme.palette||(e.theme.palette="palette4"))}},{key:"handleUserInputErrors",value:function(e){var t=e;if(t.tooltip.shared&&t.tooltip.intersect)throw new Error("tooltip.shared cannot be enabled when tooltip.intersect is true. Turn off any other option by setting it to false.");if(t.chart.type==="bar"&&t.plotOptions.bar.horizontal){if(t.yaxis.length>1)throw new Error("Multiple Y Axis for bars are not supported. Switch to column chart by setting plotOptions.bar.horizontal=false");t.yaxis[0].reversed&&(t.yaxis[0].opposite=!0),t.xaxis.tooltip.enabled=!1,t.yaxis[0].tooltip.enabled=!1,t.chart.zoom.enabled=!1}return t.chart.type!=="bar"&&t.chart.type!=="rangeBar"||t.tooltip.shared&&t.xaxis.crosshairs.width==="barWidth"&&t.series.length>1&&(t.xaxis.crosshairs.width="tickWidth"),t.chart.type!=="candlestick"&&t.chart.type!=="boxPlot"||t.yaxis[0].reversed&&(console.warn("Reversed y-axis in ".concat(t.chart.type," chart is not supported.")),t.yaxis[0].reversed=!1),t}}]),o})(),La=(function(){function o(){H(this,o)}return O(o,[{key:"initGlobalVars",value:function(e){e.series=[],e.seriesCandleO=[],e.seriesCandleH=[],e.seriesCandleM=[],e.seriesCandleL=[],e.seriesCandleC=[],e.seriesRangeStart=[],e.seriesRangeEnd=[],e.seriesRange=[],e.seriesPercent=[],e.seriesGoals=[],e.seriesX=[],e.seriesZ=[],e.seriesNames=[],e.seriesTotals=[],e.seriesLog=[],e.seriesColors=[],e.stackedSeriesTotals=[],e.seriesXvalues=[],e.seriesYvalues=[],e.labels=[],e.hasXaxisGroups=!1,e.groups=[],e.barGroups=[],e.lineGroups=[],e.areaGroups=[],e.hasSeriesGroups=!1,e.seriesGroups=[],e.categoryLabels=[],e.timescaleLabels=[],e.noLabelsProvided=!1,e.resizeTimer=null,e.selectionResizeTimer=null,e.lastWheelExecution=0,e.delayedElements=[],e.pointsArray=[],e.dataLabelsRects=[],e.isXNumeric=!1,e.skipLastTimelinelabel=!1,e.skipFirstTimelinelabel=!1,e.isDataXYZ=!1,e.isMultiLineX=!1,e.isMultipleYAxis=!1,e.maxY=-Number.MAX_VALUE,e.minY=Number.MIN_VALUE,e.minYArr=[],e.maxYArr=[],e.maxX=-Number.MAX_VALUE,e.minX=Number.MAX_VALUE,e.initialMaxX=-Number.MAX_VALUE,e.initialMinX=Number.MAX_VALUE,e.maxDate=0,e.minDate=Number.MAX_VALUE,e.minZ=Number.MAX_VALUE,e.maxZ=-Number.MAX_VALUE,e.minXDiff=Number.MAX_VALUE,e.yAxisScale=[],e.xAxisScale=null,e.xAxisTicksPositions=[],e.yLabelsCoords=[],e.yTitleCoords=[],e.barPadForNumericAxis=0,e.padHorizontal=0,e.xRange=0,e.yRange=[],e.zRange=0,e.dataPoints=0,e.xTickAmount=0,e.multiAxisTickAmount=0}},{key:"globalVars",value:function(e){return{chartID:null,cuid:null,events:{beforeMount:[],mounted:[],updated:[],clicked:[],selection:[],dataPointSelection:[],zoomed:[],scrolled:[]},colors:[],clientX:null,clientY:null,fill:{colors:[]},stroke:{colors:[]},dataLabels:{style:{colors:[]}},radarPolygons:{fill:{colors:[]}},markers:{colors:[],size:e.markers.size,largestSize:0},animationEnded:!1,isTouchDevice:"ontouchstart"in window||navigator.msMaxTouchPoints,isDirty:!1,isExecCalled:!1,initialConfig:null,initialSeries:[],lastXAxis:[],lastYAxis:[],columnSeries:null,labels:[],timescaleLabels:[],noLabelsProvided:!1,allSeriesCollapsed:!1,collapsedSeries:[],collapsedSeriesIndices:[],ancillaryCollapsedSeries:[],ancillaryCollapsedSeriesIndices:[],risingSeries:[],dataFormatXNumeric:!1,capturedSeriesIndex:-1,capturedDataPointIndex:-1,selectedDataPoints:[],invalidLogScale:!1,ignoreYAxisIndexes:[],maxValsInArrayIndex:0,radialSize:0,selection:void 0,zoomEnabled:e.chart.toolbar.autoSelected==="zoom"&&e.chart.toolbar.tools.zoom&&e.chart.zoom.enabled,panEnabled:e.chart.toolbar.autoSelected==="pan"&&e.chart.toolbar.tools.pan,selectionEnabled:e.chart.toolbar.autoSelected==="selection"&&e.chart.toolbar.tools.selection,yaxis:null,mousedown:!1,lastClientPosition:{},visibleXRange:void 0,yValueDecimal:0,total:0,SVGNS:"http://www.w3.org/2000/svg",svgWidth:0,svgHeight:0,noData:!1,locale:{},dom:{},memory:{methodsToExec:[]},shouldAnimate:!0,skipLastTimelinelabel:!1,skipFirstTimelinelabel:!1,delayedElements:[],axisCharts:!0,isDataXYZ:!1,isSlopeChart:e.plotOptions.line.isSlopeChart,resized:!1,resizeTimer:null,comboCharts:!1,dataChanged:!1,previousPaths:[],allSeriesHasEqualX:!0,pointsArray:[],dataLabelsRects:[],lastDrawnDataLabelsIndexes:[],hasNullValues:!1,zoomed:!1,gridWidth:0,gridHeight:0,rotateXLabels:!1,defaultLabels:!1,xLabelFormatter:void 0,yLabelFormatters:[],xaxisTooltipFormatter:void 0,ttKeyFormatter:void 0,ttVal:void 0,ttZFormatter:void 0,LINE_HEIGHT_RATIO:1.618,xAxisLabelsHeight:0,xAxisGroupLabelsHeight:0,xAxisLabelsWidth:0,yAxisLabelsWidth:0,scaleX:1,scaleY:1,translateX:0,translateY:0,translateYAxisX:[],yAxisWidths:[],translateXAxisY:0,translateXAxisX:0,tooltip:null,niceScaleAllowedMagMsd:[[1,1,2,5,5,5,10,10,10,10,10],[1,1,2,5,5,5,10,10,10,10,10]],niceScaleDefaultTicks:[1,2,4,4,6,6,6,6,6,6,6,6,6,6,6,6,6,6,12,12,12,12,12,12,12,12,12,24],seriesYAxisMap:[],seriesYAxisReverseMap:[]}}},{key:"init",value:function(e){var t=this.globalVars(e);return this.initGlobalVars(t),t.initialConfig=L.extend({},e),t.initialSeries=L.clone(e.series),t.lastXAxis=L.clone(t.initialConfig.xaxis),t.lastYAxis=L.clone(t.initialConfig.yaxis),t}}]),o})(),Ts=(function(){function o(e){H(this,o),this.opts=e}return O(o,[{key:"init",value:function(){var e=new yt(this.opts).init({responsiveOverride:!1});return{config:e,globals:new La().init(e)}}}]),o})(),Ie=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w,this.opts=null,this.seriesIndex=0,this.patternIDs=[]}return O(o,[{key:"clippedImgArea",value:function(e){var t=this.w,i=t.config,a=parseInt(t.globals.gridWidth,10),s=parseInt(t.globals.gridHeight,10),r=a>s?a:s,n=e.image,l=0,h=0;e.width===void 0&&e.height===void 0?i.fill.image.width!==void 0&&i.fill.image.height!==void 0?(l=i.fill.image.width+1,h=i.fill.image.height):(l=r+1,h=r):(l=e.width,h=e.height);var d=document.createElementNS(t.globals.SVGNS,"pattern");X.setAttrs(d,{id:e.patternID,patternUnits:e.patternUnits?e.patternUnits:"userSpaceOnUse",width:l+"px",height:h+"px"});var c=document.createElementNS(t.globals.SVGNS,"image");d.appendChild(c),c.setAttributeNS(window.SVG.xlink,"href",n),X.setAttrs(c,{x:0,y:0,preserveAspectRatio:"none",width:l+"px",height:h+"px"}),c.style.opacity=e.opacity,t.globals.dom.elDefs.node.appendChild(d)}},{key:"getSeriesIndex",value:function(e){var t=this.w,i=t.config.chart.type;return(i==="bar"||i==="rangeBar")&&t.config.plotOptions.bar.distributed||i==="heatmap"||i==="treemap"?this.seriesIndex=e.seriesNumber:this.seriesIndex=e.seriesNumber%t.globals.series.length,this.seriesIndex}},{key:"computeColorStops",value:function(e,t){var i,a=this.w,s=null,r=null,n=ot(e);try{for(n.s();!(i=n.n()).done;){var l=i.value;l>=t.threshold?(s===null||l>s)&&(s=l):(r===null||l-1?x=L.getOpacityFromRGBA(c):m=L.hexToRgba(L.rgb2hex(c),x),e.opacity&&(x=e.opacity),f==="pattern"&&(n=this.handlePatternFill({fillConfig:e.fillConfig,patternFill:n,fillColor:c,fillOpacity:x,defaultColor:m})),b){var v=ce(h.fill.gradient.colorStops)||[],k=h.fill.gradient.type;d&&(v[this.seriesIndex]=this.computeColorStops(s.globals.series[this.seriesIndex],h.plotOptions.line.colors),k="vertical"),l=this.handleGradientFill({type:k,fillConfig:e.fillConfig,fillColor:c,fillOpacity:x,colorStops:v,i:this.seriesIndex})}if(f==="image"){var y=h.fill.image.src,C=e.patternID?e.patternID:"",w="pattern".concat(s.globals.cuid).concat(e.seriesNumber+1).concat(C);this.patternIDs.indexOf(w)===-1&&(this.clippedImgArea({opacity:x,image:Array.isArray(y)?e.seriesNumber-1&&(p=L.getOpacityFromRGBA(g));var f=l.gradient.opacityTo===void 0?a:Array.isArray(l.gradient.opacityTo)?l.gradient.opacityTo[n]:l.gradient.opacityTo;if(l.gradient.gradientToColors===void 0||l.gradient.gradientToColors.length===0)u=l.gradient.shade==="dark"?c.shadeColor(-1*parseFloat(l.gradient.shadeIntensity),i.indexOf("rgb")>-1?L.rgb2hex(i):i):c.shadeColor(parseFloat(l.gradient.shadeIntensity),i.indexOf("rgb")>-1?L.rgb2hex(i):i);else if(l.gradient.gradientToColors[h.seriesNumber]){var x=l.gradient.gradientToColors[h.seriesNumber];u=x,x.indexOf("rgba")>-1&&(f=L.getOpacityFromRGBA(x))}else u=i;if(l.gradient.gradientFrom&&(g=l.gradient.gradientFrom),l.gradient.gradientTo&&(u=l.gradient.gradientTo),l.gradient.inverseColors){var b=g;g=u,u=b}return g.indexOf("rgb")>-1&&(g=L.rgb2hex(g)),u.indexOf("rgb")>-1&&(u=L.rgb2hex(u)),d.drawGradient(t,g,u,p,f,h.size,l.gradient.stops,r,n)}}]),o})(),st=(function(){function o(e,t){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"setGlobalMarkerSize",value:function(){var e=this.w;if(e.globals.markers.size=Array.isArray(e.config.markers.size)?e.config.markers.size:[e.config.markers.size],e.globals.markers.size.length>0){if(e.globals.markers.size.length4&&arguments[4]!==void 0&&arguments[4],r=this.w,n=t,l=e,h=null,d=new X(this.ctx),c=r.config.markers.discrete&&r.config.markers.discrete.length;if(Array.isArray(l.x))for(var u=0;u0:r.config.markers.size>0)||s||c){f||(x+=" w".concat(L.randomId()));var b=this.getMarkerConfig({cssClass:x,seriesIndex:t,dataPointIndex:p});r.config.series[n].data[p]&&(r.config.series[n].data[p].fillColor&&(b.pointFillColor=r.config.series[n].data[p].fillColor),r.config.series[n].data[p].strokeColor&&(b.pointStrokeColor=r.config.series[n].data[p].strokeColor)),a!==void 0&&(b.pSize=a),(l.x[u]<-r.globals.markers.largestSize||l.x[u]>r.globals.gridWidth+r.globals.markers.largestSize||l.y[u]<-r.globals.markers.largestSize||l.y[u]>r.globals.gridHeight+r.globals.markers.largestSize)&&(b.pSize=0),!f&&((r.globals.markers.size[t]>0||s||c)&&!h&&(h=d.group({class:s||c?"":"apexcharts-series-markers"})).attr("clip-path","url(#gridRectMarkerMask".concat(r.globals.cuid,")")),(g=d.drawMarker(l.x[u],l.y[u],b)).attr("rel",p),g.attr("j",p),g.attr("index",t),g.node.setAttribute("default-marker-size",b.pSize),new ue(this.ctx).setSelectionFilter(g,t,p),this.addEvents(g),h&&h.add(g))}else r.globals.pointsArray[t]===void 0&&(r.globals.pointsArray[t]=[]),r.globals.pointsArray[t].push([l.x[u],l.y[u]])}return h}},{key:"getMarkerConfig",value:function(e){var t=e.cssClass,i=e.seriesIndex,a=e.dataPointIndex,s=a===void 0?null:a,r=e.radius,n=r===void 0?null:r,l=e.size,h=l===void 0?null:l,d=e.strokeWidth,c=d===void 0?null:d,u=this.w,g=this.getMarkerStyle(i),p=h===null?u.globals.markers.size[i]:h,f=u.config.markers;return s!==null&&f.discrete.length&&f.discrete.map((function(x){x.seriesIndex===i&&x.dataPointIndex===s&&(g.pointStrokeColor=x.strokeColor,g.pointFillColor=x.fillColor,p=x.size,g.pointShape=x.shape)})),{pSize:n===null?p:n,pRadius:n!==null?n:f.radius,pointStrokeWidth:c!==null?c:Array.isArray(f.strokeWidth)?f.strokeWidth[i]:f.strokeWidth,pointStrokeColor:g.pointStrokeColor,pointFillColor:g.pointFillColor,shape:g.pointShape||(Array.isArray(f.shape)?f.shape[i]:f.shape),class:t,pointStrokeOpacity:Array.isArray(f.strokeOpacity)?f.strokeOpacity[i]:f.strokeOpacity,pointStrokeDashArray:Array.isArray(f.strokeDashArray)?f.strokeDashArray[i]:f.strokeDashArray,pointFillOpacity:Array.isArray(f.fillOpacity)?f.fillOpacity[i]:f.fillOpacity,seriesIndex:i}}},{key:"addEvents",value:function(e){var t=this.w,i=new X(this.ctx);e.node.addEventListener("mouseenter",i.pathMouseEnter.bind(this.ctx,e)),e.node.addEventListener("mouseleave",i.pathMouseLeave.bind(this.ctx,e)),e.node.addEventListener("mousedown",i.pathMouseDown.bind(this.ctx,e)),e.node.addEventListener("click",t.config.markers.onClick),e.node.addEventListener("dblclick",t.config.markers.onDblClick),e.node.addEventListener("touchstart",i.pathMouseDown.bind(this.ctx,e),{passive:!0})}},{key:"getMarkerStyle",value:function(e){var t=this.w,i=t.globals.markers.colors,a=t.config.markers.strokeColor||t.config.markers.strokeColors;return{pointStrokeColor:Array.isArray(a)?a[e]:a,pointFillColor:Array.isArray(i)?i[e]:i}}}]),o})(),Ma=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w,this.initialAnim=this.w.config.chart.animations.enabled}return O(o,[{key:"draw",value:function(e,t,i){var a=this.w,s=new X(this.ctx),r=i.realIndex,n=i.pointsPos,l=i.zRatio,h=i.elParent,d=s.group({class:"apexcharts-series-markers apexcharts-series-".concat(a.config.chart.type)});if(d.attr("clip-path","url(#gridRectMarkerMask".concat(a.globals.cuid,")")),Array.isArray(n.x))for(var c=0;cf.maxBubbleRadius&&(p=f.maxBubbleRadius)}var x=n.x[c],b=n.y[c];if(p=p||0,b!==null&&a.globals.series[r][u]!==void 0||(g=!1),g){var m=this.drawPoint(x,b,p,r,u,t);d.add(m)}h.add(d)}}},{key:"drawPoint",value:function(e,t,i,a,s,r){var n=this.w,l=a,h=new $e(this.ctx),d=new ue(this.ctx),c=new Ie(this.ctx),u=new st(this.ctx),g=new X(this.ctx),p=u.getMarkerConfig({cssClass:"apexcharts-marker",seriesIndex:l,dataPointIndex:s,radius:n.config.chart.type==="bubble"||n.globals.comboCharts&&n.config.series[a]&&n.config.series[a].type==="bubble"?i:null}),f=c.fillPath({seriesNumber:a,dataPointIndex:s,color:p.pointFillColor,patternUnits:"objectBoundingBox",value:n.globals.series[a][r]}),x=g.drawMarker(e,t,p);if(n.config.series[l].data[s]&&n.config.series[l].data[s].fillColor&&(f=n.config.series[l].data[s].fillColor),x.attr({fill:f}),n.config.chart.dropShadow.enabled){var b=n.config.chart.dropShadow;d.dropShadow(x,b,a)}if(!this.initialAnim||n.globals.dataChanged||n.globals.resized)n.globals.animationEnded=!0;else{var m=n.config.chart.animations.speed;h.animateMarker(x,m,n.globals.easing,(function(){window.setTimeout((function(){h.animationCompleted(x)}),100)}))}return x.attr({rel:s,j:s,index:a,"default-marker-size":p.pSize}),d.setSelectionFilter(x,a,s),u.addEvents(x),x.node.classList.add("apexcharts-marker"),x}},{key:"centerTextInBubble",value:function(e){var t=this.w;return{y:e+=parseInt(t.config.dataLabels.style.fontSize,10)/4}}}]),o})(),rt=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"dataLabelsCorrection",value:function(e,t,i,a,s,r,n){var l=this.w,h=!1,d=new X(this.ctx).getTextRects(i,n),c=d.width,u=d.height;t<0&&(t=0),t>l.globals.gridHeight+u&&(t=l.globals.gridHeight+u/2),l.globals.dataLabelsRects[a]===void 0&&(l.globals.dataLabelsRects[a]=[]),l.globals.dataLabelsRects[a].push({x:e,y:t,width:c,height:u});var g=l.globals.dataLabelsRects[a].length-2,p=l.globals.lastDrawnDataLabelsIndexes[a]!==void 0?l.globals.lastDrawnDataLabelsIndexes[a][l.globals.lastDrawnDataLabelsIndexes[a].length-1]:0;if(l.globals.dataLabelsRects[a][g]!==void 0){var f=l.globals.dataLabelsRects[a][p];(e>f.x+f.width||t>f.y+f.height||t+ut.globals.gridWidth+m.textRects.width+30)&&(l="");var v=t.globals.dataLabels.style.colors[r];((t.config.chart.type==="bar"||t.config.chart.type==="rangeBar")&&t.config.plotOptions.bar.distributed||t.config.dataLabels.distributed)&&(v=t.globals.dataLabels.style.colors[n]),typeof v=="function"&&(v=v({series:t.globals.series,seriesIndex:r,dataPointIndex:n,w:t})),g&&(v=g);var k=u.offsetX,y=u.offsetY;if(t.config.chart.type!=="bar"&&t.config.chart.type!=="rangeBar"||(k=0,y=0),t.globals.isSlopeChart&&(n!==0&&(k=-2*u.offsetX+5),n!==0&&n!==t.config.series[r].data.length-1&&(k=0)),m.drawnextLabel){if((b=i.drawText({width:100,height:parseInt(u.style.fontSize,10),x:a+k,y:s+y,foreColor:v,textAnchor:h||u.textAnchor,text:l,fontSize:d||u.style.fontSize,fontFamily:u.style.fontFamily,fontWeight:u.style.fontWeight||"normal"})).attr({class:x||"apexcharts-datalabel",cx:a,cy:s}),u.dropShadow.enabled){var C=u.dropShadow;new ue(this.ctx).dropShadow(b,C)}c.add(b),t.globals.lastDrawnDataLabelsIndexes[r]===void 0&&(t.globals.lastDrawnDataLabelsIndexes[r]=[]),t.globals.lastDrawnDataLabelsIndexes[r].push(n)}return b}},{key:"addBackgroundToDataLabel",value:function(e,t){var i=this.w,a=i.config.dataLabels.background,s=a.padding,r=a.padding/2,n=t.width,l=t.height,h=new X(this.ctx).drawRect(t.x-s,t.y-r/2,n+2*s,l+r,a.borderRadius,i.config.chart.background!=="transparent"&&i.config.chart.background?i.config.chart.background:"#fff",a.opacity,a.borderWidth,a.borderColor);return a.dropShadow.enabled&&new ue(this.ctx).dropShadow(h,a.dropShadow),h}},{key:"dataLabelsBackground",value:function(){var e=this.w;if(e.config.chart.type!=="bubble")for(var t=e.globals.dom.baseEl.querySelectorAll(".apexcharts-datalabels text"),i=0;i0&&arguments[0]!==void 0)||arguments[0],t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],a=this.w,s=L.clone(a.globals.initialSeries);a.globals.previousPaths=[],i?(a.globals.collapsedSeries=[],a.globals.ancillaryCollapsedSeries=[],a.globals.collapsedSeriesIndices=[],a.globals.ancillaryCollapsedSeriesIndices=[]):s=this.emptyCollapsedSeries(s),a.config.series=s,e&&(t&&(a.globals.zoomed=!1,this.ctx.updateHelpers.revertDefaultAxisMinMax()),this.ctx.updateHelpers._updateSeries(s,a.config.chart.animations.dynamicAnimation.enabled))}},{key:"emptyCollapsedSeries",value:function(e){for(var t=this.w,i=0;i-1&&(e[i].data=[]);return e}},{key:"highlightSeries",value:function(e){var t=this.w,i=this.getSeriesByName(e),a=parseInt(i==null?void 0:i.getAttribute("data:realIndex"),10),s=t.globals.dom.baseEl.querySelectorAll(".apexcharts-series, .apexcharts-datalabels, .apexcharts-yaxis"),r=null,n=null,l=null;if(t.globals.axisCharts||t.config.chart.type==="radialBar")if(t.globals.axisCharts){r=t.globals.dom.baseEl.querySelector(".apexcharts-series[data\\:realIndex='".concat(a,"']")),n=t.globals.dom.baseEl.querySelector(".apexcharts-datalabels[data\\:realIndex='".concat(a,"']"));var h=t.globals.seriesYAxisReverseMap[a];l=t.globals.dom.baseEl.querySelector(".apexcharts-yaxis[rel='".concat(h,"']"))}else r=t.globals.dom.baseEl.querySelector(".apexcharts-series[rel='".concat(a+1,"']"));else r=t.globals.dom.baseEl.querySelector(".apexcharts-series[rel='".concat(a+1,"'] path"));for(var d=0;d=h.from&&(u0&&arguments[0]!==void 0?arguments[0]:"asc",t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],i=this.w,a=0;if(i.config.series.length>1){for(var s=i.config.series.map((function(n,l){return n.data&&n.data.length>0&&i.globals.collapsedSeriesIndices.indexOf(l)===-1&&(!i.globals.comboCharts||t.length===0||t.length&&t.indexOf(i.config.series[l].type)>-1)?l:-1})),r=e==="asc"?0:s.length-1;e==="asc"?r=0;e==="asc"?r++:r--)if(s[r]!==-1){a=s[r];break}}return a}},{key:"getBarSeriesIndices",value:function(){return this.w.globals.comboCharts?this.w.config.series.map((function(e,t){return e.type==="bar"||e.type==="column"?t:-1})).filter((function(e){return e!==-1})):this.w.config.series.map((function(e,t){return t}))}},{key:"getPreviousPaths",value:function(){var e=this.w;function t(r,n,l){for(var h=r[n].childNodes,d={type:l,paths:[],realIndex:r[n].getAttribute("data:realIndex")},c=0;c0)for(var a=function(r){for(var n=e.globals.dom.baseEl.querySelectorAll(".apexcharts-".concat(e.config.chart.type," .apexcharts-series[data\\:realIndex='").concat(r,"'] rect")),l=[],h=function(c){var u=function(p){return n[c].getAttribute(p)},g={x:parseFloat(u("x")),y:parseFloat(u("y")),width:parseFloat(u("width")),height:parseFloat(u("height"))};l.push({rect:g,color:n[c].getAttribute("color")})},d=0;d0?t:[]}));return e}}]),o})(),Ai=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w,this.twoDSeries=[],this.threeDSeries=[],this.twoDSeriesX=[],this.seriesGoals=[],this.coreUtils=new he(this.ctx)}return O(o,[{key:"isMultiFormat",value:function(){return this.isFormatXY()||this.isFormat2DArray()}},{key:"isFormatXY",value:function(){var e=this.w.config.series.slice(),t=new Le(this.ctx);if(this.activeSeriesIndex=t.getActiveConfigSeriesIndex(),e[this.activeSeriesIndex].data!==void 0&&e[this.activeSeriesIndex].data.length>0&&e[this.activeSeriesIndex].data[0]!==null&&e[this.activeSeriesIndex].data[0].x!==void 0&&e[this.activeSeriesIndex].data[0]!==null)return!0}},{key:"isFormat2DArray",value:function(){var e=this.w.config.series.slice(),t=new Le(this.ctx);if(this.activeSeriesIndex=t.getActiveConfigSeriesIndex(),e[this.activeSeriesIndex].data!==void 0&&e[this.activeSeriesIndex].data.length>0&&e[this.activeSeriesIndex].data[0]!==void 0&&e[this.activeSeriesIndex].data[0]!==null&&e[this.activeSeriesIndex].data[0].constructor===Array)return!0}},{key:"handleFormat2DArray",value:function(e,t){for(var i=this.w.config,a=this.w.globals,s=i.chart.type==="boxPlot"||i.series[t].type==="boxPlot",r=0;r=5?this.twoDSeries.push(L.parseNumber(e[t].data[r][4])):this.twoDSeries.push(L.parseNumber(e[t].data[r][1])),a.dataFormatXNumeric=!0),i.xaxis.type==="datetime"){var n=new Date(e[t].data[r][0]);n=new Date(n).getTime(),this.twoDSeriesX.push(n)}else this.twoDSeriesX.push(e[t].data[r][0]);for(var l=0;l-1&&(r=this.activeSeriesIndex);for(var n=0;n1&&arguments[1]!==void 0?arguments[1]:this.ctx,a=this.w.config,s=this.w.globals,r=new ge(i),n=a.labels.length>0?a.labels.slice():a.xaxis.categories.slice();s.isRangeBar=a.chart.type==="rangeBar"&&s.isBarHorizontal,s.hasXaxisGroups=a.xaxis.type==="category"&&a.xaxis.group.groups.length>0,s.hasXaxisGroups&&(s.groups=a.xaxis.group.groups),e.forEach((function(g,p){g.name!==void 0?s.seriesNames.push(g.name):s.seriesNames.push("series-"+parseInt(p+1,10))})),this.coreUtils.setSeriesYAxisMappings();var l=[],h=ce(new Set(a.series.map((function(g){return g.group}))));a.series.forEach((function(g,p){var f=h.indexOf(g.group);l[f]||(l[f]=[]),l[f].push(s.seriesNames[p])})),s.seriesGroups=l;for(var d=function(){for(var g=0;g0&&(this.twoDSeriesX=n,s.seriesX.push(this.twoDSeriesX))),s.labels.push(this.twoDSeriesX);var u=e[c].data.map((function(g){return L.parseNumber(g)}));s.series.push(u)}s.seriesZ.push(this.threeDSeries),e[c].color!==void 0?s.seriesColors.push(e[c].color):s.seriesColors.push(void 0)}return this.w}},{key:"parseDataNonAxisCharts",value:function(e){var t=this.w.globals,i=this.w.config;t.series=e.slice(),t.seriesNames=i.labels.slice();for(var a=0;a0?i.labels=t.xaxis.categories:t.labels.length>0?i.labels=t.labels.slice():this.fallbackToCategory?(i.labels=i.labels[0],i.seriesRange.length&&(i.seriesRange.map((function(a){a.forEach((function(s){i.labels.indexOf(s.x)<0&&s.x&&i.labels.push(s.x)}))})),i.labels=Array.from(new Set(i.labels.map(JSON.stringify)),JSON.parse)),t.xaxis.convertedCatToNumeric&&(new vt(t).convertCatToNumericXaxis(t,this.ctx,i.seriesX[0]),this._generateExternalLabels(e))):this._generateExternalLabels(e)}},{key:"_generateExternalLabels",value:function(e){var t=this.w.globals,i=this.w.config,a=[];if(t.axisCharts){if(t.series.length>0)if(this.isFormatXY())for(var s=i.series.map((function(c,u){return c.data.filter((function(g,p,f){return f.findIndex((function(x){return x.x===g.x}))===p}))})),r=s.reduce((function(c,u,g,p){return p[c].length>u.length?c:g}),0),n=0;n0&&s==i.length&&t.push(a)})),e.globals.ignoreYAxisIndexes=t.map((function(i){return i}))}}]),o})(),Ht=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"scaleSvgNode",value:function(e,t){var i=parseFloat(e.getAttributeNS(null,"width")),a=parseFloat(e.getAttributeNS(null,"height"));e.setAttributeNS(null,"width",i*t),e.setAttributeNS(null,"height",a*t),e.setAttributeNS(null,"viewBox","0 0 "+i+" "+a)}},{key:"getSvgString",value:function(){var e=this;return new Promise((function(t){var i=e.w,a=i.config.chart.toolbar.export.width,s=i.config.chart.toolbar.export.scale||a/i.globals.svgWidth;s||(s=1);var r=e.w.globals.dom.Paper.svg(),n=e.w.globals.dom.Paper.node.cloneNode(!0);s!==1&&e.scaleSvgNode(n,s),e.convertImagesToBase64(n).then((function(){r=new XMLSerializer().serializeToString(n),t(r.replace(/ /g," "))}))}))}},{key:"convertImagesToBase64",value:function(e){var t=this,i=e.getElementsByTagName("image"),a=Array.from(i).map((function(s){var r=s.getAttributeNS("http://www.w3.org/1999/xlink","href");return r&&!r.startsWith("data:")?t.getBase64FromUrl(r).then((function(n){s.setAttributeNS("http://www.w3.org/1999/xlink","href",n)})).catch((function(n){console.error("Error converting image to base64:",n)})):Promise.resolve()}));return Promise.all(a)}},{key:"getBase64FromUrl",value:function(e){return new Promise((function(t,i){var a=new Image;a.crossOrigin="Anonymous",a.onload=function(){var s=document.createElement("canvas");s.width=a.width,s.height=a.height,s.getContext("2d").drawImage(a,0,0),t(s.toDataURL())},a.onerror=i,a.src=e}))}},{key:"cleanup",value:function(){var e=this.w,t=e.globals.dom.baseEl.getElementsByClassName("apexcharts-xcrosshairs"),i=e.globals.dom.baseEl.getElementsByClassName("apexcharts-ycrosshairs"),a=e.globals.dom.baseEl.querySelectorAll(".apexcharts-zoom-rect, .apexcharts-selection-rect");Array.prototype.forEach.call(a,(function(s){s.setAttribute("width",0)})),t&&t[0]&&(t[0].setAttribute("x",-500),t[0].setAttribute("x1",-500),t[0].setAttribute("x2",-500)),i&&i[0]&&(i[0].setAttribute("y",-100),i[0].setAttribute("y1",-100),i[0].setAttribute("y2",-100))}},{key:"svgUrl",value:function(){var e=this;return new Promise((function(t){e.cleanup(),e.getSvgString().then((function(i){var a=new Blob([i],{type:"image/svg+xml;charset=utf-8"});t(URL.createObjectURL(a))}))}))}},{key:"dataURI",value:function(e){var t=this;return new Promise((function(i){var a=t.w,s=e?e.scale||e.width/a.globals.svgWidth:1;t.cleanup();var r=document.createElement("canvas");r.width=a.globals.svgWidth*s,r.height=parseInt(a.globals.dom.elWrap.style.height,10)*s;var n=a.config.chart.background!=="transparent"&&a.config.chart.background?a.config.chart.background:"#fff",l=r.getContext("2d");l.fillStyle=n,l.fillRect(0,0,r.width*s,r.height*s),t.getSvgString().then((function(h){var d="data:image/svg+xml,"+encodeURIComponent(h),c=new Image;c.crossOrigin="anonymous",c.onload=function(){if(l.drawImage(c,0,0),r.msToBlob){var u=r.msToBlob();i({blob:u})}else{var g=r.toDataURL("image/png");i({imgURI:g})}},c.src=d}))}))}},{key:"exportToSVG",value:function(){var e=this;this.svgUrl().then((function(t){e.triggerDownload(t,e.w.config.chart.toolbar.export.svg.filename,".svg")}))}},{key:"exportToPng",value:function(){var e=this,t=this.w.config.chart.toolbar.export.scale,i=this.w.config.chart.toolbar.export.width,a=t?{scale:t}:i?{width:i}:void 0;this.dataURI(a).then((function(s){var r=s.imgURI,n=s.blob;n?navigator.msSaveOrOpenBlob(n,e.w.globals.chartID+".png"):e.triggerDownload(r,e.w.config.chart.toolbar.export.png.filename,".png")}))}},{key:"exportToCSV",value:function(e){var t=this,i=e.series,a=e.fileName,s=e.columnDelimiter,r=s===void 0?",":s,n=e.lineDelimiter,l=n===void 0?` +`:n,h=this.w;i||(i=h.config.series);var d=[],c=[],u="",g=h.globals.series.map((function(y,C){return h.globals.collapsedSeriesIndices.indexOf(C)===-1?y:[]})),p=function(y){return typeof h.config.chart.toolbar.export.csv.categoryFormatter=="function"?h.config.chart.toolbar.export.csv.categoryFormatter(y):h.config.xaxis.type==="datetime"&&String(y).length>=10?new Date(y).toDateString():L.isNumber(y)?y:y.split(r).join("")},f=function(y){return typeof h.config.chart.toolbar.export.csv.valueFormatter=="function"?h.config.chart.toolbar.export.csv.valueFormatter(y):y},x=Math.max.apply(Math,ce(i.map((function(y){return y.data?y.data.length:0})))),b=new Ai(this.ctx),m=new Fe(this.ctx),v=function(y){var C="";if(h.globals.axisCharts){if(h.config.xaxis.type==="category"||h.config.xaxis.convertedCatToNumeric)if(h.globals.isBarHorizontal){var w=h.globals.yLabelFormatters[0],A=new Le(t.ctx).getActiveConfigSeriesIndex();C=w(h.globals.labels[y],{seriesIndex:A,dataPointIndex:y,w:h})}else C=m.getLabel(h.globals.labels,h.globals.timescaleLabels,0,y).text;h.config.xaxis.type==="datetime"&&(h.config.xaxis.categories.length?C=h.config.xaxis.categories[y]:h.config.labels.length&&(C=h.config.labels[y]))}else C=h.config.labels[y];return C===null?"nullvalue":(Array.isArray(C)&&(C=C.join(" ")),L.isNumber(C)?C:C.split(r).join(""))},k=function(y,C){if(d.length&&C===0&&c.push(d.join(r)),y.data){y.data=y.data.length&&y.data||ce(Array(x)).map((function(){return""}));for(var w=0;w0&&!i.globals.isBarHorizontal&&(this.xaxisLabels=i.globals.timescaleLabels.slice()),i.config.xaxis.overwriteCategories&&(this.xaxisLabels=i.config.xaxis.overwriteCategories),this.drawnLabels=[],this.drawnLabelsRects=[],i.config.xaxis.position==="top"?this.offY=0:this.offY=i.globals.gridHeight,this.offY=this.offY+i.config.xaxis.axisBorder.offsetY,this.isCategoryBarHorizontal=i.config.chart.type==="bar"&&i.config.plotOptions.bar.horizontal,this.xaxisFontSize=i.config.xaxis.labels.style.fontSize,this.xaxisFontFamily=i.config.xaxis.labels.style.fontFamily,this.xaxisForeColors=i.config.xaxis.labels.style.colors,this.xaxisBorderWidth=i.config.xaxis.axisBorder.width,this.isCategoryBarHorizontal&&(this.xaxisBorderWidth=i.config.yaxis[0].axisBorder.width.toString()),this.xaxisBorderWidth.indexOf("%")>-1?this.xaxisBorderWidth=i.globals.gridWidth*parseInt(this.xaxisBorderWidth,10)/100:this.xaxisBorderWidth=parseInt(this.xaxisBorderWidth,10),this.xaxisBorderHeight=i.config.xaxis.axisBorder.height,this.yaxis=i.config.yaxis[0]}return O(o,[{key:"drawXaxis",value:function(){var e=this.w,t=new X(this.ctx),i=t.group({class:"apexcharts-xaxis",transform:"translate(".concat(e.config.xaxis.offsetX,", ").concat(e.config.xaxis.offsetY,")")}),a=t.group({class:"apexcharts-xaxis-texts-g",transform:"translate(".concat(e.globals.translateXAxisX,", ").concat(e.globals.translateXAxisY,")")});i.add(a);for(var s=[],r=0;r6&&arguments[6]!==void 0?arguments[6]:{},d=[],c=[],u=this.w,g=h.xaxisFontSize||this.xaxisFontSize,p=h.xaxisFontFamily||this.xaxisFontFamily,f=h.xaxisForeColors||this.xaxisForeColors,x=h.fontWeight||u.config.xaxis.labels.style.fontWeight,b=h.cssClass||u.config.xaxis.labels.style.cssClass,m=u.globals.padHorizontal,v=a.length,k=u.config.xaxis.type==="category"?u.globals.dataPoints:v;if(k===0&&v>k&&(k=v),s){var y=k>1?k-1:k;n=u.globals.gridWidth/Math.min(y,v-1),m=m+r(0,n)/2+u.config.xaxis.labels.offsetX}else n=u.globals.gridWidth/k,m=m+r(0,n)+u.config.xaxis.labels.offsetX;for(var C=function(A){var S=m-r(A,n)/2+u.config.xaxis.labels.offsetX;A===0&&v===1&&n/2===m&&k===1&&(S=u.globals.gridWidth/2);var M=l.axesUtils.getLabel(a,u.globals.timescaleLabels,S,A,d,g,e),P=28;if(u.globals.rotateXLabels&&e&&(P=22),u.config.xaxis.title.text&&u.config.xaxis.position==="top"&&(P+=parseFloat(u.config.xaxis.title.style.fontSize)+2),e||(P=P+parseFloat(g)+(u.globals.xAxisLabelsHeight-u.globals.xAxisGroupLabelsHeight)+(u.globals.rotateXLabels?10:0)),M=u.config.xaxis.tickAmount!==void 0&&u.config.xaxis.tickAmount!=="dataPoints"&&u.config.xaxis.type!=="datetime"?l.axesUtils.checkLabelBasedOnTickamount(A,M,v):l.axesUtils.checkForOverflowingLabels(A,M,v,d,c),u.config.xaxis.labels.show){var I=t.drawText({x:M.x,y:l.offY+u.config.xaxis.labels.offsetY+P-(u.config.xaxis.position==="top"?u.globals.xAxisHeight+u.config.xaxis.axisTicks.height-2:0),text:M.text,textAnchor:"middle",fontWeight:M.isBold?600:x,fontSize:g,fontFamily:p,foreColor:Array.isArray(f)?e&&u.config.xaxis.convertedCatToNumeric?f[u.globals.minX+A-1]:f[A]:f,isPlainText:!1,cssClass:(e?"apexcharts-xaxis-label ":"apexcharts-xaxis-group-label ")+b});if(i.add(I),I.on("click",(function(z){if(typeof u.config.chart.events.xAxisLabelClick=="function"){var E=Object.assign({},u,{labelIndex:A});u.config.chart.events.xAxisLabelClick(z,l.ctx,E)}})),e){var T=document.createElementNS(u.globals.SVGNS,"title");T.textContent=Array.isArray(M.text)?M.text.join(" "):M.text,I.node.appendChild(T),M.text!==""&&(d.push(M.text),c.push(M))}}Aa.globals.gridWidth)){var r=this.offY+a.config.xaxis.axisTicks.offsetY;if(t=t+r+a.config.xaxis.axisTicks.height,a.config.xaxis.position==="top"&&(t=r-a.config.xaxis.axisTicks.height),a.config.xaxis.axisTicks.show){var n=new X(this.ctx).drawLine(e+a.config.xaxis.axisTicks.offsetX,r+a.config.xaxis.offsetY,s+a.config.xaxis.axisTicks.offsetX,t+a.config.xaxis.offsetY,a.config.xaxis.axisTicks.color);i.add(n),n.node.classList.add("apexcharts-xaxis-tick")}}}},{key:"getXAxisTicksPositions",value:function(){var e=this.w,t=[],i=this.xaxisLabels.length,a=e.globals.padHorizontal;if(e.globals.timescaleLabels.length>0)for(var s=0;s0){var d=s[s.length-1].getBBox(),c=s[0].getBBox();d.x<-20&&s[s.length-1].parentNode.removeChild(s[s.length-1]),c.x+c.width>e.globals.gridWidth&&!e.globals.isBarHorizontal&&s[0].parentNode.removeChild(s[0]);for(var u=0;u0&&(this.xaxisLabels=t.globals.timescaleLabels.slice())}return O(o,[{key:"drawGridArea",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,t=this.w,i=new X(this.ctx);e||(e=i.group({class:"apexcharts-grid"}));var a=i.drawLine(t.globals.padHorizontal,1,t.globals.padHorizontal,t.globals.gridHeight,"transparent"),s=i.drawLine(t.globals.padHorizontal,t.globals.gridHeight,t.globals.gridWidth,t.globals.gridHeight,"transparent");return e.add(s),e.add(a),e}},{key:"drawGrid",value:function(){if(this.w.globals.axisCharts){var e=this.renderGrid();return this.drawGridArea(e.el),e}return null}},{key:"createGridMask",value:function(){var e=this.w,t=e.globals,i=new X(this.ctx),a=Array.isArray(e.config.stroke.width)?Math.max.apply(Math,ce(e.config.stroke.width)):e.config.stroke.width,s=function(d){var c=document.createElementNS(t.SVGNS,"clipPath");return c.setAttribute("id",d),c};t.dom.elGridRectMask=s("gridRectMask".concat(t.cuid)),t.dom.elGridRectBarMask=s("gridRectBarMask".concat(t.cuid)),t.dom.elGridRectMarkerMask=s("gridRectMarkerMask".concat(t.cuid)),t.dom.elForecastMask=s("forecastMask".concat(t.cuid)),t.dom.elNonForecastMask=s("nonForecastMask".concat(t.cuid));var r=0,n=0;(["bar","rangeBar","candlestick","boxPlot"].includes(e.config.chart.type)||e.globals.comboBarCount>0)&&e.globals.isXNumeric&&!e.globals.isBarHorizontal&&(r=Math.max(e.config.grid.padding.left,t.barPadForNumericAxis),n=Math.max(e.config.grid.padding.right,t.barPadForNumericAxis)),t.dom.elGridRect=i.drawRect(0,0,t.gridWidth,t.gridHeight,0,"#fff"),t.dom.elGridRectBar=i.drawRect(-a/2-r-2,-a/2-2,t.gridWidth+a+n+r+4,t.gridHeight+a+4,0,"#fff");var l=e.globals.markers.largestSize;t.dom.elGridRectMarker=i.drawRect(-l,-l,t.gridWidth+2*l,t.gridHeight+2*l,0,"#fff"),t.dom.elGridRectMask.appendChild(t.dom.elGridRect.node),t.dom.elGridRectBarMask.appendChild(t.dom.elGridRectBar.node),t.dom.elGridRectMarkerMask.appendChild(t.dom.elGridRectMarker.node);var h=t.dom.baseEl.querySelector("defs");h.appendChild(t.dom.elGridRectMask),h.appendChild(t.dom.elGridRectBarMask),h.appendChild(t.dom.elGridRectMarkerMask),h.appendChild(t.dom.elForecastMask),h.appendChild(t.dom.elNonForecastMask)}},{key:"_drawGridLines",value:function(e){var t=e.i,i=e.x1,a=e.y1,s=e.x2,r=e.y2,n=e.xCount,l=e.parent,h=this.w;if(!(t===0&&h.globals.skipFirstTimelinelabel||t===n-1&&h.globals.skipLastTimelinelabel&&!h.config.xaxis.labels.formatter||h.config.chart.type==="radar")){h.config.grid.xaxis.lines.show&&this._drawGridLine({i:t,x1:i,y1:a,x2:s,y2:r,xCount:n,parent:l});var d=0;if(h.globals.hasXaxisGroups&&h.config.xaxis.tickPlacement==="between"){var c=h.globals.groups;if(c){for(var u=0,g=0;u0&&e.config.xaxis.type!=="datetime"&&(s=t.yAxisScale[a].result.length-1)),this._drawXYLines({xCount:s,tickAmount:r})}else s=r,r=t.xTickAmount,this._drawInvertedXYLines({xCount:s,tickAmount:r});return this.drawGridBands(s,r),{el:this.elg,elGridBorders:this.elGridBorders,xAxisTickWidth:t.gridWidth/s}}},{key:"drawGridBands",value:function(e,t){var i,a,s=this,r=this.w;if(((i=r.config.grid.row.colors)===null||i===void 0?void 0:i.length)>0&&(function(p,f,x,b,m,v){for(var k=0,y=0;k=r.config.grid[p].colors.length&&(y=0),s._drawGridBandRect({c:y,x1:x,y1:b,x2:m,y2:v,type:p}),b+=r.globals.gridHeight/t})("row",t,0,0,r.globals.gridWidth,r.globals.gridHeight/t),((a=r.config.grid.column.colors)===null||a===void 0?void 0:a.length)>0){var n=r.globals.isBarHorizontal||r.config.xaxis.tickPlacement!=="on"||r.config.xaxis.type!=="category"&&!r.config.xaxis.convertedCatToNumeric?e:e-1;r.globals.isXNumeric&&(n=r.globals.xAxisScale.result.length-1);for(var l=r.globals.padHorizontal,h=r.globals.padHorizontal+r.globals.gridWidth/n,d=r.globals.gridHeight,c=0,u=0;c=r.config.grid.column.colors.length&&(u=0),r.config.xaxis.type==="datetime"&&(l=this.xaxisLabels[c].position,h=(((g=this.xaxisLabels[c+1])===null||g===void 0?void 0:g.position)||r.globals.gridWidth)-this.xaxisLabels[c].position),this._drawGridBandRect({c:u,x1:l,y1:0,x2:h,y2:d,type:"column"}),l+=r.globals.gridWidth/n}}}}]),o})(),Ia=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w,this.coreUtils=new he(this.ctx)}return O(o,[{key:"niceScale",value:function(e,t){var i,a,s,r,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,l=1e-11,h=this.w,d=h.globals;d.isBarHorizontal?(i=h.config.xaxis,a=Math.max((d.svgWidth-100)/25,2)):(i=h.config.yaxis[n],a=Math.max((d.svgHeight-100)/15,2)),L.isNumber(a)||(a=10),s=i.min!==void 0&&i.min!==null,r=i.max!==void 0&&i.min!==null;var c=i.stepSize!==void 0&&i.stepSize!==null,u=i.tickAmount!==void 0&&i.tickAmount!==null,g=u?i.tickAmount:d.niceScaleDefaultTicks[Math.min(Math.round(a/2),d.niceScaleDefaultTicks.length-1)];if(d.isMultipleYAxis&&!u&&d.multiAxisTickAmount>0&&(g=d.multiAxisTickAmount,u=!0),g=g==="dataPoints"?d.dataPoints-1:Math.abs(Math.round(g)),(e===Number.MIN_VALUE&&t===0||!L.isNumber(e)&&!L.isNumber(t)||e===Number.MIN_VALUE&&t===-Number.MAX_VALUE)&&(e=L.isNumber(i.min)?i.min:0,t=L.isNumber(i.max)?i.max:e+g,d.allSeriesCollapsed=!1),e>t){console.warn("axis.min cannot be greater than axis.max: swapping min and max");var p=t;t=e,e=p}else e===t&&(e=e===0?0:e-1,t=t===0?2:t+1);var f=[];g<1&&(g=1);var x=g,b=Math.abs(t-e);!s&&e>0&&e/b<.15&&(e=0,s=!0),!r&&t<0&&-t/b<.15&&(t=0,r=!0);var m=(b=Math.abs(t-e))/x,v=m,k=Math.floor(Math.log10(v)),y=Math.pow(10,k),C=Math.ceil(v/y);if(m=v=(C=d.niceScaleAllowedMagMsd[d.yValueDecimal===0?0:1][C])*y,d.isBarHorizontal&&i.stepSize&&i.type!=="datetime"?(m=i.stepSize,c=!0):c&&(m=i.stepSize),c&&i.forceNiceScale){var w=Math.floor(Math.log10(m));m*=Math.pow(10,k-w)}if(s&&r){var A=b/x;if(u)if(c)if(L.mod(b,m)!=0){var S=L.getGCD(m,A);m=A/S<10?S:A}else L.mod(m,A)==0?m=A:(A=m,u=!1);else m=A;else if(c)L.mod(b,m)==0?A=m:m=A;else if(L.mod(b,m)==0)A=m;else{A=b/(x=Math.ceil(b/m));var M=L.getGCD(b,m);b/Ma&&(e=t-m*g,e+=m*Math.floor((P-e)/m))}else if(s)if(u)t=e+m*x;else{var I=t;t=m*Math.ceil(t/m),Math.abs(t-e)/L.getGCD(b,m)>a&&(t=e+m*g,t+=m*Math.ceil((I-t)/m))}}else if(d.isMultipleYAxis&&u){var T=m*Math.floor(e/m),z=T+m*x;z0&&e16&&L.getPrimeFactors(x).length<2&&x++,!u&&i.forceNiceScale&&d.yValueDecimal===0&&x>b&&(x=b,m=Math.round(b/x)),x>a&&(!u&&!c||i.forceNiceScale)){var E=L.getPrimeFactors(x),Y=E.length-1,F=x;e:for(var _=0;_fe);return{result:f,niceMin:f[0],niceMax:f[f.length-1]}}},{key:"linearScale",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:10,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:void 0,r=Math.abs(t-e),n=[];if(e===t)return{result:n=[e],niceMin:n[0],niceMax:n[n.length-1]};(i=this._adjustTicksForSmallRange(i,a,r))==="dataPoints"&&(i=this.w.globals.dataPoints-1),s||(s=r/i),s=Math.round(10*(s+Number.EPSILON))/10,i===Number.MAX_VALUE&&(i=5,s=1);for(var l=e;i>=0;)n.push(l),l=L.preciseAddition(l,s),i-=1;return{result:n,niceMin:n[0],niceMax:n[n.length-1]}}},{key:"logarithmicScaleNice",value:function(e,t,i){t<=0&&(t=Math.max(e,i)),e<=0&&(e=Math.min(t,i));for(var a=[],s=Math.ceil(Math.log(t)/Math.log(i)+1),r=Math.floor(Math.log(e)/Math.log(i));r5?(a.allSeriesCollapsed=!1,a.yAxisScale[e]=r.forceNiceScale?this.logarithmicScaleNice(t,i,r.logBase):this.logarithmicScale(t,i,r.logBase)):i!==-Number.MAX_VALUE&&L.isNumber(i)&&t!==Number.MAX_VALUE&&L.isNumber(t)?(a.allSeriesCollapsed=!1,a.yAxisScale[e]=this.niceScale(t,i,e)):a.yAxisScale[e]=this.niceScale(Number.MIN_VALUE,0,e)}},{key:"setXScale",value:function(e,t){var i=this.w,a=i.globals,s=Math.abs(t-e);if(t!==-Number.MAX_VALUE&&L.isNumber(t)){var r=a.xTickAmount+1;s<10&&s>1&&(r=s),a.xAxisScale=this.linearScale(e,t,r,0,i.config.xaxis.stepSize)}else a.xAxisScale=this.linearScale(0,10,10);return a.xAxisScale}},{key:"scaleMultipleYAxes",value:function(){var e=this,t=this.w.config,i=this.w.globals;this.coreUtils.setSeriesYAxisMappings();var a=i.seriesYAxisMap,s=i.minYArr,r=i.maxYArr;i.allSeriesCollapsed=!0,i.barGroups=[],a.forEach((function(n,l){var h=[];n.forEach((function(d){var c=t.series[d].group;h.indexOf(c)<0&&h.push(c)})),n.length>0?(function(){var d,c,u=Number.MAX_VALUE,g=-Number.MAX_VALUE,p=u,f=g;if(t.chart.stacked)(function(){var m=new Array(i.dataPoints).fill(0),v=[],k=[],y=[];h.forEach((function(){v.push(m.map((function(){return Number.MIN_VALUE}))),k.push(m.map((function(){return Number.MIN_VALUE}))),y.push(m.map((function(){return Number.MIN_VALUE})))}));for(var C=function(A){!d&&t.series[n[A]].type&&(d=t.series[n[A]].type);var S=n[A];c=t.series[S].group?t.series[S].group:"axis-".concat(l),!(i.collapsedSeriesIndices.indexOf(S)<0&&i.ancillaryCollapsedSeriesIndices.indexOf(S)<0)||(i.allSeriesCollapsed=!1,h.forEach((function(M,P){if(t.series[S].group===M)for(var I=0;I=0?k[P][I]+=T:y[P][I]+=T,v[P][I]+=T,p=Math.min(p,T),f=Math.max(f,T)}}))),d!=="bar"&&d!=="column"||i.barGroups.push(c)},w=0;w1&&arguments[1]!==void 0?arguments[1]:Number.MAX_VALUE,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:-Number.MAX_VALUE,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,s=this.w.config,r=this.w.globals,n=-Number.MAX_VALUE,l=Number.MIN_VALUE;a===null&&(a=e+1);var h=r.series,d=h,c=h;s.chart.type==="candlestick"?(d=r.seriesCandleL,c=r.seriesCandleH):s.chart.type==="boxPlot"?(d=r.seriesCandleO,c=r.seriesCandleC):r.isRangeData&&(d=r.seriesRangeStart,c=r.seriesRangeEnd);var u=!1;if(r.seriesX.length>=a){var g,p=(g=r.brushSource)===null||g===void 0?void 0:g.w.config.chart.brush;(s.chart.zoom.enabled&&s.chart.zoom.autoScaleYaxis||p!=null&&p.enabled&&p!=null&&p.autoScaleYaxis)&&(u=!0)}for(var f=e;fb&&r.seriesX[f][m]>s.xaxis.max;m--);}for(var v=b;v<=m&&vd[f][v]&&d[f][v]<0&&(l=d[f][v])}else r.hasNullValues=!0}x!=="bar"&&x!=="column"||(l<0&&n<0&&(n=0,i=Math.max(i,0)),l===Number.MIN_VALUE&&(l=0,t=Math.min(t,0)))}return s.chart.type==="rangeBar"&&r.seriesRangeStart.length&&r.isBarHorizontal&&(l=t),s.chart.type==="bar"&&(l<0&&n<0&&(n=0),l===Number.MIN_VALUE&&(l=0)),{minY:l,maxY:n,lowestY:t,highestY:i}}},{key:"setYRange",value:function(){var e=this.w.globals,t=this.w.config;e.maxY=-Number.MAX_VALUE,e.minY=Number.MIN_VALUE;var i,a=Number.MAX_VALUE;if(e.isMultipleYAxis){a=Number.MAX_VALUE;for(var s=0;se.dataPoints&&e.dataPoints!==0&&(a=e.dataPoints-1);else if(t.xaxis.tickAmount==="dataPoints"){if(e.series.length>1&&(a=e.series[e.maxValsInArrayIndex].length-1),e.isXNumeric){var s=e.maxX-e.minX;s<30&&(a=s-1)}}else a=t.xaxis.tickAmount;if(e.xTickAmount=a,t.xaxis.max!==void 0&&typeof t.xaxis.max=="number"&&(e.maxX=t.xaxis.max),t.xaxis.min!==void 0&&typeof t.xaxis.min=="number"&&(e.minX=t.xaxis.min),t.xaxis.range!==void 0&&(e.minX=e.maxX-t.xaxis.range),e.minX!==Number.MAX_VALUE&&e.maxX!==-Number.MAX_VALUE)if(t.xaxis.convertedCatToNumeric&&!e.dataFormatXNumeric){for(var r=[],n=e.minX-1;n0&&(e.xAxisScale=this.scales.linearScale(1,e.labels.length,a-1,0,t.xaxis.stepSize),e.seriesX=e.labels.slice());i&&(e.labels=e.xAxisScale.result.slice())}return e.isBarHorizontal&&e.labels.length&&(e.xTickAmount=e.labels.length),this._handleSingleDataPoint(),this._getMinXDiff(),{minX:e.minX,maxX:e.maxX}}},{key:"setZRange",value:function(){var e=this.w.globals;if(e.isDataXYZ){for(var t=0;t0){var n=s-a[r-1];n>0&&(e.minXDiff=Math.min(n,e.minXDiff))}})),e.dataPoints!==1&&e.minXDiff!==Number.MAX_VALUE||(e.minXDiff=.5)}))}},{key:"_setStackedMinMax",value:function(){var e=this,t=this.w.globals;if(t.series.length){var i=t.seriesGroups;i.length||(i=[this.w.globals.seriesNames.map((function(r){return r}))]);var a={},s={};i.forEach((function(r){a[r]=[],s[r]=[],e.w.config.series.map((function(n,l){return r.indexOf(t.seriesNames[l])>-1?l:null})).filter((function(n){return n!==null})).forEach((function(n){for(var l=0;l0?a[r][l]+=parseFloat(t.series[n][l])+1e-4:s[r][l]+=parseFloat(t.series[n][l]))}}))})),Object.entries(a).forEach((function(r){var n=Ni(r,1)[0];a[n].forEach((function(l,h){t.maxY=Math.max(t.maxY,a[n][h]),t.minY=Math.min(t.minY,s[n][h])}))}))}}}]),o})(),Si=(function(){function o(e,t){H(this,o),this.ctx=e,this.elgrid=t,this.w=e.w;var i=this.w;this.xaxisFontSize=i.config.xaxis.labels.style.fontSize,this.axisFontFamily=i.config.xaxis.labels.style.fontFamily,this.xaxisForeColors=i.config.xaxis.labels.style.colors,this.isCategoryBarHorizontal=i.config.chart.type==="bar"&&i.config.plotOptions.bar.horizontal,this.xAxisoffX=i.config.xaxis.position==="bottom"?i.globals.gridHeight:0,this.drawnLabels=[],this.axesUtils=new Fe(e)}return O(o,[{key:"drawYaxis",value:function(e){var t=this.w,i=new X(this.ctx),a=t.config.yaxis[e].labels.style,s=a.fontSize,r=a.fontFamily,n=a.fontWeight,l=i.group({class:"apexcharts-yaxis",rel:e,transform:"translate(".concat(t.globals.translateYAxisX[e],", 0)")});if(this.axesUtils.isYAxisHidden(e))return l;var h=i.group({class:"apexcharts-yaxis-texts-g"});l.add(h);var d=t.globals.yAxisScale[e].result.length-1,c=t.globals.gridHeight/d,u=t.globals.yLabelFormatters[e],g=this.axesUtils.checkForReversedLabels(e,t.globals.yAxisScale[e].result.slice());if(t.config.yaxis[e].labels.show){var p=t.globals.translateY+t.config.yaxis[e].labels.offsetY;t.globals.isBarHorizontal?p=0:t.config.chart.type==="heatmap"&&(p-=c/2),p+=parseInt(s,10)/3;for(var f=d;f>=0;f--){var x=u(g[f],f,t),b=t.config.yaxis[e].labels.padding;t.config.yaxis[e].opposite&&t.config.yaxis.length!==0&&(b*=-1);var m=this.getTextAnchor(t.config.yaxis[e].labels.align,t.config.yaxis[e].opposite),v=this.axesUtils.getYAxisForeColor(a.colors,e),k=Array.isArray(v)?v[f]:v,y=L.listToArray(t.globals.dom.baseEl.querySelectorAll(".apexcharts-yaxis[rel='".concat(e,"'] .apexcharts-yaxis-label tspan"))).map((function(w){return w.textContent})),C=i.drawText({x:b,y:p,text:y.includes(x)&&!t.config.yaxis[e].labels.showDuplicates?"":x,textAnchor:m,fontSize:s,fontFamily:r,fontWeight:n,maxWidth:t.config.yaxis[e].labels.maxWidth,foreColor:k,isPlainText:!1,cssClass:"apexcharts-yaxis-label ".concat(a.cssClass)});h.add(C),this.addTooltip(C,x),t.config.yaxis[e].labels.rotate!==0&&this.rotateLabel(i,C,firstLabel,t.config.yaxis[e].labels.rotate),p+=c}}return this.addYAxisTitle(i,l,e),this.addAxisBorder(i,l,e,d,c),l}},{key:"getTextAnchor",value:function(e,t){return e==="left"?"start":e==="center"?"middle":e==="right"?"end":t?"start":"end"}},{key:"addTooltip",value:function(e,t){var i=document.createElementNS(this.w.globals.SVGNS,"title");i.textContent=Array.isArray(t)?t.join(" "):t,e.node.appendChild(i)}},{key:"rotateLabel",value:function(e,t,i,a){var s=e.rotateAroundCenter(i.node),r=e.rotateAroundCenter(t.node);t.node.setAttribute("transform","rotate(".concat(a," ").concat(s.x," ").concat(r.y,")"))}},{key:"addYAxisTitle",value:function(e,t,i){var a=this.w;if(a.config.yaxis[i].title.text!==void 0){var s=e.group({class:"apexcharts-yaxis-title"}),r=a.config.yaxis[i].opposite?a.globals.translateYAxisX[i]:0,n=e.drawText({x:r,y:a.globals.gridHeight/2+a.globals.translateY+a.config.yaxis[i].title.offsetY,text:a.config.yaxis[i].title.text,textAnchor:"end",foreColor:a.config.yaxis[i].title.style.color,fontSize:a.config.yaxis[i].title.style.fontSize,fontWeight:a.config.yaxis[i].title.style.fontWeight,fontFamily:a.config.yaxis[i].title.style.fontFamily,cssClass:"apexcharts-yaxis-title-text ".concat(a.config.yaxis[i].title.style.cssClass)});s.add(n),t.add(s)}}},{key:"addAxisBorder",value:function(e,t,i,a,s){var r=this.w,n=r.config.yaxis[i].axisBorder,l=31+n.offsetX;if(r.config.yaxis[i].opposite&&(l=-31-n.offsetX),n.show){var h=e.drawLine(l,r.globals.translateY+n.offsetY-2,l,r.globals.gridHeight+r.globals.translateY+n.offsetY+2,n.color,0,n.width);t.add(h)}r.config.yaxis[i].axisTicks.show&&this.axesUtils.drawYAxisTicks(l,a,n,r.config.yaxis[i].axisTicks,i,s,t)}},{key:"drawYaxisInversed",value:function(e){var t=this.w,i=new X(this.ctx),a=i.group({class:"apexcharts-xaxis apexcharts-yaxis-inversed"}),s=i.group({class:"apexcharts-xaxis-texts-g",transform:"translate(".concat(t.globals.translateXAxisX,", ").concat(t.globals.translateXAxisY,")")});a.add(s);var r=t.globals.yAxisScale[e].result.length-1,n=t.globals.gridWidth/r+.1,l=n+t.config.xaxis.labels.offsetX,h=t.globals.xLabelFormatter,d=this.axesUtils.checkForReversedLabels(e,t.globals.yAxisScale[e].result.slice()),c=t.globals.timescaleLabels;if(c.length>0&&(this.xaxisLabels=c.slice(),r=(d=c.slice()).length),t.config.xaxis.labels.show)for(var u=c.length?0:r;c.length?u=0;c.length?u++:u--){var g=h(d[u],u,t),p=t.globals.gridWidth+t.globals.padHorizontal-(l-n+t.config.xaxis.labels.offsetX);if(c.length){var f=this.axesUtils.getLabel(d,c,p,u,this.drawnLabels,this.xaxisFontSize);p=f.x,g=f.text,this.drawnLabels.push(f.text),u===0&&t.globals.skipFirstTimelinelabel&&(g=""),u===d.length-1&&t.globals.skipLastTimelinelabel&&(g="")}var x=i.drawText({x:p,y:this.xAxisoffX+t.config.xaxis.labels.offsetY+30-(t.config.xaxis.position==="top"?t.globals.xAxisHeight+t.config.xaxis.axisTicks.height-2:0),text:g,textAnchor:"middle",foreColor:Array.isArray(this.xaxisForeColors)?this.xaxisForeColors[e]:this.xaxisForeColors,fontSize:this.xaxisFontSize,fontFamily:this.xaxisFontFamily,fontWeight:t.config.xaxis.labels.style.fontWeight,isPlainText:!1,cssClass:"apexcharts-xaxis-label ".concat(t.config.xaxis.labels.style.cssClass)});s.add(x),x.tspan(g),this.addTooltip(x,g),l+=n}return this.inversedYAxisTitleText(a),this.inversedYAxisBorder(a),a}},{key:"inversedYAxisBorder",value:function(e){var t=this.w,i=new X(this.ctx),a=t.config.xaxis.axisBorder;if(a.show){var s=0;t.config.chart.type==="bar"&&t.globals.isXNumeric&&(s-=15);var r=i.drawLine(t.globals.padHorizontal+s+a.offsetX,this.xAxisoffX,t.globals.gridWidth,this.xAxisoffX,a.color,0,a.height);this.elgrid&&this.elgrid.elGridBorders&&t.config.grid.show?this.elgrid.elGridBorders.add(r):e.add(r)}}},{key:"inversedYAxisTitleText",value:function(e){var t=this.w,i=new X(this.ctx);if(t.config.xaxis.title.text!==void 0){var a=i.group({class:"apexcharts-xaxis-title apexcharts-yaxis-title-inversed"}),s=i.drawText({x:t.globals.gridWidth/2+t.config.xaxis.title.offsetX,y:this.xAxisoffX+parseFloat(this.xaxisFontSize)+parseFloat(t.config.xaxis.title.style.fontSize)+t.config.xaxis.title.offsetY+20,text:t.config.xaxis.title.text,textAnchor:"middle",fontSize:t.config.xaxis.title.style.fontSize,fontFamily:t.config.xaxis.title.style.fontFamily,fontWeight:t.config.xaxis.title.style.fontWeight,foreColor:t.config.xaxis.title.style.color,cssClass:"apexcharts-xaxis-title-text ".concat(t.config.xaxis.title.style.cssClass)});a.add(s),e.add(a)}}},{key:"yAxisTitleRotate",value:function(e,t){var i=this.w,a=new X(this.ctx),s=i.globals.dom.baseEl.querySelector(".apexcharts-yaxis[rel='".concat(e,"'] .apexcharts-yaxis-texts-g")),r=s?s.getBoundingClientRect():{width:0,height:0},n=i.globals.dom.baseEl.querySelector(".apexcharts-yaxis[rel='".concat(e,"'] .apexcharts-yaxis-title text")),l=n?n.getBoundingClientRect():{width:0,height:0};if(n){var h=this.xPaddingForYAxisTitle(e,r,l,t);n.setAttribute("x",h.xPos-(t?10:0));var d=a.rotateAroundCenter(n);n.setAttribute("transform","rotate(".concat(t?-1*i.config.yaxis[e].title.rotate:i.config.yaxis[e].title.rotate," ").concat(d.x," ").concat(d.y,")"))}}},{key:"xPaddingForYAxisTitle",value:function(e,t,i,a){var s=this.w,r=0,n=10;return s.config.yaxis[e].title.text===void 0||e<0?{xPos:r,padd:0}:(a?r=t.width+s.config.yaxis[e].title.offsetX+i.width/2+n/2:(r=-1*t.width+s.config.yaxis[e].title.offsetX+n/2+i.width/2,s.globals.isBarHorizontal&&(n=25,r=-1*t.width-s.config.yaxis[e].title.offsetX-n)),{xPos:r,padd:n})}},{key:"setYAxisXPosition",value:function(e,t){var i=this.w,a=0,s=0,r=18,n=1;i.config.yaxis.length>1&&(this.multipleYs=!0),i.config.yaxis.forEach((function(l,h){var d=i.globals.ignoreYAxisIndexes.includes(h)||!l.show||l.floating||e[h].width===0,c=e[h].width+t[h].width;l.opposite?i.globals.isBarHorizontal?(s=i.globals.gridWidth+i.globals.translateX-1,i.globals.translateYAxisX[h]=s-l.labels.offsetX):(s=i.globals.gridWidth+i.globals.translateX+n,d||(n+=c+20),i.globals.translateYAxisX[h]=s-l.labels.offsetX+20):(a=i.globals.translateX-r,d||(r+=c+20),i.globals.translateYAxisX[h]=a+l.labels.offsetX)}))}},{key:"setYAxisTextAlignments",value:function(){var e=this.w;L.listToArray(e.globals.dom.baseEl.getElementsByClassName("apexcharts-yaxis")).forEach((function(t,i){var a=e.config.yaxis[i];if(a&&!a.floating&&a.labels.align!==void 0){var s=e.globals.dom.baseEl.querySelector(".apexcharts-yaxis[rel='".concat(i,"'] .apexcharts-yaxis-texts-g")),r=L.listToArray(e.globals.dom.baseEl.querySelectorAll(".apexcharts-yaxis[rel='".concat(i,"'] .apexcharts-yaxis-label"))),n=s.getBoundingClientRect();r.forEach((function(l){l.setAttribute("text-anchor",a.labels.align)})),a.labels.align!=="left"||a.opposite?a.labels.align==="center"?s.setAttribute("transform","translate(".concat(n.width/2*(a.opposite?1:-1),", 0)")):a.labels.align==="right"&&a.opposite&&s.setAttribute("transform","translate(".concat(n.width,", 0)")):s.setAttribute("transform","translate(-".concat(n.width,", 0)"))}}))}}]),o})(),zs=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w,this.documentEvent=L.bind(this.documentEvent,this)}return O(o,[{key:"addEventListener",value:function(e,t){var i=this.w;i.globals.events.hasOwnProperty(e)?i.globals.events[e].push(t):i.globals.events[e]=[t]}},{key:"removeEventListener",value:function(e,t){var i=this.w;if(i.globals.events.hasOwnProperty(e)){var a=i.globals.events[e].indexOf(t);a!==-1&&i.globals.events[e].splice(a,1)}}},{key:"fireEvent",value:function(e,t){var i=this.w;if(i.globals.events.hasOwnProperty(e)){t&&t.length||(t=[]);for(var a=i.globals.events[e],s=a.length,r=0;r0&&(t=this.w.config.chart.locales.concat(window.Apex.chart.locales));var i=t.filter((function(s){return s.name===e}))[0];if(!i)throw new Error("Wrong locale name provided. Please make sure you set the correct locale name in options");var a=L.extend(Sa,i);this.w.globals.locale=a.options}}]),o})(),Rs=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"drawAxis",value:function(e,t){var i,a,s=this,r=this.w.globals,n=this.w.config,l=new wt(this.ctx,t),h=new Si(this.ctx,t);r.axisCharts&&e!=="radar"&&(r.isBarHorizontal?(a=h.drawYaxisInversed(0),i=l.drawXaxisInversed(0),r.dom.elGraphical.add(i),r.dom.elGraphical.add(a)):(i=l.drawXaxis(),r.dom.elGraphical.add(i),n.yaxis.map((function(d,c){if(r.ignoreYAxisIndexes.indexOf(c)===-1&&(a=h.drawYaxis(c),r.dom.Paper.add(a),s.w.config.grid.position==="back")){var u=r.dom.Paper.children()[1];u.remove(),r.dom.Paper.add(u)}}))))}}]),o})(),Li=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"drawXCrosshairs",value:function(){var e=this.w,t=new X(this.ctx),i=new ue(this.ctx),a=e.config.xaxis.crosshairs.fill.gradient,s=e.config.xaxis.crosshairs.dropShadow,r=e.config.xaxis.crosshairs.fill.type,n=a.colorFrom,l=a.colorTo,h=a.opacityFrom,d=a.opacityTo,c=a.stops,u=s.enabled,g=s.left,p=s.top,f=s.blur,x=s.color,b=s.opacity,m=e.config.xaxis.crosshairs.fill.color;if(e.config.xaxis.crosshairs.show){r==="gradient"&&(m=t.drawGradient("vertical",n,l,h,d,null,c,null));var v=t.drawRect();e.config.xaxis.crosshairs.width===1&&(v=t.drawLine());var k=e.globals.gridHeight;(!L.isNumber(k)||k<0)&&(k=0);var y=e.config.xaxis.crosshairs.width;(!L.isNumber(y)||y<0)&&(y=0),v.attr({class:"apexcharts-xcrosshairs",x:0,y:0,y2:k,width:y,height:k,fill:m,filter:"none","fill-opacity":e.config.xaxis.crosshairs.opacity,stroke:e.config.xaxis.crosshairs.stroke.color,"stroke-width":e.config.xaxis.crosshairs.stroke.width,"stroke-dasharray":e.config.xaxis.crosshairs.stroke.dashArray}),u&&(v=i.dropShadow(v,{left:g,top:p,blur:f,color:x,opacity:b})),e.globals.dom.elGraphical.add(v)}}},{key:"drawYCrosshairs",value:function(){var e=this.w,t=new X(this.ctx),i=e.config.yaxis[0].crosshairs,a=e.globals.barPadForNumericAxis;if(e.config.yaxis[0].crosshairs.show){var s=t.drawLine(-a,0,e.globals.gridWidth+a,0,i.stroke.color,i.stroke.dashArray,i.stroke.width);s.attr({class:"apexcharts-ycrosshairs"}),e.globals.dom.elGraphical.add(s)}var r=t.drawLine(-a,0,e.globals.gridWidth+a,0,i.stroke.color,0,0);r.attr({class:"apexcharts-ycrosshairs-hidden"}),e.globals.dom.elGraphical.add(r)}}]),o})(),Es=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"checkResponsiveConfig",value:function(e){var t=this,i=this.w,a=i.config;if(a.responsive.length!==0){var s=a.responsive.slice();s.sort((function(h,d){return h.breakpoint>d.breakpoint?1:d.breakpoint>h.breakpoint?-1:0})).reverse();var r=new yt({}),n=function(){var h=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},d=s[0].breakpoint,c=window.innerWidth>0?window.innerWidth:screen.width;if(c>d){var u=L.clone(i.globals.initialConfig);u.series=L.clone(i.config.series);var g=he.extendArrayProps(r,u,i);h=L.extend(g,h),h=L.extend(i.config,h),t.overrideResponsiveOptions(h)}else for(var p=0;p0&&typeof e[0]=="function"?(this.isColorFn=!0,i.config.series.map((function(a,s){var r=e[s]||e[0];return typeof r=="function"?r({value:i.globals.axisCharts?i.globals.series[s][0]||0:i.globals.series[s],seriesIndex:s,dataPointIndex:s,w:t.w}):r}))):e:this.predefined()}},{key:"applySeriesColors",value:function(e,t){e.forEach((function(i,a){i&&(t[a]=i)}))}},{key:"getMonochromeColors",value:function(e,t,i){var a=e.color,s=e.shadeIntensity,r=e.shadeTo,n=this.isBarDistributed||this.isHeatmapDistributed?t[0].length*t.length:t.length,l=1/(n/s),h=0;return Array.from({length:n},(function(){var d=r==="dark"?i.shadeColor(-1*h,a):i.shadeColor(h,a);return h+=l,d}))}},{key:"applyColorTypes",value:function(e,t){var i=this,a=this.w;e.forEach((function(s){a.globals[s].colors=a.config[s].colors===void 0?i.isColorFn?a.config.colors:t:a.config[s].colors.slice(),i.pushExtraColors(a.globals[s].colors)}))}},{key:"applyDataLabelsColors",value:function(e){var t=this.w;t.globals.dataLabels.style.colors=t.config.dataLabels.style.colors===void 0?e:t.config.dataLabels.style.colors.slice(),this.pushExtraColors(t.globals.dataLabels.style.colors,50)}},{key:"applyRadarPolygonsColors",value:function(){var e=this.w;e.globals.radarPolygons.fill.colors=e.config.plotOptions.radar.polygons.fill.colors===void 0?[e.config.theme.mode==="dark"?"#424242":"none"]:e.config.plotOptions.radar.polygons.fill.colors.slice(),this.pushExtraColors(e.globals.radarPolygons.fill.colors,20)}},{key:"applyMarkersColors",value:function(e){var t=this.w;t.globals.markers.colors=t.config.markers.colors===void 0?e:t.config.markers.colors.slice(),this.pushExtraColors(t.globals.markers.colors)}},{key:"pushExtraColors",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=this.w,s=t||a.globals.series.length;if(i===null&&(i=this.isBarDistributed||this.isHeatmapDistributed||a.config.chart.type==="heatmap"&&a.config.plotOptions.heatmap&&a.config.plotOptions.heatmap.colorScale.inverse),i&&a.globals.series.length&&(s=a.globals.series[a.globals.maxValsInArrayIndex].length*a.globals.series.length),e.lengthe.globals.svgWidth&&(this.dCtx.lgRect.width=e.globals.svgWidth/1.5),this.dCtx.lgRect}},{key:"getDatalabelsRect",value:function(){var e=this,t=this.w,i=[];t.config.series.forEach((function(l,h){l.data.forEach((function(d,c){var u;u=t.globals.series[h][c],a=t.config.dataLabels.formatter(u,{ctx:e.dCtx.ctx,seriesIndex:h,dataPointIndex:c,w:t}),i.push(a)}))}));var a=L.getLargestStringFromArr(i),s=new X(this.dCtx.ctx),r=t.config.dataLabels.style,n=s.getTextRects(a,parseInt(r.fontSize),r.fontFamily);return{width:1.05*n.width,height:n.height}}},{key:"getLargestStringFromMultiArr",value:function(e,t){var i=e;if(this.w.globals.isMultiLineX){var a=t.map((function(r,n){return Array.isArray(r)?r.length:1})),s=Math.max.apply(Math,ce(a));i=t[a.indexOf(s)]}return i}}]),o})(),Fs=(function(){function o(e){H(this,o),this.w=e.w,this.dCtx=e}return O(o,[{key:"getxAxisLabelsCoords",value:function(){var e,t=this.w,i=t.globals.labels.slice();if(t.config.xaxis.convertedCatToNumeric&&i.length===0&&(i=t.globals.categoryLabels),t.globals.timescaleLabels.length>0){var a=this.getxAxisTimeScaleLabelsCoords();e={width:a.width,height:a.height},t.globals.rotateXLabels=!1}else{this.dCtx.lgWidthForSideLegends=t.config.legend.position!=="left"&&t.config.legend.position!=="right"||t.config.legend.floating?0:this.dCtx.lgRect.width;var s=t.globals.xLabelFormatter,r=L.getLargestStringFromArr(i),n=this.dCtx.dimHelpers.getLargestStringFromMultiArr(r,i);t.globals.isBarHorizontal&&(n=r=t.globals.yAxisScale[0].result.reduce((function(p,f){return p.length>f.length?p:f}),0));var l=new mt(this.dCtx.ctx),h=r;r=l.xLabelFormat(s,r,h,{i:void 0,dateFormatter:new ge(this.dCtx.ctx).formatDate,w:t}),n=l.xLabelFormat(s,n,h,{i:void 0,dateFormatter:new ge(this.dCtx.ctx).formatDate,w:t}),(t.config.xaxis.convertedCatToNumeric&&r===void 0||String(r).trim()==="")&&(n=r="1");var d=new X(this.dCtx.ctx),c=d.getTextRects(r,t.config.xaxis.labels.style.fontSize),u=c;if(r!==n&&(u=d.getTextRects(n,t.config.xaxis.labels.style.fontSize)),(e={width:c.width>=u.width?c.width:u.width,height:c.height>=u.height?c.height:u.height}).width*i.length>t.globals.svgWidth-this.dCtx.lgWidthForSideLegends-this.dCtx.yAxisWidth-this.dCtx.gridPad.left-this.dCtx.gridPad.right&&t.config.xaxis.labels.rotate!==0||t.config.xaxis.labels.rotateAlways){if(!t.globals.isBarHorizontal){t.globals.rotateXLabels=!0;var g=function(p){return d.getTextRects(p,t.config.xaxis.labels.style.fontSize,t.config.xaxis.labels.style.fontFamily,"rotate(".concat(t.config.xaxis.labels.rotate," 0 0)"),!1)};c=g(r),r!==n&&(u=g(n)),e.height=(c.height>u.height?c.height:u.height)/1.5,e.width=c.width>u.width?c.width:u.width}}else t.globals.rotateXLabels=!1}return t.config.xaxis.labels.show||(e={width:0,height:0}),{width:e.width,height:e.height}}},{key:"getxAxisGroupLabelsCoords",value:function(){var e,t=this.w;if(!t.globals.hasXaxisGroups)return{width:0,height:0};var i,a=((e=t.config.xaxis.group.style)===null||e===void 0?void 0:e.fontSize)||t.config.xaxis.labels.style.fontSize,s=t.globals.groups.map((function(c){return c.title})),r=L.getLargestStringFromArr(s),n=this.dCtx.dimHelpers.getLargestStringFromMultiArr(r,s),l=new X(this.dCtx.ctx),h=l.getTextRects(r,a),d=h;return r!==n&&(d=l.getTextRects(n,a)),i={width:h.width>=d.width?h.width:d.width,height:h.height>=d.height?h.height:d.height},t.config.xaxis.labels.show||(i={width:0,height:0}),{width:i.width,height:i.height}}},{key:"getxAxisTitleCoords",value:function(){var e=this.w,t=0,i=0;if(e.config.xaxis.title.text!==void 0){var a=new X(this.dCtx.ctx).getTextRects(e.config.xaxis.title.text,e.config.xaxis.title.style.fontSize);t=a.width,i=a.height}return{width:t,height:i}}},{key:"getxAxisTimeScaleLabelsCoords",value:function(){var e,t=this.w;this.dCtx.timescaleLabels=t.globals.timescaleLabels.slice();var i=this.dCtx.timescaleLabels.map((function(s){return s.value})),a=i.reduce((function(s,r){return s===void 0?(console.error("You have possibly supplied invalid Date format. Please supply a valid JavaScript Date"),0):s.length>r.length?s:r}),0);return 1.05*(e=new X(this.dCtx.ctx).getTextRects(a,t.config.xaxis.labels.style.fontSize)).width*i.length>t.globals.gridWidth&&t.config.xaxis.labels.rotate!==0&&(t.globals.overlappingXLabels=!0),e}},{key:"additionalPaddingXLabels",value:function(e){var t=this,i=this.w,a=i.globals,s=i.config,r=s.xaxis.type,n=e.width;a.skipLastTimelinelabel=!1,a.skipFirstTimelinelabel=!1;var l=i.config.yaxis[0].opposite&&i.globals.isBarHorizontal,h=function(d,c){s.yaxis.length>1&&(function(u){return a.collapsedSeriesIndices.indexOf(u)!==-1})(c)||(function(u){if(t.dCtx.timescaleLabels&&t.dCtx.timescaleLabels.length){var g=t.dCtx.timescaleLabels[0],p=t.dCtx.timescaleLabels[t.dCtx.timescaleLabels.length-1].position+n/1.75-t.dCtx.yAxisWidthRight,f=g.position-n/1.75+t.dCtx.yAxisWidthLeft,x=i.config.legend.position==="right"&&t.dCtx.lgRect.width>0?t.dCtx.lgRect.width:0;p>a.svgWidth-a.translateX-x&&(a.skipLastTimelinelabel=!0),f<-(u.show&&!u.floating||s.chart.type!=="bar"&&s.chart.type!=="candlestick"&&s.chart.type!=="rangeBar"&&s.chart.type!=="boxPlot"?10:n/1.75)&&(a.skipFirstTimelinelabel=!0)}else r==="datetime"?t.dCtx.gridPad.right((w=String(c(y,l)))===null||w===void 0?void 0:w.length)?k:y}),u),p=g=c(g,l);if(g!==void 0&&g.length!==0||(g=h.niceMax),t.globals.isBarHorizontal){a=0;var f=t.globals.labels.slice();g=L.getLargestStringFromArr(f),g=c(g,{seriesIndex:n,dataPointIndex:-1,w:t}),p=e.dCtx.dimHelpers.getLargestStringFromMultiArr(g,f)}var x=new X(e.dCtx.ctx),b="rotate(".concat(r.labels.rotate," 0 0)"),m=x.getTextRects(g,r.labels.style.fontSize,r.labels.style.fontFamily,b,!1),v=m;g!==p&&(v=x.getTextRects(p,r.labels.style.fontSize,r.labels.style.fontFamily,b,!1)),i.push({width:(d>v.width||d>m.width?d:v.width>m.width?v.width:m.width)+a,height:v.height>m.height?v.height:m.height})}else i.push({width:0,height:0})})),i}},{key:"getyAxisTitleCoords",value:function(){var e=this,t=this.w,i=[];return t.config.yaxis.map((function(a,s){if(a.show&&a.title.text!==void 0){var r=new X(e.dCtx.ctx),n="rotate(".concat(a.title.rotate," 0 0)"),l=r.getTextRects(a.title.text,a.title.style.fontSize,a.title.style.fontFamily,n,!1);i.push({width:l.width,height:l.height})}else i.push({width:0,height:0})})),i}},{key:"getTotalYAxisWidth",value:function(){var e=this.w,t=0,i=0,a=0,s=e.globals.yAxisScale.length>1?10:0,r=new Fe(this.dCtx.ctx),n=function(l,h){var d=e.config.yaxis[h].floating,c=0;l.width>0&&!d?(c=l.width+s,(function(u){return e.globals.ignoreYAxisIndexes.indexOf(u)>-1})(h)&&(c=c-l.width-s)):c=d||r.isYAxisHidden(h)?0:5,e.config.yaxis[h].opposite?a+=c:i+=c,t+=c};return e.globals.yLabelsCoords.map((function(l,h){n(l,h)})),e.globals.yTitleCoords.map((function(l,h){n(l,h)})),e.globals.isBarHorizontal&&!e.config.yaxis[0].floating&&(t=e.globals.yLabelsCoords[0].width+e.globals.yTitleCoords[0].width+15),this.dCtx.yAxisWidthLeft=i,this.dCtx.yAxisWidthRight=a,t}}]),o})(),Ns=(function(){function o(e){H(this,o),this.w=e.w,this.dCtx=e}return O(o,[{key:"gridPadForColumnsInNumericAxis",value:function(e){var t=this.w,i=t.config,a=t.globals;if(a.noData||a.collapsedSeries.length+a.ancillaryCollapsedSeries.length===i.series.length)return 0;var s=function(g){return["bar","rangeBar","candlestick","boxPlot"].includes(g)},r=i.chart.type,n=0,l=s(r)?i.series.length:1;a.comboBarCount>0&&(l=a.comboBarCount),a.collapsedSeries.forEach((function(g){s(g.type)&&(l-=1)})),i.chart.stacked&&(l=1);var h=s(r)||a.comboBarCount>0,d=Math.abs(a.initialMaxX-a.initialMinX);if(h&&a.isXNumeric&&!a.isBarHorizontal&&l>0&&d!==0){d<=3&&(d=a.dataPoints);var c=d/e,u=a.minXDiff&&a.minXDiff/c>0?a.minXDiff/c:0;u>e/2&&(u/=2),(n=u*parseInt(i.plotOptions.bar.columnWidth,10)/100)<1&&(n=1),a.barPadForNumericAxis=n}return n}},{key:"gridPadFortitleSubtitle",value:function(){var e=this,t=this.w,i=t.globals,a=this.dCtx.isSparkline||!i.axisCharts?0:10;["title","subtitle"].forEach((function(n){t.config[n].text!==void 0?a+=t.config[n].margin:a+=e.dCtx.isSparkline||!i.axisCharts?0:5})),!t.config.legend.show||t.config.legend.position!=="bottom"||t.config.legend.floating||i.axisCharts||(a+=10);var s=this.dCtx.dimHelpers.getTitleSubtitleCoords("title"),r=this.dCtx.dimHelpers.getTitleSubtitleCoords("subtitle");i.gridHeight-=s.height+r.height+a,i.translateY+=s.height+r.height+a}},{key:"setGridXPosForDualYAxis",value:function(e,t){var i=this.w,a=new Fe(this.dCtx.ctx);i.config.yaxis.forEach((function(s,r){i.globals.ignoreYAxisIndexes.indexOf(r)!==-1||s.floating||a.isYAxisHidden(r)||(s.opposite&&(i.globals.translateX-=t[r].width+e[r].width+parseInt(s.labels.style.fontSize,10)/1.2+12),i.globals.translateX<2&&(i.globals.translateX=2))}))}}]),o})(),Ot=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w,this.lgRect={},this.yAxisWidth=0,this.yAxisWidthLeft=0,this.yAxisWidthRight=0,this.xAxisHeight=0,this.isSparkline=this.w.config.chart.sparkline.enabled,this.dimHelpers=new Os(this),this.dimYAxis=new Ds(this),this.dimXAxis=new Fs(this),this.dimGrid=new Ns(this),this.lgWidthForSideLegends=0,this.gridPad=this.w.config.grid.padding,this.xPadRight=0,this.xPadLeft=0}return O(o,[{key:"plotCoords",value:function(){var e=this,t=this.w,i=t.globals;this.lgRect=this.dimHelpers.getLegendsRect(),this.datalabelsCoords={width:0,height:0};var a=Array.isArray(t.config.stroke.width)?Math.max.apply(Math,ce(t.config.stroke.width)):t.config.stroke.width;this.isSparkline&&((t.config.markers.discrete.length>0||t.config.markers.size>0)&&Object.entries(this.gridPad).forEach((function(r){var n=Ni(r,2),l=n[0],h=n[1];e.gridPad[l]=Math.max(h,e.w.globals.markers.largestSize/1.5)})),this.gridPad.top=Math.max(a/2,this.gridPad.top),this.gridPad.bottom=Math.max(a/2,this.gridPad.bottom)),i.axisCharts?this.setDimensionsForAxisCharts():this.setDimensionsForNonAxisCharts(),this.dimGrid.gridPadFortitleSubtitle(),i.gridHeight=i.gridHeight-this.gridPad.top-this.gridPad.bottom,i.gridWidth=i.gridWidth-this.gridPad.left-this.gridPad.right-this.xPadRight-this.xPadLeft;var s=this.dimGrid.gridPadForColumnsInNumericAxis(i.gridWidth);i.gridWidth=i.gridWidth-2*s,i.translateX=i.translateX+this.gridPad.left+this.xPadLeft+(s>0?s:0),i.translateY=i.translateY+this.gridPad.top}},{key:"setDimensionsForAxisCharts",value:function(){var e=this,t=this.w,i=t.globals,a=this.dimYAxis.getyAxisLabelsCoords(),s=this.dimYAxis.getyAxisTitleCoords();i.isSlopeChart&&(this.datalabelsCoords=this.dimHelpers.getDatalabelsRect()),t.globals.yLabelsCoords=[],t.globals.yTitleCoords=[],t.config.yaxis.map((function(g,p){t.globals.yLabelsCoords.push({width:a[p].width,index:p}),t.globals.yTitleCoords.push({width:s[p].width,index:p})})),this.yAxisWidth=this.dimYAxis.getTotalYAxisWidth();var r=this.dimXAxis.getxAxisLabelsCoords(),n=this.dimXAxis.getxAxisGroupLabelsCoords(),l=this.dimXAxis.getxAxisTitleCoords();this.conditionalChecksForAxisCoords(r,l,n),i.translateXAxisY=t.globals.rotateXLabels?this.xAxisHeight/8:-4,i.translateXAxisX=t.globals.rotateXLabels&&t.globals.isXNumeric&&t.config.xaxis.labels.rotate<=-45?-this.xAxisWidth/4:0,t.globals.isBarHorizontal&&(i.rotateXLabels=!1,i.translateXAxisY=parseInt(t.config.xaxis.labels.style.fontSize,10)/1.5*-1),i.translateXAxisY=i.translateXAxisY+t.config.xaxis.labels.offsetY,i.translateXAxisX=i.translateXAxisX+t.config.xaxis.labels.offsetX;var h=this.yAxisWidth,d=this.xAxisHeight;i.xAxisLabelsHeight=this.xAxisHeight-l.height,i.xAxisGroupLabelsHeight=i.xAxisLabelsHeight-r.height,i.xAxisLabelsWidth=this.xAxisWidth,i.xAxisHeight=this.xAxisHeight;var c=10;(t.config.chart.type==="radar"||this.isSparkline)&&(h=0,d=0),this.isSparkline&&(this.lgRect={height:0,width:0}),(this.isSparkline||t.config.chart.type==="treemap")&&(h=0,d=0,c=0),this.isSparkline||t.config.chart.type==="treemap"||this.dimXAxis.additionalPaddingXLabels(r);var u=function(){i.translateX=h+e.datalabelsCoords.width,i.gridHeight=i.svgHeight-e.lgRect.height-d-(e.isSparkline||t.config.chart.type==="treemap"?0:t.globals.rotateXLabels?10:15),i.gridWidth=i.svgWidth-h-2*e.datalabelsCoords.width};switch(t.config.xaxis.position==="top"&&(c=i.xAxisHeight-t.config.xaxis.axisTicks.height-5),t.config.legend.position){case"bottom":i.translateY=c,u();break;case"top":i.translateY=this.lgRect.height+c,u();break;case"left":i.translateY=c,i.translateX=this.lgRect.width+h+this.datalabelsCoords.width,i.gridHeight=i.svgHeight-d-12,i.gridWidth=i.svgWidth-this.lgRect.width-h-2*this.datalabelsCoords.width;break;case"right":i.translateY=c,i.translateX=h+this.datalabelsCoords.width,i.gridHeight=i.svgHeight-d-12,i.gridWidth=i.svgWidth-this.lgRect.width-h-2*this.datalabelsCoords.width-5;break;default:throw new Error("Legend position not supported")}this.dimGrid.setGridXPosForDualYAxis(s,a),new Si(this.ctx).setYAxisXPosition(a,s)}},{key:"setDimensionsForNonAxisCharts",value:function(){var e=this.w,t=e.globals,i=e.config,a=0;e.config.legend.show&&!e.config.legend.floating&&(a=20);var s=i.chart.type==="pie"||i.chart.type==="polarArea"||i.chart.type==="donut"?"pie":"radialBar",r=i.plotOptions[s].offsetY,n=i.plotOptions[s].offsetX;if(!i.legend.show||i.legend.floating){t.gridHeight=t.svgHeight;var l=t.dom.elWrap.getBoundingClientRect().width;return t.gridWidth=Math.min(l,t.gridHeight),t.translateY=r,void(t.translateX=n+(t.svgWidth-t.gridWidth)/2)}switch(i.legend.position){case"bottom":t.gridHeight=t.svgHeight-this.lgRect.height,t.gridWidth=t.svgWidth,t.translateY=r-10,t.translateX=n+(t.svgWidth-t.gridWidth)/2;break;case"top":t.gridHeight=t.svgHeight-this.lgRect.height,t.gridWidth=t.svgWidth,t.translateY=this.lgRect.height+r+10,t.translateX=n+(t.svgWidth-t.gridWidth)/2;break;case"left":t.gridWidth=t.svgWidth-this.lgRect.width-a,t.gridHeight=i.chart.height!=="auto"?t.svgHeight:t.gridWidth,t.translateY=r,t.translateX=n+this.lgRect.width+a;break;case"right":t.gridWidth=t.svgWidth-this.lgRect.width-a-5,t.gridHeight=i.chart.height!=="auto"?t.svgHeight:t.gridWidth,t.translateY=r,t.translateX=n+10;break;default:throw new Error("Legend position not supported")}}},{key:"conditionalChecksForAxisCoords",value:function(e,t,i){var a=this.w,s=a.globals.hasXaxisGroups?2:1,r=i.height+e.height+t.height,n=a.globals.isMultiLineX?1.2:a.globals.LINE_HEIGHT_RATIO,l=a.globals.rotateXLabels?22:10,h=a.globals.rotateXLabels&&a.config.legend.position==="bottom"?10:0;this.xAxisHeight=r*n+s*l+h,this.xAxisWidth=e.width,this.xAxisHeight-t.height>a.config.xaxis.labels.maxHeight&&(this.xAxisHeight=a.config.xaxis.labels.maxHeight),a.config.xaxis.labels.minHeight&&this.xAxisHeightc&&(this.yAxisWidth=c)}}]),o})(),Ws=(function(){function o(e){H(this,o),this.w=e.w,this.lgCtx=e}return O(o,[{key:"getLegendStyles",value:function(){var e,t,i,a=document.createElement("style");a.setAttribute("type","text/css");var s=((e=this.lgCtx.ctx)===null||e===void 0||(t=e.opts)===null||t===void 0||(i=t.chart)===null||i===void 0?void 0:i.nonce)||this.w.config.chart.nonce;s&&a.setAttribute("nonce",s);var r=document.createTextNode(` + .apexcharts-flip-y { + transform: scaleY(-1) translateY(-100%); + transform-origin: top; + transform-box: fill-box; + } + .apexcharts-flip-x { + transform: scaleX(-1); + transform-origin: center; + transform-box: fill-box; + } + .apexcharts-legend { + display: flex; + overflow: auto; + padding: 0 10px; + } + .apexcharts-legend.apexcharts-legend-group-horizontal { + flex-direction: column; + } + .apexcharts-legend-group { + display: flex; + } + .apexcharts-legend-group-vertical { + flex-direction: column-reverse; + } + .apexcharts-legend.apx-legend-position-bottom, .apexcharts-legend.apx-legend-position-top { + flex-wrap: wrap + } + .apexcharts-legend.apx-legend-position-right, .apexcharts-legend.apx-legend-position-left { + flex-direction: column; + bottom: 0; + } + .apexcharts-legend.apx-legend-position-bottom.apexcharts-align-left, .apexcharts-legend.apx-legend-position-top.apexcharts-align-left, .apexcharts-legend.apx-legend-position-right, .apexcharts-legend.apx-legend-position-left { + justify-content: flex-start; + align-items: flex-start; + } + .apexcharts-legend.apx-legend-position-bottom.apexcharts-align-center, .apexcharts-legend.apx-legend-position-top.apexcharts-align-center { + justify-content: center; + align-items: center; + } + .apexcharts-legend.apx-legend-position-bottom.apexcharts-align-right, .apexcharts-legend.apx-legend-position-top.apexcharts-align-right { + justify-content: flex-end; + align-items: flex-end; + } + .apexcharts-legend-series { + cursor: pointer; + line-height: normal; + display: flex; + align-items: center; + } + .apexcharts-legend-text { + position: relative; + font-size: 14px; + } + .apexcharts-legend-text *, .apexcharts-legend-marker * { + pointer-events: none; + } + .apexcharts-legend-marker { + position: relative; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + margin-right: 1px; + } + + .apexcharts-legend-series.apexcharts-no-click { + cursor: auto; + } + .apexcharts-legend .apexcharts-hidden-zero-series, .apexcharts-legend .apexcharts-hidden-null-series { + display: none !important; + } + .apexcharts-inactive-legend { + opacity: 0.45; + } + + `);return a.appendChild(r),a}},{key:"getLegendDimensions",value:function(){var e=this.w.globals.dom.baseEl.querySelector(".apexcharts-legend").getBoundingClientRect(),t=e.width;return{clwh:e.height,clww:t}}},{key:"appendToForeignObject",value:function(){this.w.globals.dom.elLegendForeign.appendChild(this.getLegendStyles())}},{key:"toggleDataSeries",value:function(e,t){var i=this,a=this.w;if(a.globals.axisCharts||a.config.chart.type==="radialBar"){a.globals.resized=!0;var s=null,r=null;a.globals.risingSeries=[],a.globals.axisCharts?(s=a.globals.dom.baseEl.querySelector(".apexcharts-series[data\\:realIndex='".concat(e,"']")),r=parseInt(s.getAttribute("data:realIndex"),10)):(s=a.globals.dom.baseEl.querySelector(".apexcharts-series[rel='".concat(e+1,"']")),r=parseInt(s.getAttribute("rel"),10)-1),t?[{cs:a.globals.collapsedSeries,csi:a.globals.collapsedSeriesIndices},{cs:a.globals.ancillaryCollapsedSeries,csi:a.globals.ancillaryCollapsedSeriesIndices}].forEach((function(d){i.riseCollapsedSeries(d.cs,d.csi,r)})):this.hideSeries({seriesEl:s,realIndex:r})}else{var n=a.globals.dom.Paper.findOne(" .apexcharts-series[rel='".concat(e+1,"'] path")),l=a.config.chart.type;if(l==="pie"||l==="polarArea"||l==="donut"){var h=a.config.plotOptions.pie.donut.labels;new X(this.lgCtx.ctx).pathMouseDown(n,null),this.lgCtx.ctx.pie.printDataLabelsInner(n.node,h)}n.fire("click")}}},{key:"getSeriesAfterCollapsing",value:function(e){var t=e.realIndex,i=this.w,a=i.globals,s=L.clone(i.config.series);if(a.axisCharts){var r=i.config.yaxis[a.seriesYAxisReverseMap[t]],n={index:t,data:s[t].data.slice(),type:s[t].type||i.config.chart.type};if(r&&r.show&&r.showAlways)a.ancillaryCollapsedSeriesIndices.indexOf(t)<0&&(a.ancillaryCollapsedSeries.push(n),a.ancillaryCollapsedSeriesIndices.push(t));else if(a.collapsedSeriesIndices.indexOf(t)<0){a.collapsedSeries.push(n),a.collapsedSeriesIndices.push(t);var l=a.risingSeries.indexOf(t);a.risingSeries.splice(l,1)}}else a.collapsedSeries.push({index:t,data:s[t]}),a.collapsedSeriesIndices.push(t);return a.allSeriesCollapsed=a.collapsedSeries.length+a.ancillaryCollapsedSeries.length===i.config.series.length,this._getSeriesBasedOnCollapsedState(s)}},{key:"hideSeries",value:function(e){for(var t=e.seriesEl,i=e.realIndex,a=this.w,s=this.getSeriesAfterCollapsing({realIndex:i}),r=t.childNodes,n=0;n0){for(var r=0;r1;if(this.legendHelpers.appendToForeignObject(),(a||!t.axisCharts)&&i.legend.show){for(;t.dom.elLegendWrap.firstChild;)t.dom.elLegendWrap.removeChild(t.dom.elLegendWrap.firstChild);this.drawLegends(),i.legend.position==="bottom"||i.legend.position==="top"?this.legendAlignHorizontal():i.legend.position!=="right"&&i.legend.position!=="left"||this.legendAlignVertical()}}},{key:"createLegendMarker",value:function(e){var t=e.i,i=e.fillcolor,a=this.w,s=document.createElement("span");s.classList.add("apexcharts-legend-marker");var r=a.config.legend.markers.shape||a.config.markers.shape,n=r;Array.isArray(r)&&(n=r[t]);var l=Array.isArray(a.config.legend.markers.size)?parseFloat(a.config.legend.markers.size[t]):parseFloat(a.config.legend.markers.size),h=Array.isArray(a.config.legend.markers.offsetX)?parseFloat(a.config.legend.markers.offsetX[t]):parseFloat(a.config.legend.markers.offsetX),d=Array.isArray(a.config.legend.markers.offsetY)?parseFloat(a.config.legend.markers.offsetY[t]):parseFloat(a.config.legend.markers.offsetY),c=Array.isArray(a.config.legend.markers.strokeWidth)?parseFloat(a.config.legend.markers.strokeWidth[t]):parseFloat(a.config.legend.markers.strokeWidth),u=s.style;if(u.height=2*(l+c)+"px",u.width=2*(l+c)+"px",u.left=h+"px",u.top=d+"px",a.config.legend.markers.customHTML)u.background="transparent",u.color=i[t],Array.isArray(a.config.legend.markers.customHTML)?a.config.legend.markers.customHTML[t]&&(s.innerHTML=a.config.legend.markers.customHTML[t]()):s.innerHTML=a.config.legend.markers.customHTML();else{var g=new st(this.ctx).getMarkerConfig({cssClass:"apexcharts-legend-marker apexcharts-marker apexcharts-marker-".concat(n),seriesIndex:t,strokeWidth:c,size:l}),p=window.SVG().addTo(s).size("100%","100%"),f=new X(this.ctx).drawMarker(0,0,R(R({},g),{},{pointFillColor:Array.isArray(i)?i[t]:g.pointFillColor,shape:n}));a.globals.dom.Paper.find(".apexcharts-legend-marker.apexcharts-marker").forEach((function(x){x.node.classList.contains("apexcharts-marker-triangle")?x.node.style.transform="translate(50%, 45%)":x.node.style.transform="translate(50%, 50%)"})),p.add(f)}return s}},{key:"drawLegends",value:function(){var e=this,t=this,i=this.w,a=i.config.legend.fontFamily,s=i.globals.seriesNames,r=i.config.legend.markers.fillColors?i.config.legend.markers.fillColors.slice():i.globals.colors.slice();if(i.config.chart.type==="heatmap"){var n=i.config.plotOptions.heatmap.colorScale.ranges;s=n.map((function(g){return g.name?g.name:g.from+" - "+g.to})),r=n.map((function(g){return g.color}))}else this.isBarsDistributed&&(s=i.globals.labels.slice());i.config.legend.customLegendItems.length&&(s=i.config.legend.customLegendItems);var l=i.globals.legendFormatter,h=i.config.legend.inverseOrder,d=[];i.globals.seriesGroups.length>1&&i.config.legend.clusterGroupedSeries&&i.globals.seriesGroups.forEach((function(g,p){d[p]=document.createElement("div"),d[p].classList.add("apexcharts-legend-group","apexcharts-legend-group-".concat(p)),i.config.legend.clusterGroupedSeriesOrientation==="horizontal"?i.globals.dom.elLegendWrap.classList.add("apexcharts-legend-group-horizontal"):d[p].classList.add("apexcharts-legend-group-vertical")}));for(var c=function(g){var p,f=l(s[g],{seriesIndex:g,w:i}),x=!1,b=!1;if(i.globals.collapsedSeries.length>0)for(var m=0;m0)for(var v=0;v=0:u<=s.length-1;h?u--:u++)c(u);i.globals.dom.elWrap.addEventListener("click",t.onLegendClick,!0),i.config.legend.onItemHover.highlightDataSeries&&i.config.legend.customLegendItems.length===0&&(i.globals.dom.elWrap.addEventListener("mousemove",t.onLegendHovered,!0),i.globals.dom.elWrap.addEventListener("mouseout",t.onLegendHovered,!0))}},{key:"setLegendWrapXY",value:function(e,t){var i=this.w,a=i.globals.dom.elLegendWrap,s=a.clientHeight,r=0,n=0;if(i.config.legend.position==="bottom")n=i.globals.svgHeight-Math.min(s,i.globals.svgHeight/2)-5;else if(i.config.legend.position==="top"){var l=new Ot(this.ctx),h=l.dimHelpers.getTitleSubtitleCoords("title").height,d=l.dimHelpers.getTitleSubtitleCoords("subtitle").height;n=(h>0?h-10:0)+(d>0?d-10:0)}a.style.position="absolute",r=r+e+i.config.legend.offsetX,n=n+t+i.config.legend.offsetY,a.style.left=r+"px",a.style.top=n+"px",i.config.legend.position==="right"&&(a.style.left="auto",a.style.right=25+i.config.legend.offsetX+"px"),["width","height"].forEach((function(c){a.style[c]&&(a.style[c]=parseInt(i.config.legend[c],10)+"px")}))}},{key:"legendAlignHorizontal",value:function(){var e=this.w;e.globals.dom.elLegendWrap.style.right=0;var t=new Ot(this.ctx),i=t.dimHelpers.getTitleSubtitleCoords("title"),a=t.dimHelpers.getTitleSubtitleCoords("subtitle"),s=0;e.config.legend.position==="top"&&(s=i.height+a.height+e.config.title.margin+e.config.subtitle.margin-10),this.setLegendWrapXY(20,s)}},{key:"legendAlignVertical",value:function(){var e=this.w,t=this.legendHelpers.getLegendDimensions(),i=0;e.config.legend.position==="left"&&(i=20),e.config.legend.position==="right"&&(i=e.globals.svgWidth-t.clww-10),this.setLegendWrapXY(i,20)}},{key:"onLegendHovered",value:function(e){var t=this.w,i=e.target.classList.contains("apexcharts-legend-series")||e.target.classList.contains("apexcharts-legend-text")||e.target.classList.contains("apexcharts-legend-marker");if(t.config.chart.type==="heatmap"||this.isBarsDistributed){if(i){var a=parseInt(e.target.getAttribute("rel"),10)-1;this.ctx.events.fireEvent("legendHover",[this.ctx,a,this.w]),new Le(this.ctx).highlightRangeInSeries(e,e.target)}}else!e.target.classList.contains("apexcharts-inactive-legend")&&i&&new Le(this.ctx).toggleSeriesOnHover(e,e.target)}},{key:"onLegendClick",value:function(e){var t=this.w;if(!t.config.legend.customLegendItems.length&&(e.target.classList.contains("apexcharts-legend-series")||e.target.classList.contains("apexcharts-legend-text")||e.target.classList.contains("apexcharts-legend-marker"))){var i=parseInt(e.target.getAttribute("rel"),10)-1,a=e.target.getAttribute("data:collapsed")==="true",s=this.w.config.chart.events.legendClick;typeof s=="function"&&s(this.ctx,i,this.w),this.ctx.events.fireEvent("legendClick",[this.ctx,i,this.w]);var r=this.w.config.legend.markers.onClick;typeof r=="function"&&e.target.classList.contains("apexcharts-legend-marker")&&(r(this.ctx,i,this.w),this.ctx.events.fireEvent("legendMarkerClick",[this.ctx,i,this.w])),t.config.chart.type!=="treemap"&&t.config.chart.type!=="heatmap"&&!this.isBarsDistributed&&t.config.legend.onItemClick.toggleDataSeries&&this.legendHelpers.toggleDataSeries(i,a)}}}]),o})(),za=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w;var t=this.w;this.ev=this.w.config.chart.events,this.selectedClass="apexcharts-selected",this.localeValues=this.w.globals.locale.toolbar,this.minX=t.globals.minX,this.maxX=t.globals.maxX}return O(o,[{key:"createToolbar",value:function(){var e=this,t=this.w,i=function(){return document.createElement("div")},a=i();if(a.setAttribute("class","apexcharts-toolbar"),a.style.top=t.config.chart.toolbar.offsetY+"px",a.style.right=3-t.config.chart.toolbar.offsetX+"px",t.globals.dom.elWrap.appendChild(a),this.elZoom=i(),this.elZoomIn=i(),this.elZoomOut=i(),this.elPan=i(),this.elSelection=i(),this.elZoomReset=i(),this.elMenuIcon=i(),this.elMenu=i(),this.elCustomIcons=[],this.t=t.config.chart.toolbar.tools,Array.isArray(this.t.customIcons))for(var s=0;s + + + +`),n("zoomOut",this.elZoomOut,` + + + +`);var l=function(c){e.t[c]&&t.config.chart[c].enabled&&r.push({el:c==="zoom"?e.elZoom:e.elSelection,icon:typeof e.t[c]=="string"?e.t[c]:c==="zoom"?` + + + +`:` + + +`,title:e.localeValues[c==="zoom"?"selectionZoom":"selection"],class:t.globals.isTouchDevice?"apexcharts-element-hidden":"apexcharts-".concat(c,"-icon")})};l("zoom"),l("selection"),this.t.pan&&t.config.chart.zoom.enabled&&r.push({el:this.elPan,icon:typeof this.t.pan=="string"?this.t.pan:` + + + + + + + +`,title:this.localeValues.pan,class:t.globals.isTouchDevice?"apexcharts-element-hidden":"apexcharts-pan-icon"}),n("reset",this.elZoomReset,` + + +`),this.t.download&&r.push({el:this.elMenuIcon,icon:typeof this.t.download=="string"?this.t.download:'',title:this.localeValues.menu,class:"apexcharts-menu-icon"});for(var h=0;hthis.wheelDelay&&(this.executeMouseWheelZoom(i),s.globals.lastWheelExecution=r),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((function(){r-s.globals.lastWheelExecution>a.wheelDelay&&(a.executeMouseWheelZoom(i),s.globals.lastWheelExecution=r)}),this.debounceDelay)}},{key:"executeMouseWheelZoom",value:function(i){var a,s=this.w;this.minX=s.globals.isRangeBar?s.globals.minY:s.globals.minX,this.maxX=s.globals.isRangeBar?s.globals.maxY:s.globals.maxX;var r=(a=this.gridRect)===null||a===void 0?void 0:a.getBoundingClientRect();if(r){var n,l,h,d=(i.clientX-r.left)/r.width,c=this.minX,u=this.maxX,g=u-c;if(i.deltaY<0){var p=c+d*g;l=p-(n=.5*g)/2,h=p+n/2}else l=c-(n=1.5*g)/2,h=u+n/2;if(!s.globals.isRangeBar){l=Math.max(l,s.globals.initialMinX),h=Math.min(h,s.globals.initialMaxX);var f=.01*(s.globals.initialMaxX-s.globals.initialMinX);if(h-l0&&s.height>0&&(this.selectionRect.select(!1).resize(!1),this.selectionRect.select({createRot:function(){},updateRot:function(){},createHandle:function(r,n,l,h,d){return d==="l"||d==="r"?r.circle(8).css({"stroke-width":1,stroke:"#333",fill:"#fff"}):r.circle(0)},updateHandle:function(r,n){return r.center(n[0],n[1])}}).resize().on("resize",(function(){var r=a.globals.zoomEnabled?a.config.chart.zoom.type:a.config.chart.selection.type;i.handleMouseUp({zoomtype:r,isResized:!0})})))}}},{key:"preselectedSelection",value:function(){var i=this.w,a=this.xyRatios;if(!i.globals.zoomEnabled){if(i.globals.selection!==void 0&&i.globals.selection!==null)this.drawSelectionRect(R(R({},i.globals.selection),{},{translateX:i.globals.translateX,translateY:i.globals.translateY}));else if(i.config.chart.selection.xaxis.min!==void 0&&i.config.chart.selection.xaxis.max!==void 0){var s=(i.config.chart.selection.xaxis.min-i.globals.minX)/a.xRatio,r=i.globals.gridWidth-(i.globals.maxX-i.config.chart.selection.xaxis.max)/a.xRatio-s;i.globals.isRangeBar&&(s=(i.config.chart.selection.xaxis.min-i.globals.yAxisScale[0].niceMin)/a.invertedYRatio,r=(i.config.chart.selection.xaxis.max-i.config.chart.selection.xaxis.min)/a.invertedYRatio);var n={x:s,y:0,width:r,height:i.globals.gridHeight,translateX:i.globals.translateX,translateY:i.globals.translateY,selectionEnabled:!0};this.drawSelectionRect(n),this.makeSelectionRectDraggable(),typeof i.config.chart.events.selection=="function"&&i.config.chart.events.selection(this.ctx,{xaxis:{min:i.config.chart.selection.xaxis.min,max:i.config.chart.selection.xaxis.max},yaxis:{}})}}}},{key:"drawSelectionRect",value:function(i){var a=i.x,s=i.y,r=i.width,n=i.height,l=i.translateX,h=l===void 0?0:l,d=i.translateY,c=d===void 0?0:d,u=this.w,g=this.zoomRect,p=this.selectionRect;if(this.dragged||u.globals.selection!==null){var f={transform:"translate("+h+", "+c+")"};u.globals.zoomEnabled&&this.dragged&&(r<0&&(r=1),g.attr({x:a,y:s,width:r,height:n,fill:u.config.chart.zoom.zoomedArea.fill.color,"fill-opacity":u.config.chart.zoom.zoomedArea.fill.opacity,stroke:u.config.chart.zoom.zoomedArea.stroke.color,"stroke-width":u.config.chart.zoom.zoomedArea.stroke.width,"stroke-opacity":u.config.chart.zoom.zoomedArea.stroke.opacity}),X.setAttrs(g.node,f)),u.globals.selectionEnabled&&(p.attr({x:a,y:s,width:r>0?r:0,height:n>0?n:0,fill:u.config.chart.selection.fill.color,"fill-opacity":u.config.chart.selection.fill.opacity,stroke:u.config.chart.selection.stroke.color,"stroke-width":u.config.chart.selection.stroke.width,"stroke-dasharray":u.config.chart.selection.stroke.dashArray,"stroke-opacity":u.config.chart.selection.stroke.opacity}),X.setAttrs(p.node,f))}}},{key:"hideSelectionRect",value:function(i){i&&i.attr({x:0,y:0,width:0,height:0})}},{key:"selectionDrawing",value:function(i){var a=i.context,s=i.zoomtype,r=this.w,n=a,l=this.gridRect.getBoundingClientRect(),h=n.startX-1,d=n.startY,c=!1,u=!1,g=n.clientX-l.left-r.globals.barPadForNumericAxis,p=n.clientY-l.top,f=g-h,x=p-d,b={translateX:r.globals.translateX,translateY:r.globals.translateY};return Math.abs(f+h)>r.globals.gridWidth?f=r.globals.gridWidth-h:g<0&&(f=h),h>g&&(c=!0,f=Math.abs(f)),d>p&&(u=!0,x=Math.abs(x)),b=R(R({},b=s==="x"?{x:c?h-f:h,y:0,width:f,height:r.globals.gridHeight}:s==="y"?{x:0,y:u?d-x:d,width:r.globals.gridWidth,height:x}:{x:c?h-f:h,y:u?d-x:d,width:f,height:x}),{},{translateX:r.globals.translateX,translateY:r.globals.translateY}),n.drawSelectionRect(b),n.selectionDragging("resizing"),b}},{key:"selectionDragging",value:function(i,a){var s=this,r=this.w;if(a){a.preventDefault();var n=a.detail,l=n.handler,h=n.box,d=h.x,c=h.y;dthis.constraints.x2&&(d=this.constraints.x2-h.w),h.y2>this.constraints.y2&&(c=this.constraints.y2-h.h),l.move(d,c);var u=this.xyRatios,g=this.selectionRect,p=0;i==="resizing"&&(p=30);var f=function(b){return parseFloat(g.node.getAttribute(b))},x={x:f("x"),y:f("y"),width:f("width"),height:f("height")};r.globals.selection=x,typeof r.config.chart.events.selection=="function"&&r.globals.selectionEnabled&&(clearTimeout(this.w.globals.selectionResizeTimer),this.w.globals.selectionResizeTimer=window.setTimeout((function(){var b,m,v,k,y=s.gridRect.getBoundingClientRect(),C=g.node.getBoundingClientRect();r.globals.isRangeBar?(b=r.globals.yAxisScale[0].niceMin+(C.left-y.left)*u.invertedYRatio,m=r.globals.yAxisScale[0].niceMin+(C.right-y.left)*u.invertedYRatio,v=0,k=1):(b=r.globals.xAxisScale.niceMin+(C.left-y.left)*u.xRatio,m=r.globals.xAxisScale.niceMin+(C.right-y.left)*u.xRatio,v=r.globals.yAxisScale[0].niceMin+(y.bottom-C.bottom)*u.yRatio[0],k=r.globals.yAxisScale[0].niceMax-(C.top-y.top)*u.yRatio[0]);var w={xaxis:{min:b,max:m},yaxis:{min:v,max:k}};r.config.chart.events.selection(s.ctx,w),r.config.chart.brush.enabled&&r.config.chart.events.brushScrolled!==void 0&&r.config.chart.events.brushScrolled(s.ctx,w)}),p))}}},{key:"selectionDrawn",value:function(i){var a=i.context,s=i.zoomtype,r=this.w,n=a,l=this.xyRatios,h=this.ctx.toolbar;if(n.startX>n.endX){var d=n.startX;n.startX=n.endX,n.endX=d}if(n.startY>n.endY){var c=n.startY;n.startY=n.endY,n.endY=c}var u=void 0,g=void 0;r.globals.isRangeBar?(u=r.globals.yAxisScale[0].niceMin+n.startX*l.invertedYRatio,g=r.globals.yAxisScale[0].niceMin+n.endX*l.invertedYRatio):(u=r.globals.xAxisScale.niceMin+n.startX*l.xRatio,g=r.globals.xAxisScale.niceMin+n.endX*l.xRatio);var p=[],f=[];if(r.config.yaxis.forEach((function(C,w){var A=r.globals.seriesYAxisMap[w][0];p.push(r.globals.yAxisScale[w].niceMax-l.yRatio[A]*n.startY),f.push(r.globals.yAxisScale[w].niceMax-l.yRatio[A]*n.endY)})),n.dragged&&(n.dragX>10||n.dragY>10)&&u!==g){if(r.globals.zoomEnabled){var x=L.clone(r.globals.initialConfig.yaxis),b=L.clone(r.globals.initialConfig.xaxis);if(r.globals.zoomed=!0,r.config.xaxis.convertedCatToNumeric&&(u=Math.floor(u),g=Math.floor(g),u<1&&(u=1,g=r.globals.dataPoints),g-u<2&&(g=u+1)),s!=="xy"&&s!=="x"||(b={min:u,max:g}),s!=="xy"&&s!=="y"||x.forEach((function(C,w){x[w].min=f[w],x[w].max=p[w]})),h){var m=h.getBeforeZoomRange(b,x);m&&(b=m.xaxis?m.xaxis:b,x=m.yaxis?m.yaxis:x)}var v={xaxis:b};r.config.chart.group||(v.yaxis=x),n.ctx.updateHelpers._updateOptions(v,!1,n.w.config.chart.animations.dynamicAnimation.enabled),typeof r.config.chart.events.zoomed=="function"&&h.zoomCallback(b,x)}else if(r.globals.selectionEnabled){var k,y=null;k={min:u,max:g},s!=="xy"&&s!=="y"||(y=L.clone(r.config.yaxis)).forEach((function(C,w){y[w].min=f[w],y[w].max=p[w]})),r.globals.selection=n.selection,typeof r.config.chart.events.selection=="function"&&r.config.chart.events.selection(n.ctx,{xaxis:k,yaxis:y})}}}},{key:"panDragging",value:function(i){var a=i.context,s=this.w,r=a;if(s.globals.lastClientPosition.x!==void 0){var n=s.globals.lastClientPosition.x-r.clientX,l=s.globals.lastClientPosition.y-r.clientY;Math.abs(n)>Math.abs(l)&&n>0?this.moveDirection="left":Math.abs(n)>Math.abs(l)&&n<0?this.moveDirection="right":Math.abs(l)>Math.abs(n)&&l>0?this.moveDirection="up":Math.abs(l)>Math.abs(n)&&l<0&&(this.moveDirection="down")}s.globals.lastClientPosition={x:r.clientX,y:r.clientY};var h=s.globals.isRangeBar?s.globals.minY:s.globals.minX,d=s.globals.isRangeBar?s.globals.maxY:s.globals.maxX;s.config.xaxis.convertedCatToNumeric||r.panScrolled(h,d)}},{key:"delayedPanScrolled",value:function(){var i=this.w,a=i.globals.minX,s=i.globals.maxX,r=(i.globals.maxX-i.globals.minX)/2;this.moveDirection==="left"?(a=i.globals.minX+r,s=i.globals.maxX+r):this.moveDirection==="right"&&(a=i.globals.minX-r,s=i.globals.maxX-r),a=Math.floor(a),s=Math.floor(s),this.updateScrolledChart({xaxis:{min:a,max:s}},a,s)}},{key:"panScrolled",value:function(i,a){var s=this.w,r=this.xyRatios,n=L.clone(s.globals.initialConfig.yaxis),l=r.xRatio,h=s.globals.minX,d=s.globals.maxX;s.globals.isRangeBar&&(l=r.invertedYRatio,h=s.globals.minY,d=s.globals.maxY),this.moveDirection==="left"?(i=h+s.globals.gridWidth/15*l,a=d+s.globals.gridWidth/15*l):this.moveDirection==="right"&&(i=h-s.globals.gridWidth/15*l,a=d-s.globals.gridWidth/15*l),s.globals.isRangeBar||(is.globals.initialMaxX)&&(i=h,a=d);var c={xaxis:{min:i,max:a}};s.config.chart.group||(c.yaxis=n),this.updateScrolledChart(c,i,a)}},{key:"updateScrolledChart",value:function(i,a,s){var r=this.w;this.ctx.updateHelpers._updateOptions(i,!1,!1),typeof r.config.chart.events.scrolled=="function"&&r.config.chart.events.scrolled(this.ctx,{xaxis:{min:a,max:s}})}}]),t})(),Xa=(function(){function o(e){H(this,o),this.w=e.w,this.ttCtx=e,this.ctx=e.ctx}return O(o,[{key:"getNearestValues",value:function(e){var t=e.hoverArea,i=e.elGrid,a=e.clientX,s=e.clientY,r=this.w,n=i.getBoundingClientRect(),l=n.width,h=n.height,d=l/(r.globals.dataPoints-1),c=h/r.globals.dataPoints,u=this.hasBars();!r.globals.comboCharts&&!u||r.config.xaxis.convertedCatToNumeric||(d=l/r.globals.dataPoints);var g=a-n.left-r.globals.barPadForNumericAxis,p=s-n.top;g<0||p<0||g>l||p>h?(t.classList.remove("hovering-zoom"),t.classList.remove("hovering-pan")):r.globals.zoomEnabled?(t.classList.remove("hovering-pan"),t.classList.add("hovering-zoom")):r.globals.panEnabled&&(t.classList.remove("hovering-zoom"),t.classList.add("hovering-pan"));var f=Math.round(g/d),x=Math.floor(p/c);u&&!r.config.xaxis.convertedCatToNumeric&&(f=Math.ceil(g/d),f-=1);var b=null,m=null,v=r.globals.seriesXvalues.map((function(A){return A.filter((function(S){return L.isNumber(S)}))})),k=r.globals.seriesYvalues.map((function(A){return A.filter((function(S){return L.isNumber(S)}))}));if(r.globals.isXNumeric){var y=this.ttCtx.getElGrid().getBoundingClientRect(),C=g*(y.width/l),w=p*(y.height/h);b=(m=this.closestInMultiArray(C,w,v,k)).index,f=m.j,b!==null&&(v=r.globals.seriesXvalues[b],f=(m=this.closestInArray(C,v)).index)}return r.globals.capturedSeriesIndex=b===null?-1:b,(!f||f<1)&&(f=0),r.globals.isBarHorizontal?r.globals.capturedDataPointIndex=x:r.globals.capturedDataPointIndex=f,{capturedSeries:b,j:r.globals.isBarHorizontal?x:f,hoverX:g,hoverY:p}}},{key:"closestInMultiArray",value:function(e,t,i,a){var s=this.w,r=0,n=null,l=-1;s.globals.series.length>1?r=this.getFirstActiveXArray(i):n=0;var h=i[r][0],d=Math.abs(e-h);if(i.forEach((function(g){g.forEach((function(p,f){var x=Math.abs(e-p);x<=d&&(d=x,l=f)}))})),l!==-1){var c=a[r][l],u=Math.abs(t-c);n=r,a.forEach((function(g,p){var f=Math.abs(t-g[l]);f<=u&&(u=f,n=p)}))}return{index:n,j:l}}},{key:"getFirstActiveXArray",value:function(e){for(var t=this.w,i=0,a=e.map((function(r,n){return r.length>0?n:-1})),s=0;s0)for(var a=0;a *")):this.w.globals.dom.baseEl.querySelectorAll(".apexcharts-series-markers-wrap > *")}},{key:"getAllMarkers",value:function(){var e=this.w.globals.dom.baseEl.querySelectorAll(".apexcharts-series-markers-wrap");(e=ce(e)).sort((function(i,a){var s=Number(i.getAttribute("data:realIndex")),r=Number(a.getAttribute("data:realIndex"));return rs?-1:0}));var t=[];return e.forEach((function(i){t.push(i.querySelector(".apexcharts-marker"))})),t}},{key:"hasMarkers",value:function(e){return this.getElMarkers(e).length>0}},{key:"getPathFromPoint",value:function(e,t){var i=Number(e.getAttribute("cx")),a=Number(e.getAttribute("cy")),s=e.getAttribute("shape");return new X(this.ctx).getMarkerPath(i,a,s,t)}},{key:"getElBars",value:function(){return this.w.globals.dom.baseEl.querySelectorAll(".apexcharts-bar-series, .apexcharts-candlestick-series, .apexcharts-boxPlot-series, .apexcharts-rangebar-series")}},{key:"hasBars",value:function(){return this.getElBars().length>0}},{key:"getHoverMarkerSize",value:function(e){var t=this.w,i=t.config.markers.hover.size;return i===void 0&&(i=t.globals.markers.size[e]+t.config.markers.hover.sizeOffset),i}},{key:"toggleAllTooltipSeriesGroups",value:function(e){var t=this.w,i=this.ttCtx;i.allTooltipSeriesGroups.length===0&&(i.allTooltipSeriesGroups=t.globals.dom.baseEl.querySelectorAll(".apexcharts-tooltip-series-group"));for(var a=i.allTooltipSeriesGroups,s=0;s ').concat(M.attrs.name,""),S+="
".concat(M.val,"
")})),v.innerHTML=A+"",k.innerHTML=S+""};n?h.globals.seriesGoals[t][i]&&Array.isArray(h.globals.seriesGoals[t][i])?y():(v.innerHTML="",k.innerHTML=""):y()}else v.innerHTML="",k.innerHTML="";if(f!==null&&(a[t].querySelector(".apexcharts-tooltip-text-z-label").innerHTML=h.config.tooltip.z.title,a[t].querySelector(".apexcharts-tooltip-text-z-value").innerHTML=f!==void 0?f:""),n&&x[0]){if(h.config.tooltip.hideEmptySeries){var C=a[t].querySelector(".apexcharts-tooltip-marker"),w=a[t].querySelector(".apexcharts-tooltip-text");parseFloat(c)==0?(C.style.display="none",w.style.display="none"):(C.style.display="block",w.style.display="block")}c==null||h.globals.ancillaryCollapsedSeriesIndices.indexOf(t)>-1||h.globals.collapsedSeriesIndices.indexOf(t)>-1||Array.isArray(d.tConfig.enabledOnSeries)&&d.tConfig.enabledOnSeries.indexOf(t)===-1?x[0].parentNode.style.display="none":x[0].parentNode.style.display=h.config.tooltip.items.display}else Array.isArray(d.tConfig.enabledOnSeries)&&d.tConfig.enabledOnSeries.indexOf(t)===-1&&(x[0].parentNode.style.display="none")}},{key:"toggleActiveInactiveSeries",value:function(e,t){var i=this.w;if(e)this.tooltipUtil.toggleAllTooltipSeriesGroups("enable");else{this.tooltipUtil.toggleAllTooltipSeriesGroups("disable");var a=i.globals.dom.baseEl.querySelector(".apexcharts-tooltip-series-group-".concat(t));a&&(a.classList.add("apexcharts-active"),a.style.display=i.config.tooltip.items.display)}}},{key:"getValuesToPrint",value:function(e){var t=e.i,i=e.j,a=this.w,s=this.ctx.series.filteredSeriesX(),r="",n="",l=null,h=null,d={series:a.globals.series,seriesIndex:t,dataPointIndex:i,w:a},c=a.globals.ttZFormatter;i===null?h=a.globals.series[t]:a.globals.isXNumeric&&a.config.chart.type!=="treemap"?(r=s[t][i],s[t].length===0&&(r=s[this.tooltipUtil.getFirstActiveXArray(s)][i])):r=new Ai(this.ctx).isFormatXY()?a.config.series[t].data[i]!==void 0?a.config.series[t].data[i].x:"":a.globals.labels[i]!==void 0?a.globals.labels[i]:"";var u=r;return a.globals.isXNumeric&&a.config.xaxis.type==="datetime"?r=new mt(this.ctx).xLabelFormat(a.globals.ttKeyFormatter,u,u,{i:void 0,dateFormatter:new ge(this.ctx).formatDate,w:this.w}):r=a.globals.isBarHorizontal?a.globals.yLabelFormatters[0](u,d):a.globals.xLabelFormatter(u,d),a.config.tooltip.x.formatter!==void 0&&(r=a.globals.ttKeyFormatter(u,d)),a.globals.seriesZ.length>0&&a.globals.seriesZ[t].length>0&&(l=c(a.globals.seriesZ[t][i],a)),n=typeof a.config.xaxis.tooltip.formatter=="function"?a.globals.xaxisTooltipFormatter(u,d):r,{val:Array.isArray(h)?h.join(" "):h,xVal:Array.isArray(r)?r.join(" "):r,xAxisTTVal:Array.isArray(n)?n.join(" "):n,zVal:l}}},{key:"handleCustomTooltip",value:function(e){var t=e.i,i=e.j,a=e.y1,s=e.y2,r=e.w,n=this.ttCtx.getElTooltip(),l=r.config.tooltip.custom;Array.isArray(l)&&l[t]&&(l=l[t]),n.innerHTML=l({ctx:this.ctx,series:r.globals.series,seriesIndex:t,dataPointIndex:i,y1:a,y2:s,w:r})}}]),o})(),Ra=(function(){function o(e){H(this,o),this.ttCtx=e,this.ctx=e.ctx,this.w=e.w}return O(o,[{key:"moveXCrosshairs",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,i=this.ttCtx,a=this.w,s=i.getElXCrosshairs(),r=e-i.xcrosshairsWidth/2,n=a.globals.labels.slice().length;if(t!==null&&(r=a.globals.gridWidth/n*t),s===null||a.globals.isBarHorizontal||(s.setAttribute("x",r),s.setAttribute("x1",r),s.setAttribute("x2",r),s.setAttribute("y2",a.globals.gridHeight),s.classList.add("apexcharts-active")),r<0&&(r=0),r>a.globals.gridWidth&&(r=a.globals.gridWidth),i.isXAxisTooltipEnabled){var l=r;a.config.xaxis.crosshairs.width!=="tickWidth"&&a.config.xaxis.crosshairs.width!=="barWidth"||(l=r+i.xcrosshairsWidth/2),this.moveXAxisTooltip(l)}}},{key:"moveYCrosshairs",value:function(e){var t=this.ttCtx;t.ycrosshairs!==null&&X.setAttrs(t.ycrosshairs,{y1:e,y2:e}),t.ycrosshairsHidden!==null&&X.setAttrs(t.ycrosshairsHidden,{y1:e,y2:e})}},{key:"moveXAxisTooltip",value:function(e){var t=this.w,i=this.ttCtx;if(i.xaxisTooltip!==null&&i.xcrosshairsWidth!==0){i.xaxisTooltip.classList.add("apexcharts-active");var a=i.xaxisOffY+t.config.xaxis.tooltip.offsetY+t.globals.translateY+1+t.config.xaxis.offsetY;if(e-=i.xaxisTooltip.getBoundingClientRect().width/2,!isNaN(e)){e+=t.globals.translateX;var s;s=new X(this.ctx).getTextRects(i.xaxisTooltipText.innerHTML),i.xaxisTooltipText.style.minWidth=s.width+"px",i.xaxisTooltip.style.left=e+"px",i.xaxisTooltip.style.top=a+"px"}}}},{key:"moveYAxisTooltip",value:function(e){var t=this.w,i=this.ttCtx;i.yaxisTTEls===null&&(i.yaxisTTEls=t.globals.dom.baseEl.querySelectorAll(".apexcharts-yaxistooltip"));var a=parseInt(i.ycrosshairsHidden.getAttribute("y1"),10),s=t.globals.translateY+a,r=i.yaxisTTEls[e].getBoundingClientRect().height,n=t.globals.translateYAxisX[e]-2;t.config.yaxis[e].opposite&&(n-=26),s-=r/2,t.globals.ignoreYAxisIndexes.indexOf(e)===-1?(i.yaxisTTEls[e].classList.add("apexcharts-active"),i.yaxisTTEls[e].style.top=s+"px",i.yaxisTTEls[e].style.left=n+t.config.yaxis[e].tooltip.offsetX+"px"):i.yaxisTTEls[e].classList.remove("apexcharts-active")}},{key:"moveTooltip",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=this.w,s=this.ttCtx,r=s.getElTooltip(),n=s.tooltipRect,l=i!==null?parseFloat(i):1,h=parseFloat(e)+l+5,d=parseFloat(t)+l/2;if(h>a.globals.gridWidth/2&&(h=h-n.ttWidth-l-10),h>a.globals.gridWidth-n.ttWidth-10&&(h=a.globals.gridWidth-n.ttWidth),h<-20&&(h=-20),a.config.tooltip.followCursor){var c=s.getElGrid().getBoundingClientRect();(h=s.e.clientX-c.left)>a.globals.gridWidth/2&&(h-=s.tooltipRect.ttWidth),(d=s.e.clientY+a.globals.translateY-c.top)>a.globals.gridHeight/2&&(d-=s.tooltipRect.ttHeight)}else a.globals.isBarHorizontal||n.ttHeight/2+d>a.globals.gridHeight&&(d=a.globals.gridHeight-n.ttHeight+a.globals.translateY);isNaN(h)||(h+=a.globals.translateX,r.style.left=h+"px",r.style.top=d+"px")}},{key:"moveMarkers",value:function(e,t){var i=this.w,a=this.ttCtx;if(i.globals.markers.size[e]>0)for(var s=i.globals.dom.baseEl.querySelectorAll(" .apexcharts-series[data\\:realIndex='".concat(e,"'] .apexcharts-marker")),r=0;r0){var p=g.getAttribute("shape"),f=h.getMarkerPath(s,r,p,1.5*c);g.setAttribute("d",f)}this.moveXCrosshairs(s),l.fixedTooltip||this.moveTooltip(s,r,c)}}},{key:"moveDynamicPointsOnHover",value:function(e){var t,i=this.ttCtx,a=i.w,s=0,r=0,n=a.globals.pointsArray,l=new Le(this.ctx),h=new X(this.ctx);t=l.getActiveConfigSeriesIndex("asc",["line","area","scatter","bubble"]);var d=i.tooltipUtil.getHoverMarkerSize(t);n[t]&&(s=n[t][e][0],r=n[t][e][1]);var c=i.tooltipUtil.getAllMarkers();if(c!==null)for(var u=0;u0){var m=h.getMarkerPath(s,p,x,d);c[u].setAttribute("d",m)}else c[u].setAttribute("d","")}}this.moveXCrosshairs(s),i.fixedTooltip||this.moveTooltip(s,r||a.globals.gridHeight,d)}},{key:"moveStickyTooltipOverBars",value:function(e,t){var i=this.w,a=this.ttCtx,s=i.globals.columnSeries?i.globals.columnSeries.length:i.globals.series.length,r=s>=2&&s%2==0?Math.floor(s/2):Math.floor(s/2)+1;i.globals.isBarHorizontal&&(r=new Le(this.ctx).getActiveConfigSeriesIndex("desc")+1);var n=i.globals.dom.baseEl.querySelector(".apexcharts-bar-series .apexcharts-series[rel='".concat(r,"'] path[j='").concat(e,"'], .apexcharts-candlestick-series .apexcharts-series[rel='").concat(r,"'] path[j='").concat(e,"'], .apexcharts-boxPlot-series .apexcharts-series[rel='").concat(r,"'] path[j='").concat(e,"'], .apexcharts-rangebar-series .apexcharts-series[rel='").concat(r,"'] path[j='").concat(e,"']"));n||typeof t!="number"||(n=i.globals.dom.baseEl.querySelector(".apexcharts-bar-series .apexcharts-series[data\\:realIndex='".concat(t,"'] path[j='").concat(e,`'], + .apexcharts-candlestick-series .apexcharts-series[data\\:realIndex='`).concat(t,"'] path[j='").concat(e,`'], + .apexcharts-boxPlot-series .apexcharts-series[data\\:realIndex='`).concat(t,"'] path[j='").concat(e,`'], + .apexcharts-rangebar-series .apexcharts-series[data\\:realIndex='`).concat(t,"'] path[j='").concat(e,"']")));var l=n?parseFloat(n.getAttribute("cx")):0,h=n?parseFloat(n.getAttribute("cy")):0,d=n?parseFloat(n.getAttribute("barWidth")):0,c=a.getElGrid().getBoundingClientRect(),u=n&&(n.classList.contains("apexcharts-candlestick-area")||n.classList.contains("apexcharts-boxPlot-area"));i.globals.isXNumeric?(n&&!u&&(l-=s%2!=0?d/2:0),n&&u&&(l-=d/2)):i.globals.isBarHorizontal||(l=a.xAxisTicksPositions[e-1]+a.dataPointsDividedWidth/2,isNaN(l)&&(l=a.xAxisTicksPositions[e]-a.dataPointsDividedWidth/2)),i.globals.isBarHorizontal?h-=a.tooltipRect.ttHeight:i.config.tooltip.followCursor?h=a.e.clientY-c.top-a.tooltipRect.ttHeight/2:h+a.tooltipRect.ttHeight+15>i.globals.gridHeight&&(h=i.globals.gridHeight),i.globals.isBarHorizontal||this.moveXCrosshairs(l),a.fixedTooltip||this.moveTooltip(l,h||i.globals.gridHeight)}}]),o})(),Gs=(function(){function o(e){H(this,o),this.w=e.w,this.ttCtx=e,this.ctx=e.ctx,this.tooltipPosition=new Ra(e)}return O(o,[{key:"drawDynamicPoints",value:function(){var e=this.w,t=new X(this.ctx),i=new st(this.ctx),a=e.globals.dom.baseEl.querySelectorAll(".apexcharts-series");a=ce(a),e.config.chart.stacked&&a.sort((function(c,u){return parseFloat(c.getAttribute("data:realIndex"))-parseFloat(u.getAttribute("data:realIndex"))}));for(var s=0;s2&&arguments[2]!==void 0?arguments[2]:null,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,s=this.w;s.config.chart.type!=="bubble"&&this.newPointSize(e,t);var r=t.getAttribute("cx"),n=t.getAttribute("cy");if(i!==null&&a!==null&&(r=i,n=a),this.tooltipPosition.moveXCrosshairs(r),!this.fixedTooltip){if(s.config.chart.type==="radar"){var l=this.ttCtx.getElGrid().getBoundingClientRect();r=this.ttCtx.e.clientX-l.left}this.tooltipPosition.moveTooltip(r,n,s.config.markers.hover.size)}}},{key:"enlargePoints",value:function(e){for(var t=this.w,i=this,a=this.ttCtx,s=e,r=t.globals.dom.baseEl.querySelectorAll(".apexcharts-series:not(.apexcharts-series-collapsed) .apexcharts-marker"),n=t.config.markers.hover.size,l=0;l0){var a=this.ttCtx.tooltipUtil.getPathFromPoint(e[t],i);e[t].setAttribute("d",a)}else e[t].setAttribute("d","M0,0")}}}]),o})(),js=(function(){function o(e){H(this,o),this.w=e.w;var t=this.w;this.ttCtx=e,this.isVerticalGroupedRangeBar=!t.globals.isBarHorizontal&&t.config.chart.type==="rangeBar"&&t.config.plotOptions.bar.rangeBarGroupRows}return O(o,[{key:"getAttr",value:function(e,t){return parseFloat(e.target.getAttribute(t))}},{key:"handleHeatTreeTooltip",value:function(e){var t=e.e,i=e.opt,a=e.x,s=e.y,r=e.type,n=this.ttCtx,l=this.w;if(t.target.classList.contains("apexcharts-".concat(r,"-rect"))){var h=this.getAttr(t,"i"),d=this.getAttr(t,"j"),c=this.getAttr(t,"cx"),u=this.getAttr(t,"cy"),g=this.getAttr(t,"width"),p=this.getAttr(t,"height");if(n.tooltipLabels.drawSeriesTexts({ttItems:i.ttItems,i:h,j:d,shared:!1,e:t}),l.globals.capturedSeriesIndex=h,l.globals.capturedDataPointIndex=d,a=c+n.tooltipRect.ttWidth/2+g,s=u+n.tooltipRect.ttHeight/2-p/2,n.tooltipPosition.moveXCrosshairs(c+g/2),a>l.globals.gridWidth/2&&(a=c-n.tooltipRect.ttWidth/2+g),n.w.config.tooltip.followCursor){var f=l.globals.dom.elWrap.getBoundingClientRect();a=l.globals.clientX-f.left-(a>l.globals.gridWidth/2?n.tooltipRect.ttWidth:0),s=l.globals.clientY-f.top-(s>l.globals.gridHeight/2?n.tooltipRect.ttHeight:0)}}return{x:a,y:s}}},{key:"handleMarkerTooltip",value:function(e){var t,i,a=e.e,s=e.opt,r=e.x,n=e.y,l=this.w,h=this.ttCtx;if(a.target.classList.contains("apexcharts-marker")){var d=parseInt(s.paths.getAttribute("cx"),10),c=parseInt(s.paths.getAttribute("cy"),10),u=parseFloat(s.paths.getAttribute("val"));if(i=parseInt(s.paths.getAttribute("rel"),10),t=parseInt(s.paths.parentNode.parentNode.parentNode.getAttribute("rel"),10)-1,h.intersect){var g=L.findAncestor(s.paths,"apexcharts-series");g&&(t=parseInt(g.getAttribute("data:realIndex"),10))}if(h.tooltipLabels.drawSeriesTexts({ttItems:s.ttItems,i:t,j:i,shared:!h.showOnIntersect&&l.config.tooltip.shared,e:a}),a.type==="mouseup"&&h.markerClick(a,t,i),l.globals.capturedSeriesIndex=t,l.globals.capturedDataPointIndex=i,r=d,n=c+l.globals.translateY-1.4*h.tooltipRect.ttHeight,h.w.config.tooltip.followCursor){var p=h.getElGrid().getBoundingClientRect();n=h.e.clientY+l.globals.translateY-p.top}u<0&&(n=c),h.marker.enlargeCurrentPoint(i,s.paths,r,n)}return{x:r,y:n}}},{key:"handleBarTooltip",value:function(e){var t,i,a=e.e,s=e.opt,r=this.w,n=this.ttCtx,l=n.getElTooltip(),h=0,d=0,c=0,u=this.getBarTooltipXY({e:a,opt:s});if(u.j!==null||u.barHeight!==0||u.barWidth!==0){t=u.i;var g=u.j;if(r.globals.capturedSeriesIndex=t,r.globals.capturedDataPointIndex=g,r.globals.isBarHorizontal&&n.tooltipUtil.hasBars()||!r.config.tooltip.shared?(d=u.x,c=u.y,i=Array.isArray(r.config.stroke.width)?r.config.stroke.width[t]:r.config.stroke.width,h=d):r.globals.comboCharts||r.config.tooltip.shared||(h/=2),isNaN(c)&&(c=r.globals.svgHeight-n.tooltipRect.ttHeight),parseInt(s.paths.parentNode.getAttribute("data:realIndex"),10),d+n.tooltipRect.ttWidth>r.globals.gridWidth?d-=n.tooltipRect.ttWidth:d<0&&(d=0),n.w.config.tooltip.followCursor){var p=n.getElGrid().getBoundingClientRect();c=n.e.clientY-p.top}n.tooltip===null&&(n.tooltip=r.globals.dom.baseEl.querySelector(".apexcharts-tooltip")),r.config.tooltip.shared||(r.globals.comboBarCount>0?n.tooltipPosition.moveXCrosshairs(h+i/2):n.tooltipPosition.moveXCrosshairs(h)),!n.fixedTooltip&&(!r.config.tooltip.shared||r.globals.isBarHorizontal&&n.tooltipUtil.hasBars())&&(c=c+r.globals.translateY-n.tooltipRect.ttHeight/2,l.style.left=d+r.globals.translateX+"px",l.style.top=c+"px")}}},{key:"getBarTooltipXY",value:function(e){var t=this,i=e.e,a=e.opt,s=this.w,r=null,n=this.ttCtx,l=0,h=0,d=0,c=0,u=0,g=i.target.classList;if(g.contains("apexcharts-bar-area")||g.contains("apexcharts-candlestick-area")||g.contains("apexcharts-boxPlot-area")||g.contains("apexcharts-rangebar-area")){var p=i.target,f=p.getBoundingClientRect(),x=a.elGrid.getBoundingClientRect(),b=f.height;u=f.height;var m=f.width,v=parseInt(p.getAttribute("cx"),10),k=parseInt(p.getAttribute("cy"),10);c=parseFloat(p.getAttribute("barWidth"));var y=i.type==="touchmove"?i.touches[0].clientX:i.clientX;r=parseInt(p.getAttribute("j"),10),l=parseInt(p.parentNode.getAttribute("rel"),10)-1;var C=p.getAttribute("data-range-y1"),w=p.getAttribute("data-range-y2");s.globals.comboCharts&&(l=parseInt(p.parentNode.getAttribute("data:realIndex"),10));var A=function(M){return s.globals.isXNumeric?v-m/2:t.isVerticalGroupedRangeBar?v+m/2:v-n.dataPointsDividedWidth+m/2},S=function(){return k-n.dataPointsDividedHeight+b/2-n.tooltipRect.ttHeight/2};n.tooltipLabels.drawSeriesTexts({ttItems:a.ttItems,i:l,j:r,y1:C?parseInt(C,10):null,y2:w?parseInt(w,10):null,shared:!n.showOnIntersect&&s.config.tooltip.shared,e:i}),s.config.tooltip.followCursor?s.globals.isBarHorizontal?(h=y-x.left+15,d=S()):(h=A(),d=i.clientY-x.top-n.tooltipRect.ttHeight/2-15):s.globals.isBarHorizontal?((h=v)0&&i.setAttribute("width",t.xcrosshairsWidth)}},{key:"handleYCrosshair",value:function(){var e=this.w,t=this.ttCtx;t.ycrosshairs=e.globals.dom.baseEl.querySelector(".apexcharts-ycrosshairs"),t.ycrosshairsHidden=e.globals.dom.baseEl.querySelector(".apexcharts-ycrosshairs-hidden")}},{key:"drawYaxisTooltipText",value:function(e,t,i){var a=this.ttCtx,s=this.w,r=s.globals,n=r.seriesYAxisMap[e];if(a.yaxisTooltips[e]&&n.length>0){var l=r.yLabelFormatters[e],h=a.getElGrid().getBoundingClientRect(),d=n[0],c=0;i.yRatio.length>1&&(c=d);var u=(t-h.top)*i.yRatio[c],g=r.maxYArr[d]-r.minYArr[d],p=r.minYArr[d]+(g-u);s.config.yaxis[e].reversed&&(p=r.maxYArr[d]-(g-u)),a.tooltipPosition.moveYCrosshairs(t-h.top),a.yaxisTooltipText[e].innerHTML=l(p),a.tooltipPosition.moveYAxisTooltip(e)}}}]),o})(),Ea=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w;var t=this.w;this.tConfig=t.config.tooltip,this.tooltipUtil=new Xa(this),this.tooltipLabels=new Bs(this),this.tooltipPosition=new Ra(this),this.marker=new Gs(this),this.intersect=new js(this),this.axesTooltip=new Vs(this),this.showOnIntersect=this.tConfig.intersect,this.showTooltipTitle=this.tConfig.x.show,this.fixedTooltip=this.tConfig.fixed.enabled,this.xaxisTooltip=null,this.yaxisTTEls=null,this.isBarShared=!t.globals.isBarHorizontal&&this.tConfig.shared,this.lastHoverTime=Date.now()}return O(o,[{key:"getElTooltip",value:function(e){return e||(e=this),e.w.globals.dom.baseEl?e.w.globals.dom.baseEl.querySelector(".apexcharts-tooltip"):null}},{key:"getElXCrosshairs",value:function(){return this.w.globals.dom.baseEl.querySelector(".apexcharts-xcrosshairs")}},{key:"getElGrid",value:function(){return this.w.globals.dom.baseEl.querySelector(".apexcharts-grid")}},{key:"drawTooltip",value:function(e){var t=this.w;this.xyRatios=e,this.isXAxisTooltipEnabled=t.config.xaxis.tooltip.enabled&&t.globals.axisCharts,this.yaxisTooltips=t.config.yaxis.map((function(r,n){return!!(r.show&&r.tooltip.enabled&&t.globals.axisCharts)})),this.allTooltipSeriesGroups=[],t.globals.axisCharts||(this.showTooltipTitle=!1);var i=document.createElement("div");if(i.classList.add("apexcharts-tooltip"),t.config.tooltip.cssClass&&i.classList.add(t.config.tooltip.cssClass),i.classList.add("apexcharts-theme-".concat(this.tConfig.theme)),t.globals.dom.elWrap.appendChild(i),t.globals.axisCharts){this.axesTooltip.drawXaxisTooltip(),this.axesTooltip.drawYaxisTooltip(),this.axesTooltip.setXCrosshairWidth(),this.axesTooltip.handleYCrosshair();var a=new wt(this.ctx);this.xAxisTicksPositions=a.getXAxisTicksPositions()}if(!t.globals.comboCharts&&!this.tConfig.intersect&&t.config.chart.type!=="rangeBar"||this.tConfig.shared||(this.showOnIntersect=!0),t.config.markers.size!==0&&t.globals.markers.largestSize!==0||this.marker.drawDynamicPoints(this),t.globals.collapsedSeries.length!==t.globals.series.length){this.dataPointsDividedHeight=t.globals.gridHeight/t.globals.dataPoints,this.dataPointsDividedWidth=t.globals.gridWidth/t.globals.dataPoints,this.showTooltipTitle&&(this.tooltipTitle=document.createElement("div"),this.tooltipTitle.classList.add("apexcharts-tooltip-title"),this.tooltipTitle.style.fontFamily=this.tConfig.style.fontFamily||t.config.chart.fontFamily,this.tooltipTitle.style.fontSize=this.tConfig.style.fontSize,i.appendChild(this.tooltipTitle));var s=t.globals.series.length;(t.globals.xyCharts||t.globals.comboCharts)&&this.tConfig.shared&&(s=this.showOnIntersect?1:t.globals.series.length),this.legendLabels=t.globals.dom.baseEl.querySelectorAll(".apexcharts-legend-text"),this.ttItems=this.createTTElements(s),this.addSVGEvents()}}},{key:"createTTElements",value:function(e){for(var t=this,i=this.w,a=[],s=this.getElTooltip(),r=function(l){var h=document.createElement("div");h.classList.add("apexcharts-tooltip-series-group","apexcharts-tooltip-series-group-".concat(l)),h.style.order=i.config.tooltip.inverseOrder?e-l:l+1;var d=document.createElement("span");d.classList.add("apexcharts-tooltip-marker"),d.style.backgroundColor=i.globals.colors[l],h.appendChild(d);var c=document.createElement("div");c.classList.add("apexcharts-tooltip-text"),c.style.fontFamily=t.tConfig.style.fontFamily||i.config.chart.fontFamily,c.style.fontSize=t.tConfig.style.fontSize,["y","goals","z"].forEach((function(u){var g=document.createElement("div");g.classList.add("apexcharts-tooltip-".concat(u,"-group"));var p=document.createElement("span");p.classList.add("apexcharts-tooltip-text-".concat(u,"-label")),g.appendChild(p);var f=document.createElement("span");f.classList.add("apexcharts-tooltip-text-".concat(u,"-value")),g.appendChild(f),c.appendChild(g)})),h.appendChild(c),s.appendChild(h),a.push(h)},n=0;n0&&this.addPathsEventListeners(p,c),this.tooltipUtil.hasBars()&&!this.tConfig.shared&&this.addDatapointEventsListeners(c)}}},{key:"drawFixedTooltipRect",value:function(){var e=this.w,t=this.getElTooltip(),i=t.getBoundingClientRect(),a=i.width+10,s=i.height+10,r=this.tConfig.fixed.offsetX,n=this.tConfig.fixed.offsetY,l=this.tConfig.fixed.position.toLowerCase();return l.indexOf("right")>-1&&(r=r+e.globals.svgWidth-a+10),l.indexOf("bottom")>-1&&(n=n+e.globals.svgHeight-s-10),t.style.left=r+"px",t.style.top=n+"px",{x:r,y:n,ttWidth:a,ttHeight:s}}},{key:"addDatapointEventsListeners",value:function(e){var t=this.w.globals.dom.baseEl.querySelectorAll(".apexcharts-series-markers .apexcharts-marker, .apexcharts-bar-area, .apexcharts-candlestick-area, .apexcharts-boxPlot-area, .apexcharts-rangebar-area");this.addPathsEventListeners(t,e)}},{key:"addPathsEventListeners",value:function(e,t){for(var i=this,a=function(r){var n={paths:e[r],tooltipEl:t.tooltipEl,tooltipY:t.tooltipY,tooltipX:t.tooltipX,elGrid:t.elGrid,hoverArea:t.hoverArea,ttItems:t.ttItems};["mousemove","mouseup","touchmove","mouseout","touchend"].map((function(l){return e[r].addEventListener(l,i.onSeriesHover.bind(i,n),{capture:!1,passive:!0})}))},s=0;s=20?this.seriesHover(e,t):(clearTimeout(this.seriesHoverTimeout),this.seriesHoverTimeout=setTimeout((function(){i.seriesHover(e,t)}),20-a))}},{key:"seriesHover",value:function(e,t){var i=this;this.lastHoverTime=Date.now();var a=[],s=this.w;s.config.chart.group&&(a=this.ctx.getGroupedCharts()),s.globals.axisCharts&&(s.globals.minX===-1/0&&s.globals.maxX===1/0||s.globals.dataPoints===0)||(a.length?a.forEach((function(r){var n=i.getElTooltip(r),l={paths:e.paths,tooltipEl:n,tooltipY:e.tooltipY,tooltipX:e.tooltipX,elGrid:e.elGrid,hoverArea:e.hoverArea,ttItems:r.w.globals.tooltip.ttItems};r.w.globals.minX===i.w.globals.minX&&r.w.globals.maxX===i.w.globals.maxX&&r.w.globals.tooltip.seriesHoverByContext({chartCtx:r,ttCtx:r.w.globals.tooltip,opt:l,e:t})})):this.seriesHoverByContext({chartCtx:this.ctx,ttCtx:this.w.globals.tooltip,opt:e,e:t}))}},{key:"seriesHoverByContext",value:function(e){var t=e.chartCtx,i=e.ttCtx,a=e.opt,s=e.e,r=t.w,n=this.getElTooltip(t);n&&(i.tooltipRect={x:0,y:0,ttWidth:n.getBoundingClientRect().width,ttHeight:n.getBoundingClientRect().height},i.e=s,i.tooltipUtil.hasBars()&&!r.globals.comboCharts&&!i.isBarShared&&this.tConfig.onDatasetHover.highlightDataSeries&&new Le(t).toggleSeriesOnHover(s,s.target.parentNode),i.fixedTooltip&&i.drawFixedTooltipRect(),r.globals.axisCharts?i.axisChartsTooltips({e:s,opt:a,tooltipRect:i.tooltipRect}):i.nonAxisChartsTooltips({e:s,opt:a,tooltipRect:i.tooltipRect}))}},{key:"axisChartsTooltips",value:function(e){var t,i,a=e.e,s=e.opt,r=this.w,n=s.elGrid.getBoundingClientRect(),l=a.type==="touchmove"?a.touches[0].clientX:a.clientX,h=a.type==="touchmove"?a.touches[0].clientY:a.clientY;if(this.clientY=h,this.clientX=l,r.globals.capturedSeriesIndex=-1,r.globals.capturedDataPointIndex=-1,hn.top+n.height)this.handleMouseOut(s);else{if(Array.isArray(this.tConfig.enabledOnSeries)&&!r.config.tooltip.shared){var d=parseInt(s.paths.getAttribute("index"),10);if(this.tConfig.enabledOnSeries.indexOf(d)<0)return void this.handleMouseOut(s)}var c=this.getElTooltip(),u=this.getElXCrosshairs(),g=[];r.config.chart.group&&(g=this.ctx.getSyncedCharts());var p=r.globals.xyCharts||r.config.chart.type==="bar"&&!r.globals.isBarHorizontal&&this.tooltipUtil.hasBars()&&this.tConfig.shared||r.globals.comboCharts&&this.tooltipUtil.hasBars();if(a.type==="mousemove"||a.type==="touchmove"||a.type==="mouseup"){if(r.globals.collapsedSeries.length+r.globals.ancillaryCollapsedSeries.length===r.globals.series.length)return;u!==null&&u.classList.add("apexcharts-active");var f=this.yaxisTooltips.filter((function(m){return m===!0}));if(this.ycrosshairs!==null&&f.length&&this.ycrosshairs.classList.add("apexcharts-active"),p&&!this.showOnIntersect||g.length>1)this.handleStickyTooltip(a,l,h,s);else if(r.config.chart.type==="heatmap"||r.config.chart.type==="treemap"){var x=this.intersect.handleHeatTreeTooltip({e:a,opt:s,x:t,y:i,type:r.config.chart.type});t=x.x,i=x.y,c.style.left=t+"px",c.style.top=i+"px"}else this.tooltipUtil.hasBars()&&this.intersect.handleBarTooltip({e:a,opt:s}),this.tooltipUtil.hasMarkers()&&this.intersect.handleMarkerTooltip({e:a,opt:s,x:t,y:i});if(this.yaxisTooltips.length)for(var b=0;bh.width)this.handleMouseOut(a);else if(l!==null)this.handleStickyCapturedSeries(e,l,a,n);else if(this.tooltipUtil.isXoverlap(n)||s.globals.isBarHorizontal){var d=s.globals.series.findIndex((function(c,u){return!s.globals.collapsedSeriesIndices.includes(u)}));this.create(e,this,d,n,a.ttItems)}}},{key:"handleStickyCapturedSeries",value:function(e,t,i,a){var s=this.w;if(!this.tConfig.shared&&s.globals.series[t][a]===null)return void this.handleMouseOut(i);if(s.globals.series[t][a]!==void 0)this.tConfig.shared&&this.tooltipUtil.isXoverlap(a)&&this.tooltipUtil.isInitialSeriesSameLen()?this.create(e,this,t,a,i.ttItems):this.create(e,this,t,a,i.ttItems,!1);else if(this.tooltipUtil.isXoverlap(a)){var r=s.globals.series.findIndex((function(n,l){return!s.globals.collapsedSeriesIndices.includes(l)}));this.create(e,this,r,a,i.ttItems)}}},{key:"deactivateHoverFilter",value:function(){for(var e=this.w,t=new X(this.ctx),i=e.globals.dom.Paper.find(".apexcharts-bar-area"),a=0;a5&&arguments[5]!==void 0?arguments[5]:null,w=this.w,A=t;e.type==="mouseup"&&this.markerClick(e,i,a),C===null&&(C=this.tConfig.shared);var S=this.tooltipUtil.hasMarkers(i),M=this.tooltipUtil.getElBars();if(w.config.legend.tooltipHoverFormatter){var P=w.config.legend.tooltipHoverFormatter,I=Array.from(this.legendLabels);I.forEach((function(ne){var oe=ne.getAttribute("data:default-text");ne.innerHTML=decodeURIComponent(oe)}));for(var T=0;T0?A.marker.enlargePoints(a):A.tooltipPosition.moveDynamicPointsOnHover(a);else if(this.tooltipUtil.hasBars()&&(this.barSeriesHeight=this.tooltipUtil.getBarsHeight(M),this.barSeriesHeight>0)){var W=new X(this.ctx),G=w.globals.dom.Paper.find(".apexcharts-bar-area[j='".concat(a,"']"));this.deactivateHoverFilter(),this.tooltipPosition.moveStickyTooltipOverBars(a,i);for(var B=0;B0&&t.config.plotOptions.bar.hideZeroBarsWhenGrouped&&(g-=d*w)),C&&(g=g+u.height/2-m/2-2);var S=t.globals.series[i][a]<0,M=l;switch(this.barCtx.isReversed&&(M=l+(S?c:-c)),x.position){case"center":p=C?S?M-c/2+k:M+c/2-k:S?M-c/2+u.height/2+k:M+c/2+u.height/2-k;break;case"bottom":p=C?S?M-c+k:M+c-k:S?M-c+u.height+m+k:M+c-u.height/2+m-k;break;case"top":p=C?S?M+k:M-k:S?M-u.height/2-k:M+u.height+k}if(this.barCtx.lastActiveBarSerieIndex===s&&b.enabled){var P=new X(this.barCtx.ctx).getTextRects(this.getStackedTotalDataLabel({realIndex:s,j:a}),f.fontSize);r=S?M-P.height/2-k-b.offsetY+18:M+P.height+k+b.offsetY-18;var I=A;n=y+(t.globals.isXNumeric?-d*t.globals.barGroups.length/2:t.globals.barGroups.length*d/2-(t.globals.barGroups.length-1)*d-I)+b.offsetX}return t.config.chart.stacked||(p<0?p=0+m:p+u.height/3>t.globals.gridHeight&&(p=t.globals.gridHeight-m)),{bcx:h,bcy:l,dataLabelsX:g,dataLabelsY:p,totalDataLabelsX:n,totalDataLabelsY:r,totalDataLabelsAnchor:"middle"}}},{key:"calculateBarsDataLabelsPosition",value:function(e){var t=this.w,i=e.x,a=e.i,s=e.j,r=e.realIndex,n=e.bcy,l=e.barHeight,h=e.barWidth,d=e.textRects,c=e.dataLabelsX,u=e.strokeWidth,g=e.dataLabelsConfig,p=e.barDataLabelsConfig,f=e.barTotalDataLabelsConfig,x=e.offX,b=e.offY,m=t.globals.gridHeight/t.globals.dataPoints;h=Math.abs(h);var v,k,y=n-(this.barCtx.isRangeBar?0:m)+l/2+d.height/2+b-3,C="start",w=t.globals.series[a][s]<0,A=i;switch(this.barCtx.isReversed&&(A=i+(w?-h:h),C=w?"start":"end"),p.position){case"center":c=w?A+h/2-x:Math.max(d.width/2,A-h/2)+x;break;case"bottom":c=w?A+h-u-x:A-h+u+x;break;case"top":c=w?A-u-x:A-u+x}if(this.barCtx.lastActiveBarSerieIndex===r&&f.enabled){var S=new X(this.barCtx.ctx).getTextRects(this.getStackedTotalDataLabel({realIndex:r,j:s}),g.fontSize);w?(v=A-u-x-f.offsetX,C="end"):v=A+x+f.offsetX+(this.barCtx.isReversed?-(h+u):u),k=y-d.height/2+S.height/2+f.offsetY+u}return t.config.chart.stacked||(g.textAnchor==="start"?c-d.width<0?c=w?d.width+u:u:c+d.width>t.globals.gridWidth&&(c=w?t.globals.gridWidth-u:t.globals.gridWidth-d.width-u):g.textAnchor==="middle"?c-d.width/2<0?c=d.width/2+u:c+d.width/2>t.globals.gridWidth&&(c=t.globals.gridWidth-d.width/2-u):g.textAnchor==="end"&&(c<1?c=d.width+u:c+1>t.globals.gridWidth&&(c=t.globals.gridWidth-d.width-u))),{bcx:i,bcy:n,dataLabelsX:c,dataLabelsY:y,totalDataLabelsX:v,totalDataLabelsY:k,totalDataLabelsAnchor:C}}},{key:"drawCalculatedDataLabels",value:function(e){var t=e.x,i=e.y,a=e.val,s=e.i,r=e.j,n=e.textRects,l=e.barHeight,h=e.barWidth,d=e.dataLabelsConfig,c=this.w,u="rotate(0)";c.config.plotOptions.bar.dataLabels.orientation==="vertical"&&(u="rotate(-90, ".concat(t,", ").concat(i,")"));var g=new rt(this.barCtx.ctx),p=new X(this.barCtx.ctx),f=d.formatter,x=null,b=c.globals.collapsedSeriesIndices.indexOf(s)>-1;if(d.enabled&&!b){x=p.group({class:"apexcharts-data-labels",transform:u});var m="";a!==void 0&&(m=f(a,R(R({},c),{},{seriesIndex:s,dataPointIndex:r,w:c}))),!a&&c.config.plotOptions.bar.hideZeroBarsWhenGrouped&&(m="");var v=c.globals.series[s][r]<0,k=c.config.plotOptions.bar.dataLabels.position;c.config.plotOptions.bar.dataLabels.orientation==="vertical"&&(k==="top"&&(d.textAnchor=v?"end":"start"),k==="center"&&(d.textAnchor="middle"),k==="bottom"&&(d.textAnchor=v?"end":"start")),this.barCtx.isRangeBar&&this.barCtx.barOptions.dataLabels.hideOverflowingLabels&&hMath.abs(h)&&(m=""):n.height/1.6>Math.abs(l)&&(m=""));var y=R({},d);this.barCtx.isHorizontal&&a<0&&(d.textAnchor==="start"?y.textAnchor="end":d.textAnchor==="end"&&(y.textAnchor="start")),g.plotDataLabelsText({x:t,y:i,text:m,i:s,j:r,parent:x,dataLabelsConfig:y,alwaysDrawDataLabel:!0,offsetCorrection:!0})}return x}},{key:"drawTotalDataLabels",value:function(e){var t=e.x,i=e.y,a=e.val,s=e.realIndex,r=e.textAnchor,n=e.barTotalDataLabelsConfig;this.w;var l,h=new X(this.barCtx.ctx);return n.enabled&&t!==void 0&&i!==void 0&&this.barCtx.lastActiveBarSerieIndex===s&&(l=h.drawText({x:t,y:i,foreColor:n.style.color,text:a,textAnchor:r,fontFamily:n.style.fontFamily,fontSize:n.style.fontSize,fontWeight:n.style.fontWeight})),l}}]),o})(),qs=(function(){function o(e){H(this,o),this.w=e.w,this.barCtx=e}return O(o,[{key:"initVariables",value:function(e){var t=this.w;this.barCtx.series=e,this.barCtx.totalItems=0,this.barCtx.seriesLen=0,this.barCtx.visibleI=-1,this.barCtx.visibleItems=1;for(var i=0;i0&&(this.barCtx.seriesLen=this.barCtx.seriesLen+1,this.barCtx.totalItems+=e[i].length),t.globals.isXNumeric)for(var a=0;at.globals.minX&&t.globals.seriesX[i][a]0&&(a=h.globals.minXDiff/u),(r=a/c*parseInt(this.barCtx.barOptions.columnWidth,10)/100)<1&&(r=1)}String(this.barCtx.barOptions.columnWidth).indexOf("%")===-1&&(r=parseInt(this.barCtx.barOptions.columnWidth,10)),n=h.globals.gridHeight-this.barCtx.baseLineY[this.barCtx.translationsIndex]-(this.barCtx.isReversed?h.globals.gridHeight:0)+(this.barCtx.isReversed?2*this.barCtx.baseLineY[this.barCtx.translationsIndex]:0),e=h.globals.padHorizontal+(a-r*this.barCtx.seriesLen)/2}return h.globals.barHeight=s,h.globals.barWidth=r,{x:e,y:t,yDivision:i,xDivision:a,barHeight:s,barWidth:r,zeroH:n,zeroW:l}}},{key:"initializeStackedPrevVars",value:function(e){e.w.globals.seriesGroups.forEach((function(t){e[t]||(e[t]={}),e[t].prevY=[],e[t].prevX=[],e[t].prevYF=[],e[t].prevXF=[],e[t].prevYVal=[],e[t].prevXVal=[]}))}},{key:"initializeStackedXYVars",value:function(e){e.w.globals.seriesGroups.forEach((function(t){e[t]||(e[t]={}),e[t].xArrj=[],e[t].xArrjF=[],e[t].xArrjVal=[],e[t].yArrj=[],e[t].yArrjF=[],e[t].yArrjVal=[]}))}},{key:"getPathFillColor",value:function(e,t,i,a){var s,r,n,l,h=this.w,d=this.barCtx.ctx.fill,c=null,u=this.barCtx.barOptions.distributed?i:t;return this.barCtx.barOptions.colors.ranges.length>0&&this.barCtx.barOptions.colors.ranges.map((function(g){e[t][i]>=g.from&&e[t][i]<=g.to&&(c=g.color)})),d.fillPath({seriesNumber:this.barCtx.barOptions.distributed?u:a,dataPointIndex:i,color:c,value:e[t][i],fillConfig:(s=h.config.series[t].data[i])===null||s===void 0?void 0:s.fill,fillType:(r=h.config.series[t].data[i])!==null&&r!==void 0&&(n=r.fill)!==null&&n!==void 0&&n.type?(l=h.config.series[t].data[i])===null||l===void 0?void 0:l.fill.type:Array.isArray(h.config.fill.type)?h.config.fill.type[a]:h.config.fill.type})}},{key:"getStrokeWidth",value:function(e,t,i){var a=0,s=this.w;return this.barCtx.series[e][t]?this.barCtx.isNullValue=!1:this.barCtx.isNullValue=!0,s.config.stroke.show&&(this.barCtx.isNullValue||(a=Array.isArray(this.barCtx.strokeWidth)?this.barCtx.strokeWidth[i]:this.barCtx.strokeWidth)),a}},{key:"createBorderRadiusArr",value:function(e){var t,i=this.w,a=!this.w.config.chart.stacked||i.config.plotOptions.bar.borderRadius<=0,s=e.length,r=0|((t=e[0])===null||t===void 0?void 0:t.length),n=Array.from({length:s},(function(){return Array(r).fill(a?"top":"none")}));if(a)return n;for(var l=0;l0?(h.push(u),c++):g<0&&(d.push(u),c++)}if(h.length>0&&d.length===0)if(h.length===1)n[h[0]][l]="both";else{var p,f=h[0],x=h[h.length-1],b=ot(h);try{for(b.s();!(p=b.n()).done;){var m=p.value;n[m][l]=m===f?"bottom":m===x?"top":"none"}}catch(Y){b.e(Y)}finally{b.f()}}else if(d.length>0&&h.length===0)if(d.length===1)n[d[0]][l]="both";else{var v,k=Math.max.apply(Math,d),y=Math.min.apply(Math,d),C=ot(d);try{for(C.s();!(v=C.n()).done;){var w=v.value;n[w][l]=w===k?"bottom":w===y?"top":"none"}}catch(Y){C.e(Y)}finally{C.f()}}else if(h.length>0&&d.length>0){var A,S=h[h.length-1],M=ot(h);try{for(M.s();!(A=M.n()).done;){var P=A.value;n[P][l]=P===S?"top":"none"}}catch(Y){M.e(Y)}finally{M.f()}var I,T=Math.max.apply(Math,d),z=ot(d);try{for(z.s();!(I=z.n()).done;){var E=I.value;n[E][l]=E===T?"bottom":"none"}}catch(Y){z.e(Y)}finally{z.f()}}else c===1&&(n[h[0]||d[0]][l]="both")}return n}},{key:"barBackground",value:function(e){var t=e.j,i=e.i,a=e.x1,s=e.x2,r=e.y1,n=e.y2,l=e.elSeries,h=this.w,d=new X(this.barCtx.ctx),c=new Le(this.barCtx.ctx).getActiveConfigSeriesIndex();if(this.barCtx.barOptions.colors.backgroundBarColors.length>0&&c===i){t>=this.barCtx.barOptions.colors.backgroundBarColors.length&&(t%=this.barCtx.barOptions.colors.backgroundBarColors.length);var u=this.barCtx.barOptions.colors.backgroundBarColors[t],g=d.drawRect(a!==void 0?a:0,r!==void 0?r:0,s!==void 0?s:h.globals.gridWidth,n!==void 0?n:h.globals.gridHeight,this.barCtx.barOptions.colors.backgroundBarRadius,u,this.barCtx.barOptions.colors.backgroundBarOpacity);l.add(g),g.node.classList.add("apexcharts-backgroundBar")}}},{key:"getColumnPaths",value:function(e){var t,i=e.barWidth,a=e.barXPosition,s=e.y1,r=e.y2,n=e.strokeWidth,l=e.isReversed,h=e.series,d=e.seriesGroup,c=e.realIndex,u=e.i,g=e.j,p=e.w,f=new X(this.barCtx.ctx);(n=Array.isArray(n)?n[c]:n)||(n=0);var x=i,b=a;(t=p.config.series[c].data[g])!==null&&t!==void 0&&t.columnWidthOffset&&(b=a-p.config.series[c].data[g].columnWidthOffset/2,x=i+p.config.series[c].data[g].columnWidthOffset);var m=n/2,v=b+m,k=b+x-m,y=(h[u][g]>=0?1:-1)*(l?-1:1);s+=.001-m*y,r+=.001+m*y;var C=f.move(v,s),w=f.move(v,s),A=f.line(k,s);if(p.globals.previousPaths.length>0&&(w=this.barCtx.getPreviousPath(c,g,!1)),C=C+f.line(v,r)+f.line(k,r)+A+(p.config.plotOptions.bar.borderRadiusApplication==="around"||this.arrBorderRadius[c][g]==="both"?" Z":" z"),w=w+f.line(v,s)+A+A+A+A+A+f.line(v,s)+(p.config.plotOptions.bar.borderRadiusApplication==="around"||this.arrBorderRadius[c][g]==="both"?" Z":" z"),this.arrBorderRadius[c][g]!=="none"&&(C=f.roundPathCorners(C,p.config.plotOptions.bar.borderRadius)),p.config.chart.stacked){var S=this.barCtx;(S=this.barCtx[d]).yArrj.push(r-m*y),S.yArrjF.push(Math.abs(s-r+n*y)),S.yArrjVal.push(this.barCtx.series[u][g])}return{pathTo:C,pathFrom:w}}},{key:"getBarpaths",value:function(e){var t,i=e.barYPosition,a=e.barHeight,s=e.x1,r=e.x2,n=e.strokeWidth,l=e.isReversed,h=e.series,d=e.seriesGroup,c=e.realIndex,u=e.i,g=e.j,p=e.w,f=new X(this.barCtx.ctx);(n=Array.isArray(n)?n[c]:n)||(n=0);var x=i,b=a;(t=p.config.series[c].data[g])!==null&&t!==void 0&&t.barHeightOffset&&(x=i-p.config.series[c].data[g].barHeightOffset/2,b=a+p.config.series[c].data[g].barHeightOffset);var m=n/2,v=x+m,k=x+b-m,y=(h[u][g]>=0?1:-1)*(l?-1:1);s+=.001+m*y,r+=.001-m*y;var C=f.move(s,v),w=f.move(s,v);p.globals.previousPaths.length>0&&(w=this.barCtx.getPreviousPath(c,g,!1));var A=f.line(s,k);if(C=C+f.line(r,v)+f.line(r,k)+A+(p.config.plotOptions.bar.borderRadiusApplication==="around"||this.arrBorderRadius[c][g]==="both"?" Z":" z"),w=w+f.line(s,v)+A+A+A+A+A+f.line(s,v)+(p.config.plotOptions.bar.borderRadiusApplication==="around"||this.arrBorderRadius[c][g]==="both"?" Z":" z"),this.arrBorderRadius[c][g]!=="none"&&(C=f.roundPathCorners(C,p.config.plotOptions.bar.borderRadius)),p.config.chart.stacked){var S=this.barCtx;(S=this.barCtx[d]).xArrj.push(r+m*y),S.xArrjF.push(Math.abs(s-r-n*y)),S.xArrjVal.push(this.barCtx.series[u][g])}return{pathTo:C,pathFrom:w}}},{key:"checkZeroSeries",value:function(e){for(var t=e.series,i=this.w,a=0;a2&&arguments[2]!==void 0)||arguments[2]?t:null;return e!=null&&(i=t+e/this.barCtx.invertedYRatio-2*(this.barCtx.isReversed?e/this.barCtx.invertedYRatio:0)),i}},{key:"getYForValue",value:function(e,t,i){var a=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3]?t:null;return e!=null&&(a=t-e/this.barCtx.yRatio[i]+2*(this.barCtx.isReversed?e/this.barCtx.yRatio[i]:0)),a}},{key:"getGoalValues",value:function(e,t,i,a,s,r){var n=this,l=this.w,h=[],d=function(g,p){var f;h.push((Ct(f={},e,e==="x"?n.getXForValue(g,t,!1):n.getYForValue(g,i,r,!1)),Ct(f,"attrs",p),f))};if(l.globals.seriesGoals[a]&&l.globals.seriesGoals[a][s]&&Array.isArray(l.globals.seriesGoals[a][s])&&l.globals.seriesGoals[a][s].forEach((function(g){d(g.value,g)})),this.barCtx.barOptions.isDumbbell&&l.globals.seriesRange.length){var c=this.barCtx.barOptions.dumbbellColors?this.barCtx.barOptions.dumbbellColors:l.globals.colors,u={strokeHeight:e==="x"?0:l.globals.markers.size[a],strokeWidth:e==="x"?l.globals.markers.size[a]:0,strokeDashArray:0,strokeLineCap:"round",strokeColor:Array.isArray(c[a])?c[a][0]:c[a]};d(l.globals.seriesRangeStart[a][s],u),d(l.globals.seriesRangeEnd[a][s],R(R({},u),{},{strokeColor:Array.isArray(c[a])?c[a][1]:c[a]}))}return h}},{key:"drawGoalLine",value:function(e){var t=e.barXPosition,i=e.barYPosition,a=e.goalX,s=e.goalY,r=e.barWidth,n=e.barHeight,l=new X(this.barCtx.ctx),h=l.group({className:"apexcharts-bar-goals-groups"});h.node.classList.add("apexcharts-element-hidden"),this.barCtx.w.globals.delayedElements.push({el:h.node}),h.attr("clip-path","url(#gridRectMarkerMask".concat(this.barCtx.w.globals.cuid,")"));var d=null;return this.barCtx.isHorizontal?Array.isArray(a)&&a.forEach((function(c){if(c.x>=-1&&c.x<=l.w.globals.gridWidth+1){var u=c.attrs.strokeHeight!==void 0?c.attrs.strokeHeight:n/2,g=i+u+n/2;d=l.drawLine(c.x,g-2*u,c.x,g,c.attrs.strokeColor?c.attrs.strokeColor:void 0,c.attrs.strokeDashArray,c.attrs.strokeWidth?c.attrs.strokeWidth:2,c.attrs.strokeLineCap),h.add(d)}})):Array.isArray(s)&&s.forEach((function(c){if(c.y>=-1&&c.y<=l.w.globals.gridHeight+1){var u=c.attrs.strokeWidth!==void 0?c.attrs.strokeWidth:r/2,g=t+u+r/2;d=l.drawLine(g-2*u,c.y,g,c.y,c.attrs.strokeColor?c.attrs.strokeColor:void 0,c.attrs.strokeDashArray,c.attrs.strokeHeight?c.attrs.strokeHeight:2,c.attrs.strokeLineCap),h.add(d)}})),h}},{key:"drawBarShadow",value:function(e){var t=e.prevPaths,i=e.currPaths,a=e.color,s=this.w,r=t.x,n=t.x1,l=t.barYPosition,h=i.x,d=i.x1,c=i.barYPosition,u=l+i.barHeight,g=new X(this.barCtx.ctx),p=new L,f=g.move(n,u)+g.line(r,u)+g.line(h,c)+g.line(d,c)+g.line(n,u)+(s.config.plotOptions.bar.borderRadiusApplication==="around"||this.arrBorderRadius[realIndex][j]==="both"?" Z":" z");return g.drawPath({d:f,fill:p.shadeColor(.5,L.rgb2hex(a)),stroke:"none",strokeWidth:0,fillOpacity:1,classes:"apexcharts-bar-shadow apexcharts-decoration-element"})}},{key:"getZeroValueEncounters",value:function(e){var t,i=e.i,a=e.j,s=this.w,r=0,n=0;return(s.config.plotOptions.bar.horizontal?s.globals.series.map((function(l,h){return h})):((t=s.globals.columnSeries)===null||t===void 0?void 0:t.i.map((function(l){return l})))||[]).forEach((function(l){var h=s.globals.seriesPercent[l][a];h&&r++,l-1})),a=this.barCtx.columnGroupIndices,s=a.indexOf(i);return s<0&&(a.push(i),s=a.length-1),{groupIndex:i,columnGroupIndex:s}}}]),o})(),nt=(function(){function o(e,t){H(this,o),this.ctx=e,this.w=e.w;var i=this.w;this.barOptions=i.config.plotOptions.bar,this.isHorizontal=this.barOptions.horizontal,this.strokeWidth=i.config.stroke.width,this.isNullValue=!1,this.isRangeBar=i.globals.seriesRange.length&&this.isHorizontal,this.isVerticalGroupedRangeBar=!i.globals.isBarHorizontal&&i.globals.seriesRange.length&&i.config.plotOptions.bar.rangeBarGroupRows,this.isFunnel=this.barOptions.isFunnel,this.xyRatios=t,this.xyRatios!==null&&(this.xRatio=t.xRatio,this.yRatio=t.yRatio,this.invertedXRatio=t.invertedXRatio,this.invertedYRatio=t.invertedYRatio,this.baseLineY=t.baseLineY,this.baseLineInvertedY=t.baseLineInvertedY),this.yaxisIndex=0,this.translationsIndex=0,this.seriesLen=0,this.pathArr=[];var a=new Le(this.ctx);this.lastActiveBarSerieIndex=a.getActiveConfigSeriesIndex("desc",["bar","column"]),this.columnGroupIndices=[];var s=a.getBarSeriesIndices(),r=new he(this.ctx);this.stackedSeriesTotals=r.getStackedSeriesTotals(this.w.config.series.map((function(n,l){return s.indexOf(l)===-1?l:-1})).filter((function(n){return n!==-1}))),this.barHelpers=new qs(this)}return O(o,[{key:"draw",value:function(e,t){var i=this.w,a=new X(this.ctx),s=new he(this.ctx,i);e=s.getLogSeries(e),this.series=e,this.yRatio=s.getLogYRatios(this.yRatio),this.barHelpers.initVariables(e);var r=a.group({class:"apexcharts-bar-series apexcharts-plot-series"});i.config.dataLabels.enabled&&this.totalItems>this.barOptions.dataLabels.maxItems&&console.warn("WARNING: DataLabels are enabled but there are too many to display. This may cause performance issue when rendering - ApexCharts");for(var n=0,l=0;n0&&(this.visibleI=this.visibleI+1);var k=0,y=0;this.yRatio.length>1&&(this.yaxisIndex=i.globals.seriesYAxisReverseMap[b],this.translationsIndex=b);var C=this.translationsIndex;this.isReversed=i.config.yaxis[this.yaxisIndex]&&i.config.yaxis[this.yaxisIndex].reversed;var w=this.barHelpers.initialPositions();p=w.y,k=w.barHeight,d=w.yDivision,u=w.zeroW,g=w.x,y=w.barWidth,h=w.xDivision,c=w.zeroH,this.isHorizontal||x.push(g+y/2);var A=a.group({class:"apexcharts-datalabels","data:realIndex":b});i.globals.delayedElements.push({el:A.node}),A.node.classList.add("apexcharts-element-hidden");var S=a.group({class:"apexcharts-bar-goals-markers"}),M=a.group({class:"apexcharts-bar-shadows"});i.globals.delayedElements.push({el:M.node}),M.node.classList.add("apexcharts-element-hidden");for(var P=0;P0){var Y=this.barHelpers.drawBarShadow({color:typeof E=="string"&&(E==null?void 0:E.indexOf("url"))===-1?E:L.hexToRgba(i.globals.colors[n]),prevPaths:this.pathArr[this.pathArr.length-1],currPaths:T});M.add(Y),i.config.chart.dropShadow.enabled&&new ue(this.ctx).dropShadow(Y,i.config.chart.dropShadow,b)}this.pathArr.push(T);var F=this.barHelpers.drawGoalLine({barXPosition:T.barXPosition,barYPosition:T.barYPosition,goalX:T.goalX,goalY:T.goalY,barHeight:k,barWidth:y});F&&S.add(F),p=T.y,g=T.x,P>0&&x.push(g+y/2),f.push(p),this.renderSeries({realIndex:b,pathFill:E,j:P,i:n,columnGroupIndex:m,pathFrom:T.pathFrom,pathTo:T.pathTo,strokeWidth:I,elSeries:v,x:g,y:p,series:e,barHeight:Math.abs(T.barHeight?T.barHeight:k),barWidth:Math.abs(T.barWidth?T.barWidth:y),elDataLabelsWrap:A,elGoalsMarkers:S,elBarShadows:M,visibleSeries:this.visibleI,type:"bar"})}i.globals.seriesXvalues[b]=x,i.globals.seriesYvalues[b]=f,r.add(v)}return r}},{key:"renderSeries",value:function(e){var t=e.realIndex,i=e.pathFill,a=e.lineFill,s=e.j,r=e.i,n=e.columnGroupIndex,l=e.pathFrom,h=e.pathTo,d=e.strokeWidth,c=e.elSeries,u=e.x,g=e.y,p=e.y1,f=e.y2,x=e.series,b=e.barHeight,m=e.barWidth,v=e.barXPosition,k=e.barYPosition,y=e.elDataLabelsWrap,C=e.elGoalsMarkers,w=e.elBarShadows,A=e.visibleSeries,S=e.type,M=e.classes,P=this.w,I=new X(this.ctx);if(!a){var T=typeof P.globals.stroke.colors[t]=="function"?(function(_){var W,G=P.config.stroke.colors;return Array.isArray(G)&&G.length>0&&((W=G[_])||(W=""),typeof W=="function")?W({value:P.globals.series[_][s],dataPointIndex:s,w:P}):W})(t):P.globals.stroke.colors[t];a=this.barOptions.distributed?P.globals.stroke.colors[s]:T}P.config.series[r].data[s]&&P.config.series[r].data[s].strokeColor&&(a=P.config.series[r].data[s].strokeColor),this.isNullValue&&(i="none");var z=s/P.config.chart.animations.animateGradually.delay*(P.config.chart.animations.speed/P.globals.dataPoints)/2.4,E=I.renderPaths({i:r,j:s,realIndex:t,pathFrom:l,pathTo:h,stroke:a,strokeWidth:d,strokeLineCap:P.config.stroke.lineCap,fill:i,animationDelay:z,initialSpeed:P.config.chart.animations.speed,dataChangeSpeed:P.config.chart.animations.dynamicAnimation.speed,className:"apexcharts-".concat(S,"-area ").concat(M),chartType:S});E.attr("clip-path","url(#gridRectBarMask".concat(P.globals.cuid,")"));var Y=P.config.forecastDataPoints;Y.count>0&&s>=P.globals.dataPoints-Y.count&&(E.node.setAttribute("stroke-dasharray",Y.dashArray),E.node.setAttribute("stroke-width",Y.strokeWidth),E.node.setAttribute("fill-opacity",Y.fillOpacity)),p!==void 0&&f!==void 0&&(E.attr("data-range-y1",p),E.attr("data-range-y2",f)),new ue(this.ctx).setSelectionFilter(E,t,s),c.add(E);var F=new Us(this).handleBarDataLabels({x:u,y:g,y1:p,y2:f,i:r,j:s,series:x,realIndex:t,columnGroupIndex:n,barHeight:b,barWidth:m,barXPosition:v,barYPosition:k,renderedPath:E,visibleSeries:A});return F.dataLabels!==null&&y.add(F.dataLabels),F.totalDataLabels&&y.add(F.totalDataLabels),c.add(y),C&&c.add(C),w&&c.add(w),c}},{key:"drawBarPaths",value:function(e){var t,i=e.indexes,a=e.barHeight,s=e.strokeWidth,r=e.zeroW,n=e.x,l=e.y,h=e.yDivision,d=e.elSeries,c=this.w,u=i.i,g=i.j;if(c.globals.isXNumeric)t=(l=(c.globals.seriesX[u][g]-c.globals.minX)/this.invertedXRatio-a)+a*this.visibleI;else if(c.config.plotOptions.bar.hideZeroBarsWhenGrouped){var p=0,f=0;c.globals.seriesPercent.forEach((function(b,m){b[g]&&p++,m0&&(a=this.seriesLen*a/p),t=l+a*this.visibleI,t-=a*f}else t=l+a*this.visibleI;this.isFunnel&&(r-=(this.barHelpers.getXForValue(this.series[u][g],r)-r)/2),n=this.barHelpers.getXForValue(this.series[u][g],r);var x=this.barHelpers.getBarpaths({barYPosition:t,barHeight:a,x1:r,x2:n,strokeWidth:s,isReversed:this.isReversed,series:this.series,realIndex:i.realIndex,i:u,j:g,w:c});return c.globals.isXNumeric||(l+=h),this.barHelpers.barBackground({j:g,i:u,y1:t-a*this.visibleI,y2:a*this.seriesLen,elSeries:d}),{pathTo:x.pathTo,pathFrom:x.pathFrom,x1:r,x:n,y:l,goalX:this.barHelpers.getGoalValues("x",r,null,u,g),barYPosition:t,barHeight:a}}},{key:"drawColumnPaths",value:function(e){var t,i=e.indexes,a=e.x,s=e.y,r=e.xDivision,n=e.barWidth,l=e.zeroH,h=e.strokeWidth,d=e.elSeries,c=this.w,u=i.realIndex,g=i.translationsIndex,p=i.i,f=i.j,x=i.bc;if(c.globals.isXNumeric){var b=this.getBarXForNumericXAxis({x:a,j:f,realIndex:u,barWidth:n});a=b.x,t=b.barXPosition}else if(c.config.plotOptions.bar.hideZeroBarsWhenGrouped){var m=this.barHelpers.getZeroValueEncounters({i:p,j:f}),v=m.nonZeroColumns,k=m.zeroEncounters;v>0&&(n=this.seriesLen*n/v),t=a+n*this.visibleI,t-=n*k}else t=a+n*this.visibleI;s=this.barHelpers.getYForValue(this.series[p][f],l,g);var y=this.barHelpers.getColumnPaths({barXPosition:t,barWidth:n,y1:l,y2:s,strokeWidth:h,isReversed:this.isReversed,series:this.series,realIndex:u,i:p,j:f,w:c});return c.globals.isXNumeric||(a+=r),this.barHelpers.barBackground({bc:x,j:f,i:p,x1:t-h/2-n*this.visibleI,x2:n*this.seriesLen+h/2,elSeries:d}),{pathTo:y.pathTo,pathFrom:y.pathFrom,x:a,y:s,goalY:this.barHelpers.getGoalValues("y",null,l,p,f,g),barXPosition:t,barWidth:n}}},{key:"getBarXForNumericXAxis",value:function(e){var t=e.x,i=e.barWidth,a=e.realIndex,s=e.j,r=this.w,n=a;return r.globals.seriesX[a].length||(n=r.globals.maxValsInArrayIndex),L.isNumber(r.globals.seriesX[n][s])&&(t=(r.globals.seriesX[n][s]-r.globals.minX)/this.xRatio-i*this.seriesLen/2),{barXPosition:t+i*this.visibleI,x:t}}},{key:"getPreviousPath",value:function(e,t){for(var i,a=this.w,s=0;s0&&parseInt(r.realIndex,10)===parseInt(e,10)&&a.globals.previousPaths[s].paths[t]!==void 0&&(i=a.globals.previousPaths[s].paths[t].d)}return i}}]),o})(),Ya=(function(o){ht(t,nt);var e=lt(t);function t(){return H(this,t),e.apply(this,arguments)}return O(t,[{key:"draw",value:function(i,a){var s=this,r=this.w;this.graphics=new X(this.ctx),this.bar=new nt(this.ctx,this.xyRatios);var n=new he(this.ctx,r);i=n.getLogSeries(i),this.yRatio=n.getLogYRatios(this.yRatio),this.barHelpers.initVariables(i),r.config.chart.stackType==="100%"&&(i=r.globals.comboCharts?a.map((function(p){return r.globals.seriesPercent[p]})):r.globals.seriesPercent.slice()),this.series=i,this.barHelpers.initializeStackedPrevVars(this);for(var l=this.graphics.group({class:"apexcharts-bar-series apexcharts-plot-series"}),h=0,d=0,c=function(p,f){var x=void 0,b=void 0,m=void 0,v=void 0,k=r.globals.comboCharts?a[p]:p,y=s.barHelpers.getGroupIndex(k),C=y.groupIndex,w=y.columnGroupIndex;s.groupCtx=s[r.globals.seriesGroups[C]];var A=[],S=[],M=0;s.yRatio.length>1&&(s.yaxisIndex=r.globals.seriesYAxisReverseMap[k][0],M=k),s.isReversed=r.config.yaxis[s.yaxisIndex]&&r.config.yaxis[s.yaxisIndex].reversed;var P=s.graphics.group({class:"apexcharts-series",seriesName:L.escapeString(r.globals.seriesNames[k]),rel:p+1,"data:realIndex":k});s.ctx.series.addCollapsedClassToSeries(P,k);var I=s.graphics.group({class:"apexcharts-datalabels","data:realIndex":k}),T=s.graphics.group({class:"apexcharts-bar-goals-markers"}),z=0,E=0,Y=s.initialPositions(h,d,x,b,m,v,M);d=Y.y,z=Y.barHeight,b=Y.yDivision,v=Y.zeroW,h=Y.x,E=Y.barWidth,x=Y.xDivision,m=Y.zeroH,r.globals.barHeight=z,r.globals.barWidth=E,s.barHelpers.initializeStackedXYVars(s),s.groupCtx.prevY.length===1&&s.groupCtx.prevY[0].every((function(fe){return isNaN(fe)}))&&(s.groupCtx.prevY[0]=s.groupCtx.prevY[0].map((function(){return m})),s.groupCtx.prevYF[0]=s.groupCtx.prevYF[0].map((function(){return 0})));for(var F=0;F0||s.barHelpers.arrBorderRadius[k][F]==="top"&&r.globals.series[k][F]<0)&&(oe=se),P=s.renderSeries({realIndex:k,pathFill:ne,j:F,i:p,columnGroupIndex:w,pathFrom:G.pathFrom,pathTo:G.pathTo,strokeWidth:_,elSeries:P,x:h,y:d,series:i,barHeight:z,barWidth:E,elDataLabelsWrap:I,elGoalsMarkers:T,type:"bar",visibleSeries:w,classes:oe})}r.globals.seriesXvalues[k]=A,r.globals.seriesYvalues[k]=S,s.groupCtx.prevY.push(s.groupCtx.yArrj),s.groupCtx.prevYF.push(s.groupCtx.yArrjF),s.groupCtx.prevYVal.push(s.groupCtx.yArrjVal),s.groupCtx.prevX.push(s.groupCtx.xArrj),s.groupCtx.prevXF.push(s.groupCtx.xArrjF),s.groupCtx.prevXVal.push(s.groupCtx.xArrjVal),l.add(P)},u=0,g=0;u1?c=(s=u.globals.minXDiff/this.xRatio)*parseInt(this.barOptions.columnWidth,10)/100:String(p).indexOf("%")===-1?c=parseInt(p,10):c*=parseInt(p,10)/100,n=this.isReversed?this.baseLineY[h]:u.globals.gridHeight-this.baseLineY[h],i=u.globals.padHorizontal+(s-c)/2}var f=u.globals.barGroups.length||1;return{x:i,y:a,yDivision:r,xDivision:s,barHeight:d/f,barWidth:c/f,zeroH:n,zeroW:l}}},{key:"drawStackedBarPaths",value:function(i){for(var a,s=i.indexes,r=i.barHeight,n=i.strokeWidth,l=i.zeroW,h=i.x,d=i.y,c=i.columnGroupIndex,u=i.seriesGroup,g=i.yDivision,p=i.elSeries,f=this.w,x=d+c*r,b=s.i,m=s.j,v=s.realIndex,k=s.translationsIndex,y=0,C=0;C0){var A=l;this.groupCtx.prevXVal[w-1][m]<0?A=this.series[b][m]>=0?this.groupCtx.prevX[w-1][m]+y-2*(this.isReversed?y:0):this.groupCtx.prevX[w-1][m]:this.groupCtx.prevXVal[w-1][m]>=0&&(A=this.series[b][m]>=0?this.groupCtx.prevX[w-1][m]:this.groupCtx.prevX[w-1][m]-y+2*(this.isReversed?y:0)),a=A}else a=l;h=this.series[b][m]===null?a:a+this.series[b][m]/this.invertedYRatio-2*(this.isReversed?this.series[b][m]/this.invertedYRatio:0);var S=this.barHelpers.getBarpaths({barYPosition:x,barHeight:r,x1:a,x2:h,strokeWidth:n,isReversed:this.isReversed,series:this.series,realIndex:s.realIndex,seriesGroup:u,i:b,j:m,w:f});return this.barHelpers.barBackground({j:m,i:b,y1:x,y2:r,elSeries:p}),d+=g,{pathTo:S.pathTo,pathFrom:S.pathFrom,goalX:this.barHelpers.getGoalValues("x",l,null,b,m,k),barXPosition:a,barYPosition:x,x:h,y:d}}},{key:"drawStackedColumnPaths",value:function(i){var a=i.indexes,s=i.x,r=i.y,n=i.xDivision,l=i.barWidth,h=i.zeroH,d=i.columnGroupIndex,c=i.seriesGroup,u=i.elSeries,g=this.w,p=a.i,f=a.j,x=a.bc,b=a.realIndex,m=a.translationsIndex;if(g.globals.isXNumeric){var v=g.globals.seriesX[b][f];v||(v=0),s=(v-g.globals.minX)/this.xRatio-l/2*g.globals.barGroups.length}for(var k,y=s+d*l,C=0,w=0;w0&&!g.globals.isXNumeric||A>0&&g.globals.isXNumeric&&g.globals.seriesX[b-1][f]===g.globals.seriesX[b][f]){var S,M,P,I=Math.min(this.yRatio.length+1,b+1);if(this.groupCtx.prevY[A-1]!==void 0&&this.groupCtx.prevY[A-1].length)for(var T=1;T=0?P-C+2*(this.isReversed?C:0):P;break}if(((F=this.groupCtx.prevYVal[A-E])===null||F===void 0?void 0:F[f])>=0){M=this.series[p][f]>=0?P:P+C-2*(this.isReversed?C:0);break}}M===void 0&&(M=g.globals.gridHeight),k=(S=this.groupCtx.prevYF[0])!==null&&S!==void 0&&S.every((function(W){return W===0}))&&this.groupCtx.prevYF.slice(1,A).every((function(W){return W.every((function(G){return isNaN(G)}))}))?h:M}else k=h;r=this.series[p][f]?k-this.series[p][f]/this.yRatio[m]+2*(this.isReversed?this.series[p][f]/this.yRatio[m]:0):k;var _=this.barHelpers.getColumnPaths({barXPosition:y,barWidth:l,y1:k,y2:r,yRatio:this.yRatio[m],strokeWidth:this.strokeWidth,isReversed:this.isReversed,series:this.series,seriesGroup:c,realIndex:a.realIndex,i:p,j:f,w:g});return this.barHelpers.barBackground({bc:x,j:f,i:p,x1:y,x2:l,elSeries:u}),{pathTo:_.pathTo,pathFrom:_.pathFrom,goalY:this.barHelpers.getGoalValues("y",null,h,p,f),barXPosition:y,x:g.globals.isXNumeric?s:s+n,y:r}}}]),t})(),Mi=(function(o){ht(t,nt);var e=lt(t);function t(){return H(this,t),e.apply(this,arguments)}return O(t,[{key:"draw",value:function(i,a,s){var r=this,n=this.w,l=new X(this.ctx),h=n.globals.comboCharts?a:n.config.chart.type,d=new Ie(this.ctx);this.candlestickOptions=this.w.config.plotOptions.candlestick,this.boxOptions=this.w.config.plotOptions.boxPlot,this.isHorizontal=n.config.plotOptions.bar.horizontal;var c=new he(this.ctx,n);i=c.getLogSeries(i),this.series=i,this.yRatio=c.getLogYRatios(this.yRatio),this.barHelpers.initVariables(i);for(var u=l.group({class:"apexcharts-".concat(h,"-series apexcharts-plot-series")}),g=function(f){r.isBoxPlot=n.config.chart.type==="boxPlot"||n.config.series[f].type==="boxPlot";var x,b,m,v,k=void 0,y=void 0,C=[],w=[],A=n.globals.comboCharts?s[f]:f,S=r.barHelpers.getGroupIndex(A).columnGroupIndex,M=l.group({class:"apexcharts-series",seriesName:L.escapeString(n.globals.seriesNames[A]),rel:f+1,"data:realIndex":A});r.ctx.series.addCollapsedClassToSeries(M,A),i[f].length>0&&(r.visibleI=r.visibleI+1);var P,I,T=0;r.yRatio.length>1&&(r.yaxisIndex=n.globals.seriesYAxisReverseMap[A][0],T=A);var z=r.barHelpers.initialPositions();y=z.y,P=z.barHeight,b=z.yDivision,v=z.zeroW,k=z.x,I=z.barWidth,x=z.xDivision,m=z.zeroH,w.push(k+I/2);for(var E=l.group({class:"apexcharts-datalabels","data:realIndex":A}),Y=l.group({class:"apexcharts-bar-goals-markers"}),F=function(W){var G=r.barHelpers.getStrokeWidth(f,W,A),B=null,ne={indexes:{i:f,j:W,realIndex:A,translationsIndex:T},x:k,y,strokeWidth:G,elSeries:M};B=r.isHorizontal?r.drawHorizontalBoxPaths(R(R({},ne),{},{yDivision:b,barHeight:P,zeroW:v})):r.drawVerticalBoxPaths(R(R({},ne),{},{xDivision:x,barWidth:I,zeroH:m})),y=B.y,k=B.x;var oe=r.barHelpers.drawGoalLine({barXPosition:B.barXPosition,barYPosition:B.barYPosition,goalX:B.goalX,goalY:B.goalY,barHeight:P,barWidth:I});oe&&Y.add(oe),W>0&&w.push(k+I/2),C.push(y),B.pathTo.forEach((function(se,fe){var J=!r.isBoxPlot&&r.candlestickOptions.wick.useFillColor?B.color[fe]:n.globals.stroke.colors[f],$=d.fillPath({seriesNumber:A,dataPointIndex:W,color:B.color[fe],value:i[f][W]});r.renderSeries({realIndex:A,pathFill:$,lineFill:J,j:W,i:f,pathFrom:B.pathFrom,pathTo:se,strokeWidth:G,elSeries:M,x:k,y,series:i,columnGroupIndex:S,barHeight:P,barWidth:I,elDataLabelsWrap:E,elGoalsMarkers:Y,visibleSeries:r.visibleI,type:n.config.chart.type})}))},_=0;_0&&(z=this.getPreviousPath(x,g,!0)),T=this.isBoxPlot?[c.move(I,S)+c.line(I+n/2,S)+c.line(I+n/2,C)+c.line(I+n/4,C)+c.line(I+n-n/4,C)+c.line(I+n/2,C)+c.line(I+n/2,S)+c.line(I+n,S)+c.line(I+n,P)+c.line(I,P)+c.line(I,S+h/2),c.move(I,P)+c.line(I+n,P)+c.line(I+n,M)+c.line(I+n/2,M)+c.line(I+n/2,w)+c.line(I+n-n/4,w)+c.line(I+n/4,w)+c.line(I+n/2,w)+c.line(I+n/2,M)+c.line(I,M)+c.line(I,P)+"z"]:[c.move(I,M)+c.line(I+n/2,M)+c.line(I+n/2,C)+c.line(I+n/2,M)+c.line(I+n,M)+c.line(I+n,S)+c.line(I+n/2,S)+c.line(I+n/2,w)+c.line(I+n/2,S)+c.line(I,S)+c.line(I,M-h/2)],z+=c.move(I,S),d.globals.isXNumeric||(s+=r),{pathTo:T,pathFrom:z,x:s,y:M,goalY:this.barHelpers.getGoalValues("y",null,l,u,g,a.translationsIndex),barXPosition:I,color:A}}},{key:"drawHorizontalBoxPaths",value:function(i){var a=i.indexes;i.x;var s=i.y,r=i.yDivision,n=i.barHeight,l=i.zeroW,h=i.strokeWidth,d=this.w,c=new X(this.ctx),u=a.i,g=a.j,p=this.boxOptions.colors.lower;this.isBoxPlot&&(p=[this.boxOptions.colors.lower,this.boxOptions.colors.upper]);var f=this.invertedYRatio,x=a.realIndex,b=this.getOHLCValue(x,g),m=l,v=l,k=Math.min(b.o,b.c),y=Math.max(b.o,b.c),C=b.m;d.globals.isXNumeric&&(s=(d.globals.seriesX[x][g]-d.globals.minX)/this.invertedXRatio-n/2);var w=s+n*this.visibleI;this.series[u][g]===void 0||this.series[u][g]===null?(k=l,y=l):(k=l+k/f,y=l+y/f,m=l+b.h/f,v=l+b.l/f,C=l+b.m/f);var A=c.move(l,w),S=c.move(k,w+n/2);return d.globals.previousPaths.length>0&&(S=this.getPreviousPath(x,g,!0)),A=[c.move(k,w)+c.line(k,w+n/2)+c.line(m,w+n/2)+c.line(m,w+n/2-n/4)+c.line(m,w+n/2+n/4)+c.line(m,w+n/2)+c.line(k,w+n/2)+c.line(k,w+n)+c.line(C,w+n)+c.line(C,w)+c.line(k+h/2,w),c.move(C,w)+c.line(C,w+n)+c.line(y,w+n)+c.line(y,w+n/2)+c.line(v,w+n/2)+c.line(v,w+n-n/4)+c.line(v,w+n/4)+c.line(v,w+n/2)+c.line(y,w+n/2)+c.line(y,w)+c.line(C,w)+"z"],S+=c.move(k,w),d.globals.isXNumeric||(s+=r),{pathTo:A,pathFrom:S,x:y,y:s,goalX:this.barHelpers.getGoalValues("x",l,null,u,g),barYPosition:w,color:p}}},{key:"getOHLCValue",value:function(i,a){var s=this.w,r=new he(this.ctx,s),n=r.getLogValAtSeriesIndex(s.globals.seriesCandleH[i][a],i),l=r.getLogValAtSeriesIndex(s.globals.seriesCandleO[i][a],i),h=r.getLogValAtSeriesIndex(s.globals.seriesCandleM[i][a],i),d=r.getLogValAtSeriesIndex(s.globals.seriesCandleC[i][a],i),c=r.getLogValAtSeriesIndex(s.globals.seriesCandleL[i][a],i);return{o:this.isBoxPlot?n:l,h:this.isBoxPlot?l:n,m:h,l:this.isBoxPlot?d:c,c:this.isBoxPlot?c:d}}}]),t})(),Ha=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"checkColorRange",value:function(){var e=this.w,t=!1,i=e.config.plotOptions[e.config.chart.type];return i.colorScale.ranges.length>0&&i.colorScale.ranges.map((function(a,s){a.from<=0&&(t=!0)})),t}},{key:"getShadeColor",value:function(e,t,i,a){var s=this.w,r=1,n=s.config.plotOptions[e].shadeIntensity,l=this.determineColor(e,t,i);s.globals.hasNegs||a?r=s.config.plotOptions[e].reverseNegativeShade?l.percent<0?l.percent/100*(1.25*n):(1-l.percent/100)*(1.25*n):l.percent<=0?1-(1+l.percent/100)*n:(1-l.percent/100)*n:(r=1-l.percent/100,e==="treemap"&&(r=(1-l.percent/100)*(1.25*n)));var h=l.color,d=new L;if(s.config.plotOptions[e].enableShades)if(this.w.config.theme.mode==="dark"){var c=d.shadeColor(-1*r,l.color);h=L.hexToRgba(L.isColorHex(c)?c:L.rgb2hex(c),s.config.fill.opacity)}else{var u=d.shadeColor(r,l.color);h=L.hexToRgba(L.isColorHex(u)?u:L.rgb2hex(u),s.config.fill.opacity)}return{color:h,colorProps:l}}},{key:"determineColor",value:function(e,t,i){var a=this.w,s=a.globals.series[t][i],r=a.config.plotOptions[e],n=r.colorScale.inverse?i:t;r.distributed&&a.config.chart.type==="treemap"&&(n=i);var l=a.globals.colors[n],h=null,d=Math.min.apply(Math,ce(a.globals.series[t])),c=Math.max.apply(Math,ce(a.globals.series[t]));r.distributed||e!=="heatmap"||(d=a.globals.minY,c=a.globals.maxY),r.colorScale.min!==void 0&&(d=r.colorScale.mina.globals.maxY?r.colorScale.max:a.globals.maxY);var u=Math.abs(c)+Math.abs(d),g=100*s/(u===0?u-1e-6:u);return r.colorScale.ranges.length>0&&r.colorScale.ranges.map((function(p,f){if(s>=p.from&&s<=p.to){l=p.color,h=p.foreColor?p.foreColor:null,d=p.from,c=p.to;var x=Math.abs(c)+Math.abs(d);g=100*s/(x===0?x-1e-6:x)}})),{color:l,foreColor:h,percent:g}}},{key:"calculateDataLabels",value:function(e){var t=e.text,i=e.x,a=e.y,s=e.i,r=e.j,n=e.colorProps,l=e.fontSize,h=this.w.config.dataLabels,d=new X(this.ctx),c=new rt(this.ctx),u=null;if(h.enabled){u=d.group({class:"apexcharts-data-labels"});var g=h.offsetX,p=h.offsetY,f=i+g,x=a+parseFloat(h.style.fontSize)/3+p;c.plotDataLabelsText({x:f,y:x,text:t,i:s,j:r,color:n.foreColor,parent:u,fontSize:l,dataLabelsConfig:h})}return u}},{key:"addListeners",value:function(e){var t=new X(this.ctx);e.node.addEventListener("mouseenter",t.pathMouseEnter.bind(this,e)),e.node.addEventListener("mouseleave",t.pathMouseLeave.bind(this,e)),e.node.addEventListener("mousedown",t.pathMouseDown.bind(this,e))}}]),o})(),Zs=(function(){function o(e,t){H(this,o),this.ctx=e,this.w=e.w,this.xRatio=t.xRatio,this.yRatio=t.yRatio,this.dynamicAnim=this.w.config.chart.animations.dynamicAnimation,this.helpers=new Ha(e),this.rectRadius=this.w.config.plotOptions.heatmap.radius,this.strokeWidth=this.w.config.stroke.show?this.w.config.stroke.width:0}return O(o,[{key:"draw",value:function(e){var t=this.w,i=new X(this.ctx),a=i.group({class:"apexcharts-heatmap"});a.attr("clip-path","url(#gridRectMask".concat(t.globals.cuid,")"));var s=t.globals.gridWidth/t.globals.dataPoints,r=t.globals.gridHeight/t.globals.series.length,n=0,l=!1;this.negRange=this.helpers.checkColorRange();var h=e.slice();t.config.yaxis[0].reversed&&(l=!0,h.reverse());for(var d=l?0:h.length-1;l?d=0;l?d++:d--){var c=i.group({class:"apexcharts-series apexcharts-heatmap-series",seriesName:L.escapeString(t.globals.seriesNames[d]),rel:d+1,"data:realIndex":d});if(this.ctx.series.addCollapsedClassToSeries(c,d),t.config.chart.dropShadow.enabled){var u=t.config.chart.dropShadow;new ue(this.ctx).dropShadow(c,u,d)}for(var g=0,p=t.config.plotOptions.heatmap.shadeIntensity,f=0,x=0;x=h[d].length)break;var b=this.helpers.getShadeColor(t.config.chart.type,d,f,this.negRange),m=b.color,v=b.colorProps;t.config.fill.type==="image"&&(m=new Ie(this.ctx).fillPath({seriesNumber:d,dataPointIndex:f,opacity:t.globals.hasNegs?v.percent<0?1-(1+v.percent/100):p+v.percent/100:v.percent/100,patternID:L.randomId(),width:t.config.fill.image.width?t.config.fill.image.width:s,height:t.config.fill.image.height?t.config.fill.image.height:r}));var k=this.rectRadius,y=i.drawRect(g,n,s,r,k);if(y.attr({cx:g,cy:n}),y.node.classList.add("apexcharts-heatmap-rect"),c.add(y),y.attr({fill:m,i:d,index:d,j:f,val:e[d][f],"stroke-width":this.strokeWidth,stroke:t.config.plotOptions.heatmap.useFillColorAsStroke?m:t.globals.stroke.colors[0],color:m}),this.helpers.addListeners(y),t.config.chart.animations.enabled&&!t.globals.dataChanged){var C=1;t.globals.resized||(C=t.config.chart.animations.speed),this.animateHeatMap(y,g,n,s,r,C)}if(t.globals.dataChanged){var w=1;if(this.dynamicAnim.enabled&&t.globals.shouldAnimate){w=this.dynamicAnim.speed;var A=t.globals.previousPaths[d]&&t.globals.previousPaths[d][f]&&t.globals.previousPaths[d][f].color;A||(A="rgba(255, 255, 255, 0)"),this.animateHeatColor(y,L.isColorHex(A)?A:L.rgb2hex(A),L.isColorHex(m)?m:L.rgb2hex(m),w)}}var S=(0,t.config.dataLabels.formatter)(t.globals.series[d][f],{value:t.globals.series[d][f],seriesIndex:d,dataPointIndex:f,w:t}),M=this.helpers.calculateDataLabels({text:S,x:g+s/2,y:n+r/2,i:d,j:f,colorProps:v,series:h});M!==null&&c.add(M),g+=s,f++}n+=r,a.add(c)}var P=t.globals.yAxisScale[0].result.slice();return t.config.yaxis[0].reversed?P.unshift(""):P.push(""),t.globals.yAxisScale[0].result=P,a}},{key:"animateHeatMap",value:function(e,t,i,a,s,r){var n=new $e(this.ctx);n.animateRect(e,{x:t+a/2,y:i+s/2,width:0,height:0},{x:t,y:i,width:a,height:s},r,(function(){n.animationCompleted(e)}))}},{key:"animateHeatColor",value:function(e,t,i,a){e.attr({fill:t}).animate(a).attr({fill:i})}}]),o})(),Oa=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"drawYAxisTexts",value:function(e,t,i,a){var s=this.w,r=s.config.yaxis[0],n=s.globals.yLabelFormatters[0];return new X(this.ctx).drawText({x:e+r.labels.offsetX,y:t+r.labels.offsetY,text:n(a,i),textAnchor:"middle",fontSize:r.labels.style.fontSize,fontFamily:r.labels.style.fontFamily,foreColor:Array.isArray(r.labels.style.colors)?r.labels.style.colors[i]:r.labels.style.colors})}}]),o})(),Fa=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w;var t=this.w;this.chartType=this.w.config.chart.type,this.initialAnim=this.w.config.chart.animations.enabled,this.dynamicAnim=this.initialAnim&&this.w.config.chart.animations.dynamicAnimation.enabled,this.animBeginArr=[0],this.animDur=0,this.donutDataLabels=this.w.config.plotOptions.pie.donut.labels,this.lineColorArr=t.globals.stroke.colors!==void 0?t.globals.stroke.colors:t.globals.colors,this.defaultSize=Math.min(t.globals.gridWidth,t.globals.gridHeight),this.centerY=this.defaultSize/2,this.centerX=t.globals.gridWidth/2,t.config.chart.type==="radialBar"?this.fullAngle=360:this.fullAngle=Math.abs(t.config.plotOptions.pie.endAngle-t.config.plotOptions.pie.startAngle),this.initialAngle=t.config.plotOptions.pie.startAngle%this.fullAngle,t.globals.radialSize=this.defaultSize/2.05-t.config.stroke.width-(t.config.chart.sparkline.enabled?0:t.config.chart.dropShadow.blur),this.donutSize=t.globals.radialSize*parseInt(t.config.plotOptions.pie.donut.size,10)/100;var i=t.config.plotOptions.pie.customScale,a=t.globals.gridWidth/2,s=t.globals.gridHeight/2;this.translateX=a-a*i,this.translateY=s-s*i,this.dataLabelsGroup=new X(this.ctx).group({class:"apexcharts-datalabels-group",transform:"translate(".concat(this.translateX,", ").concat(this.translateY,") scale(").concat(i,")")}),this.maxY=0,this.sliceLabels=[],this.sliceSizes=[],this.prevSectorAngleArr=[]}return O(o,[{key:"draw",value:function(e){var t=this,i=this.w,a=new X(this.ctx),s=a.group({class:"apexcharts-pie"});if(i.globals.noData)return s;for(var r=0,n=0;n-1&&this.pieClicked(u),i.config.dataLabels.enabled){var y=v.x,C=v.y,w=100*p/this.fullAngle+"%";if(p!==0&&i.config.plotOptions.pie.dataLabels.minAngleToShowLabelthis.fullAngle?t.endAngle=t.endAngle-(a+n):a+n=this.fullAngle+this.w.config.plotOptions.pie.startAngle%this.fullAngle&&(d=this.fullAngle+this.w.config.plotOptions.pie.startAngle%this.fullAngle-.01),Math.ceil(d)>this.fullAngle&&(d-=this.fullAngle);var c=Math.PI*(d-90)/180,u=i.centerX+r*Math.cos(h),g=i.centerY+r*Math.sin(h),p=i.centerX+r*Math.cos(c),f=i.centerY+r*Math.sin(c),x=L.polarToCartesian(i.centerX,i.centerY,i.donutSize,d),b=L.polarToCartesian(i.centerX,i.centerY,i.donutSize,l),m=s>180?1:0,v=["M",u,g,"A",r,r,0,m,1,p,f];return t=i.chartType==="donut"?[].concat(v,["L",x.x,x.y,"A",i.donutSize,i.donutSize,0,m,0,b.x,b.y,"L",u,g,"z"]).join(" "):i.chartType==="pie"||i.chartType==="polarArea"?[].concat(v,["L",i.centerX,i.centerY,"L",u,g]).join(" "):[].concat(v).join(" "),n.roundPathCorners(t,2*this.strokeWidth)}},{key:"drawPolarElements",value:function(e){var t=this.w,i=new Ia(this.ctx),a=new X(this.ctx),s=new Oa(this.ctx),r=a.group(),n=a.group(),l=i.niceScale(0,Math.ceil(this.maxY),0),h=l.result.reverse(),d=l.result.length;this.maxY=l.niceMax;for(var c=t.globals.radialSize,u=c/(d-1),g=0;g1&&e.total.show&&(s=e.total.color);var n=r.globals.dom.baseEl.querySelector(".apexcharts-datalabel-label"),l=r.globals.dom.baseEl.querySelector(".apexcharts-datalabel-value");i=(0,e.value.formatter)(i,r),a||typeof e.total.formatter!="function"||(i=e.total.formatter(r));var h=t===e.total.label;t=this.donutDataLabels.total.label?e.name.formatter(t,h,r):"",n!==null&&(n.textContent=t),l!==null&&(l.textContent=i),n!==null&&(n.style.fill=s)}},{key:"printDataLabelsInner",value:function(e,t){var i=this.w,a=e.getAttribute("data:value"),s=i.globals.seriesNames[parseInt(e.parentNode.getAttribute("rel"),10)-1];i.globals.series.length>1&&this.printInnerLabels(t,s,a,e);var r=i.globals.dom.baseEl.querySelector(".apexcharts-datalabels-group");r!==null&&(r.style.opacity=1)}},{key:"drawSpokes",value:function(e){var t=this,i=this.w,a=new X(this.ctx),s=i.config.plotOptions.polarArea.spokes;if(s.strokeWidth!==0){for(var r=[],n=360/i.globals.series.length,l=0;l0&&(C=t.getPreviousPath(b));for(var w=0;w=10?e.x>0?(i="start",a+=10):e.x<0&&(i="end",a-=10):i="middle",Math.abs(e.y)>=t-10&&(e.y<0?s-=10:e.y>0&&(s+=10)),{textAnchor:i,newX:a,newY:s}}},{key:"getPreviousPath",value:function(e){for(var t=this.w,i=null,a=0;a0&&parseInt(s.realIndex,10)===parseInt(e,10)&&t.globals.previousPaths[a].paths[0]!==void 0&&(i=t.globals.previousPaths[a].paths[0].d)}return i}},{key:"getDataPointsPos",value:function(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.dataPointsLen;e=e||[],t=t||[];for(var a=[],s=0;s=360&&(f=360-Math.abs(this.startAngle)-.1);var x=s.drawPath({d:"",stroke:g,strokeWidth:h*parseInt(u.strokeWidth,10)/100,fill:"none",strokeOpacity:u.opacity,classes:"apexcharts-radialbar-area"});if(u.dropShadow.enabled){var b=u.dropShadow;n.dropShadow(x,b)}c.add(x),x.attr("id","apexcharts-radialbarTrack-"+d),this.animatePaths(x,{centerX:i.centerX,centerY:i.centerY,endAngle:f,startAngle:p,size:i.size,i:d,totalItems:2,animBeginArr:0,dur:0,isTrack:!0})}return r}},{key:"drawArcs",value:function(i){var a=this.w,s=new X(this.ctx),r=new Ie(this.ctx),n=new ue(this.ctx),l=s.group(),h=this.getStrokeWidth(i);i.size=i.size-h/2;var d=a.config.plotOptions.radialBar.hollow.background,c=i.size-h*i.series.length-this.margin*i.series.length-h*parseInt(a.config.plotOptions.radialBar.track.strokeWidth,10)/100/2,u=c-a.config.plotOptions.radialBar.hollow.margin;a.config.plotOptions.radialBar.hollow.image!==void 0&&(d=this.drawHollowImage(i,l,c,d));var g=this.drawHollow({size:u,centerX:i.centerX,centerY:i.centerY,fill:d||"transparent"});if(a.config.plotOptions.radialBar.hollow.dropShadow.enabled){var p=a.config.plotOptions.radialBar.hollow.dropShadow;n.dropShadow(g,p)}var f=1;!this.radialDataLabels.total.show&&a.globals.series.length>1&&(f=0);var x=null;if(this.radialDataLabels.show){var b=a.globals.dom.Paper.findOne(".apexcharts-datalabels-group");x=this.renderInnerDataLabels(b,this.radialDataLabels,{hollowSize:c,centerX:i.centerX,centerY:i.centerY,opacity:f})}a.config.plotOptions.radialBar.hollow.position==="back"&&(l.add(g),x&&l.add(x));var m=!1;a.config.plotOptions.radialBar.inverseOrder&&(m=!0);for(var v=m?i.series.length-1:0;m?v>=0:v100?100:i.series[v])/100,S=Math.round(this.totalAngle*A)+this.startAngle,M=void 0;a.globals.dataChanged&&(w=this.startAngle,M=Math.round(this.totalAngle*L.negToZero(a.globals.previousPaths[v])/100)+w),Math.abs(S)+Math.abs(C)>360&&(S-=.01),Math.abs(M)+Math.abs(w)>360&&(M-=.01);var P=S-C,I=Array.isArray(a.config.stroke.dashArray)?a.config.stroke.dashArray[v]:a.config.stroke.dashArray,T=s.drawPath({d:"",stroke:y,strokeWidth:h,fill:"none",fillOpacity:a.config.fill.opacity,classes:"apexcharts-radialbar-area apexcharts-radialbar-slice-"+v,strokeDashArray:I});if(X.setAttrs(T.node,{"data:angle":P,"data:value":i.series[v]}),a.config.chart.dropShadow.enabled){var z=a.config.chart.dropShadow;n.dropShadow(T,z,v)}if(n.setSelectionFilter(T,0,v),this.addListeners(T,this.radialDataLabels),k.add(T),T.attr({index:0,j:v}),this.barLabels.enabled){var E=L.polarToCartesian(i.centerX,i.centerY,i.size,C),Y=this.barLabels.formatter(a.globals.seriesNames[v],{seriesIndex:v,w:a}),F=["apexcharts-radialbar-label"];this.barLabels.onClick||F.push("apexcharts-no-click");var _=this.barLabels.useSeriesColors?a.globals.colors[v]:a.config.chart.foreColor;_||(_=a.config.chart.foreColor);var W=E.x+this.barLabels.offsetX,G=E.y+this.barLabels.offsetY,B=s.drawText({x:W,y:G,text:Y,textAnchor:"end",dominantBaseline:"middle",fontFamily:this.barLabels.fontFamily,fontWeight:this.barLabels.fontWeight,fontSize:this.barLabels.fontSize,foreColor:_,cssClass:F.join(" ")});B.on("click",this.onBarLabelClick),B.attr({rel:v+1}),C!==0&&B.attr({"transform-origin":"".concat(W," ").concat(G),transform:"rotate(".concat(C," 0 0)")}),k.add(B)}var ne=0;!this.initialAnim||a.globals.resized||a.globals.dataChanged||(ne=a.config.chart.animations.speed),a.globals.dataChanged&&(ne=a.config.chart.animations.dynamicAnimation.speed),this.animDur=ne/(1.2*i.series.length)+this.animDur,this.animBeginArr.push(this.animDur),this.animatePaths(T,{centerX:i.centerX,centerY:i.centerY,endAngle:S,startAngle:C,prevEndAngle:M,prevStartAngle:w,size:i.size,i:v,totalItems:2,animBeginArr:this.animBeginArr,dur:ne,shouldSetPrevPaths:!0})}return{g:l,elHollow:g,dataLabels:x}}},{key:"drawHollow",value:function(i){var a=new X(this.ctx).drawCircle(2*i.size);return a.attr({class:"apexcharts-radialbar-hollow",cx:i.centerX,cy:i.centerY,r:i.size,fill:i.fill}),a}},{key:"drawHollowImage",value:function(i,a,s,r){var n=this.w,l=new Ie(this.ctx),h=L.randomId(),d=n.config.plotOptions.radialBar.hollow.image;if(n.config.plotOptions.radialBar.hollow.imageClipped)l.clippedImgArea({width:s,height:s,image:d,patternID:"pattern".concat(n.globals.cuid).concat(h)}),r="url(#pattern".concat(n.globals.cuid).concat(h,")");else{var c=n.config.plotOptions.radialBar.hollow.imageWidth,u=n.config.plotOptions.radialBar.hollow.imageHeight;if(c===void 0&&u===void 0){var g=n.globals.dom.Paper.image(d,(function(f){this.move(i.centerX-f.width/2+n.config.plotOptions.radialBar.hollow.imageOffsetX,i.centerY-f.height/2+n.config.plotOptions.radialBar.hollow.imageOffsetY)}));a.add(g)}else{var p=n.globals.dom.Paper.image(d,(function(f){this.move(i.centerX-c/2+n.config.plotOptions.radialBar.hollow.imageOffsetX,i.centerY-u/2+n.config.plotOptions.radialBar.hollow.imageOffsetY),this.size(c,u)}));a.add(p)}}return r}},{key:"getStrokeWidth",value:function(i){var a=this.w;return i.size*(100-parseInt(a.config.plotOptions.radialBar.hollow.size,10))/100/(i.series.length+1)-this.margin}},{key:"onBarLabelClick",value:function(i){var a=parseInt(i.target.getAttribute("rel"),10)-1,s=this.barLabels.onClick,r=this.w;s&&s(r.globals.seriesNames[a],{w:r,seriesIndex:a})}}]),t})(),Qs=(function(o){ht(t,nt);var e=lt(t);function t(){return H(this,t),e.apply(this,arguments)}return O(t,[{key:"draw",value:function(i,a){var s=this.w,r=new X(this.ctx);this.rangeBarOptions=this.w.config.plotOptions.rangeBar,this.series=i,this.seriesRangeStart=s.globals.seriesRangeStart,this.seriesRangeEnd=s.globals.seriesRangeEnd,this.barHelpers.initVariables(i);for(var n=r.group({class:"apexcharts-rangebar-series apexcharts-plot-series"}),l=0;l0&&(this.visibleI=this.visibleI+1);var m=0,v=0,k=0;this.yRatio.length>1&&(this.yaxisIndex=s.globals.seriesYAxisReverseMap[f][0],k=f);var y=this.barHelpers.initialPositions();p=y.y,u=y.zeroW,g=y.x,v=y.barWidth,m=y.barHeight,h=y.xDivision,d=y.yDivision,c=y.zeroH;for(var C=r.group({class:"apexcharts-datalabels","data:realIndex":f}),w=r.group({class:"apexcharts-rangebar-goals-markers"}),A=0;A0}));return this.isHorizontal?(r=f.config.plotOptions.bar.rangeBarGroupRows?l+u*k:l+d*this.visibleI+u*k,y>-1&&!f.config.plotOptions.bar.rangeBarOverlap&&(x=f.globals.seriesRange[a][y].overlaps).indexOf(b)>-1&&(r=(d=p.barHeight/x.length)*this.visibleI+u*(100-parseInt(this.barOptions.barHeight,10))/100/2+d*(this.visibleI+x.indexOf(b))+u*k)):(k>-1&&!f.globals.timescaleLabels.length&&(n=f.config.plotOptions.bar.rangeBarGroupRows?h+g*k:h+c*this.visibleI+g*k),y>-1&&!f.config.plotOptions.bar.rangeBarOverlap&&(x=f.globals.seriesRange[a][y].overlaps).indexOf(b)>-1&&(n=(c=p.barWidth/x.length)*this.visibleI+g*(100-parseInt(this.barOptions.barWidth,10))/100/2+c*(this.visibleI+x.indexOf(b))+g*k)),{barYPosition:r,barXPosition:n,barHeight:d,barWidth:c}}},{key:"drawRangeColumnPaths",value:function(i){var a=i.indexes,s=i.x,r=i.xDivision,n=i.barWidth,l=i.barXPosition,h=i.zeroH,d=this.w,c=a.i,u=a.j,g=a.realIndex,p=a.translationsIndex,f=this.yRatio[p],x=this.getRangeValue(g,u),b=Math.min(x.start,x.end),m=Math.max(x.start,x.end);this.series[c][u]===void 0||this.series[c][u]===null?b=h:(b=h-b/f,m=h-m/f);var v=Math.abs(m-b),k=this.barHelpers.getColumnPaths({barXPosition:l,barWidth:n,y1:b,y2:m,strokeWidth:this.strokeWidth,series:this.seriesRangeEnd,realIndex:g,i:g,j:u,w:d});if(d.globals.isXNumeric){var y=this.getBarXForNumericXAxis({x:s,j:u,realIndex:g,barWidth:n});s=y.x,l=y.barXPosition}else s+=r;return{pathTo:k.pathTo,pathFrom:k.pathFrom,barHeight:v,x:s,y:x.start<0&&x.end<0?b:m,goalY:this.barHelpers.getGoalValues("y",null,h,c,u,p),barXPosition:l}}},{key:"preventBarOverflow",value:function(i){var a=this.w;return i<0&&(i=0),i>a.globals.gridWidth&&(i=a.globals.gridWidth),i}},{key:"drawRangeBarPaths",value:function(i){var a=i.indexes,s=i.y,r=i.y1,n=i.y2,l=i.yDivision,h=i.barHeight,d=i.barYPosition,c=i.zeroW,u=this.w,g=a.realIndex,p=a.j,f=this.preventBarOverflow(c+r/this.invertedYRatio),x=this.preventBarOverflow(c+n/this.invertedYRatio),b=this.getRangeValue(g,p),m=Math.abs(x-f),v=this.barHelpers.getBarpaths({barYPosition:d,barHeight:h,x1:f,x2:x,strokeWidth:this.strokeWidth,series:this.seriesRangeEnd,i:g,realIndex:g,j:p,w:u});return u.globals.isXNumeric||(s+=l),{pathTo:v.pathTo,pathFrom:v.pathFrom,barWidth:m,x:b.start<0&&b.end<0?f:x,goalX:this.barHelpers.getGoalValues("x",c,null,g,p),y:s}}},{key:"getRangeValue",value:function(i,a){var s=this.w;return{start:s.globals.seriesRangeStart[i][a],end:s.globals.seriesRangeEnd[i][a]}}}]),t})(),Ks=(function(){function o(e){H(this,o),this.w=e.w,this.lineCtx=e}return O(o,[{key:"sameValueSeriesFix",value:function(e,t){var i=this.w;if((i.config.fill.type==="gradient"||i.config.fill.type[e]==="gradient")&&new he(this.lineCtx.ctx,i).seriesHaveSameValues(e)){var a=t[e].slice();a[a.length-1]=a[a.length-1]+1e-6,t[e]=a}return t}},{key:"calculatePoints",value:function(e){var t=e.series,i=e.realIndex,a=e.x,s=e.y,r=e.i,n=e.j,l=e.prevY,h=this.w,d=[],c=[];if(n===0){var u=this.lineCtx.categoryAxisCorrection+h.config.markers.offsetX;h.globals.isXNumeric&&(u=(h.globals.seriesX[i][0]-h.globals.minX)/this.lineCtx.xRatio+h.config.markers.offsetX),d.push(u),c.push(L.isNumber(t[r][0])?l+h.config.markers.offsetY:null),d.push(a+h.config.markers.offsetX),c.push(L.isNumber(t[r][n+1])?s+h.config.markers.offsetY:null)}else d.push(a+h.config.markers.offsetX),c.push(L.isNumber(t[r][n+1])?s+h.config.markers.offsetY:null);return{x:d,y:c}}},{key:"checkPreviousPaths",value:function(e){for(var t=e.pathFromLine,i=e.pathFromArea,a=e.realIndex,s=this.w,r=0;r0&&parseInt(n.realIndex,10)===parseInt(a,10)&&(n.type==="line"?(this.lineCtx.appendPathFrom=!1,t=s.globals.previousPaths[r].paths[0].d):n.type==="area"&&(this.lineCtx.appendPathFrom=!1,i=s.globals.previousPaths[r].paths[0].d,s.config.stroke.show&&s.globals.previousPaths[r].paths[1]&&(t=s.globals.previousPaths[r].paths[1].d)))}return{pathFromLine:t,pathFromArea:i}}},{key:"determineFirstPrevY",value:function(e){var t,i,a,s=e.i,r=e.realIndex,n=e.series,l=e.prevY,h=e.lineYPosition,d=e.translationsIndex,c=this.w,u=c.config.chart.stacked&&!c.globals.comboCharts||c.config.chart.stacked&&c.globals.comboCharts&&(!this.w.config.chart.stackOnlyBar||((t=this.w.config.series[r])===null||t===void 0?void 0:t.type)==="bar"||((i=this.w.config.series[r])===null||i===void 0?void 0:i.type)==="column");if(((a=n[s])===null||a===void 0?void 0:a[0])!==void 0)l=(h=u&&s>0?this.lineCtx.prevSeriesY[s-1][0]:this.lineCtx.zeroY)-n[s][0]/this.lineCtx.yRatio[d]+2*(this.lineCtx.isReversed?n[s][0]/this.lineCtx.yRatio[d]:0);else if(u&&s>0&&n[s][0]===void 0){for(var g=s-1;g>=0;g--)if(n[g][0]!==null&&n[g][0]!==void 0){l=h=this.lineCtx.prevSeriesY[g][0];break}}return{prevY:l,lineYPosition:h}}}]),o})(),er=function(o){for(var e,t,i,a,s=(function(d){for(var c=[],u=d[0],g=d[1],p=c[0]=Pi(u,g),f=1,x=d.length-1;f9&&(a=3*i/Math.sqrt(a),s[l]=a*e,s[l+1]=a*t);for(var h=0;h<=r;h++)a=(o[Math.min(r,h+1)][0]-o[Math.max(0,h-1)][0])/(6*(1+s[h]*s[h])),n.push([a||0,s[h]*a||0]);return n},tr=function(o){var e=er(o),t=o[1],i=o[0],a=[],s=e[1],r=e[0];a.push(i,[i[0]+r[0],i[1]+r[1],t[0]-s[0],t[1]-s[1],t[0],t[1]]);for(var n=2,l=e.length;n1&&i[1].length<6){var a=i[0].length;i[1]=[2*i[0][a-2]-i[0][a-4],2*i[0][a-1]-i[0][a-3]].concat(i[1])}i[0]=i[0].slice(-2)}return i};function Pi(o,e){return(e[1]-o[1])/(e[0]-o[0])}var Ii=(function(){function o(e,t,i){H(this,o),this.ctx=e,this.w=e.w,this.xyRatios=t,this.pointsChart=!(this.w.config.chart.type!=="bubble"&&this.w.config.chart.type!=="scatter")||i,this.scatter=new Ma(this.ctx),this.noNegatives=this.w.globals.minX===Number.MAX_VALUE,this.lineHelpers=new Ks(this),this.markers=new st(this.ctx),this.prevSeriesY=[],this.categoryAxisCorrection=0,this.yaxisIndex=0}return O(o,[{key:"draw",value:function(e,t,i,a){var s,r=this.w,n=new X(this.ctx),l=r.globals.comboCharts?t:r.config.chart.type,h=n.group({class:"apexcharts-".concat(l,"-series apexcharts-plot-series")}),d=new he(this.ctx,r);this.yRatio=this.xyRatios.yRatio,this.zRatio=this.xyRatios.zRatio,this.xRatio=this.xyRatios.xRatio,this.baseLineY=this.xyRatios.baseLineY,e=d.getLogSeries(e),this.yRatio=d.getLogYRatios(this.yRatio),this.prevSeriesY=[];for(var c=[],u=0;u1?g:0;this._initSerieVariables(e,u,g);var f=[],x=[],b=[],m=r.globals.padHorizontal+this.categoryAxisCorrection;this.ctx.series.addCollapsedClassToSeries(this.elSeries,g),r.globals.isXNumeric&&r.globals.seriesX.length>0&&(m=(r.globals.seriesX[g][0]-r.globals.minX)/this.xRatio),b.push(m);var v,k=m,y=void 0,C=k,w=this.zeroY,A=this.zeroY;w=this.lineHelpers.determineFirstPrevY({i:u,realIndex:g,series:e,prevY:w,lineYPosition:0,translationsIndex:p}).prevY,r.config.stroke.curve==="monotoneCubic"&&e[u][0]===null?f.push(null):f.push(w),v=w,l==="rangeArea"&&(y=A=this.lineHelpers.determineFirstPrevY({i:u,realIndex:g,series:a,prevY:A,lineYPosition:0,translationsIndex:p}).prevY,x.push(f[0]!==null?A:null));var S=this._calculatePathsFrom({type:l,series:e,i:u,realIndex:g,translationsIndex:p,prevX:C,prevY:w,prevY2:A}),M=[f[0]],P=[x[0]],I={type:l,series:e,realIndex:g,translationsIndex:p,i:u,x:m,y:1,pX:k,pY:v,pathsFrom:S,linePaths:[],areaPaths:[],seriesIndex:i,lineYPosition:0,xArrj:b,yArrj:f,y2Arrj:x,seriesRangeEnd:a},T=this._iterateOverDataPoints(R(R({},I),{},{iterations:l==="rangeArea"?e[u].length-1:void 0,isRangeStart:!0}));if(l==="rangeArea"){for(var z=this._calculatePathsFrom({series:a,i:u,realIndex:g,prevX:C,prevY:A}),E=this._iterateOverDataPoints(R(R({},I),{},{series:a,xArrj:[m],yArrj:M,y2Arrj:P,pY:y,areaPaths:T.areaPaths,pathsFrom:z,iterations:a[u].length-1,isRangeStart:!1})),Y=T.linePaths.length/2,F=0;F=0;_--)h.add(c[_]);else for(var W=0;W1&&(this.yaxisIndex=a.globals.seriesYAxisReverseMap[i],r=i),this.isReversed=a.config.yaxis[this.yaxisIndex]&&a.config.yaxis[this.yaxisIndex].reversed,this.zeroY=a.globals.gridHeight-this.baseLineY[r]-(this.isReversed?a.globals.gridHeight:0)+(this.isReversed?2*this.baseLineY[r]:0),this.areaBottomY=this.zeroY,(this.zeroY>a.globals.gridHeight||a.config.plotOptions.area.fillTo==="end")&&(this.areaBottomY=a.globals.gridHeight),this.categoryAxisCorrection=this.xDivision/2,this.elSeries=s.group({class:"apexcharts-series",zIndex:a.config.series[i].zIndex!==void 0?a.config.series[i].zIndex:i,seriesName:L.escapeString(a.globals.seriesNames[i])}),this.elPointsMain=s.group({class:"apexcharts-series-markers-wrap","data:realIndex":i}),this.elDataLabelsWrap=s.group({class:"apexcharts-datalabels","data:realIndex":i});var n=e[t].length===a.globals.dataPoints;this.elSeries.attr({"data:longestSeries":n,rel:t+1,"data:realIndex":i}),this.appendPathFrom=!0}},{key:"_calculatePathsFrom",value:function(e){var t,i,a,s,r=e.type,n=e.series,l=e.i,h=e.realIndex,d=e.translationsIndex,c=e.prevX,u=e.prevY,g=e.prevY2,p=this.w,f=new X(this.ctx);if(n[l][0]===null){for(var x=0;x0){var b=this.lineHelpers.checkPreviousPaths({pathFromLine:a,pathFromArea:s,realIndex:h});a=b.pathFromLine,s=b.pathFromArea}return{prevX:c,prevY:u,linePath:t,areaPath:i,pathFromLine:a,pathFromArea:s}}},{key:"_handlePaths",value:function(e){var t=e.type,i=e.realIndex,a=e.i,s=e.paths,r=this.w,n=new X(this.ctx),l=new Ie(this.ctx);this.prevSeriesY.push(s.yArrj),r.globals.seriesXvalues[i]=s.xArrj,r.globals.seriesYvalues[i]=s.yArrj;var h=r.config.forecastDataPoints;if(h.count>0&&t!=="rangeArea"){var d=r.globals.seriesXvalues[i][r.globals.seriesXvalues[i].length-h.count-1],c=n.drawRect(d,0,r.globals.gridWidth,r.globals.gridHeight,0);r.globals.dom.elForecastMask.appendChild(c.node);var u=n.drawRect(0,0,d,r.globals.gridHeight,0);r.globals.dom.elNonForecastMask.appendChild(u.node)}this.pointsChart||r.globals.delayedElements.push({el:this.elPointsMain.node,index:i});var g={i:a,realIndex:i,animationDelay:a,initialSpeed:r.config.chart.animations.speed,dataChangeSpeed:r.config.chart.animations.dynamicAnimation.speed,className:"apexcharts-".concat(t)};if(t==="area")for(var p=l.fillPath({seriesNumber:i}),f=0;f0&&t!=="rangeArea"){var w=n.renderPaths(y);w.node.setAttribute("stroke-dasharray",h.dashArray),h.strokeWidth&&w.node.setAttribute("stroke-width",h.strokeWidth),this.elSeries.add(w),w.attr("clip-path","url(#forecastMask".concat(r.globals.cuid,")")),C.attr("clip-path","url(#nonForecastMask".concat(r.globals.cuid,")"))}}}}},{key:"_iterateOverDataPoints",value:function(e){var t,i,a=this,s=e.type,r=e.series,n=e.iterations,l=e.realIndex,h=e.translationsIndex,d=e.i,c=e.x,u=e.y,g=e.pX,p=e.pY,f=e.pathsFrom,x=e.linePaths,b=e.areaPaths,m=e.seriesIndex,v=e.lineYPosition,k=e.xArrj,y=e.yArrj,C=e.y2Arrj,w=e.isRangeStart,A=e.seriesRangeEnd,S=this.w,M=new X(this.ctx),P=this.yRatio,I=f.prevY,T=f.linePath,z=f.areaPath,E=f.pathFromLine,Y=f.pathFromArea,F=L.isNumber(S.globals.minYArr[l])?S.globals.minYArr[l]:S.globals.minY;n||(n=S.globals.dataPoints>1?S.globals.dataPoints-1:S.globals.dataPoints);var _=function(pe,xe){return xe-pe/P[h]+2*(a.isReversed?pe/P[h]:0)},W=u,G=S.config.chart.stacked&&!S.globals.comboCharts||S.config.chart.stacked&&S.globals.comboCharts&&(!this.w.config.chart.stackOnlyBar||((t=this.w.config.series[l])===null||t===void 0?void 0:t.type)==="bar"||((i=this.w.config.series[l])===null||i===void 0?void 0:i.type)==="column"),B=S.config.stroke.curve;Array.isArray(B)&&(B=Array.isArray(m)?B[m[d]]:B[d]);for(var ne,oe=0,se=0;se0&&S.globals.collapsedSeries.length0;xe--){if(!(S.globals.collapsedSeriesIndices.indexOf((m==null?void 0:m[xe])||xe)>-1))return xe;xe--}return 0})(d-1)][se+1]:v=this.zeroY:v=this.zeroY,fe?u=_(F,v):(u=_(r[d][se+1],v),s==="rangeArea"&&(W=_(A[d][se+1],v))),k.push(c),!fe||S.config.stroke.curve!=="smooth"&&S.config.stroke.curve!=="monotoneCubic"?(y.push(u),C.push(W)):(y.push(null),C.push(null));var $=this.lineHelpers.calculatePoints({series:r,x:c,y:u,realIndex:l,i:d,j:se,prevY:I}),te=this._createPaths({type:s,series:r,i:d,realIndex:l,j:se,x:c,y:u,y2:W,xArrj:k,yArrj:y,y2Arrj:C,pX:g,pY:p,pathState:oe,segmentStartX:ne,linePath:T,areaPath:z,linePaths:x,areaPaths:b,curve:B,isRangeStart:w});b=te.areaPaths,x=te.linePaths,g=te.pX,p=te.pY,oe=te.pathState,ne=te.segmentStartX,z=te.areaPath,T=te.linePath,!this.appendPathFrom||S.globals.hasNullValues||B==="monotoneCubic"&&s==="rangeArea"||(E+=M.line(c,this.areaBottomY),Y+=M.line(c,this.areaBottomY)),this.handleNullDataPoints(r,$,d,se,l),this._handleMarkersAndLabels({type:s,pointsPos:$,i:d,j:se,realIndex:l,isRangeStart:w})}return{yArrj:y,xArrj:k,pathFromArea:Y,areaPaths:b,pathFromLine:E,linePaths:x,linePath:T,areaPath:z}}},{key:"_handleMarkersAndLabels",value:function(e){var t=e.type,i=e.pointsPos,a=e.isRangeStart,s=e.i,r=e.j,n=e.realIndex,l=this.w,h=new rt(this.ctx);if(this.pointsChart)this.scatter.draw(this.elSeries,r,{realIndex:n,pointsPos:i,zRatio:this.zRatio,elParent:this.elPointsMain});else{l.globals.series[s].length>1&&this.elPointsMain.node.classList.add("apexcharts-element-hidden");var d=this.markers.plotChartMarkers(i,n,r+1);d!==null&&this.elPointsMain.add(d)}var c=h.drawDataLabel({type:t,isRangeStart:a,pos:i,i:n,j:r+1});c!==null&&this.elDataLabelsWrap.add(c)}},{key:"_createPaths",value:function(e){var t=e.type,i=e.series,a=e.i;e.realIndex;var s,r=e.j,n=e.x,l=e.y,h=e.xArrj,d=e.yArrj,c=e.y2,u=e.y2Arrj,g=e.pX,p=e.pY,f=e.pathState,x=e.segmentStartX,b=e.linePath,m=e.areaPath,v=e.linePaths,k=e.areaPaths,y=e.curve,C=e.isRangeStart,w=new X(this.ctx),A=this.areaBottomY,S=t==="rangeArea",M=t==="rangeArea"&&C;switch(y){case"monotoneCubic":var P=C?d:u;switch(f){case 0:if(P[r+1]===null)break;f=1;case 1:if(!(S?h.length===i[a].length:r===i[a].length-2))break;case 2:var I=C?h:h.slice().reverse(),T=C?P:P.slice().reverse(),z=(s=T,I.map((function(J,$){return[J,s[$]]})).filter((function(J){return J[1]!==null}))),E=z.length>1?tr(z):z,Y=[];S&&(M?k=z:Y=k.reverse());var F=0,_=0;if((function(J,$){for(var te=(function(kt){var ve=[],Re=0;return kt.forEach((function(cr){cr!==null?Re++:Re>0&&(ve.push(Re),Re=0)})),Re>0&&ve.push(Re),ve})(J),pe=[],xe=0,Te=0;xe4?(Te+="C".concat(ve[0],", ").concat(ve[1]),Te+=", ".concat(ve[2],", ").concat(ve[3]),Te+=", ".concat(ve[4],", ").concat(ve[5])):Re>2&&(Te+="S".concat(ve[0],", ").concat(ve[1]),Te+=", ".concat(ve[2],", ").concat(ve[3]))}return Te})(J),te=_,pe=(_+=J.length)-1;M?b=w.move(z[te][0],z[te][1])+$:S?b=w.move(Y[te][0],Y[te][1])+w.line(z[te][0],z[te][1])+$+w.line(Y[pe][0],Y[pe][1]):(b=w.move(z[te][0],z[te][1])+$,m=b+w.line(z[pe][0],A)+w.line(z[te][0],A)+"z",k.push(m)),v.push(b)})),S&&F>1&&!M){var W=v.slice(F).reverse();v.splice(F),W.forEach((function(J){return v.push(J)}))}f=0}break;case"smooth":var G=.35*(n-g);if(i[a][r]===null)f=0;else switch(f){case 0:if(x=g,b=M?w.move(g,u[r])+w.line(g,p):w.move(g,p),m=w.move(g,p),i[a][r+1]===null){v.push(b),k.push(m);break}if(f=1,r=i[a].length-2&&(M&&(b+=w.curve(n,l,n,l,n,c)+w.move(n,c)),m+=w.curve(n,l,n,l,n,A)+w.line(x,A)+"z",v.push(b),k.push(m),f=-1)}}g=n,p=l;break;default:var oe=function(J,$,te){var pe=[];switch(J){case"stepline":pe=w.line($,null,"H")+w.line(null,te,"V");break;case"linestep":pe=w.line(null,te,"V")+w.line($,null,"H");break;case"straight":pe=w.line($,te)}return pe};if(i[a][r]===null)f=0;else switch(f){case 0:if(x=g,b=M?w.move(g,u[r])+w.line(g,p):w.move(g,p),m=w.move(g,p),i[a][r+1]===null){v.push(b),k.push(m);break}if(f=1,r=i[a].length-2&&(M&&(b+=w.line(n,c)),m+=w.line(n,A)+w.line(x,A)+"z",v.push(b),k.push(m),f=-1)}}g=n,p=l}return{linePaths:v,areaPaths:k,pX:g,pY:p,pathState:f,segmentStartX:x,linePath:b,areaPath:m}}},{key:"handleNullDataPoints",value:function(e,t,i,a,s){var r=this.w;if(e[i][a]===null&&r.config.markers.showNullDataPoints||e[i].length===1){var n=this.strokeWidth-r.config.markers.strokeWidth/2;n>0||(n=0);var l=this.markers.plotChartMarkers(t,s,a+1,n,!0);l!==null&&this.elPointsMain.add(l)}}}]),o})();window.TreemapSquared={},window.TreemapSquared.generate=(function(){function o(n,l,h,d){this.xoffset=n,this.yoffset=l,this.height=d,this.width=h,this.shortestEdge=function(){return Math.min(this.height,this.width)},this.getCoordinates=function(c){var u,g=[],p=this.xoffset,f=this.yoffset,x=s(c)/this.height,b=s(c)/this.width;if(this.width>=this.height)for(u=0;u=this.height){var g=c/this.height,p=this.width-g;u=new o(this.xoffset+g,this.yoffset,p,this.height)}else{var f=c/this.width,x=this.height-f;u=new o(this.xoffset,this.yoffset+f,this.width,x)}return u}}function e(n,l,h,d,c){d=d===void 0?0:d,c=c===void 0?0:c;var u=t((function(g,p){var f,x=[],b=p/s(g);for(f=0;f=v})(l,u=n[0],c)?(l.push(u),t(n.slice(1),l,h,d)):(g=h.cutArea(s(l),d),d.push(h.getCoordinates(l)),t(n,[],g,d)),d;d.push(h.getCoordinates(l))}function i(n,l){var h=Math.min.apply(Math,n),d=Math.max.apply(Math,n),c=s(n);return Math.max(Math.pow(l,2)*d/Math.pow(c,2),Math.pow(c,2)/(Math.pow(l,2)*h))}function a(n){return n&&n.constructor===Array}function s(n){var l,h=0;for(l=0;lr-a&&h.width<=n-s){var d=l.rotateAroundCenter(e.node);e.node.setAttribute("transform","rotate(-90 ".concat(d.x," ").concat(d.y,") translate(").concat(h.height/3,")"))}}},{key:"truncateLabels",value:function(e,t,i,a,s,r){var n=new X(this.ctx),l=n.getTextRects(e,t).width+this.w.config.stroke.width+5>s-i&&r-a>s-i?r-a:s-i,h=n.getTextBasedOnMaxWidth({text:e,maxWidth:l,fontSize:t});return e.length!==h.length&&l/t<5?"":h}},{key:"animateTreemap",value:function(e,t,i,a){var s=new $e(this.ctx);s.animateRect(e,{x:t.x,y:t.y,width:t.width,height:t.height},{x:i.x,y:i.y,width:i.width,height:i.height},a,(function(){s.animationCompleted(e)}))}}]),o})(),Da=86400,sr=10/Da,rr=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w,this.timeScaleArray=[],this.utc=this.w.config.xaxis.labels.datetimeUTC}return O(o,[{key:"calculateTimeScaleTicks",value:function(e,t){var i=this,a=this.w;if(a.globals.allSeriesCollapsed)return a.globals.labels=[],a.globals.timescaleLabels=[],[];var s=new ge(this.ctx),r=(t-e)/864e5;this.determineInterval(r),a.globals.disableZoomIn=!1,a.globals.disableZoomOut=!1,r5e4&&(a.globals.disableZoomOut=!0);var n=s.getTimeUnitsfromTimestamp(e,t,this.utc),l=a.globals.gridWidth/r,h=l/24,d=h/60,c=d/60,u=Math.floor(24*r),g=Math.floor(1440*r),p=Math.floor(r*Da),f=Math.floor(r),x=Math.floor(r/30),b=Math.floor(r/365),m={minMillisecond:n.minMillisecond,minSecond:n.minSecond,minMinute:n.minMinute,minHour:n.minHour,minDate:n.minDate,minMonth:n.minMonth,minYear:n.minYear},v={firstVal:m,currentMillisecond:m.minMillisecond,currentSecond:m.minSecond,currentMinute:m.minMinute,currentHour:m.minHour,currentMonthDate:m.minDate,currentDate:m.minDate,currentMonth:m.minMonth,currentYear:m.minYear,daysWidthOnXAxis:l,hoursWidthOnXAxis:h,minutesWidthOnXAxis:d,secondsWidthOnXAxis:c,numberOfSeconds:p,numberOfMinutes:g,numberOfHours:u,numberOfDays:f,numberOfMonths:x,numberOfYears:b};switch(this.tickInterval){case"years":this.generateYearScale(v);break;case"months":case"half_year":this.generateMonthScale(v);break;case"months_days":case"months_fortnight":case"days":case"week_days":this.generateDayScale(v);break;case"hours":this.generateHourScale(v);break;case"minutes_fives":case"minutes":this.generateMinuteScale(v);break;case"seconds_tens":case"seconds_fives":case"seconds":this.generateSecondScale(v)}var k=this.timeScaleArray.map((function(y){var C={position:y.position,unit:y.unit,year:y.year,day:y.day?y.day:1,hour:y.hour?y.hour:0,month:y.month+1};return y.unit==="month"?R(R({},C),{},{day:1,value:y.value+1}):y.unit==="day"||y.unit==="hour"?R(R({},C),{},{value:y.value}):y.unit==="minute"?R(R({},C),{},{value:y.value,minute:y.value}):y.unit==="second"?R(R({},C),{},{value:y.value,minute:y.minute,second:y.second}):y}));return k.filter((function(y){var C=1,w=Math.ceil(a.globals.gridWidth/120),A=y.value;a.config.xaxis.tickAmount!==void 0&&(w=a.config.xaxis.tickAmount),k.length>w&&(C=Math.floor(k.length/w));var S=!1,M=!1;switch(i.tickInterval){case"years":y.unit==="year"&&(S=!0);break;case"half_year":C=7,y.unit==="year"&&(S=!0);break;case"months":C=1,y.unit==="year"&&(S=!0);break;case"months_fortnight":C=15,y.unit!=="year"&&y.unit!=="month"||(S=!0),A===30&&(M=!0);break;case"months_days":C=10,y.unit==="month"&&(S=!0),A===30&&(M=!0);break;case"week_days":C=8,y.unit==="month"&&(S=!0);break;case"days":C=1,y.unit==="month"&&(S=!0);break;case"hours":y.unit==="day"&&(S=!0);break;case"minutes_fives":case"seconds_fives":A%5!=0&&(M=!0);break;case"seconds_tens":A%10!=0&&(M=!0)}if(i.tickInterval==="hours"||i.tickInterval==="minutes_fives"||i.tickInterval==="seconds_tens"||i.tickInterval==="seconds_fives"){if(!M)return!0}else if((A%C==0||S)&&!M)return!0}))}},{key:"recalcDimensionsBasedOnFormat",value:function(e,t){var i=this.w,a=this.formatDates(e),s=this.removeOverlappingTS(a);i.globals.timescaleLabels=s.slice(),new Ot(this.ctx).plotCoords()}},{key:"determineInterval",value:function(e){var t=24*e,i=60*t;switch(!0){case e/365>5:this.tickInterval="years";break;case e>800:this.tickInterval="half_year";break;case e>180:this.tickInterval="months";break;case e>90:this.tickInterval="months_fortnight";break;case e>60:this.tickInterval="months_days";break;case e>30:this.tickInterval="week_days";break;case e>2:this.tickInterval="days";break;case t>2.4:this.tickInterval="hours";break;case i>15:this.tickInterval="minutes_fives";break;case i>5:this.tickInterval="minutes";break;case i>1:this.tickInterval="seconds_tens";break;case 60*i>20:this.tickInterval="seconds_fives";break;default:this.tickInterval="seconds"}}},{key:"generateYearScale",value:function(e){var t=e.firstVal,i=e.currentMonth,a=e.currentYear,s=e.daysWidthOnXAxis,r=e.numberOfYears,n=t.minYear,l=0,h=new ge(this.ctx),d="year";if(t.minDate>1||t.minMonth>0){var c=h.determineRemainingDaysOfYear(t.minYear,t.minMonth,t.minDate);l=(h.determineDaysOfYear(t.minYear)-c+1)*s,n=t.minYear+1,this.timeScaleArray.push({position:l,value:n,unit:d,year:n,month:L.monthMod(i+1)})}else t.minDate===1&&t.minMonth===0&&this.timeScaleArray.push({position:l,value:n,unit:d,year:a,month:L.monthMod(i+1)});for(var u=n,g=l,p=0;p1){h=(d.determineDaysOfMonths(a+1,t.minYear)-i+1)*r,l=L.monthMod(a+1);var g=s+u,p=L.monthMod(l),f=l;l===0&&(c="year",f=g,p=1,g+=u+=1),this.timeScaleArray.push({position:h,value:f,unit:c,year:g,month:p})}else this.timeScaleArray.push({position:h,value:l,unit:c,year:s,month:L.monthMod(a)});for(var x=l+1,b=h,m=0,v=1;mn.determineDaysOfMonths(k+1,y)&&(d=1,l="month",g=k+=1),k},u=(24-t.minHour)*s,g=h,p=c(d,i,a);t.minHour===0&&t.minDate===1?(u=0,g=L.monthMod(t.minMonth),l="month",d=t.minDate):t.minDate!==1&&t.minHour===0&&t.minMinute===0&&(u=0,h=t.minDate,g=h,p=c(d=h,i,a),g!==1&&(l="day")),this.timeScaleArray.push({position:u,value:g,unit:l,year:this._getYear(a,p,0),month:L.monthMod(p),day:d});for(var f=u,x=0;xl.determineDaysOfMonths(w+1,s)&&(x=1,w+=1),{month:w,date:x}},c=function(C,w){return C>l.determineDaysOfMonths(w+1,s)?w+=1:w},u=60-(t.minMinute+t.minSecond/60),g=u*r,p=t.minHour+1,f=p;u===60&&(g=0,f=p=t.minHour);var x=i;f>=24&&(f=0,h="day",p=x+=1);var b=d(x,a).month;b=c(x,b),this.timeScaleArray.push({position:g,value:p,unit:h,day:x,hour:f,year:s,month:L.monthMod(b)}),f++;for(var m=g,v=0;v=24&&(f=0,h="day",b=d(x+=1,b).month,b=c(x,b));var k=this._getYear(s,b,0);m=60*r+m;var y=f===0?x:f;this.timeScaleArray.push({position:m,value:y,unit:h,hour:f,day:x,year:k,month:L.monthMod(b)}),f++}}},{key:"generateMinuteScale",value:function(e){for(var t=e.currentMillisecond,i=e.currentSecond,a=e.currentMinute,s=e.currentHour,r=e.currentDate,n=e.currentMonth,l=e.currentYear,h=e.minutesWidthOnXAxis,d=e.secondsWidthOnXAxis,c=e.numberOfMinutes,u=a+1,g=r,p=n,f=l,x=s,b=(60-i-t/1e3)*d,m=0;m=60&&(u=0,(x+=1)===24&&(x=0)),this.timeScaleArray.push({position:b,value:u,unit:"minute",hour:x,minute:u,day:g,year:this._getYear(f,p,0),month:L.monthMod(p)}),b+=h,u++}},{key:"generateSecondScale",value:function(e){for(var t=e.currentMillisecond,i=e.currentSecond,a=e.currentMinute,s=e.currentHour,r=e.currentDate,n=e.currentMonth,l=e.currentYear,h=e.secondsWidthOnXAxis,d=e.numberOfSeconds,c=i+1,u=a,g=r,p=n,f=l,x=s,b=(1e3-t)/1e3*h,m=0;m=60&&(c=0,++u>=60&&(u=0,++x===24&&(x=0))),this.timeScaleArray.push({position:b,value:c,unit:"second",hour:x,minute:u,second:c,day:g,year:this._getYear(f,p,0),month:L.monthMod(p)}),b+=h,c++}},{key:"createRawDateString",value:function(e,t){var i=e.year;return e.month===0&&(e.month=1),i+="-"+("0"+e.month.toString()).slice(-2),e.unit==="day"?i+=e.unit==="day"?"-"+("0"+t).slice(-2):"-01":i+="-"+("0"+(e.day?e.day:"1")).slice(-2),e.unit==="hour"?i+=e.unit==="hour"?"T"+("0"+t).slice(-2):"T00":i+="T"+("0"+(e.hour?e.hour:"0")).slice(-2),e.unit==="minute"?i+=":"+("0"+t).slice(-2):i+=":"+(e.minute?("0"+e.minute).slice(-2):"00"),e.unit==="second"?i+=":"+("0"+t).slice(-2):i+=":00",this.utc&&(i+=".000Z"),i}},{key:"formatDates",value:function(e){var t=this,i=this.w;return e.map((function(a){var s=a.value.toString(),r=new ge(t.ctx),n=t.createRawDateString(a,s),l=r.getDate(r.parseDate(n));if(t.utc||(l=r.getDate(r.parseDateWithTimezone(n))),i.config.xaxis.labels.format===void 0){var h="dd MMM",d=i.config.xaxis.labels.datetimeFormatter;a.unit==="year"&&(h=d.year),a.unit==="month"&&(h=d.month),a.unit==="day"&&(h=d.day),a.unit==="hour"&&(h=d.hour),a.unit==="minute"&&(h=d.minute),a.unit==="second"&&(h=d.second),s=r.formatDate(l,h)}else s=r.formatDate(l,i.config.xaxis.labels.format);return{dateString:n,position:a.position,value:s,unit:a.unit,year:a.year,month:a.month}}))}},{key:"removeOverlappingTS",value:function(e){var t,i=this,a=new X(this.ctx),s=!1;e.length>0&&e[0].value&&e.every((function(l){return l.value.length===e[0].value.length}))&&(s=!0,t=a.getTextRects(e[0].value).width);var r=0,n=e.map((function(l,h){if(h>0&&i.w.config.xaxis.labels.hideOverlappingLabels){var d=s?t:a.getTextRects(e[r].value).width,c=e[r].position;return l.position>c+d+10?(r=h,l):null}return l}));return n=n.filter((function(l){return l!==null}))}},{key:"_getYear",value:function(e,t,i){return e+Math.floor(t/12)+i}}]),o})(),nr=(function(){function o(e,t){H(this,o),this.ctx=t,this.w=t.w,this.el=e}return O(o,[{key:"setupElements",value:function(){var e=this.w,t=e.globals,i=e.config,a=i.chart.type;t.axisCharts=["line","area","bar","rangeBar","rangeArea","candlestick","boxPlot","scatter","bubble","radar","heatmap","treemap"].includes(a),t.xyCharts=["line","area","bar","rangeBar","rangeArea","candlestick","boxPlot","scatter","bubble"].includes(a),t.isBarHorizontal=["bar","rangeBar","boxPlot"].includes(a)&&i.plotOptions.bar.horizontal,t.chartClass=".apexcharts".concat(t.chartID),t.dom.baseEl=this.el,t.dom.elWrap=document.createElement("div"),X.setAttrs(t.dom.elWrap,{id:t.chartClass.substring(1),class:"apexcharts-canvas ".concat(t.chartClass.substring(1))}),this.el.appendChild(t.dom.elWrap),t.dom.Paper=window.SVG().addTo(t.dom.elWrap),t.dom.Paper.attr({class:"apexcharts-svg","xmlns:data":"ApexChartsNS",transform:"translate(".concat(i.chart.offsetX,", ").concat(i.chart.offsetY,")")}),t.dom.Paper.node.style.background=i.theme.mode!=="dark"||i.chart.background?i.theme.mode!=="light"||i.chart.background?i.chart.background:"#fff":"#424242",this.setSVGDimensions(),t.dom.elLegendForeign=document.createElementNS(t.SVGNS,"foreignObject"),X.setAttrs(t.dom.elLegendForeign,{x:0,y:0,width:t.svgWidth,height:t.svgHeight}),t.dom.elLegendWrap=document.createElement("div"),t.dom.elLegendWrap.classList.add("apexcharts-legend"),t.dom.elLegendWrap.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),t.dom.elLegendForeign.appendChild(t.dom.elLegendWrap),t.dom.Paper.node.appendChild(t.dom.elLegendForeign),t.dom.elGraphical=t.dom.Paper.group().attr({class:"apexcharts-inner apexcharts-graphical"}),t.dom.elDefs=t.dom.Paper.defs(),t.dom.Paper.add(t.dom.elGraphical),t.dom.elGraphical.add(t.dom.elDefs)}},{key:"plotChartType",value:function(e,t){var i=this.w,a=this.ctx,s=i.config,r=i.globals,n={line:{series:[],i:[]},area:{series:[],i:[]},scatter:{series:[],i:[]},bubble:{series:[],i:[]},column:{series:[],i:[]},candlestick:{series:[],i:[]},boxPlot:{series:[],i:[]},rangeBar:{series:[],i:[]},rangeArea:{series:[],seriesRangeEnd:[],i:[]}},l=s.chart.type||"line",h=null,d=0;r.series.forEach((function(C,w){var A=e[w].type||l;n[A]?(A==="rangeArea"?(n[A].series.push(r.seriesRangeStart[w]),n[A].seriesRangeEnd.push(r.seriesRangeEnd[w])):n[A].series.push(C),n[A].i.push(w),A!=="column"&&A!=="bar"||(i.globals.columnSeries=n.column)):["heatmap","treemap","pie","donut","polarArea","radialBar","radar"].includes(A)?h=A:A==="bar"?(n.column.series.push(C),n.column.i.push(w)):console.warn("You have specified an unrecognized series type (".concat(A,").")),l!==A&&A!=="scatter"&&d++})),d>0&&(h&&console.warn("Chart or series type ".concat(h," cannot appear with other chart or series types.")),n.column.series.length>0&&s.plotOptions.bar.horizontal&&(d-=n.column.series.length,n.column={series:[],i:[]},i.globals.columnSeries={series:[],i:[]},console.warn("Horizontal bars are not supported in a mixed/combo chart. Please turn off `plotOptions.bar.horizontal`"))),r.comboCharts||(r.comboCharts=d>0);var c=new Ii(a,t),u=new Mi(a,t);a.pie=new Fa(a);var g=new Js(a);a.rangeBar=new Qs(a,t);var p=new $s(a),f=[];if(r.comboCharts){var x,b,m=new he(a);if(n.area.series.length>0&&(x=f).push.apply(x,ce(m.drawSeriesByGroup(n.area,r.areaGroups,"area",c))),n.column.series.length>0)if(s.chart.stacked){var v=new Ya(a,t);f.push(v.draw(n.column.series,n.column.i))}else a.bar=new nt(a,t),f.push(a.bar.draw(n.column.series,n.column.i));if(n.rangeArea.series.length>0&&f.push(c.draw(n.rangeArea.series,"rangeArea",n.rangeArea.i,n.rangeArea.seriesRangeEnd)),n.line.series.length>0&&(b=f).push.apply(b,ce(m.drawSeriesByGroup(n.line,r.lineGroups,"line",c))),n.candlestick.series.length>0&&f.push(u.draw(n.candlestick.series,"candlestick",n.candlestick.i)),n.boxPlot.series.length>0&&f.push(u.draw(n.boxPlot.series,"boxPlot",n.boxPlot.i)),n.rangeBar.series.length>0&&f.push(a.rangeBar.draw(n.rangeBar.series,n.rangeBar.i)),n.scatter.series.length>0){var k=new Ii(a,t,!0);f.push(k.draw(n.scatter.series,"scatter",n.scatter.i))}if(n.bubble.series.length>0){var y=new Ii(a,t,!0);f.push(y.draw(n.bubble.series,"bubble",n.bubble.i))}}else switch(s.chart.type){case"line":f=c.draw(r.series,"line");break;case"area":f=c.draw(r.series,"area");break;case"bar":s.chart.stacked?f=new Ya(a,t).draw(r.series):(a.bar=new nt(a,t),f=a.bar.draw(r.series));break;case"candlestick":f=new Mi(a,t).draw(r.series,"candlestick");break;case"boxPlot":f=new Mi(a,t).draw(r.series,s.chart.type);break;case"rangeBar":f=a.rangeBar.draw(r.series);break;case"rangeArea":f=c.draw(r.seriesRangeStart,"rangeArea",void 0,r.seriesRangeEnd);break;case"heatmap":f=new Zs(a,t).draw(r.series);break;case"treemap":f=new ar(a,t).draw(r.series);break;case"pie":case"donut":case"polarArea":f=a.pie.draw(r.series);break;case"radialBar":f=g.draw(r.series);break;case"radar":f=p.draw(r.series);break;default:f=c.draw(r.series)}return f}},{key:"setSVGDimensions",value:function(){var e=this.w,t=e.globals,i=e.config;i.chart.width=i.chart.width||"100%",i.chart.height=i.chart.height||"auto",t.svgWidth=i.chart.width,t.svgHeight=i.chart.height;var a=L.getDimensions(this.el),s=i.chart.width.toString().split(/[0-9]+/g).pop();s==="%"?L.isNumber(a[0])&&(a[0].width===0&&(a=L.getDimensions(this.el.parentNode)),t.svgWidth=a[0]*parseInt(i.chart.width,10)/100):s!=="px"&&s!==""||(t.svgWidth=parseInt(i.chart.width,10));var r=String(i.chart.height).toString().split(/[0-9]+/g).pop();if(t.svgHeight!=="auto"&&t.svgHeight!=="")if(r==="%"){var n=L.getDimensions(this.el.parentNode);t.svgHeight=n[1]*parseInt(i.chart.height,10)/100}else t.svgHeight=parseInt(i.chart.height,10);else t.svgHeight=t.axisCharts?t.svgWidth/1.61:t.svgWidth/1.2;if(t.svgWidth=Math.max(t.svgWidth,0),t.svgHeight=Math.max(t.svgHeight,0),X.setAttrs(t.dom.Paper.node,{width:t.svgWidth,height:t.svgHeight}),r!=="%"){var l=i.chart.sparkline.enabled?0:t.axisCharts?i.chart.parentHeightOffset:0;t.dom.Paper.node.parentNode.parentNode.style.minHeight="".concat(t.svgHeight+l,"px")}t.dom.elWrap.style.width="".concat(t.svgWidth,"px"),t.dom.elWrap.style.height="".concat(t.svgHeight,"px")}},{key:"shiftGraphPosition",value:function(){var e=this.w.globals,t=e.translateY,i=e.translateX;X.setAttrs(e.dom.elGraphical.node,{transform:"translate(".concat(i,", ").concat(t,")")})}},{key:"resizeNonAxisCharts",value:function(){var e=this.w,t=e.globals,i=0,a=e.config.chart.sparkline.enabled?1:15;a+=e.config.grid.padding.bottom,["top","bottom"].includes(e.config.legend.position)&&e.config.legend.show&&!e.config.legend.floating&&(i=new Ta(this.ctx).legendHelpers.getLegendDimensions().clwh+7);var s=e.globals.dom.baseEl.querySelector(".apexcharts-radialbar, .apexcharts-pie"),r=2.05*e.globals.radialSize;if(s&&!e.config.chart.sparkline.enabled&&e.config.plotOptions.radialBar.startAngle!==0){var n=L.getBoundingClientRect(s);r=n.bottom;var l=n.bottom-n.top;r=Math.max(2.05*e.globals.radialSize,l)}var h=Math.ceil(r+t.translateY+i+a);t.dom.elLegendForeign&&t.dom.elLegendForeign.setAttribute("height",h),e.config.chart.height&&String(e.config.chart.height).includes("%")||(t.dom.elWrap.style.height="".concat(h,"px"),X.setAttrs(t.dom.Paper.node,{height:h}),t.dom.Paper.node.parentNode.parentNode.style.minHeight="".concat(h,"px"))}},{key:"coreCalculations",value:function(){new Ci(this.ctx).init()}},{key:"resetGlobals",value:function(){var e=this,t=function(){return e.w.config.series.map((function(){return[]}))},i=new La,a=this.w.globals;i.initGlobalVars(a),a.seriesXvalues=t(),a.seriesYvalues=t()}},{key:"isMultipleY",value:function(){return!!(Array.isArray(this.w.config.yaxis)&&this.w.config.yaxis.length>1)&&(this.w.globals.isMultipleYAxis=!0,!0)}},{key:"xySettings",value:function(){var e=this.w,t=null;if(e.globals.axisCharts){if(e.config.xaxis.crosshairs.position==="back"&&new Li(this.ctx).drawXCrosshairs(),e.config.yaxis[0].crosshairs.position==="back"&&new Li(this.ctx).drawYCrosshairs(),e.config.xaxis.type==="datetime"&&e.config.xaxis.labels.formatter===void 0){this.ctx.timeScale=new rr(this.ctx);var i=[];isFinite(e.globals.minX)&&isFinite(e.globals.maxX)&&!e.globals.isBarHorizontal?i=this.ctx.timeScale.calculateTimeScaleTicks(e.globals.minX,e.globals.maxX):e.globals.isBarHorizontal&&(i=this.ctx.timeScale.calculateTimeScaleTicks(e.globals.minY,e.globals.maxY)),this.ctx.timeScale.recalcDimensionsBasedOnFormat(i)}t=new he(this.ctx).getCalculatedRatios()}return t}},{key:"updateSourceChart",value:function(e){this.ctx.w.globals.selection=void 0,this.ctx.updateHelpers._updateOptions({chart:{selection:{xaxis:{min:e.w.globals.minX,max:e.w.globals.maxX}}}},!1,!1)}},{key:"setupBrushHandler",value:function(){var e=this,t=this.w;if(t.config.chart.brush.enabled&&typeof t.config.chart.events.selection!="function"){var i=Array.isArray(t.config.chart.brush.targets)?t.config.chart.brush.targets:[t.config.chart.brush.target];i.forEach((function(a){var s=ApexCharts.getChartByID(a);s.w.globals.brushSource=e.ctx,typeof s.w.config.chart.events.zoomed!="function"&&(s.w.config.chart.events.zoomed=function(){return e.updateSourceChart(s)}),typeof s.w.config.chart.events.scrolled!="function"&&(s.w.config.chart.events.scrolled=function(){return e.updateSourceChart(s)})})),t.config.chart.events.selection=function(a,s){i.forEach((function(r){ApexCharts.getChartByID(r).ctx.updateHelpers._updateOptions({xaxis:{min:s.xaxis.min,max:s.xaxis.max}},!1,!1,!1,!1)}))}}}}]),o})(),or=(function(){function o(e){H(this,o),this.ctx=e,this.w=e.w}return O(o,[{key:"_updateOptions",value:function(e){var t=this,i=arguments.length>1&&arguments[1]!==void 0&&arguments[1],a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],s=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3],r=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return new Promise((function(n){var l=[t.ctx];s&&(l=t.ctx.getSyncedCharts()),t.ctx.w.globals.isExecCalled&&(l=[t.ctx],t.ctx.w.globals.isExecCalled=!1),l.forEach((function(h,d){var c=h.w;if(c.globals.shouldAnimate=a,i||(c.globals.resized=!0,c.globals.dataChanged=!0,a&&h.series.getPreviousPaths()),e&&Ze(e)==="object"&&(h.config=new yt(e),e=he.extendArrayProps(h.config,e,c),h.w.globals.chartID!==t.ctx.w.globals.chartID&&delete e.series,c.config=L.extend(c.config,e),r&&(c.globals.lastXAxis=e.xaxis?L.clone(e.xaxis):[],c.globals.lastYAxis=e.yaxis?L.clone(e.yaxis):[],c.globals.initialConfig=L.extend({},c.config),c.globals.initialSeries=L.clone(c.config.series),e.series))){for(var u=0;u2&&arguments[2]!==void 0&&arguments[2];return new Promise((function(s){var r,n=i.w;return n.globals.shouldAnimate=t,n.globals.dataChanged=!0,t&&i.ctx.series.getPreviousPaths(),n.globals.axisCharts?((r=e.map((function(l,h){return i._extendSeries(l,h)}))).length===0&&(r=[{data:[]}]),n.config.series=r):n.config.series=e.slice(),a&&(n.globals.initialConfig.series=L.clone(n.config.series),n.globals.initialSeries=L.clone(n.config.series)),i.ctx.update().then((function(){s(i.ctx)}))}))}},{key:"_extendSeries",value:function(e,t){var i=this.w,a=i.config.series[t];return R(R({},i.config.series[t]),{},{name:e.name?e.name:a==null?void 0:a.name,color:e.color?e.color:a==null?void 0:a.color,type:e.type?e.type:a==null?void 0:a.type,group:e.group?e.group:a==null?void 0:a.group,hidden:e.hidden!==void 0?e.hidden:a==null?void 0:a.hidden,data:e.data?e.data:a==null?void 0:a.data,zIndex:e.zIndex!==void 0?e.zIndex:t})}},{key:"toggleDataPointSelection",value:function(e,t){var i=this.w,a=null,s=".apexcharts-series[data\\:realIndex='".concat(e,"']");return i.globals.axisCharts?a=i.globals.dom.Paper.findOne("".concat(s," path[j='").concat(t,"'], ").concat(s," circle[j='").concat(t,"'], ").concat(s," rect[j='").concat(t,"']")):t===void 0&&(a=i.globals.dom.Paper.findOne("".concat(s," path[j='").concat(e,"']")),i.config.chart.type!=="pie"&&i.config.chart.type!=="polarArea"&&i.config.chart.type!=="donut"||this.ctx.pie.pieClicked(e)),a?(new X(this.ctx).pathMouseDown(a,null),a.node?a.node:null):(console.warn("toggleDataPointSelection: Element not found"),null)}},{key:"forceXAxisUpdate",value:function(e){var t=this.w;if(["min","max"].forEach((function(a){e.xaxis[a]!==void 0&&(t.config.xaxis[a]=e.xaxis[a],t.globals.lastXAxis[a]=e.xaxis[a])})),e.xaxis.categories&&e.xaxis.categories.length&&(t.config.xaxis.categories=e.xaxis.categories),t.config.xaxis.convertedCatToNumeric){var i=new vt(e);e=i.convertCatToNumericXaxis(e,this.ctx)}return e}},{key:"forceYAxisUpdate",value:function(e){return e.chart&&e.chart.stacked&&e.chart.stackType==="100%"&&(Array.isArray(e.yaxis)?e.yaxis.forEach((function(t,i){e.yaxis[i].min=0,e.yaxis[i].max=100})):(e.yaxis.min=0,e.yaxis.max=100)),e}},{key:"revertDefaultAxisMinMax",value:function(e){var t=this,i=this.w,a=i.globals.lastXAxis,s=i.globals.lastYAxis;e&&e.xaxis&&(a=e.xaxis),e&&e.yaxis&&(s=e.yaxis),i.config.xaxis.min=a.min,i.config.xaxis.max=a.max;var r=function(n){s[n]!==void 0&&(i.config.yaxis[n].min=s[n].min,i.config.yaxis[n].max=s[n].max)};i.config.yaxis.map((function(n,l){i.globals.zoomed||s[l]!==void 0?r(l):t.ctx.opts.yaxis[l]!==void 0&&(n.min=t.ctx.opts.yaxis[l].min,n.max=t.ctx.opts.yaxis[l].max)}))}}]),o})();(function(){function o(){for(var s=arguments.length>0&&arguments[0]!==c?arguments[0]:[],r=arguments.length>1?arguments[1]:c,n=arguments.length>2?arguments[2]:c,l=arguments.length>3?arguments[3]:c,h=arguments.length>4?arguments[4]:c,d=arguments.length>5?arguments[5]:c,c=arguments.length>6?arguments[6]:c,u=s.slice(r,n||c),g=l.slice(h,d||c),p=0,f={pos:[0,0],start:[0,0]},x={pos:[0,0],start:[0,0]};u[p]=e.call(f,u[p]),g[p]=e.call(x,g[p]),u[p][0]!=g[p][0]||u[p][0]=="M"||u[p][0]=="A"&&(u[p][4]!=g[p][4]||u[p][5]!=g[p][5])?(Array.prototype.splice.apply(u,[p,1].concat(i.call(f,u[p]))),Array.prototype.splice.apply(g,[p,1].concat(i.call(x,g[p])))):(u[p]=t.call(f,u[p]),g[p]=t.call(x,g[p])),!(++p==u.length&&p==g.length);)p==u.length&&u.push(["C",f.pos[0],f.pos[1],f.pos[0],f.pos[1],f.pos[0],f.pos[1]]),p==g.length&&g.push(["C",x.pos[0],x.pos[1],x.pos[0],x.pos[1],x.pos[0],x.pos[1]]);return{start:u,dest:g}}function e(s){switch(s[0]){case"z":case"Z":s[0]="L",s[1]=this.start[0],s[2]=this.start[1];break;case"H":s[0]="L",s[2]=this.pos[1];break;case"V":s[0]="L",s[2]=s[1],s[1]=this.pos[0];break;case"T":s[0]="Q",s[3]=s[1],s[4]=s[2],s[1]=this.reflection[1],s[2]=this.reflection[0];break;case"S":s[0]="C",s[6]=s[4],s[5]=s[3],s[4]=s[2],s[3]=s[1],s[2]=this.reflection[1],s[1]=this.reflection[0]}return s}function t(s){var r=s.length;return this.pos=[s[r-2],s[r-1]],"SCQT".indexOf(s[0])!=-1&&(this.reflection=[2*this.pos[0]-s[r-4],2*this.pos[1]-s[r-3]]),s}function i(s){var r=[s];switch(s[0]){case"M":return this.pos=this.start=[s[1],s[2]],r;case"L":s[5]=s[3]=s[1],s[6]=s[4]=s[2],s[1]=this.pos[0],s[2]=this.pos[1];break;case"Q":s[6]=s[4],s[5]=s[3],s[4]=1*s[4]/3+2*s[2]/3,s[3]=1*s[3]/3+2*s[1]/3,s[2]=1*this.pos[1]/3+2*s[2]/3,s[1]=1*this.pos[0]/3+2*s[1]/3;break;case"A":r=(function(n,l){var h,d,c,u,g,p,f,x,b,m,v,k,y,C,w,A,S,M,P,I,T,z,E,Y,F,_,W=Math.abs(l[1]),G=Math.abs(l[2]),B=l[3]%360,ne=l[4],oe=l[5],se=l[6],fe=l[7],J=new Q(n),$=new Q(se,fe),te=[];if(W===0||G===0||J.x===$.x&&J.y===$.y)return[["C",J.x,J.y,$.x,$.y,$.x,$.y]];for(h=new Q((J.x-$.x)/2,(J.y-$.y)/2).transform(new D().rotate(B)),d=h.x*h.x/(W*W)+h.y*h.y/(G*G),d>1&&(W*=d=Math.sqrt(d),G*=d),c=new D().rotate(B).scale(1/W,1/G).rotate(-B),J=J.transform(c),$=$.transform(c),u=[$.x-J.x,$.y-J.y],p=u[0]*u[0]+u[1]*u[1],g=Math.sqrt(p),u[0]/=g,u[1]/=g,f=p<4?Math.sqrt(1-p/4):0,ne===oe&&(f*=-1),x=new Q(($.x+J.x)/2+f*-u[1],($.y+J.y)/2+f*u[0]),b=new Q(J.x-x.x,J.y-x.y),m=new Q($.x-x.x,$.y-x.y),v=Math.acos(b.x/Math.sqrt(b.x*b.x+b.y*b.y)),b.y<0&&(v*=-1),k=Math.acos(m.x/Math.sqrt(m.x*m.x+m.y*m.y)),m.y<0&&(k*=-1),oe&&v>k&&(k+=2*Math.PI),!oe&&v0&&arguments[0]!==void 0?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0;if(r===!1)return!1;for(var n=r,l=s.length;n(o.changedTouches&&(o=o.changedTouches[0]),{x:o.clientX,y:o.clientY});class lr{constructor(e){e.remember("_draggable",this),this.el=e,this.drag=this.drag.bind(this),this.startDrag=this.startDrag.bind(this),this.endDrag=this.endDrag.bind(this)}init(e){e?(this.el.on("mousedown.drag",this.startDrag),this.el.on("touchstart.drag",this.startDrag,{passive:!1})):(this.el.off("mousedown.drag"),this.el.off("touchstart.drag"))}startDrag(e){const t=!e.type.indexOf("mouse");if(t&&e.which!==1&&e.buttons!==0||this.el.dispatch("beforedrag",{event:e,handler:this}).defaultPrevented)return;e.preventDefault(),e.stopPropagation(),this.init(!1),this.box=this.el.bbox(),this.lastClick=this.el.point(Na(e));const i=(t?"mouseup":"touchend")+".drag";Xe(window,(t?"mousemove":"touchmove")+".drag",this.drag,this,{passive:!1}),Xe(window,i,this.endDrag,this,{passive:!1}),this.el.fire("dragstart",{event:e,handler:this,box:this.box})}drag(e){const{box:t,lastClick:i}=this,a=this.el.point(Na(e)),s=a.x-i.x,r=a.y-i.y;if(!s&&!r)return t;const n=t.x+s,l=t.y+r;this.box=new le(n,l,t.w,t.h),this.lastClick=a,this.el.dispatch("dragmove",{event:e,handler:this,box:this.box}).defaultPrevented||this.move(n,l)}move(e,t){this.el.type==="svg"?Oe.prototype.move.call(this.el,e,t):this.el.move(e,t)}endDrag(e){this.drag(e),this.el.fire("dragend",{event:e,handler:this,box:this.box}),Ce(window,"mousemove.drag"),Ce(window,"touchmove.drag"),Ce(window,"mouseup.drag"),Ce(window,"touchend.drag"),this.init(!0)}}/*! +* @svgdotjs/svg.select.js - An extension of svg.js which allows to select elements with mouse +* @version 4.0.1 +* https://github.com/svgdotjs/svg.select.js +* +* @copyright Ulrich-Matthias Schäfer +* @license MIT +* +* BUILT: Mon Jul 01 2024 15:04:42 GMT+0200 (Central European Summer Time) +*/function Ti(o,e,t,i=null){return function(a){a.preventDefault(),a.stopPropagation();var s=a.pageX||a.touches[0].pageX,r=a.pageY||a.touches[0].pageY;e.fire(o,{x:s,y:r,event:a,index:i,points:t})}}function zi([o,e],{a:t,b:i,c:a,d:s,e:r,f:n}){return[o*t+e*a+r,o*i+e*s+n]}N(de,{draggable(o=!0){return(this.remember("_draggable")||new lr(this)).init(o),this}});let Wa=class{constructor(o){this.el=o,o.remember("_selectHandler",this),this.selection=new Oe,this.order=["lt","t","rt","r","rb","b","lb","l","rot"],this.mutationHandler=this.mutationHandler.bind(this);const e=ct();this.observer=new e.MutationObserver(this.mutationHandler)}init(o){this.createHandle=o.createHandle||this.createHandleFn,this.createRot=o.createRot||this.createRotFn,this.updateHandle=o.updateHandle||this.updateHandleFn,this.updateRot=o.updateRot||this.updateRotFn,this.el.root().put(this.selection),this.updatePoints(),this.createSelection(),this.createResizeHandles(),this.updateResizeHandles(),this.createRotationHandle(),this.updateRotationHandle(),this.observer.observe(this.el.node,{attributes:!0})}active(o,e){if(!o)return this.selection.clear().remove(),void this.observer.disconnect();this.init(e)}createSelection(){this.selection.polygon(this.handlePoints).addClass("svg_select_shape")}updateSelection(){this.selection.get(0).plot(this.handlePoints)}createResizeHandles(){this.handlePoints.forEach(((o,e,t)=>{const i=this.order[e];this.createHandle.call(this,this.selection,o,e,t,i),this.selection.get(e+1).addClass("svg_select_handle svg_select_handle_"+i).on("mousedown.selection touchstart.selection",Ti(i,this.el,this.handlePoints,e))}))}createHandleFn(o){o.polyline()}updateHandleFn(o,e,t,i){const a=i.at(t-1),s=i[(t+1)%i.length],r=e,n=[r[0]-a[0],r[1]-a[1]],l=[r[0]-s[0],r[1]-s[1]],h=Math.sqrt(n[0]*n[0]+n[1]*n[1]),d=Math.sqrt(l[0]*l[0]+l[1]*l[1]),c=[n[0]/h,n[1]/h],u=[l[0]/d,l[1]/d],g=[r[0]-10*c[0],r[1]-10*c[1]],p=[r[0]-10*u[0],r[1]-10*u[1]];o.plot([g,r,p])}updateResizeHandles(){this.handlePoints.forEach(((o,e,t)=>{const i=this.order[e];this.updateHandle.call(this,this.selection.get(e+1),o,e,t,i)}))}createRotFn(o){o.line(),o.circle(5)}getPoint(o){return this.handlePoints[this.order.indexOf(o)]}getPointHandle(o){return this.selection.get(this.order.indexOf(o)+1)}updateRotFn(o,e){const t=this.getPoint("t");o.get(0).plot(t[0],t[1],e[0],e[1]),o.get(1).center(e[0],e[1])}createRotationHandle(){const o=this.selection.group().addClass("svg_select_handle_rot").on("mousedown.selection touchstart.selection",Ti("rot",this.el,this.handlePoints));this.createRot.call(this,o)}updateRotationHandle(){const o=this.selection.findOne("g.svg_select_handle_rot");this.updateRot(o,this.rotationPoint,this.handlePoints)}updatePoints(){const o=this.el.bbox(),e=this.el.parent().screenCTM().inverseO().multiplyO(this.el.screenCTM());this.handlePoints=this.getHandlePoints(o).map((t=>zi(t,e))),this.rotationPoint=zi(this.getRotationPoint(o),e)}getHandlePoints({x:o,x2:e,y:t,y2:i,cx:a,cy:s}=this.el.bbox()){return[[o,t],[a,t],[e,t],[e,s],[e,i],[a,i],[o,i],[o,s]]}getRotationPoint({y:o,cx:e}=this.el.bbox()){return[e,o-20]}mutationHandler(){this.updatePoints(),this.updateSelection(),this.updateResizeHandles(),this.updateRotationHandle()}};const _a=o=>function(e=!0,t={}){typeof e=="object"&&(t=e,e=!0);let i=this.remember("_"+o.name);return i||(e.prototype instanceof Wa?(i=new e(this),e=!0):i=new o(this),this.remember("_"+o.name,i)),i.active(e,t),this};/*! +* @svgdotjs/svg.resize.js - An extension for svg.js which allows to resize elements which are selected +* @version 2.0.4 +* https://github.com/svgdotjs/svg.resize.js +* +* @copyright [object Object] +* @license MIT +* +* BUILT: Fri Sep 13 2024 12:43:14 GMT+0200 (Central European Summer Time) +*//*! +* @svgdotjs/svg.select.js - An extension of svg.js which allows to select elements with mouse +* @version 4.0.1 +* https://github.com/svgdotjs/svg.select.js +* +* @copyright Ulrich-Matthias Schäfer +* @license MIT +* +* BUILT: Mon Jul 01 2024 15:04:42 GMT+0200 (Central European Summer Time) +*/function Xi(o,e,t,i=null){return function(a){a.preventDefault(),a.stopPropagation();var s=a.pageX||a.touches[0].pageX,r=a.pageY||a.touches[0].pageY;e.fire(o,{x:s,y:r,event:a,index:i,points:t})}}function Ri([o,e],{a:t,b:i,c:a,d:s,e:r,f:n}){return[o*t+e*a+r,o*i+e*s+n]}N(de,{select:_a(Wa)}),N([Ve,Ue,Be],{pointSelect:_a(class{constructor(o){this.el=o,o.remember("_pointSelectHandler",this),this.selection=new Oe,this.order=["lt","t","rt","r","rb","b","lb","l","rot"],this.mutationHandler=this.mutationHandler.bind(this);const e=ct();this.observer=new e.MutationObserver(this.mutationHandler)}init(o){this.createHandle=o.createHandle||this.createHandleFn,this.updateHandle=o.updateHandle||this.updateHandleFn,this.el.root().put(this.selection),this.updatePoints(),this.createSelection(),this.createPointHandles(),this.updatePointHandles(),this.observer.observe(this.el.node,{attributes:!0})}active(o,e){if(!o)return this.selection.clear().remove(),void this.observer.disconnect();this.init(e)}createSelection(){this.selection.polygon(this.points).addClass("svg_select_shape_pointSelect")}updateSelection(){this.selection.get(0).plot(this.points)}createPointHandles(){this.points.forEach(((o,e,t)=>{this.createHandle.call(this,this.selection,o,e,t),this.selection.get(e+1).addClass("svg_select_handle_point").on("mousedown.selection touchstart.selection",Ti("point",this.el,this.points,e))}))}createHandleFn(o){o.circle(5)}updateHandleFn(o,e){o.center(e[0],e[1])}updatePointHandles(){this.points.forEach(((o,e,t)=>{this.updateHandle.call(this,this.selection.get(e+1),o,e,t)}))}updatePoints(){const o=this.el.parent().screenCTM().inverseO().multiplyO(this.el.screenCTM());this.points=this.el.array().map((e=>zi(e,o)))}mutationHandler(){this.updatePoints(),this.updateSelection(),this.updatePointHandles()}})});class Ba{constructor(e){this.el=e,e.remember("_selectHandler",this),this.selection=new Oe,this.order=["lt","t","rt","r","rb","b","lb","l","rot"],this.mutationHandler=this.mutationHandler.bind(this);const t=ct();this.observer=new t.MutationObserver(this.mutationHandler)}init(e){this.createHandle=e.createHandle||this.createHandleFn,this.createRot=e.createRot||this.createRotFn,this.updateHandle=e.updateHandle||this.updateHandleFn,this.updateRot=e.updateRot||this.updateRotFn,this.el.root().put(this.selection),this.updatePoints(),this.createSelection(),this.createResizeHandles(),this.updateResizeHandles(),this.createRotationHandle(),this.updateRotationHandle(),this.observer.observe(this.el.node,{attributes:!0})}active(e,t){if(!e)return this.selection.clear().remove(),void this.observer.disconnect();this.init(t)}createSelection(){this.selection.polygon(this.handlePoints).addClass("svg_select_shape")}updateSelection(){this.selection.get(0).plot(this.handlePoints)}createResizeHandles(){this.handlePoints.forEach(((e,t,i)=>{const a=this.order[t];this.createHandle.call(this,this.selection,e,t,i,a),this.selection.get(t+1).addClass("svg_select_handle svg_select_handle_"+a).on("mousedown.selection touchstart.selection",Xi(a,this.el,this.handlePoints,t))}))}createHandleFn(e){e.polyline()}updateHandleFn(e,t,i,a){const s=a.at(i-1),r=a[(i+1)%a.length],n=t,l=[n[0]-s[0],n[1]-s[1]],h=[n[0]-r[0],n[1]-r[1]],d=Math.sqrt(l[0]*l[0]+l[1]*l[1]),c=Math.sqrt(h[0]*h[0]+h[1]*h[1]),u=[l[0]/d,l[1]/d],g=[h[0]/c,h[1]/c],p=[n[0]-10*u[0],n[1]-10*u[1]],f=[n[0]-10*g[0],n[1]-10*g[1]];e.plot([p,n,f])}updateResizeHandles(){this.handlePoints.forEach(((e,t,i)=>{const a=this.order[t];this.updateHandle.call(this,this.selection.get(t+1),e,t,i,a)}))}createRotFn(e){e.line(),e.circle(5)}getPoint(e){return this.handlePoints[this.order.indexOf(e)]}getPointHandle(e){return this.selection.get(this.order.indexOf(e)+1)}updateRotFn(e,t){const i=this.getPoint("t");e.get(0).plot(i[0],i[1],t[0],t[1]),e.get(1).center(t[0],t[1])}createRotationHandle(){const e=this.selection.group().addClass("svg_select_handle_rot").on("mousedown.selection touchstart.selection",Xi("rot",this.el,this.handlePoints));this.createRot.call(this,e)}updateRotationHandle(){const e=this.selection.findOne("g.svg_select_handle_rot");this.updateRot(e,this.rotationPoint,this.handlePoints)}updatePoints(){const e=this.el.bbox(),t=this.el.parent().screenCTM().inverseO().multiplyO(this.el.screenCTM());this.handlePoints=this.getHandlePoints(e).map((i=>Ri(i,t))),this.rotationPoint=Ri(this.getRotationPoint(e),t)}getHandlePoints({x:e,x2:t,y:i,y2:a,cx:s,cy:r}=this.el.bbox()){return[[e,i],[s,i],[t,i],[t,r],[t,a],[s,a],[e,a],[e,r]]}getRotationPoint({y:e,cx:t}=this.el.bbox()){return[t,e-20]}mutationHandler(){this.updatePoints(),this.updateSelection(),this.updateResizeHandles(),this.updateRotationHandle()}}const Ga=o=>function(e=!0,t={}){typeof e=="object"&&(t=e,e=!0);let i=this.remember("_"+o.name);return i||(e.prototype instanceof Ba?(i=new e(this),e=!0):i=new o(this),this.remember("_"+o.name,i)),i.active(e,t),this};N(de,{select:Ga(Ba)}),N([Ve,Ue,Be],{pointSelect:Ga(class{constructor(o){this.el=o,o.remember("_pointSelectHandler",this),this.selection=new Oe,this.order=["lt","t","rt","r","rb","b","lb","l","rot"],this.mutationHandler=this.mutationHandler.bind(this);const e=ct();this.observer=new e.MutationObserver(this.mutationHandler)}init(o){this.createHandle=o.createHandle||this.createHandleFn,this.updateHandle=o.updateHandle||this.updateHandleFn,this.el.root().put(this.selection),this.updatePoints(),this.createSelection(),this.createPointHandles(),this.updatePointHandles(),this.observer.observe(this.el.node,{attributes:!0})}active(o,e){if(!o)return this.selection.clear().remove(),void this.observer.disconnect();this.init(e)}createSelection(){this.selection.polygon(this.points).addClass("svg_select_shape_pointSelect")}updateSelection(){this.selection.get(0).plot(this.points)}createPointHandles(){this.points.forEach(((o,e,t)=>{this.createHandle.call(this,this.selection,o,e,t),this.selection.get(e+1).addClass("svg_select_handle_point").on("mousedown.selection touchstart.selection",Xi("point",this.el,this.points,e))}))}createHandleFn(o){o.circle(5)}updateHandleFn(o,e){o.center(e[0],e[1])}updatePointHandles(){this.points.forEach(((o,e,t)=>{this.updateHandle.call(this,this.selection.get(e+1),o,e,t)}))}updatePoints(){const o=this.el.parent().screenCTM().inverseO().multiplyO(this.el.screenCTM());this.points=this.el.array().map((e=>Ri(e,o)))}mutationHandler(){this.updatePoints(),this.updateSelection(),this.updatePointHandles()}})});const Ft=o=>(o.changedTouches&&(o=o.changedTouches[0]),{x:o.clientX,y:o.clientY}),ja=o=>{let e=1/0,t=1/0,i=-1/0,a=-1/0;for(let s=0;s{const C=k-b[0],w=(y-b[1])*m;return[C*m+b[0],w+b[1]]}));return ja(v)})(this.box,p,f)}this.el.dispatch("resize",{box:new le(h),angle:0,eventType:this.eventType,event:e,handler:this}).defaultPrevented||this.el.size(h.width,h.height).move(h.x,h.y)}movePoint(e){this.lastEvent=e;const{x:t,y:i}=this.snapToGrid(this.el.point(Ft(e))),a=this.el.array().slice();a[this.index]=[t,i],this.el.dispatch("resize",{box:ja(a),angle:0,eventType:this.eventType,event:e,handler:this}).defaultPrevented||this.el.plot(a)}rotate(e){this.lastEvent=e;const t=this.startPoint,i=this.el.point(Ft(e)),{cx:a,cy:s}=this.box,r=t.x-a,n=t.y-s,l=i.x-a,h=i.y-s,d=Math.sqrt(r*r+n*n)*Math.sqrt(l*l+h*h);if(d===0)return;let c=Math.acos((r*l+n*h)/d)/Math.PI*180;if(!c)return;i.xdiv { + margin: 4px 0 +} + +.apexcharts-tooltip-box span.value { + font-weight: 700 +} + +.apexcharts-tooltip-rangebar { + padding: 5px 8px +} + +.apexcharts-tooltip-rangebar .category { + font-weight: 600; + color: #777 +} + +.apexcharts-tooltip-rangebar .series-name { + font-weight: 700; + display: block; + margin-bottom: 5px +} + +.apexcharts-xaxistooltip, +.apexcharts-yaxistooltip { + opacity: 0; + pointer-events: none; + color: #373d3f; + font-size: 13px; + text-align: center; + border-radius: 2px; + position: absolute; + z-index: 10; + background: #eceff1; + border: 1px solid #90a4ae +} + +.apexcharts-xaxistooltip { + padding: 9px 10px; + transition: .15s ease all +} + +.apexcharts-xaxistooltip.apexcharts-theme-dark { + background: rgba(0, 0, 0, .7); + border: 1px solid rgba(0, 0, 0, .5); + color: #fff +} + +.apexcharts-xaxistooltip:after, +.apexcharts-xaxistooltip:before { + left: 50%; + border: solid transparent; + content: " "; + height: 0; + width: 0; + position: absolute; + pointer-events: none +} + +.apexcharts-xaxistooltip:after { + border-color: transparent; + border-width: 6px; + margin-left: -6px +} + +.apexcharts-xaxistooltip:before { + border-color: transparent; + border-width: 7px; + margin-left: -7px +} + +.apexcharts-xaxistooltip-bottom:after, +.apexcharts-xaxistooltip-bottom:before { + bottom: 100% +} + +.apexcharts-xaxistooltip-top:after, +.apexcharts-xaxistooltip-top:before { + top: 100% +} + +.apexcharts-xaxistooltip-bottom:after { + border-bottom-color: #eceff1 +} + +.apexcharts-xaxistooltip-bottom:before { + border-bottom-color: #90a4ae +} + +.apexcharts-xaxistooltip-bottom.apexcharts-theme-dark:after, +.apexcharts-xaxistooltip-bottom.apexcharts-theme-dark:before { + border-bottom-color: rgba(0, 0, 0, .5) +} + +.apexcharts-xaxistooltip-top:after { + border-top-color: #eceff1 +} + +.apexcharts-xaxistooltip-top:before { + border-top-color: #90a4ae +} + +.apexcharts-xaxistooltip-top.apexcharts-theme-dark:after, +.apexcharts-xaxistooltip-top.apexcharts-theme-dark:before { + border-top-color: rgba(0, 0, 0, .5) +} + +.apexcharts-xaxistooltip.apexcharts-active { + opacity: 1; + transition: .15s ease all +} + +.apexcharts-yaxistooltip { + padding: 4px 10px +} + +.apexcharts-yaxistooltip.apexcharts-theme-dark { + background: rgba(0, 0, 0, .7); + border: 1px solid rgba(0, 0, 0, .5); + color: #fff +} + +.apexcharts-yaxistooltip:after, +.apexcharts-yaxistooltip:before { + top: 50%; + border: solid transparent; + content: " "; + height: 0; + width: 0; + position: absolute; + pointer-events: none +} + +.apexcharts-yaxistooltip:after { + border-color: transparent; + border-width: 6px; + margin-top: -6px +} + +.apexcharts-yaxistooltip:before { + border-color: transparent; + border-width: 7px; + margin-top: -7px +} + +.apexcharts-yaxistooltip-left:after, +.apexcharts-yaxistooltip-left:before { + left: 100% +} + +.apexcharts-yaxistooltip-right:after, +.apexcharts-yaxistooltip-right:before { + right: 100% +} + +.apexcharts-yaxistooltip-left:after { + border-left-color: #eceff1 +} + +.apexcharts-yaxistooltip-left:before { + border-left-color: #90a4ae +} + +.apexcharts-yaxistooltip-left.apexcharts-theme-dark:after, +.apexcharts-yaxistooltip-left.apexcharts-theme-dark:before { + border-left-color: rgba(0, 0, 0, .5) +} + +.apexcharts-yaxistooltip-right:after { + border-right-color: #eceff1 +} + +.apexcharts-yaxistooltip-right:before { + border-right-color: #90a4ae +} + +.apexcharts-yaxistooltip-right.apexcharts-theme-dark:after, +.apexcharts-yaxistooltip-right.apexcharts-theme-dark:before { + border-right-color: rgba(0, 0, 0, .5) +} + +.apexcharts-yaxistooltip.apexcharts-active { + opacity: 1 +} + +.apexcharts-yaxistooltip-hidden { + display: none +} + +.apexcharts-xcrosshairs, +.apexcharts-ycrosshairs { + pointer-events: none; + opacity: 0; + transition: .15s ease all +} + +.apexcharts-xcrosshairs.apexcharts-active, +.apexcharts-ycrosshairs.apexcharts-active { + opacity: 1; + transition: .15s ease all +} + +.apexcharts-ycrosshairs-hidden { + opacity: 0 +} + +.apexcharts-selection-rect { + cursor: move +} + +.svg_select_shape { + stroke-width: 1; + stroke-dasharray: 10 10; + stroke: black; + stroke-opacity: 0.1; + pointer-events: none; + fill: none; +} + +.svg_select_handle { + stroke-width: 3; + stroke: black; + fill: none; +} + +.svg_select_handle_r { + cursor: e-resize; +} + +.svg_select_handle_l { + cursor: w-resize; +} + +.apexcharts-svg.apexcharts-zoomable.hovering-zoom { + cursor: crosshair +} + +.apexcharts-svg.apexcharts-zoomable.hovering-pan { + cursor: move +} + +.apexcharts-menu-icon, +.apexcharts-pan-icon, +.apexcharts-reset-icon, +.apexcharts-selection-icon, +.apexcharts-toolbar-custom-icon, +.apexcharts-zoom-icon, +.apexcharts-zoomin-icon, +.apexcharts-zoomout-icon { + cursor: pointer; + width: 20px; + height: 20px; + line-height: 24px; + color: #6e8192; + text-align: center +} + +.apexcharts-menu-icon svg, +.apexcharts-reset-icon svg, +.apexcharts-zoom-icon svg, +.apexcharts-zoomin-icon svg, +.apexcharts-zoomout-icon svg { + fill: #6e8192 +} + +.apexcharts-selection-icon svg { + fill: #444; + transform: scale(.76) +} + +.apexcharts-theme-dark .apexcharts-menu-icon svg, +.apexcharts-theme-dark .apexcharts-pan-icon svg, +.apexcharts-theme-dark .apexcharts-reset-icon svg, +.apexcharts-theme-dark .apexcharts-selection-icon svg, +.apexcharts-theme-dark .apexcharts-toolbar-custom-icon svg, +.apexcharts-theme-dark .apexcharts-zoom-icon svg, +.apexcharts-theme-dark .apexcharts-zoomin-icon svg, +.apexcharts-theme-dark .apexcharts-zoomout-icon svg { + fill: #f3f4f5 +} + +.apexcharts-canvas .apexcharts-reset-zoom-icon.apexcharts-selected svg, +.apexcharts-canvas .apexcharts-selection-icon.apexcharts-selected svg, +.apexcharts-canvas .apexcharts-zoom-icon.apexcharts-selected svg { + fill: #008ffb +} + +.apexcharts-theme-light .apexcharts-menu-icon:hover svg, +.apexcharts-theme-light .apexcharts-reset-icon:hover svg, +.apexcharts-theme-light .apexcharts-selection-icon:not(.apexcharts-selected):hover svg, +.apexcharts-theme-light .apexcharts-zoom-icon:not(.apexcharts-selected):hover svg, +.apexcharts-theme-light .apexcharts-zoomin-icon:hover svg, +.apexcharts-theme-light .apexcharts-zoomout-icon:hover svg { + fill: #333 +} + +.apexcharts-menu-icon, +.apexcharts-selection-icon { + position: relative +} + +.apexcharts-reset-icon { + margin-left: 5px +} + +.apexcharts-menu-icon, +.apexcharts-reset-icon, +.apexcharts-zoom-icon { + transform: scale(.85) +} + +.apexcharts-zoomin-icon, +.apexcharts-zoomout-icon { + transform: scale(.7) +} + +.apexcharts-zoomout-icon { + margin-right: 3px +} + +.apexcharts-pan-icon { + transform: scale(.62); + position: relative; + left: 1px; + top: 0 +} + +.apexcharts-pan-icon svg { + fill: #fff; + stroke: #6e8192; + stroke-width: 2 +} + +.apexcharts-pan-icon.apexcharts-selected svg { + stroke: #008ffb +} + +.apexcharts-pan-icon:not(.apexcharts-selected):hover svg { + stroke: #333 +} + +.apexcharts-toolbar { + position: absolute; + z-index: 11; + max-width: 176px; + text-align: right; + border-radius: 3px; + padding: 0 6px 2px; + display: flex; + justify-content: space-between; + align-items: center +} + +.apexcharts-menu { + background: #fff; + position: absolute; + top: 100%; + border: 1px solid #ddd; + border-radius: 3px; + padding: 3px; + right: 10px; + opacity: 0; + min-width: 110px; + transition: .15s ease all; + pointer-events: none +} + +.apexcharts-menu.apexcharts-menu-open { + opacity: 1; + pointer-events: all; + transition: .15s ease all +} + +.apexcharts-menu-item { + padding: 6px 7px; + font-size: 12px; + cursor: pointer +} + +.apexcharts-theme-light .apexcharts-menu-item:hover { + background: #eee +} + +.apexcharts-theme-dark .apexcharts-menu { + background: rgba(0, 0, 0, .7); + color: #fff +} + +@media screen and (min-width:768px) { + .apexcharts-canvas:hover .apexcharts-toolbar { + opacity: 1 + } +} + +.apexcharts-canvas .apexcharts-element-hidden, +.apexcharts-datalabel.apexcharts-element-hidden, +.apexcharts-hide .apexcharts-series-points { + opacity: 0; +} + +.apexcharts-hidden-element-shown { + opacity: 1; + transition: 0.25s ease all; +} + +.apexcharts-datalabel, +.apexcharts-datalabel-label, +.apexcharts-datalabel-value, +.apexcharts-datalabels, +.apexcharts-pie-label { + cursor: default; + pointer-events: none +} + +.apexcharts-pie-label-delay { + opacity: 0; + animation-name: opaque; + animation-duration: .3s; + animation-fill-mode: forwards; + animation-timing-function: ease +} + +.apexcharts-radialbar-label { + cursor: pointer; +} + +.apexcharts-annotation-rect, +.apexcharts-area-series .apexcharts-area, +.apexcharts-gridline, +.apexcharts-line, +.apexcharts-point-annotation-label, +.apexcharts-radar-series path:not(.apexcharts-marker), +.apexcharts-radar-series polygon, +.apexcharts-toolbar svg, +.apexcharts-tooltip .apexcharts-marker, +.apexcharts-xaxis-annotation-label, +.apexcharts-yaxis-annotation-label, +.apexcharts-zoom-rect, +.no-pointer-events { + pointer-events: none +} + +.apexcharts-tooltip-active .apexcharts-marker { + transition: .15s ease all +} + +.resize-triggers { + animation: 1ms resizeanim; + visibility: hidden; + opacity: 0; + height: 100%; + width: 100%; + overflow: hidden +} + +.contract-trigger:before, +.resize-triggers, +.resize-triggers>div { + content: " "; + display: block; + position: absolute; + top: 0; + left: 0 +} + +.resize-triggers>div { + height: 100%; + width: 100%; + background: #eee; + overflow: auto +} + +.contract-trigger:before { + overflow: hidden; + width: 200%; + height: 200% +} + +.apexcharts-bar-goals-markers { + pointer-events: none +} + +.apexcharts-bar-shadows { + pointer-events: none +} + +.apexcharts-rangebar-goals-markers { + pointer-events: none +}`;var d=((h=e.opts.chart)===null||h===void 0?void 0:h.nonce)||e.w.config.chart.nonce;d&&l.setAttribute("nonce",d),r?s.prepend(l):n.head.appendChild(l)}var c=e.create(e.w.config.series,{});if(!c)return t(e);e.mount(c).then((function(){typeof e.w.config.chart.events.mounted=="function"&&e.w.config.chart.events.mounted(e,e.w),e.events.fireEvent("mounted",[e,e.w]),t(c)})).catch((function(u){i(u)}))}else i(new Error("Element not found"))}))}},{key:"create",value:function(e,t){var i=this,a=this.w;new Ua(this).initModules();var s=this.w.globals;if(s.noData=!1,s.animationEnded=!1,!L.elementExists(this.el))return s.animationEnded=!0,this.destroy(),null;if(this.responsive.checkResponsiveConfig(t),a.config.xaxis.convertedCatToNumeric&&new vt(a.config).convertCatToNumericXaxis(a.config,this.ctx),this.core.setupElements(),a.config.chart.type==="treemap"&&(a.config.grid.show=!1,a.config.yaxis[0].show=!1),s.svgWidth===0)return s.animationEnded=!0,null;var r=e;e.forEach((function(u,g){u.hidden&&(r=i.legend.legendHelpers.getSeriesAfterCollapsing({realIndex:g}))}));var n=he.checkComboSeries(r,a.config.chart.type);s.comboCharts=n.comboCharts,s.comboBarCount=n.comboBarCount;var l=r.every((function(u){return u.data&&u.data.length===0}));(r.length===0||l&&s.collapsedSeries.length<1)&&this.series.handleNoData(),this.events.setupEventHandlers(),this.data.parseData(r),this.theme.init(),new st(this).setGlobalMarkerSize(),this.formatters.setLabelFormatters(),this.titleSubtitle.draw(),s.noData&&s.collapsedSeries.length!==s.series.length&&!a.config.legend.showForSingleSeries||this.legend.init(),this.series.hasAllSeriesEqualX(),s.axisCharts&&(this.core.coreCalculations(),a.config.xaxis.type!=="category"&&this.formatters.setLabelFormatters(),this.ctx.toolbar.minX=a.globals.minX,this.ctx.toolbar.maxX=a.globals.maxX),this.formatters.heatmapLabelFormatters(),new he(this).getLargestMarkerSize(),this.dimensions.plotCoords();var h=this.core.xySettings();this.grid.createGridMask();var d=this.core.plotChartType(r,h),c=new rt(this);return c.bringForward(),a.config.dataLabels.background.enabled&&c.dataLabelsBackground(),this.core.shiftGraphPosition(),{elGraph:d,xyRatios:h,dimensions:{plot:{left:a.globals.translateX,top:a.globals.translateY,width:a.globals.gridWidth,height:a.globals.gridHeight}}}}},{key:"mount",value:function(){var e=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,i=this,a=i.w;return new Promise((function(s,r){if(i.el===null)return r(new Error("Not enough data to display or target element not found"));(t===null||a.globals.allSeriesCollapsed)&&i.series.handleNoData(),i.grid=new Pa(i);var n,l,h=i.grid.drawGrid();if(i.annotations=new Is(i),i.annotations.drawImageAnnos(),i.annotations.drawTextAnnos(),a.config.grid.position==="back"&&(h&&a.globals.dom.elGraphical.add(h.el),h!=null&&(n=h.elGridBorders)!==null&&n!==void 0&&n.node&&a.globals.dom.elGraphical.add(h.elGridBorders)),Array.isArray(t.elGraph))for(var d=0;d0&&a.globals.memory.methodsToExec.forEach((function(p){p.method(p.params,!1,p.context)})),a.globals.axisCharts||a.globals.noData||i.core.resizeNonAxisCharts(),s(i)}))}},{key:"destroy",value:function(){window.removeEventListener("resize",this.windowResizeHandler),(function(t,i){var a=Ei.get(i);a&&(a.disconnect(),Ei.delete(i))})(this.el.parentNode,this.parentResizeHandler);var e=this.w.config.chart.id;e&&Apex._chartInstances.forEach((function(t,i){t.id===L.escapeString(e)&&Apex._chartInstances.splice(i,1)})),new qa(this.ctx).clear({isUpdating:!1})}},{key:"updateOptions",value:function(e){var t=this,i=arguments.length>1&&arguments[1]!==void 0&&arguments[1],a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],s=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3],r=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],n=this.w;return this.opts=e,n.globals.selection=void 0,e.series&&(this.series.resetSeries(!1,!0,!1),e.series.length&&e.series[0].data&&(e.series=e.series.map((function(l,h){return t.updateHelpers._extendSeries(l,h)}))),this.updateHelpers.revertDefaultAxisMinMax()),e.xaxis&&(e=this.updateHelpers.forceXAxisUpdate(e)),e.yaxis&&(e=this.updateHelpers.forceYAxisUpdate(e)),n.globals.collapsedSeriesIndices.length>0&&this.series.clearPreviousPaths(),e.theme&&(e=this.theme.updateThemeOptions(e)),this.updateHelpers._updateOptions(e,i,a,s,r)}},{key:"updateSeries",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];return this.series.resetSeries(!1),this.updateHelpers.revertDefaultAxisMinMax(),this.updateHelpers._updateSeries(e,t,i)}},{key:"appendSeries",value:function(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],a=this.w.config.series.slice();return a.push(e),this.series.resetSeries(!1),this.updateHelpers.revertDefaultAxisMinMax(),this.updateHelpers._updateSeries(a,t,i)}},{key:"appendData",value:function(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=this;i.w.globals.dataChanged=!0,i.series.getPreviousPaths();for(var a=i.w.config.series.slice(),s=0;s0&&arguments[0]!==void 0)||arguments[0],t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];this.series.resetSeries(e,t)}},{key:"addEventListener",value:function(e,t){this.events.addEventListener(e,t)}},{key:"removeEventListener",value:function(e,t){this.events.removeEventListener(e,t)}},{key:"addXaxisAnnotation",value:function(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0,a=this;i&&(a=i),a.annotations.addXaxisAnnotationExternal(e,t,a)}},{key:"addYaxisAnnotation",value:function(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0,a=this;i&&(a=i),a.annotations.addYaxisAnnotationExternal(e,t,a)}},{key:"addPointAnnotation",value:function(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0,a=this;i&&(a=i),a.annotations.addPointAnnotationExternal(e,t,a)}},{key:"clearAnnotations",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0,t=this;e&&(t=e),t.annotations.clearAnnotations(t)}},{key:"removeAnnotation",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,i=this;t&&(i=t),i.annotations.removeAnnotation(i,e)}},{key:"getChartArea",value:function(){return this.w.globals.dom.baseEl.querySelector(".apexcharts-inner")}},{key:"getSeriesTotalXRange",value:function(e,t){return this.coreUtils.getSeriesTotalsXRange(e,t)}},{key:"getHighestValueInSeries",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return new Ci(this.ctx).getMinYMaxY(e).highestY}},{key:"getLowestValueInSeries",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return new Ci(this.ctx).getMinYMaxY(e).lowestY}},{key:"getSeriesTotal",value:function(){return this.w.globals.seriesTotals}},{key:"toggleDataPointSelection",value:function(e,t){return this.updateHelpers.toggleDataPointSelection(e,t)}},{key:"zoomX",value:function(e,t){this.ctx.toolbar.zoomUpdateOptions(e,t)}},{key:"setLocale",value:function(e){this.localization.setCurrentLocaleValues(e)}},{key:"dataURI",value:function(e){return new Ht(this.ctx).dataURI(e)}},{key:"exportToCSV",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return new Ht(this.ctx).exportToCSV(e)}},{key:"paper",value:function(){return this.w.globals.dom.Paper}},{key:"_parentResizeCallback",value:function(){this.w.globals.animationEnded&&this.w.config.chart.redrawOnParentResize&&this._windowResize()}},{key:"_windowResize",value:function(){var e=this;clearTimeout(this.w.globals.resizeTimer),this.w.globals.resizeTimer=window.setTimeout((function(){e.w.globals.resized=!0,e.w.globals.dataChanged=!1,e.ctx.update()}),150)}},{key:"_windowResizeHandler",value:function(){var e=this.w.config.chart.redrawOnWindowResize;typeof e=="function"&&(e=e()),e&&this._windowResize()}}],[{key:"getChartByID",value:function(e){var t=L.escapeString(e);if(Apex._chartInstances){var i=Apex._chartInstances.filter((function(a){return a.id===t}))[0];return i&&i.chart}}},{key:"initOnLoad",value:function(){for(var e=document.querySelectorAll("[data-apexcharts]"),t=0;t2?s-2:0),n=2;nt=>{const n=ki.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),k=e=>(e=e.toLowerCase(),t=>it(t)===e),st=e=>t=>typeof t===e,{isArray:_e}=Array,pe=st("undefined");function Le(e){return e!==null&&!pe(e)&&e.constructor!==null&&!pe(e.constructor)&&N(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Qn=k("ArrayBuffer");function Bi(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Qn(e.buffer),t}const Ii=st("string"),N=st("function"),er=st("number"),je=e=>e!==null&&typeof e=="object",Di=e=>e===!0||e===!1,Xe=e=>{if(it(e)!=="object")return!1;const t=Ht(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Zn in e)&&!(rt in e)},$i=e=>{if(!je(e)||Le(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Ui=k("Date"),qi=k("File"),Hi=k("Blob"),zi=k("FileList"),Ki=e=>je(e)&&N(e.pipe),Ji=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||N(e.append)&&((t=it(e))==="formdata"||t==="object"&&N(e.toString)&&e.toString()==="[object FormData]"))},Wi=k("URLSearchParams"),[Vi,Xi,Gi,Yi]=["ReadableStream","Request","Response","Headers"].map(k),Zi=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ke(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,i;if(typeof e!="object"&&(e=[e]),_e(e))for(r=0,i=e.length;r0;)if(i=n[r],t===i.toLowerCase())return i;return null}const G=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nr=e=>!pe(e)&&e!==G;function St(){const{caseless:e,skipUndefined:t}=nr(this)&&this||{},n={},r=(i,s)=>{const o=e&&tr(n,s)||s;Xe(n[o])&&Xe(i)?n[o]=St(n[o],i):Xe(i)?n[o]=St({},i):_e(i)?n[o]=i.slice():(!t||!pe(i))&&(n[o]=i)};for(let i=0,s=arguments.length;i(ke(t,(i,s)=>{n&&N(i)?e[s]=Yn(i,n):e[s]=i},{allOwnKeys:r}),e),es=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),ts=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},ns=(e,t,n,r)=>{let i,s,o;const a={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],(!r||r(o,e,t))&&!a[o]&&(t[o]=e[o],a[o]=!0);e=n!==!1&&Ht(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},rs=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},is=e=>{if(!e)return null;if(_e(e))return e;let t=e.length;if(!er(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},ss=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Ht(Uint8Array)),os=(e,t)=>{const r=(e&&e[rt]).call(e);let i;for(;(i=r.next())&&!i.done;){const s=i.value;t.call(e,s[0],s[1])}},as=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},cs=k("HTMLFormElement"),us=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),xn=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),ls=k("RegExp"),rr=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};ke(n,(i,s)=>{let o;(o=t(i,s,e))!==!1&&(r[s]=o||i)}),Object.defineProperties(e,r)},fs=e=>{rr(e,(t,n)=>{if(N(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(N(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},ds=(e,t)=>{const n={},r=i=>{i.forEach(s=>{n[s]=!0})};return _e(e)?r(e):r(String(e).split(t)),n},ps=()=>{},hs=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function _s(e){return!!(e&&N(e.append)&&e[Zn]==="FormData"&&e[rt])}const ms=e=>{const t=new Array(10),n=(r,i)=>{if(je(r)){if(t.indexOf(r)>=0)return;if(Le(r))return r;if(!("toJSON"in r)){t[i]=r;const s=_e(r)?[]:{};return ke(r,(o,a)=>{const c=n(o,i+1);!pe(c)&&(s[a]=c)}),t[i]=void 0,s}}return r};return n(e,0)},gs=k("AsyncFunction"),ys=e=>e&&(je(e)||N(e))&&N(e.then)&&N(e.catch),ir=((e,t)=>e?setImmediate:t?((n,r)=>(G.addEventListener("message",({source:i,data:s})=>{i===G&&s===n&&r.length&&r.shift()()},!1),i=>{r.push(i),G.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",N(G.postMessage)),bs=typeof queueMicrotask<"u"?queueMicrotask.bind(G):typeof process<"u"&&process.nextTick||ir,ws=e=>e!=null&&N(e[rt]),f={isArray:_e,isArrayBuffer:Qn,isBuffer:Le,isFormData:Ji,isArrayBufferView:Bi,isString:Ii,isNumber:er,isBoolean:Di,isObject:je,isPlainObject:Xe,isEmptyObject:$i,isReadableStream:Vi,isRequest:Xi,isResponse:Gi,isHeaders:Yi,isUndefined:pe,isDate:Ui,isFile:qi,isBlob:Hi,isRegExp:ls,isFunction:N,isStream:Ki,isURLSearchParams:Wi,isTypedArray:ss,isFileList:zi,forEach:ke,merge:St,extend:Qi,trim:Zi,stripBOM:es,inherits:ts,toFlatObject:ns,kindOf:it,kindOfTest:k,endsWith:rs,toArray:is,forEachEntry:os,matchAll:as,isHTMLForm:cs,hasOwnProperty:xn,hasOwnProp:xn,reduceDescriptors:rr,freezeMethods:fs,toObjectSet:ds,toCamelCase:us,noop:ps,toFiniteNumber:hs,findKey:tr,global:G,isContextDefined:nr,isSpecCompliantForm:_s,toJSONObject:ms,isAsyncFn:gs,isThenable:ys,setImmediate:ir,asap:bs,isIterable:ws};function y(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}f.inherits(y,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:f.toJSONObject(this.config),code:this.code,status:this.status}}});const sr=y.prototype,or={};["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(e=>{or[e]={value:e}});Object.defineProperties(y,or);Object.defineProperty(sr,"isAxiosError",{value:!0});y.from=(e,t,n,r,i,s)=>{const o=Object.create(sr);f.toFlatObject(e,o,function(l){return l!==Error.prototype},u=>u!=="isAxiosError");const a=e&&e.message?e.message:"Error",c=t==null&&e?e.code:t;return y.call(o,a,c,n,r,i),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",s&&Object.assign(o,s),o};const xs=null;function At(e){return f.isPlainObject(e)||f.isArray(e)}function ar(e){return f.endsWith(e,"[]")?e.slice(0,-2):e}function En(e,t,n){return e?e.concat(t).map(function(i,s){return i=ar(i),!n&&s?"["+i+"]":i}).join(n?".":""):t}function Es(e){return f.isArray(e)&&!e.some(At)}const Ss=f.toFlatObject(f,{},null,function(t){return/^is[A-Z]/.test(t)});function ot(e,t,n){if(!f.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=f.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,d){return!f.isUndefined(d[_])});const r=n.metaTokens,i=n.visitor||l,s=n.dots,o=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&f.isSpecCompliantForm(t);if(!f.isFunction(i))throw new TypeError("visitor must be a function");function u(p){if(p===null)return"";if(f.isDate(p))return p.toISOString();if(f.isBoolean(p))return p.toString();if(!c&&f.isBlob(p))throw new y("Blob is not supported. Use a Buffer instead.");return f.isArrayBuffer(p)||f.isTypedArray(p)?c&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function l(p,_,d){let m=p;if(p&&!d&&typeof p=="object"){if(f.endsWith(_,"{}"))_=r?_:_.slice(0,-2),p=JSON.stringify(p);else if(f.isArray(p)&&Es(p)||(f.isFileList(p)||f.endsWith(_,"[]"))&&(m=f.toArray(p)))return _=ar(_),m.forEach(function(b,E){!(f.isUndefined(b)||b===null)&&t.append(o===!0?En([_],E,s):o===null?_:_+"[]",u(b))}),!1}return At(p)?!0:(t.append(En(d,_,s),u(p)),!1)}const h=[],g=Object.assign(Ss,{defaultVisitor:l,convertValue:u,isVisitable:At});function x(p,_){if(!f.isUndefined(p)){if(h.indexOf(p)!==-1)throw Error("Circular reference detected in "+_.join("."));h.push(p),f.forEach(p,function(m,w){(!(f.isUndefined(m)||m===null)&&i.call(t,m,f.isString(w)?w.trim():w,_,g))===!0&&x(m,_?_.concat(w):[w])}),h.pop()}}if(!f.isObject(e))throw new TypeError("data must be an object");return x(e),t}function Sn(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function zt(e,t){this._pairs=[],e&&ot(e,this,t)}const cr=zt.prototype;cr.append=function(t,n){this._pairs.push([t,n])};cr.toString=function(t){const n=t?function(r){return t.call(this,r,Sn)}:Sn;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function As(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function ur(e,t,n){if(!t)return e;const r=n&&n.encode||As;f.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let s;if(i?s=i(t,n):s=f.isURLSearchParams(t)?t.toString():new zt(t,n).toString(r),s){const o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class An{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){f.forEach(this.handlers,function(r){r!==null&&t(r)})}}const lr={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Os=typeof URLSearchParams<"u"?URLSearchParams:zt,vs=typeof FormData<"u"?FormData:null,Rs=typeof Blob<"u"?Blob:null,Ts={isBrowser:!0,classes:{URLSearchParams:Os,FormData:vs,Blob:Rs},protocols:["http","https","file","blob","url","data"]},Kt=typeof window<"u"&&typeof document<"u",Ot=typeof navigator=="object"&&navigator||void 0,Cs=Kt&&(!Ot||["ReactNative","NativeScript","NS"].indexOf(Ot.product)<0),Ps=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Ns=Kt&&window.location.href||"http://localhost",Ms=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Kt,hasStandardBrowserEnv:Cs,hasStandardBrowserWebWorkerEnv:Ps,navigator:Ot,origin:Ns},Symbol.toStringTag,{value:"Module"})),T={...Ms,...Ts};function Fs(e,t){return ot(e,new T.classes.URLSearchParams,{visitor:function(n,r,i,s){return T.isNode&&f.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...t})}function Ls(e){return f.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function js(e){const t={},n=Object.keys(e);let r;const i=n.length;let s;for(r=0;r=n.length;return o=!o&&f.isArray(i)?i.length:o,c?(f.hasOwnProp(i,o)?i[o]=[i[o],r]:i[o]=r,!a):((!i[o]||!f.isObject(i[o]))&&(i[o]=[]),t(n,r,i[o],s)&&f.isArray(i[o])&&(i[o]=js(i[o])),!a)}if(f.isFormData(e)&&f.isFunction(e.entries)){const n={};return f.forEachEntry(e,(r,i)=>{t(Ls(r),i,n,0)}),n}return null}function ks(e,t,n){if(f.isString(e))try{return(t||JSON.parse)(e),f.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Be={transitional:lr,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,s=f.isObject(t);if(s&&f.isHTMLForm(t)&&(t=new FormData(t)),f.isFormData(t))return i?JSON.stringify(fr(t)):t;if(f.isArrayBuffer(t)||f.isBuffer(t)||f.isStream(t)||f.isFile(t)||f.isBlob(t)||f.isReadableStream(t))return t;if(f.isArrayBufferView(t))return t.buffer;if(f.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return Fs(t,this.formSerializer).toString();if((a=f.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return ot(a?{"files[]":t}:t,c&&new c,this.formSerializer)}}return s||i?(n.setContentType("application/json",!1),ks(t)):t}],transformResponse:[function(t){const n=this.transitional||Be.transitional,r=n&&n.forcedJSONParsing,i=this.responseType==="json";if(f.isResponse(t)||f.isReadableStream(t))return t;if(t&&f.isString(t)&&(r&&!this.responseType||i)){const o=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(a){if(o)throw a.name==="SyntaxError"?y.from(a,y.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:T.classes.FormData,Blob:T.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};f.forEach(["delete","get","head","post","put","patch"],e=>{Be.headers[e]={}});const Bs=f.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"]),Is=e=>{const t={};let n,r,i;return e&&e.split(` +`).forEach(function(o){i=o.indexOf(":"),n=o.substring(0,i).trim().toLowerCase(),r=o.substring(i+1).trim(),!(!n||t[n]&&Bs[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},On=Symbol("internals");function Ae(e){return e&&String(e).trim().toLowerCase()}function Ge(e){return e===!1||e==null?e:f.isArray(e)?e.map(Ge):String(e)}function Ds(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const $s=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function mt(e,t,n,r,i){if(f.isFunction(r))return r.call(this,t,n);if(i&&(t=n),!!f.isString(t)){if(f.isString(r))return t.indexOf(r)!==-1;if(f.isRegExp(r))return r.test(t)}}function Us(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function qs(e,t){const n=f.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(i,s,o){return this[r].call(this,t,i,s,o)},configurable:!0})})}let M=class{constructor(t){t&&this.set(t)}set(t,n,r){const i=this;function s(a,c,u){const l=Ae(c);if(!l)throw new Error("header name must be a non-empty string");const h=f.findKey(i,l);(!h||i[h]===void 0||u===!0||u===void 0&&i[h]!==!1)&&(i[h||c]=Ge(a))}const o=(a,c)=>f.forEach(a,(u,l)=>s(u,l,c));if(f.isPlainObject(t)||t instanceof this.constructor)o(t,n);else if(f.isString(t)&&(t=t.trim())&&!$s(t))o(Is(t),n);else if(f.isObject(t)&&f.isIterable(t)){let a={},c,u;for(const l of t){if(!f.isArray(l))throw TypeError("Object iterator must return a key-value pair");a[u=l[0]]=(c=a[u])?f.isArray(c)?[...c,l[1]]:[c,l[1]]:l[1]}o(a,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=Ae(t),t){const r=f.findKey(this,t);if(r){const i=this[r];if(!n)return i;if(n===!0)return Ds(i);if(f.isFunction(n))return n.call(this,i,r);if(f.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Ae(t),t){const r=f.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||mt(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let i=!1;function s(o){if(o=Ae(o),o){const a=f.findKey(r,o);a&&(!n||mt(r,r[a],a,n))&&(delete r[a],i=!0)}}return f.isArray(t)?t.forEach(s):s(t),i}clear(t){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const s=n[r];(!t||mt(this,this[s],s,t,!0))&&(delete this[s],i=!0)}return i}normalize(t){const n=this,r={};return f.forEach(this,(i,s)=>{const o=f.findKey(r,s);if(o){n[o]=Ge(i),delete n[s];return}const a=t?Us(s):String(s).trim();a!==s&&delete n[s],n[a]=Ge(i),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return f.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=t&&f.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(i=>r.set(i)),r}static accessor(t){const r=(this[On]=this[On]={accessors:{}}).accessors,i=this.prototype;function s(o){const a=Ae(o);r[a]||(qs(i,o),r[a]=!0)}return f.isArray(t)?t.forEach(s):s(t),this}};M.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);f.reduceDescriptors(M.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});f.freezeMethods(M);function gt(e,t){const n=this||Be,r=t||n,i=M.from(r.headers);let s=r.data;return f.forEach(e,function(a){s=a.call(n,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function dr(e){return!!(e&&e.__CANCEL__)}function me(e,t,n){y.call(this,e??"canceled",y.ERR_CANCELED,t,n),this.name="CanceledError"}f.inherits(me,y,{__CANCEL__:!0});function pr(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new y("Request failed with status code "+n.status,[y.ERR_BAD_REQUEST,y.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Hs(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function zs(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i=0,s=0,o;return t=t!==void 0?t:1e3,function(c){const u=Date.now(),l=r[s];o||(o=u),n[i]=c,r[i]=u;let h=s,g=0;for(;h!==i;)g+=n[h++],h=h%e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),u-o{n=l,i=null,s&&(clearTimeout(s),s=null),e(...u)};return[(...u)=>{const l=Date.now(),h=l-n;h>=r?o(u,l):(i=u,s||(s=setTimeout(()=>{s=null,o(i)},r-h)))},()=>i&&o(i)]}const Qe=(e,t,n=3)=>{let r=0;const i=zs(50,250);return Ks(s=>{const o=s.loaded,a=s.lengthComputable?s.total:void 0,c=o-r,u=i(c),l=o<=a;r=o;const h={loaded:o,total:a,progress:a?o/a:void 0,bytes:c,rate:u||void 0,estimated:u&&a&&l?(a-o)/u:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(h)},n)},vn=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Rn=e=>(...t)=>f.asap(()=>e(...t)),Js=T.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,T.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(T.origin),T.navigator&&/(msie|trident)/i.test(T.navigator.userAgent)):()=>!0,Ws=T.hasStandardBrowserEnv?{write(e,t,n,r,i,s){const o=[e+"="+encodeURIComponent(t)];f.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),f.isString(r)&&o.push("path="+r),f.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Vs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Xs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function hr(e,t,n){let r=!Vs(t);return e&&(r||n==!1)?Xs(e,t):t}const Tn=e=>e instanceof M?{...e}:e;function re(e,t){t=t||{};const n={};function r(u,l,h,g){return f.isPlainObject(u)&&f.isPlainObject(l)?f.merge.call({caseless:g},u,l):f.isPlainObject(l)?f.merge({},l):f.isArray(l)?l.slice():l}function i(u,l,h,g){if(f.isUndefined(l)){if(!f.isUndefined(u))return r(void 0,u,h,g)}else return r(u,l,h,g)}function s(u,l){if(!f.isUndefined(l))return r(void 0,l)}function o(u,l){if(f.isUndefined(l)){if(!f.isUndefined(u))return r(void 0,u)}else return r(void 0,l)}function a(u,l,h){if(h in t)return r(u,l);if(h in e)return r(void 0,u)}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(u,l,h)=>i(Tn(u),Tn(l),h,!0)};return f.forEach(Object.keys({...e,...t}),function(l){const h=c[l]||i,g=h(e[l],t[l],l);f.isUndefined(g)&&h!==a||(n[l]=g)}),n}const _r=e=>{const t=re({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:s,headers:o,auth:a}=t;if(t.headers=o=M.from(o),t.url=ur(hr(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),f.isFormData(n)){if(T.hasStandardBrowserEnv||T.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(f.isFunction(n.getHeaders)){const c=n.getHeaders(),u=["content-type","content-length"];Object.entries(c).forEach(([l,h])=>{u.includes(l.toLowerCase())&&o.set(l,h)})}}if(T.hasStandardBrowserEnv&&(r&&f.isFunction(r)&&(r=r(t)),r||r!==!1&&Js(t.url))){const c=i&&s&&Ws.read(s);c&&o.set(i,c)}return t},Gs=typeof XMLHttpRequest<"u",Ys=Gs&&function(e){return new Promise(function(n,r){const i=_r(e);let s=i.data;const o=M.from(i.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:u}=i,l,h,g,x,p;function _(){x&&x(),p&&p(),i.cancelToken&&i.cancelToken.unsubscribe(l),i.signal&&i.signal.removeEventListener("abort",l)}let d=new XMLHttpRequest;d.open(i.method.toUpperCase(),i.url,!0),d.timeout=i.timeout;function m(){if(!d)return;const b=M.from("getAllResponseHeaders"in d&&d.getAllResponseHeaders()),R={data:!a||a==="text"||a==="json"?d.responseText:d.response,status:d.status,statusText:d.statusText,headers:b,config:e,request:d};pr(function(C){n(C),_()},function(C){r(C),_()},R),d=null}"onloadend"in d?d.onloadend=m:d.onreadystatechange=function(){!d||d.readyState!==4||d.status===0&&!(d.responseURL&&d.responseURL.indexOf("file:")===0)||setTimeout(m)},d.onabort=function(){d&&(r(new y("Request aborted",y.ECONNABORTED,e,d)),d=null)},d.onerror=function(E){const R=E&&E.message?E.message:"Network Error",F=new y(R,y.ERR_NETWORK,e,d);F.event=E||null,r(F),d=null},d.ontimeout=function(){let E=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const R=i.transitional||lr;i.timeoutErrorMessage&&(E=i.timeoutErrorMessage),r(new y(E,R.clarifyTimeoutError?y.ETIMEDOUT:y.ECONNABORTED,e,d)),d=null},s===void 0&&o.setContentType(null),"setRequestHeader"in d&&f.forEach(o.toJSON(),function(E,R){d.setRequestHeader(R,E)}),f.isUndefined(i.withCredentials)||(d.withCredentials=!!i.withCredentials),a&&a!=="json"&&(d.responseType=i.responseType),u&&([g,p]=Qe(u,!0),d.addEventListener("progress",g)),c&&d.upload&&([h,x]=Qe(c),d.upload.addEventListener("progress",h),d.upload.addEventListener("loadend",x)),(i.cancelToken||i.signal)&&(l=b=>{d&&(r(!b||b.type?new me(null,e,d):b),d.abort(),d=null)},i.cancelToken&&i.cancelToken.subscribe(l),i.signal&&(i.signal.aborted?l():i.signal.addEventListener("abort",l)));const w=Hs(i.url);if(w&&T.protocols.indexOf(w)===-1){r(new y("Unsupported protocol "+w+":",y.ERR_BAD_REQUEST,e));return}d.send(s||null)})},Zs=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,i;const s=function(u){if(!i){i=!0,a();const l=u instanceof Error?u:this.reason;r.abort(l instanceof y?l:new me(l instanceof Error?l.message:l))}};let o=t&&setTimeout(()=>{o=null,s(new y(`timeout ${t} of ms exceeded`,y.ETIMEDOUT))},t);const a=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(s):u.removeEventListener("abort",s)}),e=null)};e.forEach(u=>u.addEventListener("abort",s));const{signal:c}=r;return c.unsubscribe=()=>f.asap(a),c}},Qs=function*(e,t){let n=e.byteLength;if(n{const i=eo(e,t);let s=0,o,a=c=>{o||(o=!0,r&&r(c))};return new ReadableStream({async pull(c){try{const{done:u,value:l}=await i.next();if(u){a(),c.close();return}let h=l.byteLength;if(n){let g=s+=h;n(g)}c.enqueue(new Uint8Array(l))}catch(u){throw a(u),u}},cancel(c){return a(c),i.return()}},{highWaterMark:2})},Pn=64*1024,{isFunction:qe}=f,no=(({Request:e,Response:t})=>({Request:e,Response:t}))(f.global),{ReadableStream:Nn,TextEncoder:Mn}=f.global,Fn=(e,...t)=>{try{return!!e(...t)}catch{return!1}},ro=e=>{e=f.merge.call({skipUndefined:!0},no,e);const{fetch:t,Request:n,Response:r}=e,i=t?qe(t):typeof fetch=="function",s=qe(n),o=qe(r);if(!i)return!1;const a=i&&qe(Nn),c=i&&(typeof Mn=="function"?(p=>_=>p.encode(_))(new Mn):async p=>new Uint8Array(await new n(p).arrayBuffer())),u=s&&a&&Fn(()=>{let p=!1;const _=new n(T.origin,{body:new Nn,method:"POST",get duplex(){return p=!0,"half"}}).headers.has("Content-Type");return p&&!_}),l=o&&a&&Fn(()=>f.isReadableStream(new r("").body)),h={stream:l&&(p=>p.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(p=>{!h[p]&&(h[p]=(_,d)=>{let m=_&&_[p];if(m)return m.call(_);throw new y(`Response type '${p}' is not supported`,y.ERR_NOT_SUPPORT,d)})});const g=async p=>{if(p==null)return 0;if(f.isBlob(p))return p.size;if(f.isSpecCompliantForm(p))return(await new n(T.origin,{method:"POST",body:p}).arrayBuffer()).byteLength;if(f.isArrayBufferView(p)||f.isArrayBuffer(p))return p.byteLength;if(f.isURLSearchParams(p)&&(p=p+""),f.isString(p))return(await c(p)).byteLength},x=async(p,_)=>{const d=f.toFiniteNumber(p.getContentLength());return d??g(_)};return async p=>{let{url:_,method:d,data:m,signal:w,cancelToken:b,timeout:E,onDownloadProgress:R,onUploadProgress:F,responseType:C,headers:Ee,withCredentials:ue="same-origin",fetchOptions:De}=_r(p),mn=t||fetch;C=C?(C+"").toLowerCase():"text";let $e=Zs([w,b&&b.toAbortSignal()],E),Se=null;const V=$e&&$e.unsubscribe&&(()=>{$e.unsubscribe()});let gn;try{if(F&&u&&d!=="get"&&d!=="head"&&(gn=await x(Ee,m))!==0){let H=new n(_,{method:"POST",body:m,duplex:"half"}),le;if(f.isFormData(m)&&(le=H.headers.get("content-type"))&&Ee.setContentType(le),H.body){const[_t,Ue]=vn(gn,Qe(Rn(F)));m=Cn(H.body,Pn,_t,Ue)}}f.isString(ue)||(ue=ue?"include":"omit");const I=s&&"credentials"in n.prototype,yn={...De,signal:$e,method:d.toUpperCase(),headers:Ee.normalize().toJSON(),body:m,duplex:"half",credentials:I?ue:void 0};Se=s&&new n(_,yn);let q=await(s?mn(Se,De):mn(_,yn));const bn=l&&(C==="stream"||C==="response");if(l&&(R||bn&&V)){const H={};["status","statusText","headers"].forEach(wn=>{H[wn]=q[wn]});const le=f.toFiniteNumber(q.headers.get("content-length")),[_t,Ue]=R&&vn(le,Qe(Rn(R),!0))||[];q=new r(Cn(q.body,Pn,_t,()=>{Ue&&Ue(),V&&V()}),H)}C=C||"text";let ji=await h[f.findKey(h,C)||"text"](q,p);return!bn&&V&&V(),await new Promise((H,le)=>{pr(H,le,{data:ji,headers:M.from(q.headers),status:q.status,statusText:q.statusText,config:p,request:Se})})}catch(I){throw V&&V(),I&&I.name==="TypeError"&&/Load failed|fetch/i.test(I.message)?Object.assign(new y("Network Error",y.ERR_NETWORK,p,Se),{cause:I.cause||I}):y.from(I,I&&I.code,p,Se)}}},io=new Map,mr=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:i}=t,s=[r,i,n];let o=s.length,a=o,c,u,l=io;for(;a--;)c=s[a],u=l.get(c),u===void 0&&l.set(c,u=a?new Map:ro(t)),l=u;return u};mr();const vt={http:xs,xhr:Ys,fetch:{get:mr}};f.forEach(vt,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Ln=e=>`- ${e}`,so=e=>f.isFunction(e)||e===null||e===!1,gr={getAdapter:(e,t)=>{e=f.isArray(e)?e:[e];const{length:n}=e;let r,i;const s={};for(let o=0;o`adapter ${c} `+(u===!1?"is not supported by the environment":"is not available in the build"));let a=n?o.length>1?`since : +`+o.map(Ln).join(` +`):" "+Ln(o[0]):"as no adapter specified";throw new y("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i},adapters:vt};function yt(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new me(null,e)}function jn(e){return yt(e),e.headers=M.from(e.headers),e.data=gt.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),gr.getAdapter(e.adapter||Be.adapter,e)(e).then(function(r){return yt(e),r.data=gt.call(e,e.transformResponse,r),r.headers=M.from(r.headers),r},function(r){return dr(r)||(yt(e),r&&r.response&&(r.response.data=gt.call(e,e.transformResponse,r.response),r.response.headers=M.from(r.response.headers))),Promise.reject(r)})}const yr="1.12.2",at={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{at[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const kn={};at.transitional=function(t,n,r){function i(s,o){return"[Axios v"+yr+"] Transitional option '"+s+"'"+o+(r?". "+r:"")}return(s,o,a)=>{if(t===!1)throw new y(i(o," has been removed"+(n?" in "+n:"")),y.ERR_DEPRECATED);return n&&!kn[o]&&(kn[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,o,a):!0}};at.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function oo(e,t,n){if(typeof e!="object")throw new y("options must be an object",y.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const s=r[i],o=t[s];if(o){const a=e[s],c=a===void 0||o(a,s,e);if(c!==!0)throw new y("option "+s+" must be "+c,y.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new y("Unknown option "+s,y.ERR_BAD_OPTION)}}const Ye={assertOptions:oo,validators:at},D=Ye.validators;let Z=class{constructor(t){this.defaults=t||{},this.interceptors={request:new An,response:new An}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const s=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=re(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&Ye.assertOptions(r,{silentJSONParsing:D.transitional(D.boolean),forcedJSONParsing:D.transitional(D.boolean),clarifyTimeoutError:D.transitional(D.boolean)},!1),i!=null&&(f.isFunction(i)?n.paramsSerializer={serialize:i}:Ye.assertOptions(i,{encode:D.function,serialize:D.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Ye.assertOptions(n,{baseUrl:D.spelling("baseURL"),withXsrfToken:D.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=s&&f.merge(s.common,s[n.method]);s&&f.forEach(["delete","get","head","post","put","patch","common"],p=>{delete s[p]}),n.headers=M.concat(o,s);const a=[];let c=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(c=c&&_.synchronous,a.unshift(_.fulfilled,_.rejected))});const u=[];this.interceptors.response.forEach(function(_){u.push(_.fulfilled,_.rejected)});let l,h=0,g;if(!c){const p=[jn.bind(this),void 0];for(p.unshift(...a),p.push(...u),g=p.length,l=Promise.resolve(n);h{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](i);r._listeners=null}),this.promise.then=i=>{let s;const o=new Promise(a=>{r.subscribe(a),s=a}).then(i);return o.cancel=function(){r.unsubscribe(s)},o},t(function(s,o,a){r.reason||(r.reason=new me(s,o,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new br(function(i){t=i}),cancel:t}}};function co(e){return function(n){return e.apply(null,n)}}function uo(e){return f.isObject(e)&&e.isAxiosError===!0}const Rt={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(Rt).forEach(([e,t])=>{Rt[t]=e});function wr(e){const t=new Z(e),n=Yn(Z.prototype.request,t);return f.extend(n,Z.prototype,t,{allOwnKeys:!0}),f.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return wr(re(e,i))},n}const O=wr(Be);O.Axios=Z;O.CanceledError=me;O.CancelToken=ao;O.isCancel=dr;O.VERSION=yr;O.toFormData=ot;O.AxiosError=y;O.Cancel=O.CanceledError;O.all=function(t){return Promise.all(t)};O.spread=co;O.isAxiosError=uo;O.mergeConfig=re;O.AxiosHeaders=M;O.formToJSON=e=>fr(f.isHTMLForm(e)?new FormData(e):e);O.getAdapter=gr.getAdapter;O.HttpStatusCode=Rt;O.default=O;const{Axios:Cc,AxiosError:Pc,CanceledError:Nc,isCancel:Mc,CancelToken:Fc,VERSION:Lc,all:jc,Cancel:kc,isAxiosError:Bc,spread:Ic,toFormData:Dc,AxiosHeaders:$c,HttpStatusCode:Uc,formToJSON:qc,getAdapter:Hc,mergeConfig:zc}=O;window.axios=O;window.axios.defaults.headers.common["X-Requested-With"]="XMLHttpRequest";var Tt=!1,Ct=!1,Q=[],Pt=-1,Jt=!1;function lo(e){ho(e)}function fo(){Jt=!0}function po(){Jt=!1,xr()}function ho(e){Q.includes(e)||Q.push(e),xr()}function _o(e){let t=Q.indexOf(e);t!==-1&&t>Pt&&Q.splice(t,1)}function xr(){if(!Ct&&!Tt){if(Jt)return;Tt=!0,queueMicrotask(mo)}}function mo(){Tt=!1,Ct=!0;for(let e=0;ee.effect(t,{scheduler:n=>{Nt?lo(n):n()}}),Er=e.raw}function Bn(e){ce=e}function bo(e){let t=()=>{};return[r=>{let i=ce(r);return e._x_effects||(e._x_effects=new Set,e._x_runEffects=()=>{e._x_effects.forEach(s=>s())}),e._x_effects.add(i),t=()=>{i!==void 0&&(e._x_effects.delete(i),ye(i))},i},()=>{t()}]}function Sr(e,t){let n=!0,r,i=ce(()=>{let s=e();if(JSON.stringify(s),!n&&(typeof s=="object"||s!==r)){let o=r;queueMicrotask(()=>{t(s,o)})}r=s,n=!1});return()=>ye(i)}async function wo(e){fo();try{await e(),await Promise.resolve()}finally{po()}}var Ar=[],Or=[],vr=[];function xo(e){vr.push(e)}function Wt(e,t){typeof t=="function"?(e._x_cleanups||(e._x_cleanups=[]),e._x_cleanups.push(t)):(t=e,Or.push(t))}function Rr(e){Ar.push(e)}function Tr(e,t,n){e._x_attributeCleanups||(e._x_attributeCleanups={}),e._x_attributeCleanups[t]||(e._x_attributeCleanups[t]=[]),e._x_attributeCleanups[t].push(n)}function Cr(e,t){e._x_attributeCleanups&&Object.entries(e._x_attributeCleanups).forEach(([n,r])=>{(t===void 0||t.includes(n))&&(r.forEach(i=>i()),delete e._x_attributeCleanups[n])})}function Eo(e){var t,n;for((t=e._x_effects)==null||t.forEach(_o);(n=e._x_cleanups)!=null&&n.length;)e._x_cleanups.pop()()}var Vt=new MutationObserver(Zt),Xt=!1;function Gt(){Vt.observe(document,{subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0}),Xt=!0}function Pr(){So(),Vt.disconnect(),Xt=!1}var Oe=[];function So(){let e=Vt.takeRecords();Oe.push(()=>e.length>0&&Zt(e));let t=Oe.length;queueMicrotask(()=>{if(Oe.length===t)for(;Oe.length>0;)Oe.shift()()})}function A(e){if(!Xt)return e();Pr();let t=e();return Gt(),t}var Yt=!1,et=[];function Ao(){Yt=!0}function Oo(){Yt=!1,Zt(et),et=[]}function Zt(e){if(Yt){et=et.concat(e);return}let t=[],n=new Set,r=new Map,i=new Map;for(let s=0;s{o.nodeType===1&&o._x_marker&&n.add(o)}),e[s].addedNodes.forEach(o=>{if(o.nodeType===1){if(n.has(o)){n.delete(o);return}o._x_marker||t.push(o)}})),e[s].type==="attributes")){let o=e[s].target,a=e[s].attributeName,c=e[s].oldValue,u=()=>{r.has(o)||r.set(o,[]),r.get(o).push({name:a,value:o.getAttribute(a)})},l=()=>{i.has(o)||i.set(o,[]),i.get(o).push(a)};o.hasAttribute(a)&&c===null?u():o.hasAttribute(a)?(l(),u()):l()}i.forEach((s,o)=>{Cr(o,s)}),r.forEach((s,o)=>{Ar.forEach(a=>a(o,s))});for(let s of n)t.some(o=>o.contains(s))||Or.forEach(o=>o(s));for(let s of t)s.isConnected&&vr.forEach(o=>o(s));t=null,n=null,r=null,i=null}function Nr(e){return se(ie(e))}function Ie(e,t,n){return e._x_dataStack=[t,...ie(n||e)],()=>{e._x_dataStack=e._x_dataStack.filter(r=>r!==t)}}function ie(e){return e._x_dataStack?e._x_dataStack:typeof ShadowRoot=="function"&&e instanceof ShadowRoot?ie(e.host):e.parentNode?ie(e.parentNode):[]}function se(e){return new Proxy({objects:e},vo)}var vo={ownKeys({objects:e}){return Array.from(new Set(e.flatMap(t=>Object.keys(t))))},has({objects:e},t){return t==Symbol.unscopables?!1:e.some(n=>Object.prototype.hasOwnProperty.call(n,t)||Reflect.has(n,t))},get({objects:e},t,n){return t=="toJSON"?Ro:Reflect.get(e.find(r=>Reflect.has(r,t))||{},t,n)},set({objects:e},t,n,r){const i=e.find(o=>Object.prototype.hasOwnProperty.call(o,t))||e[e.length-1],s=Object.getOwnPropertyDescriptor(i,t);return s!=null&&s.set&&(s!=null&&s.get)?s.set.call(r,n)||!0:Reflect.set(i,t,n)}};function Ro(){return Reflect.ownKeys(this).reduce((t,n)=>(t[n]=Reflect.get(this,n),t),{})}function Qt(e){let t=r=>typeof r=="object"&&!Array.isArray(r)&&r!==null,n=(r,i="")=>{Object.entries(Object.getOwnPropertyDescriptors(r)).forEach(([s,{value:o,enumerable:a}])=>{if(a===!1||o===void 0||typeof o=="object"&&o!==null&&o.__v_skip)return;let c=i===""?s:`${i}.${s}`;typeof o=="object"&&o!==null&&o._x_interceptor?r[s]=o.initialize(e,c,s):t(o)&&o!==r&&!(o instanceof Element)&&n(o,c)})};return n(e)}function Mr(e,t=()=>{}){let n={initialValue:void 0,_x_interceptor:!0,initialize(r,i,s){return e(this.initialValue,()=>To(r,i),o=>Mt(r,i,o),i,s)}};return t(n),r=>{if(typeof r=="object"&&r!==null&&r._x_interceptor){let i=n.initialize.bind(n);n.initialize=(s,o,a)=>{let c=r.initialize(s,o,a);return n.initialValue=c,i(s,o,a)}}else n.initialValue=r;return n}}function To(e,t){return t.split(".").reduce((n,r)=>n[r],e)}function Mt(e,t,n){if(typeof t=="string"&&(t=t.split(".")),t.length===1)e[t[0]]=n;else{if(t.length===0)throw error;return e[t[0]]||(e[t[0]]={}),Mt(e[t[0]],t.slice(1),n)}}var Fr={};function B(e,t){Fr[e]=t}function Ne(e,t){let n=Co(t);return Object.entries(Fr).forEach(([r,i])=>{Object.defineProperty(e,`$${r}`,{get(){return i(t,n)},enumerable:!1})}),e}function Co(e){let[t,n]=Ur(e),r={interceptor:Mr,...t};return Wt(e,n),r}function Po(e,t,n,...r){try{return n(...r)}catch(i){Me(i,e,t)}}function Me(...e){return Lr(...e)}var Lr=Mo;function No(e){Lr=e}function Mo(e,t,n=void 0){e=Object.assign(e??{message:"No error message given."},{el:t,expression:n}),console.warn(`Alpine Expression Error: ${e.message} + +${n?'Expression: "'+n+`" + +`:""}`,t),setTimeout(()=>{throw e},0)}var de=!0;function jr(e){let t=de;de=!1;let n=e();return de=t,n}function ee(e,t,n={}){let r;return P(e,t)(i=>r=i,n),r}function P(...e){return kr(...e)}var kr=Ir;function Fo(e){kr=e}var Br;function Lo(e){Br=e}function Ir(e,t){let n={};Ne(n,e);let r=[n,...ie(e)],i=typeof t=="function"?jo(r,t):Bo(r,t,e);return Po.bind(null,e,t,i)}function jo(e,t){return(n=()=>{},{scope:r={},params:i=[],context:s}={})=>{if(!de){Fe(n,t,se([r,...e]),i);return}let o=t.apply(se([r,...e]),i);Fe(n,o)}}var bt={};function ko(e,t){if(bt[e])return bt[e];let n=Object.getPrototypeOf(async function(){}).constructor,r=/^[\n\s]*if.*\(.*\)/.test(e.trim())||/^(let|const)\s/.test(e.trim())?`(async()=>{ ${e} })()`:e,s=(()=>{try{let o=new n(["__self","scope"],`with (scope) { __self.result = ${r} }; __self.finished = true; return __self.result;`);return Object.defineProperty(o,"name",{value:`[Alpine] ${e}`}),o}catch(o){return Me(o,t,e),Promise.resolve()}})();return bt[e]=s,s}function Bo(e,t,n){let r=ko(t,n);return(i=()=>{},{scope:s={},params:o=[],context:a}={})=>{r.result=void 0,r.finished=!1;let c=se([s,...e]);if(typeof r=="function"){let u=r.call(a,r,c).catch(l=>Me(l,n,t));r.finished?(Fe(i,r.result,c,o,n),r.result=void 0):u.then(l=>{Fe(i,l,c,o,n)}).catch(l=>Me(l,n,t)).finally(()=>r.result=void 0)}}}function Fe(e,t,n,r,i){if(de&&typeof t=="function"){let s=t.apply(n,r);s instanceof Promise?s.then(o=>Fe(e,o,n,r)).catch(o=>Me(o,i,t)):e(s)}else typeof t=="object"&&t instanceof Promise?t.then(s=>e(s)):e(t)}function Io(...e){return Br(...e)}function Do(e,t,n={}){let r={};Ne(r,e);let i=[r,...ie(e)],s=se([n.scope??{},...i]),o=n.params??[];if(t.includes("await")){let a=Object.getPrototypeOf(async function(){}).constructor,c=/^[\n\s]*if.*\(.*\)/.test(t.trim())||/^(let|const)\s/.test(t.trim())?`(async()=>{ ${t} })()`:t;return new a(["scope"],`with (scope) { let __result = ${c}; return __result }`).call(n.context,s)}else{let a=/^[\n\s]*if.*\(.*\)/.test(t.trim())||/^(let|const)\s/.test(t.trim())?`(()=>{ ${t} })()`:t,u=new Function(["scope"],`with (scope) { let __result = ${a}; return __result }`).call(n.context,s);return typeof u=="function"&&de?u.apply(s,o):u}}var en="x-";function be(e=""){return en+e}function $o(e){en=e}var tt={};function v(e,t){return tt[e]=t,{before(n){if(!tt[n]){console.warn(String.raw`Cannot find directive \`${n}\`. \`${e}\` will use the default order of execution`);return}const r=Y.indexOf(n);Y.splice(r>=0?r:Y.indexOf("DEFAULT"),0,e)}}}function Uo(e){return Object.keys(tt).includes(e)}function tn(e,t,n){if(t=Array.from(t),e._x_virtualDirectives){let s=Object.entries(e._x_virtualDirectives).map(([a,c])=>({name:a,value:c})),o=Dr(s);s=s.map(a=>o.find(c=>c.name===a.name)?{name:`x-bind:${a.name}`,value:`"${a.value}"`}:a),t=t.concat(s)}let r={};return t.map(zr((s,o)=>r[s]=o)).filter(Jr).map(zo(r,n)).sort(Ko).map(s=>Ho(e,s))}function Dr(e){return Array.from(e).map(zr()).filter(t=>!Jr(t))}var Ft=!1,Te=new Map,$r=Symbol();function qo(e){Ft=!0;let t=Symbol();$r=t,Te.set(t,[]);let n=()=>{for(;Te.get(t).length;)Te.get(t).shift()();Te.delete(t)},r=()=>{Ft=!1,n()};e(n),r()}function Ur(e){let t=[],n=a=>t.push(a),[r,i]=bo(e);return t.push(i),[{Alpine:xe,effect:r,cleanup:n,evaluateLater:P.bind(P,e),evaluate:ee.bind(ee,e)},()=>t.forEach(a=>a())]}function Ho(e,t){let n=()=>{},r=tt[t.type]||n,[i,s]=Ur(e);Tr(e,t.original,s);let o=()=>{e._x_ignore||e._x_ignoreSelf||(r.inline&&r.inline(e,t,i),r=r.bind(r,e,t,i),Ft?Te.get($r).push(r):r())};return o.runCleanups=s,o}var qr=(e,t)=>({name:n,value:r})=>(n.startsWith(e)&&(n=n.replace(e,t)),{name:n,value:r}),Hr=e=>e;function zr(e=()=>{}){return({name:t,value:n})=>{let{name:r,value:i}=Kr.reduce((s,o)=>o(s),{name:t,value:n});return r!==t&&e(r,t),{name:r,value:i}}}var Kr=[];function nn(e){Kr.push(e)}function Jr({name:e}){return Wr().test(e)}var Wr=()=>new RegExp(`^${en}([^:^.]+)\\b`);function zo(e,t){return({name:n,value:r})=>{n===r&&(r="");let i=n.match(Wr()),s=n.match(/:([a-zA-Z0-9\-_:]+)/),o=n.match(/\.[^.\]]+(?=[^\]]*$)/g)||[],a=t||e[n]||n;return{type:i?i[1]:null,value:s?s[1]:null,modifiers:o.map(c=>c.replace(".","")),expression:r,original:a}}}var Lt="DEFAULT",Y=["ignore","ref","data","id","anchor","bind","init","for","model","modelable","transition","show","if",Lt,"teleport"];function Ko(e,t){let n=Y.indexOf(e.type)===-1?Lt:e.type,r=Y.indexOf(t.type)===-1?Lt:t.type;return Y.indexOf(n)-Y.indexOf(r)}function Ce(e,t,n={}){e.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,composed:!0,cancelable:!0}))}function oe(e,t){if(typeof ShadowRoot=="function"&&e instanceof ShadowRoot){Array.from(e.children).forEach(i=>oe(i,t));return}let n=!1;if(t(e,()=>n=!0),n)return;let r=e.firstElementChild;for(;r;)oe(r,t),r=r.nextElementSibling}function L(e,...t){console.warn(`Alpine Warning: ${e}`,...t)}var In=!1;function Jo(){In&&L("Alpine has already been initialized on this page. Calling Alpine.start() more than once can cause problems."),In=!0,document.body||L("Unable to initialize. Trying to load Alpine before `` is available. Did you forget to add `defer` in Alpine's ` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/build/manifest.json b/public/build/manifest.json new file mode 100644 index 00000000..7d9fbc1f --- /dev/null +++ b/public/build/manifest.json @@ -0,0 +1,239 @@ +{ + "__commonjsHelpers-CqkleIqs.js": { + "file": "assets/_commonjsHelpers-CqkleIqs.js", + "name": "_commonjsHelpers" + }, + "_index.html": { + "file": "index.html", + "src": "_index.html" + }, + "resources/assets/css/demo.css": { + "file": "assets/demo--dN7KDn2.css", + "src": "resources/assets/css/demo.css", + "isEntry": true + }, + "resources/assets/js/clientes-form.js": { + "file": "assets/clientes-form-DRAYp1GX.js", + "name": "clientes-form", + "src": "resources/assets/js/clientes-form.js", + "isEntry": true + }, + "resources/assets/js/compra-form.js": { + "file": "assets/compra-form-CkCT8zYP.js", + "name": "compra-form", + "src": "resources/assets/js/compra-form.js", + "isEntry": true + }, + "resources/assets/js/config.js": { + "file": "assets/config-DvyemKWy.js", + "name": "config", + "src": "resources/assets/js/config.js", + "isEntry": true + }, + "resources/assets/js/dashboards-analytics.js": { + "file": "assets/dashboards-analytics-2GdtvCmv.js", + "name": "dashboards-analytics", + "src": "resources/assets/js/dashboards-analytics.js", + "isEntry": true + }, + "resources/assets/js/documentos-form.js": { + "file": "assets/documentos-form-Dtwn65C6.js", + "name": "documentos-form", + "src": "resources/assets/js/documentos-form.js", + "isEntry": true + }, + "resources/assets/js/extended-ui-perfect-scrollbar.js": { + "file": "assets/extended-ui-perfect-scrollbar-87gYG_r1.js", + "name": "extended-ui-perfect-scrollbar", + "src": "resources/assets/js/extended-ui-perfect-scrollbar.js", + "isEntry": true + }, + "resources/assets/js/form-basic-inputs.js": { + "file": "assets/form-basic-inputs-CjS8llQr.js", + "name": "form-basic-inputs", + "src": "resources/assets/js/form-basic-inputs.js", + "isEntry": true + }, + "resources/assets/js/main.js": { + "file": "assets/main-TEy-IOuY.js", + "name": "main", + "src": "resources/assets/js/main.js", + "isEntry": true + }, + "resources/assets/js/movimentacoes-estoque-form.js": { + "file": "assets/movimentacoes-estoque-form-DcdXrZ93.js", + "name": "movimentacoes-estoque-form", + "src": "resources/assets/js/movimentacoes-estoque-form.js", + "isEntry": true + }, + "resources/assets/js/pages-account-settings-account.js": { + "file": "assets/pages-account-settings-account-CFTyzG2K.js", + "name": "pages-account-settings-account", + "src": "resources/assets/js/pages-account-settings-account.js", + "isEntry": true + }, + "resources/assets/js/pdv.js": { + "file": "assets/pdv-CLyL41Eh.js", + "name": "pdv", + "src": "resources/assets/js/pdv.js", + "isEntry": true + }, + "resources/assets/js/produtos-form.js": { + "file": "assets/produtos-form-BOD04I1Z.js", + "name": "produtos-form", + "src": "resources/assets/js/produtos-form.js", + "isEntry": true + }, + "resources/assets/js/ui-modals.js": { + "file": "assets/ui-modals-CYNbp-iO.js", + "name": "ui-modals", + "src": "resources/assets/js/ui-modals.js", + "isEntry": true + }, + "resources/assets/js/ui-popover.js": { + "file": "assets/ui-popover-CbvAU9Mu.js", + "name": "ui-popover", + "src": "resources/assets/js/ui-popover.js", + "isEntry": true + }, + "resources/assets/js/ui-toasts.js": { + "file": "assets/ui-toasts-D2tjOEuf.js", + "name": "ui-toasts", + "src": "resources/assets/js/ui-toasts.js", + "isEntry": true + }, + "resources/assets/vendor/fonts/iconify/iconify.css": { + "file": "assets/iconify-DDZnTNbY.css", + "src": "resources/assets/vendor/fonts/iconify/iconify.css", + "isEntry": true + }, + "resources/assets/vendor/fonts/iconify/iconify.js": { + "file": "assets/iconify-C8wdrYoI.js", + "name": "iconify", + "src": "resources/assets/vendor/fonts/iconify/iconify.js", + "isEntry": true + }, + "resources/assets/vendor/js/bootstrap.js": { + "file": "assets/bootstrap-BqFZZLXP.js", + "name": "bootstrap", + "src": "resources/assets/vendor/js/bootstrap.js", + "isEntry": true + }, + "resources/assets/vendor/js/helpers.js": { + "file": "assets/helpers-CB19AG1d.js", + "name": "helpers", + "src": "resources/assets/vendor/js/helpers.js", + "isEntry": true + }, + "resources/assets/vendor/js/menu.js": { + "file": "assets/menu-Bldkajpn.js", + "name": "menu", + "src": "resources/assets/vendor/js/menu.js", + "isEntry": true + }, + "resources/assets/vendor/libs/apex-charts/apex-charts.scss": { + "file": "assets/apex-charts-BSEhqGnV.css", + "src": "resources/assets/vendor/libs/apex-charts/apex-charts.scss", + "isEntry": true + }, + "resources/assets/vendor/libs/apex-charts/apexcharts.js": { + "file": "assets/apexcharts-DrruP4Np.js", + "name": "apexcharts", + "src": "resources/assets/vendor/libs/apex-charts/apexcharts.js", + "isEntry": true, + "imports": [ + "__commonjsHelpers-CqkleIqs.js" + ] + }, + "resources/assets/vendor/libs/highlight/highlight-github.scss": { + "file": "assets/highlight-github-BfC0goYb.css", + "src": "resources/assets/vendor/libs/highlight/highlight-github.scss", + "isEntry": true + }, + "resources/assets/vendor/libs/highlight/highlight.js": { + "file": "assets/highlight-BJVHAriQ.js", + "name": "highlight", + "src": "resources/assets/vendor/libs/highlight/highlight.js", + "isEntry": true, + "imports": [ + "__commonjsHelpers-CqkleIqs.js" + ] + }, + "resources/assets/vendor/libs/highlight/highlight.scss": { + "file": "assets/highlight-DGVygr29.css", + "src": "resources/assets/vendor/libs/highlight/highlight.scss", + "isEntry": true + }, + "resources/assets/vendor/libs/jquery/jquery.js": { + "file": "assets/jquery-Bh41zue2.js", + "name": "jquery", + "src": "resources/assets/vendor/libs/jquery/jquery.js", + "isEntry": true, + "imports": [ + "__commonjsHelpers-CqkleIqs.js" + ] + }, + "resources/assets/vendor/libs/masonry/masonry.js": { + "file": "assets/masonry-Di3k0CUD.js", + "name": "masonry", + "src": "resources/assets/vendor/libs/masonry/masonry.js", + "isEntry": true, + "imports": [ + "__commonjsHelpers-CqkleIqs.js" + ] + }, + "resources/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.js": { + "file": "assets/perfect-scrollbar-uMurzE2-.js", + "name": "perfect-scrollbar", + "src": "resources/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.js", + "isEntry": true, + "imports": [ + "__commonjsHelpers-CqkleIqs.js" + ] + }, + "resources/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.scss": { + "file": "assets/perfect-scrollbar-CfyPsj0y.css", + "src": "resources/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.scss", + "isEntry": true + }, + "resources/assets/vendor/libs/popper/popper.js": { + "file": "assets/popper-Ck0tsB3H.js", + "name": "popper", + "src": "resources/assets/vendor/libs/popper/popper.js", + "isEntry": true, + "imports": [ + "__commonjsHelpers-CqkleIqs.js" + ] + }, + "resources/assets/vendor/scss/core.scss": { + "file": "assets/core-DPkZ6__9.css", + "src": "resources/assets/vendor/scss/core.scss", + "isEntry": true + }, + "resources/assets/vendor/scss/pages/page-auth.scss": { + "file": "assets/page-auth-Cz9xnkSz.css", + "src": "resources/assets/vendor/scss/pages/page-auth.scss", + "isEntry": true + }, + "resources/assets/vendor/scss/pages/page-icons.scss": { + "file": "assets/page-icons-BhNyGxXr.css", + "src": "resources/assets/vendor/scss/pages/page-icons.scss", + "isEntry": true + }, + "resources/assets/vendor/scss/pages/page-misc.scss": { + "file": "assets/page-misc-D9kg9eYx.css", + "src": "resources/assets/vendor/scss/pages/page-misc.scss", + "isEntry": true + }, + "resources/css/app.css": { + "file": "assets/app-CsC4wx9G.css", + "src": "resources/css/app.css", + "isEntry": true + }, + "resources/js/app.js": { + "file": "assets/app-Bv13RJqf.js", + "name": "app", + "src": "resources/js/app.js", + "isEntry": true + } +} \ No newline at end of file diff --git a/resources/assets/js/clientes-form.js b/resources/assets/js/clientes-form.js new file mode 100644 index 00000000..e96c9fd7 --- /dev/null +++ b/resources/assets/js/clientes-form.js @@ -0,0 +1,169 @@ +const tipoPessoaEl = document.getElementById('tipo_pessoa'); + +if (tipoPessoaEl) { + const cpfCnpjEl = document.getElementById('cpf_cnpj'); + const btnBuscarCnpj = document.getElementById('btn_buscar_cnpj'); + const labelDocumento = document.getElementById('label_documento'); + const labelNome = document.getElementById('label_nome'); + const labelRgIe = document.getElementById('label_rg_ie'); + const labelData = document.getElementById('label_data'); + const ufEl = document.getElementById('uf'); + const cidadeEl = document.getElementById('cidade'); + + const camposPf = document.querySelectorAll('.campo-pf'); + const camposPj = document.querySelectorAll('.campo-pj'); + + const onlyDigits = value => (value || '').replace(/\D/g, ''); + + const maskCpf = value => value + .replace(/\D/g, '') + .replace(/(\d{3})(\d)/, '$1.$2') + .replace(/(\d{3})(\d)/, '$1.$2') + .replace(/(\d{3})(\d{1,2})$/, '$1-$2') + .slice(0, 14); + + const maskCnpj = value => value + .replace(/\D/g, '') + .replace(/^(\d{2})(\d)/, '$1.$2') + .replace(/^(\d{2})\.(\d{3})(\d)/, '$1.$2.$3') + .replace(/\.(\d{3})(\d)/, '.$1/$2') + .replace(/(\d{4})(\d)/, '$1-$2') + .slice(0, 18); + + const maskCep = value => value + .replace(/\D/g, '') + .replace(/(\d{5})(\d)/, '$1-$2') + .slice(0, 9); + + const maskPhone = value => { + const digits = value.replace(/\D/g, '').slice(0, 11); + if (digits.length <= 10) { + return digits + .replace(/(\d{2})(\d)/, '($1) $2') + .replace(/(\d{4})(\d)/, '$1-$2'); + } + return digits + .replace(/(\d{2})(\d)/, '($1) $2') + .replace(/(\d{5})(\d)/, '$1-$2'); + }; + + const updateTipoPessoaUI = () => { + const isPj = tipoPessoaEl.value === 'PJ'; + labelDocumento.textContent = isPj ? 'CNPJ' : 'CPF'; + labelNome.textContent = isPj ? 'Razao Social' : 'Nome Completo'; + labelRgIe.textContent = isPj ? 'Inscricao Estadual' : 'RG'; + labelData.textContent = isPj ? 'Data de Fundacao' : 'Data de Nascimento'; + btnBuscarCnpj.classList.toggle('d-none', !isPj); + camposPf.forEach(el => el.classList.toggle('d-none', isPj)); + camposPj.forEach(el => el.classList.toggle('d-none', !isPj)); + cpfCnpjEl.value = isPj ? maskCnpj(cpfCnpjEl.value) : maskCpf(cpfCnpjEl.value); + }; + + const fillInput = (id, value) => { + if (value === null || value === undefined || value === '') return; + const el = document.getElementById(id); + if (el) el.value = value; + }; + + const loadCidades = async (uf, selectedCidade = '') => { + if (!cidadeEl) return; + cidadeEl.innerHTML = ''; + if (!uf) { + cidadeEl.innerHTML = ''; + return; + } + + try { + const response = await fetch(`/clientes/cidades/${uf}`); + const payload = await response.json(); + const cidades = payload.cidades || []; + cidadeEl.innerHTML = ''; + cidades.forEach(cidade => { + const option = document.createElement('option'); + option.value = cidade; + option.textContent = cidade; + cidadeEl.appendChild(option); + }); + if (selectedCidade) { + const option = Array.from(cidadeEl.options).find(item => item.value === selectedCidade); + if (!option) { + const newOption = document.createElement('option'); + newOption.value = selectedCidade; + newOption.textContent = selectedCidade; + cidadeEl.appendChild(newOption); + } + cidadeEl.value = selectedCidade; + } + } catch (error) { + cidadeEl.innerHTML = ''; + } + }; + + tipoPessoaEl.addEventListener('change', updateTipoPessoaUI); + + cpfCnpjEl.addEventListener('input', () => { + cpfCnpjEl.value = tipoPessoaEl.value === 'PJ' ? maskCnpj(cpfCnpjEl.value) : maskCpf(cpfCnpjEl.value); + }); + + document.getElementById('cep')?.addEventListener('input', e => { + e.target.value = maskCep(e.target.value); + }); + + ['telefone', 'celular'].forEach(fieldId => { + document.getElementById(fieldId)?.addEventListener('input', e => { + e.target.value = maskPhone(e.target.value); + }); + }); + + btnBuscarCnpj.addEventListener('click', async () => { + const cnpj = onlyDigits(cpfCnpjEl.value); + if (cnpj.length !== 14) { + alert('Informe um CNPJ valido para consulta.'); + return; + } + + btnBuscarCnpj.disabled = true; + btnBuscarCnpj.textContent = 'Buscando...'; + + try { + const response = await fetch(`/clientes/cnpj/${cnpj}`); + const payload = await response.json(); + + if (!response.ok) { + throw new Error(payload.message || 'Erro ao consultar CNPJ.'); + } + + fillInput('nome', payload.nome); + fillInput('nome_fantasia', payload.nome_fantasia); + fillInput('email', payload.email); + fillInput('telefone', payload.telefone); + fillInput('cep', maskCep(payload.cep || '')); + fillInput('logradouro', payload.logradouro); + fillInput('numero', payload.numero); + fillInput('complemento', payload.complemento); + fillInput('bairro', payload.bairro); + fillInput('codigo_ibge', payload.codigo_ibge); + fillInput('pais', payload.pais); + + if (payload.uf) { + ufEl.value = payload.uf; + await loadCidades(payload.uf, payload.cidade || ''); + } + } catch (error) { + alert(error.message || 'Nao foi possivel buscar dados do CNPJ.'); + } finally { + btnBuscarCnpj.disabled = false; + btnBuscarCnpj.textContent = 'Buscar CNPJ'; + } + }); + + ufEl.addEventListener('change', e => { + loadCidades(e.target.value); + }); + + updateTipoPessoaUI(); + if (ufEl.value && cidadeEl.options.length <= 1) { + const cidadeSelecionada = cidadeEl.value; + loadCidades(ufEl.value, cidadeSelecionada); + } +} diff --git a/resources/assets/js/compra-form.js b/resources/assets/js/compra-form.js new file mode 100644 index 00000000..0d5fc7ca --- /dev/null +++ b/resources/assets/js/compra-form.js @@ -0,0 +1,72 @@ +const tabela = document.querySelector('#compra-itens-table tbody'); +const addBtn = document.getElementById('add-item-row'); + +const currency = (v) => `R$ ${Number(v || 0).toFixed(2).replace('.', ',')}`; + +const renumber = () => { + [...tabela.querySelectorAll('tr[data-row]')].forEach((row, index) => { + row.querySelectorAll('input, select').forEach((el) => { + const name = el.getAttribute('name'); + if (!name) return; + el.setAttribute('name', name.replace(/itens\[\d+\]/, `itens[${index}]`)); + }); + }); +}; + +const syncTotals = () => { + let totalItens = 0; + let totalValor = 0; + + [...tabela.querySelectorAll('tr[data-row]')].forEach((row) => { + const qtd = Number(row.querySelector('.item-qtd')?.value || 0); + const preco = Number(row.querySelector('.item-preco')?.value || 0); + totalItens += qtd; + totalValor += qtd * preco; + }); + + const itensEl = document.getElementById('compra-total-itens'); + const valorEl = document.getElementById('compra-total-valor'); + if (itensEl) itensEl.textContent = totalItens.toFixed(3).replace('.', ','); + if (valorEl) valorEl.textContent = currency(totalValor); +}; + +const bindRow = (row) => { + row.querySelectorAll('.item-qtd, .item-preco').forEach((el) => { + el.addEventListener('input', syncTotals); + }); + + row.querySelector('.remove-row')?.addEventListener('click', () => { + if (tabela.querySelectorAll('tr[data-row]').length <= 1) { + row.querySelector('.item-produto').value = ''; + row.querySelector('.item-qtd').value = '1'; + row.querySelector('.item-preco').value = '0'; + syncTotals(); + return; + } + row.remove(); + renumber(); + syncTotals(); + }); +}; + +addBtn?.addEventListener('click', () => { + const firstRow = tabela.querySelector('tr[data-row]'); + if (!firstRow) return; + const clone = firstRow.cloneNode(true); + clone.querySelectorAll('input').forEach((el) => { + if (el.type === 'number') { + el.value = el.classList.contains('item-qtd') ? '1' : '0'; + } else if (el.type === 'date' || el.type === 'text') { + el.value = ''; + } + }); + clone.querySelector('select.item-produto').value = ''; + tabela.appendChild(clone); + renumber(); + bindRow(clone); + syncTotals(); +}); + +[...tabela.querySelectorAll('tr[data-row]')].forEach(bindRow); +renumber(); +syncTotals(); diff --git a/resources/assets/js/documentos-form.js b/resources/assets/js/documentos-form.js new file mode 100644 index 00000000..2d1fc54a --- /dev/null +++ b/resources/assets/js/documentos-form.js @@ -0,0 +1,361 @@ +const tbody = document.querySelector('#documento-itens-table tbody'); +const tipoEl = document.querySelector('[data-tipo-documento]'); +const searchInput = document.getElementById('produto-search-input'); +const resultsBox = document.getElementById('produto-search-results'); +const searchUrl = window.documentoProdutoSearchUrl || ''; +const clienteSearchInput = document.getElementById('cliente-search-input'); +const clienteIdInput = document.getElementById('cliente_id'); +const clienteResultsBox = document.getElementById('cliente-search-results'); +const clienteMeta = document.getElementById('cliente-selected-meta'); +const clienteSearchUrl = window.documentoClienteSearchUrl || ''; +const statusEl = document.querySelector('[data-status-documento]'); +const statusOptionsByTipo = window.documentoStatusOptionsByTipo || {}; +const regrasEdicao = window.documentoRegrasEdicao || {}; +const bloqueiaItens = Boolean(regrasEdicao && regrasEdicao.permite_alterar_itens === false); + +const formatCurrency = (value) => `R$ ${Number(value || 0).toFixed(2).replace('.', ',')}`; + +const allowItemPriceEdit = () => (tipoEl?.value || 'ORCAMENTO') === 'ORCAMENTO'; + +const renumberRows = () => { + [...tbody.querySelectorAll('tr[data-row]')].forEach((row, index) => { + row.querySelectorAll('input').forEach((el) => { + const name = el.getAttribute('name'); + if (!name) return; + el.setAttribute('name', name.replace(/itens\[\d+\]/, `itens[${index}]`)); + }); + }); +}; + +const calcRow = (row) => { + const qtdEl = row.querySelector('.item-quantidade'); + const precoEl = row.querySelector('.item-preco'); + const subtotalEl = row.querySelector('.item-subtotal'); + + const qtd = Number(qtdEl.value || 0); + const preco = Number(precoEl.value || 0); + const subtotal = qtd * preco; + subtotalEl.value = formatCurrency(subtotal); + + return subtotal; +}; + +const calcTotals = () => { + const subtotal = [...tbody.querySelectorAll('tr[data-row]')].reduce((acc, row) => acc + calcRow(row), 0); + + const desconto = Number(document.getElementById('desconto_total')?.value || 0); + const acrescimo = Number(document.getElementById('acrescimo_total')?.value || 0); + const impostos = Number(document.getElementById('impostos_total')?.value || 0); + const total = Math.max(0, subtotal - desconto + acrescimo + impostos); + + const subtotalPreview = document.getElementById('subtotal-preview'); + const totalPreview = document.getElementById('total-preview'); + if (subtotalPreview) subtotalPreview.textContent = formatCurrency(subtotal); + if (totalPreview) totalPreview.textContent = formatCurrency(total); +}; + +const updatePriceMode = () => { + const editable = allowItemPriceEdit(); + tbody.querySelectorAll('.item-preco').forEach((el) => { + if (bloqueiaItens) { + el.setAttribute('readonly', 'readonly'); + el.classList.add('bg-label-secondary'); + return; + } + + if (editable) { + el.removeAttribute('readonly'); + el.classList.remove('bg-label-secondary'); + } else { + el.setAttribute('readonly', 'readonly'); + el.classList.add('bg-label-secondary'); + } + }); +}; + +const updateStatusOptionsByTipo = () => { + if (!tipoEl || !statusEl) return; + + const tipo = tipoEl.value || 'ORCAMENTO'; + const options = statusOptionsByTipo[tipo] || []; + const selected = statusEl.value; + + statusEl.innerHTML = options + .map((status) => ``) + .join(''); + + if (options.includes(selected)) { + statusEl.value = selected; + return; + } + + if (options.length) { + statusEl.value = options[0]; + } +}; + +const bindRowEvents = (row) => { + row.querySelectorAll('.item-quantidade, .item-preco').forEach((el) => { + el.addEventListener('input', calcTotals); + el.addEventListener('change', calcTotals); + }); + + row.querySelector('.remove-item-btn')?.addEventListener('click', () => { + if (tbody.querySelectorAll('tr[data-row]').length <= 1) { + row.querySelector('.item-produto-id').value = ''; + row.querySelector('.item-produto-nome').value = ''; + row.querySelector('.item-produto-meta').textContent = ''; + row.querySelector('.item-quantidade').value = '1'; + row.querySelector('.item-preco').value = '0'; + calcTotals(); + return; + } + + row.remove(); + renumberRows(); + calcTotals(); + }); +}; + +const getRowByProductId = (productId) => + [...tbody.querySelectorAll('tr[data-row]')].find((row) => row.querySelector('.item-produto-id').value === String(productId)); + +const addOrIncrementItem = (produto) => { + if (bloqueiaItens) return; + + const existingRow = getRowByProductId(produto.id); + if (existingRow) { + const qtdEl = existingRow.querySelector('.item-quantidade'); + qtdEl.value = Number(qtdEl.value || 0) + 1; + + if (!allowItemPriceEdit()) { + existingRow.querySelector('.item-preco').value = Number(produto.preco || 0).toFixed(4); + } + + calcTotals(); + return; + } + + const hasBlankRow = [...tbody.querySelectorAll('tr[data-row]')].find((row) => !row.querySelector('.item-produto-id').value); + const row = hasBlankRow || document.createElement('tr'); + + if (!hasBlankRow) { + const index = tbody.querySelectorAll('tr[data-row]').length; + row.setAttribute('data-row', '1'); + row.innerHTML = ` + + + + + + + + + + `; + tbody.appendChild(row); + } + + row.querySelector('.item-produto-id').value = String(produto.id); + row.querySelector('.item-produto-nome').value = `${produto.nome} (${produto.sku || '-'})`; + row.querySelector('.item-produto-meta').textContent = `${produto.unidade || 'UN'} • EAN: ${produto.ean || '-'}`; + row.querySelector('.item-quantidade').value = '1'; + row.querySelector('.item-preco').value = Number(produto.preco || 0).toFixed(4); + + renumberRows(); + bindRowEvents(row); + updatePriceMode(); + calcTotals(); +}; + +let searchTimeout = null; +const hideResults = () => { + resultsBox.innerHTML = ''; + resultsBox.style.display = 'none'; +}; + +const renderResults = (items) => { + if (!items.length) { + resultsBox.innerHTML = '
Nenhum produto encontrado.
'; + resultsBox.style.display = 'block'; + return; + } + + resultsBox.innerHTML = items + .map( + (p) => ` + + ` + ) + .join(''); + + resultsBox.style.display = 'block'; +}; + +const fetchProducts = async (term) => { + if (!searchUrl) return; + const response = await fetch(`${searchUrl}?termo=${encodeURIComponent(term)}`); + if (!response.ok) return; + const data = await response.json(); + renderResults(data.produtos || []); +}; + +searchInput?.addEventListener('input', () => { + const term = (searchInput.value || '').trim(); + if (term.length < 2) { + hideResults(); + return; + } + + clearTimeout(searchTimeout); + searchTimeout = setTimeout(() => { + fetchProducts(term); + }, 250); +}); + +resultsBox?.addEventListener('click', (event) => { + const target = event.target.closest('.produto-result-item'); + if (!target) return; + + addOrIncrementItem({ + id: target.dataset.id, + nome: target.dataset.nome, + sku: target.dataset.sku, + ean: target.dataset.ean, + unidade: target.dataset.unidade, + preco: Number(target.dataset.preco || 0), + }); + + searchInput.value = ''; + hideResults(); + searchInput.focus(); +}); + +document.addEventListener('click', (event) => { + if (resultsBox && !resultsBox.contains(event.target) && event.target !== searchInput) { + hideResults(); + } +}); + +let clienteSearchTimeout = null; +const hideClienteResults = () => { + if (!clienteResultsBox) return; + clienteResultsBox.innerHTML = ''; + clienteResultsBox.style.display = 'none'; +}; + +const renderClienteResults = (items) => { + if (!clienteResultsBox) return; + if (!items.length) { + clienteResultsBox.innerHTML = '
Nenhum cliente encontrado.
'; + clienteResultsBox.style.display = 'block'; + return; + } + + clienteResultsBox.innerHTML = items + .map( + (c) => ` + + ` + ) + .join(''); + + clienteResultsBox.style.display = 'block'; +}; + +const fetchClientes = async (term) => { + if (!clienteSearchUrl) return; + try { + const response = await fetch(`${clienteSearchUrl}?termo=${encodeURIComponent(term)}`); + if (!response.ok) { + renderClienteResults([]); + return; + } + const data = await response.json(); + renderClienteResults(data.clientes || []); + } catch (error) { + renderClienteResults([]); + } +}; + +clienteSearchInput?.addEventListener('input', () => { + const term = (clienteSearchInput.value || '').trim(); + if (term.length < 2) { + hideClienteResults(); + return; + } + + if (clienteIdInput) { + clienteIdInput.value = ''; + } + if (clienteMeta) { + clienteMeta.textContent = ''; + } + + clearTimeout(clienteSearchTimeout); + clienteSearchTimeout = setTimeout(() => { + fetchClientes(term); + }, 250); +}); + +clienteResultsBox?.addEventListener('click', (event) => { + const target = event.target.closest('.cliente-result-item'); + if (!target) return; + + if (clienteIdInput) { + clienteIdInput.value = target.dataset.id || ''; + } + if (clienteSearchInput) { + clienteSearchInput.value = target.dataset.nome || ''; + } + if (clienteMeta) { + clienteMeta.textContent = `${target.dataset.tipo || '-'} • ${target.dataset.cpfcnpj || '-'} • ${target.dataset.telefone || '-'}`; + } + hideClienteResults(); +}); + +document.addEventListener('click', (event) => { + if (clienteResultsBox && !clienteResultsBox.contains(event.target) && event.target !== clienteSearchInput) { + hideClienteResults(); + } +}); + +tipoEl?.addEventListener('change', () => { + updateStatusOptionsByTipo(); + updatePriceMode(); + calcTotals(); +}); + +document.querySelectorAll('.documento-ajuste').forEach((el) => { + el.addEventListener('input', calcTotals); +}); + +[...tbody.querySelectorAll('tr[data-row]')].forEach((row) => { + bindRowEvents(row); +}); + +renumberRows(); +updateStatusOptionsByTipo(); +updatePriceMode(); +calcTotals(); + +document.getElementById('documento-form')?.addEventListener('submit', (event) => { + if (!clienteIdInput?.value) { + event.preventDefault(); + alert('Selecione um cliente na busca antes de salvar.'); + clienteSearchInput?.focus(); + } +}); diff --git a/resources/assets/js/movimentacoes-estoque-form.js b/resources/assets/js/movimentacoes-estoque-form.js new file mode 100644 index 00000000..626c6a5b --- /dev/null +++ b/resources/assets/js/movimentacoes-estoque-form.js @@ -0,0 +1,32 @@ +const produtoEl = document.getElementById('produto_id'); +const tipoEl = document.getElementById('tipo'); +const ajusteWrap = document.querySelector('.ajuste-direcao-wrap'); +const loteWraps = document.querySelectorAll('.lote-wrap'); +const validadeWrap = document.querySelector('.validade-wrap'); +const entradaWrap = document.querySelector('.entrada-wrap'); + +if (produtoEl && tipoEl) { + const toggleByTipo = () => { + const tipo = tipoEl.value; + const isAjuste = tipo === 'AJUSTE'; + const isEntrada = tipo === 'ENTRADA'; + ajusteWrap.classList.toggle('d-none', !isAjuste); + entradaWrap.classList.toggle('d-none', !(isEntrada || isAjuste)); + }; + + const toggleByProduto = () => { + const selected = produtoEl.options[produtoEl.selectedIndex]; + if (!selected) return; + + const controlaLote = selected.dataset.controlaLote === '1'; + const controlaValidade = selected.dataset.controlaValidade === '1'; + + loteWraps.forEach(el => el.classList.toggle('d-none', !controlaLote)); + validadeWrap.classList.toggle('d-none', !controlaValidade); + }; + + tipoEl.addEventListener('change', toggleByTipo); + produtoEl.addEventListener('change', toggleByProduto); + toggleByTipo(); + toggleByProduto(); +} diff --git a/resources/assets/js/pdv.js b/resources/assets/js/pdv.js new file mode 100644 index 00000000..e0f091e2 --- /dev/null +++ b/resources/assets/js/pdv.js @@ -0,0 +1,331 @@ +const produtos = Array.isArray(window.pdvProdutos) ? window.pdvProdutos : []; +const carrinhoTbody = document.querySelector('#pdv-carrinho tbody'); +const searchEl = document.getElementById('pdv-search'); +const searchResultsEl = document.getElementById('pdv-search-results'); +const form = document.getElementById('pdv-form'); +const clienteEl = document.getElementById('cliente_id'); +const clearBtn = document.getElementById('pdv-clear-cart'); + +const totalItensEl = document.getElementById('pdv-total-itens'); +const totalVolumeEl = document.getElementById('pdv-total-volume'); + +const cart = new Map(); +let highlightedResult = -1; +let visibleResults = []; +let lastAddedProductId = null; + +const currency = (v) => `R$ ${Number(v || 0).toFixed(2).replace('.', ',')}`; +const qtyFmt = (v) => Number(v || 0).toFixed(3).replace('.', ','); + +const findProducts = (query, limit = 10) => { + const term = (query || '').trim().toLowerCase(); + if (!term) return []; + + return produtos + .map((p) => { + const nome = String(p.nome || '').toLowerCase(); + const sku = String(p.sku || '').toLowerCase(); + const ean = String(p.ean || '').toLowerCase(); + let score = 0; + + if (ean && ean === term) score += 100; + if (sku && sku === term) score += 90; + if (nome.startsWith(term)) score += 80; + if (sku.startsWith(term)) score += 70; + if (ean.startsWith(term)) score += 60; + if (nome.includes(term)) score += 50; + if (sku.includes(term)) score += 40; + if (ean.includes(term)) score += 30; + + return { produto: p, score }; + }) + .filter((x) => x.score > 0) + .sort((a, b) => b.score - a.score || String(a.produto.nome).localeCompare(String(b.produto.nome))) + .slice(0, limit) + .map((x) => x.produto); +}; + +const syncTotals = () => { + const subtotal = [...cart.values()].reduce((acc, item) => acc + item.preco * item.qtd, 0); + const volume = [...cart.values()].reduce((acc, item) => acc + item.qtd, 0); + const desconto = Number(document.getElementById('pdv-desconto')?.value || 0); + const acrescimo = Number(document.getElementById('pdv-acrescimo')?.value || 0); + const impostos = Number(document.getElementById('pdv-impostos')?.value || 0); + const total = Math.max(0, subtotal - desconto + acrescimo + impostos); + + const subtotalEl = document.getElementById('pdv-subtotal'); + const totalEl = document.getElementById('pdv-total'); + if (subtotalEl) subtotalEl.textContent = currency(subtotal); + if (totalEl) totalEl.textContent = currency(total); + if (totalItensEl) totalItensEl.textContent = String(cart.size); + if (totalVolumeEl) totalVolumeEl.textContent = qtyFmt(volume); +}; + +const renderCarrinho = () => { + carrinhoTbody.innerHTML = ''; + + [...cart.values()].forEach((item, index) => { + const tr = document.createElement('tr'); + tr.innerHTML = ` + + ${item.nome}
+ ${item.sku || '-'} • Estoque: ${qtyFmt(item.estoque)} + + + + + ${currency(item.preco)} + ${currency(item.preco * item.qtd)} + + `; + carrinhoTbody.appendChild(tr); + }); + + syncTotals(); +}; + +const addProductToCart = (product) => { + if (!product) return; + const key = String(product.id); + const existing = cart.get(key); + if (existing) { + existing.qtd += 1; + } else { + cart.set(key, { ...product, qtd: 1 }); + } + lastAddedProductId = key; + renderCarrinho(); +}; + +const hideResults = () => { + if (!searchResultsEl) return; + searchResultsEl.innerHTML = ''; + searchResultsEl.style.display = 'none'; + visibleResults = []; + highlightedResult = -1; +}; + +const highlightResult = (index) => { + highlightedResult = index; + if (!searchResultsEl) return; + const nodes = searchResultsEl.querySelectorAll('.pdv-result-item'); + nodes.forEach((node, i) => { + if (i === index) { + node.classList.add('active'); + node.scrollIntoView({ block: 'nearest' }); + } else { + node.classList.remove('active'); + } + }); +}; + +const renderResults = (items) => { + if (!searchResultsEl) return; + visibleResults = items; + highlightedResult = items.length ? 0 : -1; + + if (!items.length) { + searchResultsEl.innerHTML = '
Nenhum produto encontrado.
'; + searchResultsEl.style.display = 'block'; + return; + } + + searchResultsEl.innerHTML = items + .map( + (p, i) => ` + + ` + ) + .join(''); + + searchResultsEl.style.display = 'block'; +}; + +const tryAutoAddExactMatch = (term) => { + const clean = String(term || '').trim().toLowerCase(); + if (!clean) return false; + + const exact = produtos.find((p) => { + const ean = String(p.ean || '').toLowerCase(); + const sku = String(p.sku || '').toLowerCase(); + return (ean && ean === clean) || (sku && sku === clean); + }); + + if (!exact) return false; + addProductToCart(exact); + return true; +}; + +const openConferenciaAndSubmit = () => { + if (cart.size === 0) { + alert('Adicione pelo menos 1 item no carrinho.'); + return; + } + + if (!clienteEl?.value) { + alert('Selecione um cliente antes de finalizar.'); + clienteEl?.focus(); + return; + } + + const subtotal = [...cart.values()].reduce((acc, item) => acc + item.preco * item.qtd, 0); + const desconto = Number(document.getElementById('pdv-desconto')?.value || 0); + const acrescimo = Number(document.getElementById('pdv-acrescimo')?.value || 0); + const impostos = Number(document.getElementById('pdv-impostos')?.value || 0); + const total = Math.max(0, subtotal - desconto + acrescimo + impostos); + const totalQtd = [...cart.values()].reduce((acc, item) => acc + item.qtd, 0); + + const ok = window.confirm( + `Conferência de fechamento:\n` + + `Itens distintos: ${cart.size}\n` + + `Quantidade total: ${qtyFmt(totalQtd)}\n` + + `Subtotal: ${currency(subtotal)}\n` + + `Total final: ${currency(total)}\n\n` + + `Confirma finalizar a venda?` + ); + + if (ok) { + form?.submit(); + } +}; + +searchEl?.addEventListener('input', () => { + const term = searchEl.value || ''; + if (!term.trim()) { + hideResults(); + return; + } + + renderResults(findProducts(term)); +}); + +searchEl?.addEventListener('keydown', (event) => { + const term = searchEl.value || ''; + + if (event.key === 'ArrowDown') { + event.preventDefault(); + if (!visibleResults.length) return; + highlightResult(Math.min(highlightedResult + 1, visibleResults.length - 1)); + return; + } + + if (event.key === 'ArrowUp') { + event.preventDefault(); + if (!visibleResults.length) return; + highlightResult(Math.max(highlightedResult - 1, 0)); + return; + } + + if (event.key === 'Escape') { + hideResults(); + return; + } + + if (event.key !== 'Enter') return; + event.preventDefault(); + + if (tryAutoAddExactMatch(term)) { + searchEl.value = ''; + hideResults(); + return; + } + + const result = visibleResults[highlightedResult] || visibleResults[0] || findProducts(term, 1)[0]; + if (!result) return; + addProductToCart(result); + searchEl.value = ''; + hideResults(); +}); + +searchResultsEl?.addEventListener('click', (event) => { + const btn = event.target.closest('.pdv-result-item'); + if (!btn) return; + const id = String(btn.getAttribute('data-id')); + const product = produtos.find((p) => String(p.id) === id); + addProductToCart(product); + searchEl.value = ''; + hideResults(); + searchEl.focus(); +}); + +document.addEventListener('click', (event) => { + if (!searchResultsEl || !searchEl) return; + if (!searchResultsEl.contains(event.target) && event.target !== searchEl) { + hideResults(); + } +}); + +carrinhoTbody?.addEventListener('input', (event) => { + const target = event.target; + if (!(target instanceof HTMLInputElement) || !target.classList.contains('pdv-qtd')) return; + const id = target.dataset.id; + const item = cart.get(String(id)); + if (!item) return; + item.qtd = Math.max(0.001, Number(target.value || 0.001)); + renderCarrinho(); +}); + +carrinhoTbody?.addEventListener('click', (event) => { + const target = event.target; + if (!(target instanceof HTMLElement) || !target.classList.contains('pdv-remove')) return; + const id = target.getAttribute('data-id'); + cart.delete(String(id)); + renderCarrinho(); +}); + +['pdv-desconto', 'pdv-acrescimo', 'pdv-impostos'].forEach((id) => { + document.getElementById(id)?.addEventListener('input', syncTotals); +}); + +clearBtn?.addEventListener('click', () => { + if (!cart.size) return; + if (!window.confirm('Limpar todo o carrinho?')) return; + cart.clear(); + lastAddedProductId = null; + renderCarrinho(); + searchEl?.focus(); +}); + +document.addEventListener('keydown', (event) => { + if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLSelectElement) { + if (event.key !== 'F2' && event.key !== 'F4' && event.key !== 'F8') { + return; + } + } + + if (event.key === 'F2') { + event.preventDefault(); + searchEl?.focus(); + searchEl?.select(); + return; + } + + if (event.key === 'F4') { + event.preventDefault(); + openConferenciaAndSubmit(); + return; + } + + if (event.key === 'F8') { + event.preventDefault(); + clearBtn?.click(); + return; + } + + if (event.key === 'Backspace' && event.ctrlKey) { + event.preventDefault(); + if (!lastAddedProductId) return; + cart.delete(lastAddedProductId); + renderCarrinho(); + } +}); + +form?.addEventListener('submit', (event) => { + event.preventDefault(); + openConferenciaAndSubmit(); +}); + +renderCarrinho(); diff --git a/resources/assets/js/produtos-form.js b/resources/assets/js/produtos-form.js new file mode 100644 index 00000000..df207a27 --- /dev/null +++ b/resources/assets/js/produtos-form.js @@ -0,0 +1,27 @@ +const precoCustoEl = document.getElementById('preco_custo'); +const precoVendaEl = document.getElementById('preco_venda'); +const margemVisualEl = document.getElementById('margem_visual'); + +if (precoCustoEl && precoVendaEl && margemVisualEl) { + const formatPercent = value => value.toLocaleString('pt-BR', { + minimumFractionDigits: 2, + maximumFractionDigits: 2 + }); + + const recomputeMargin = () => { + const custo = parseFloat(precoCustoEl.value || '0'); + const venda = parseFloat(precoVendaEl.value || '0'); + + if (custo <= 0) { + margemVisualEl.value = '0,00'; + return; + } + + const margin = ((venda - custo) / custo) * 100; + margemVisualEl.value = formatPercent(margin); + }; + + precoCustoEl.addEventListener('input', recomputeMargin); + precoVendaEl.addEventListener('input', recomputeMargin); + recomputeMargin(); +} diff --git a/resources/css/app.css b/resources/css/app.css index e69de29b..b5c61c95 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; diff --git a/resources/js/app.js b/resources/js/app.js index cda08dd1..a8093bee 100644 --- a/resources/js/app.js +++ b/resources/js/app.js @@ -1,9 +1,7 @@ import './bootstrap'; -/* - Add custom scripts here -*/ -import.meta.glob([ - '../assets/img/**', - // '../assets/json/**', - '../assets/vendor/fonts/**' -]); + +import Alpine from 'alpinejs'; + +window.Alpine = Alpine; + +Alpine.start(); diff --git a/resources/menu/verticalMenu.json b/resources/menu/verticalMenu.json index 22852a33..eb95f136 100644 --- a/resources/menu/verticalMenu.json +++ b/resources/menu/verticalMenu.json @@ -2,480 +2,182 @@ "menu": [ { "url": "/", - "name": "Dashboards", + "name": "Dashboard", "icon": "menu-icon icon-base bx bx-home-smile", - "slug": "dashboard", - "badge": [ - "danger", - "5" - ], - "submenu": [ - { - "url": "/", - "name": "Analytics", - "slug": "dashboard-analytics" - }, - { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/dashboard/crm", - "name": "CRM", - "slug": "dashboard-crm", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" - ] - }, - { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/app/ecommerce/dashboard", - "name": "eCommerce", - "slug": "app-ecommerce-dashboard", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" - ] - }, - { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/app/logistics/dashboard", - "name": "Logistics", - "slug": "app-logistics-dashboard", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" - ] - }, - { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/app/academy/dashboard", - "name": "Academy", - "slug": "app-academy-dashboard", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" - ] - } - ] + "slug": "dashboard-analytics", + "permission": "dashboard.view" + }, + { + "menuHeader": "Gestao" + }, + { + "url": "clientes", + "name": "Clientes", + "icon": "menu-icon icon-base bx bx-group", + "slug": "clientes", + "permission": "clientes.view" + }, + { + "url": "produtos", + "name": "Produtos", + "icon": "menu-icon icon-base bx bx-box", + "slug": "produtos", + "permission": "produtos.view" }, { - "name": "Layouts", - "icon": "menu-icon icon-base bx bx-layout", - "slug": "layouts", + "name": "Vendas", + "icon": "menu-icon icon-base bx bx-cart-alt", + "slug": "vendas", "submenu": [ { - "url": "layouts/without-menu", - "name": "Without menu", - "slug": "layouts-without-menu" - }, - { - "url": "layouts/without-navbar", - "name": "Without navbar", - "slug": "layouts-without-navbar" - }, - { - "url": "layouts/container", - "name": "Container", - "slug": "layouts-container" + "url": "documentos-comerciais", + "name": "Documentos", + "slug": "documentos-comerciais", + "permission": "vendas.documentos.view" }, { - "url": "layouts/fluid", - "name": "Fluid", - "slug": "layouts-fluid" - }, - { - "url": "layouts/blank", - "name": "Blank", - "slug": "layouts-blank", - "target": "_blank" + "url": "pdv", + "name": "PDV Rapido", + "slug": "pdv", + "permission": "vendas.pdv.use" } ] }, { - "name": "Front Pages", - "icon": "menu-icon icon-base bx bx-store", - "slug": "front-pages", - "badge": [ - "label-primary fs-tiny", - "Pro" - ], + "name": "Cadastros Base", + "icon": "menu-icon icon-base bx bx-layer", + "slug": "cadastros", "submenu": [ { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/front-pages/landing", - "name": "Landing", - "slug": "front-pages-landing", - "target": "_blank" - }, - { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/front-pages/pricing", - "name": "Pricing", - "slug": "front-pages-pricing", - "target": "_blank" + "url": "categorias-produto", + "name": "Categorias", + "slug": "categorias-produto", + "permission": "cadastros_base.view" }, { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/front-pages/payment", - "name": "Payment", - "slug": "front-pages-payment", - "target": "_blank" + "url": "unidades-medida", + "name": "Unidades", + "slug": "unidades-medida", + "permission": "cadastros_base.view" }, { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/front-pages/checkout", - "name": "Checkout", - "slug": "front-pages-checkout", - "target": "_blank" - }, - { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/front-pages/help-center", - "name": "Help Center", - "slug": "front-pages-help-center", - "target": "_blank" + "url": "tabelas-preco", + "name": "Tabelas de Preco", + "slug": "tabelas-preco", + "permission": "cadastros_base.view" } ] }, { - "name": "Laravel Crud", - "icon": "menu-icon icon-base bx bxl-php", - "slug": "laravel-example", - "badge": [ - "label-primary fs-tiny", - "Pro" - ], - "submenu": [ - { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/laravel/user-management", - "name": "User Management", - "slug": "laravel-example-user-management", - "target": "_blank" - } - ] + "url": "movimentacoes-estoque", + "name": "Movimentacao Estoque", + "icon": "menu-icon icon-base bx bx-transfer", + "slug": "movimentacoes-estoque", + "permission": "estoque.movimentacoes.view" }, { - "menuHeader": "Apps & Pages" + "url": "estoque/alertas", + "name": "Alertas de Estoque", + "icon": "menu-icon icon-base bx bx-error-circle", + "slug": "estoque-alertas", + "permission": "estoque.alertas.view" }, { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/app/email", - "name": "Email", - "icon": "menu-icon icon-base bx bx-envelope", - "slug": "app-email", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" - ] + "url": "contas-receber", + "name": "Contas a Receber", + "icon": "menu-icon icon-base bx bx-wallet", + "slug": "contas-receber", + "permission": "financeiro.contas_receber.view" }, { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/app/chat", - "name": "Chat", - "icon": "menu-icon icon-base bx bx-chat", - "slug": "app-chat", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" - ] + "url": "contas-pagar", + "name": "Contas a Pagar", + "icon": "menu-icon icon-base bx bx-receipt", + "slug": "contas-pagar", + "permission": "financeiro.contas_pagar.view" }, { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/app/calendar", - "name": "Calendar", - "icon": "menu-icon icon-base bx bx-calendar", - "slug": "app-calendar", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" + "name": "Compras", + "icon": "menu-icon icon-base bx bx-cart-download", + "slug": "compras", + "submenu": [ + { + "url": "fornecedores", + "name": "Fornecedores", + "slug": "fornecedores", + "permission": "compras.fornecedores.view" + }, + { + "url": "compras", + "name": "Entradas de Compra", + "slug": "compras-lista", + "permission": "compras.compras.view" + } ] }, { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/app/kanban", - "name": "Kanban", - "icon": "menu-icon icon-base bx bx-grid", - "slug": "app-kanban", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" - ] + "url": "usuarios", + "name": "Usuarios e Acessos", + "icon": "menu-icon icon-base bx bx-shield-quarter", + "slug": "usuarios", + "permission": "usuarios.view" }, { - "name": "Account Settings", - "icon": "menu-icon icon-base bx bx-dock-top", + "url": "auditoria", + "name": "Auditoria", + "icon": "menu-icon icon-base bx bx-history", + "slug": "auditoria", + "permission": "auditoria.view" + }, + { + "name": "Conta", + "icon": "menu-icon icon-base bx bx-user", "slug": "pages-account-settings", + "permission": "dashboard.view", "submenu": [ { "url": "pages/account-settings-account", - "name": "Account", + "name": "Perfil", "slug": "pages-account-settings-account" }, { "url": "pages/account-settings-notifications", - "name": "Notifications", + "name": "Notificacoes", "slug": "pages-account-settings-notifications" }, { "url": "pages/account-settings-connections", - "name": "Connections", + "name": "Conexoes", "slug": "pages-account-settings-connections" } ] }, { - "name": "Authentications", + "menuHeader": "Acesso", + "auth": "guest" + }, + { + "name": "Autenticacao", "icon": "menu-icon icon-base bx bx-lock-open-alt", "slug": "auth", + "auth": "guest", "submenu": [ { "url": "auth/login-basic", "name": "Login", - "slug": "auth-login-basic", - "target": "_blank" + "slug": "auth-login-basic" }, { "url": "auth/register-basic", - "name": "Register", - "slug": "auth-register-basic", - "target": "_blank" + "name": "Cadastro", + "slug": "auth-register-basic" }, { "url": "auth/forgot-password-basic", - "name": "Forgot Password", - "slug": "auth-forgot-password-basic", - "target": "_blank" - } - ] - }, - { - "name": "Misc", - "icon": "menu-icon icon-base bx bx-cube-alt", - "slug": "pages-misc", - "submenu": [ - { - "url": "pages/misc-error", - "name": "Error", - "slug": "pages-misc-error", - "target": "_blank" - }, - { - "url": "pages/misc-under-maintenance", - "name": "Under Maintenance", - "slug": "pages-misc-under-maintenance", - "target": "_blank" - } - ] - }, - { - "menuHeader": "Components" - }, - { - "name": "Cards", - "icon": "menu-icon icon-base bx bx-collection", - "slug": "cards-basic", - "url": "cards/basic" - }, - { - "name": "User interface", - "icon": "menu-icon icon-base bx bx-box", - "slug": "ui", - "submenu": [ - { - "url": "ui/accordion", - "name": "Accordion", - "slug": "ui-accordion" - }, - { - "url": "ui/alerts", - "name": "Alerts", - "slug": "ui-alerts" - }, - { - "url": "ui/badges", - "name": "Badges", - "slug": "ui-badges" - }, - { - "url": "ui/buttons", - "name": "Buttons", - "slug": "ui-buttons" - }, - { - "url": "ui/carousel", - "name": "Carousel", - "slug": "ui-carousel" - }, - { - "url": "ui/collapse", - "name": "Collapse", - "slug": "ui-collapse" - }, - { - "url": "ui/dropdowns", - "name": "Dropdowns", - "slug": "ui-dropdowns" - }, - { - "url": "ui/footer", - "name": "Footer", - "slug": "ui-footer" - }, - { - "url": "ui/list-groups", - "name": "List groups", - "slug": "ui-list-groups" - }, - { - "url": "ui/modals", - "name": "Modals", - "slug": "ui-modals" - }, - { - "url": "ui/navbar", - "name": "Navbar", - "slug": "ui-navbar" - }, - { - "url": "ui/offcanvas", - "name": "Offcanvas", - "slug": "ui-offcanvas" - }, - { - "url": "ui/pagination-breadcrumbs", - "name": "Pagination & Breadcrumbs", - "slug": "ui-pagination-breadcrumbs" - }, - { - "url": "ui/progress", - "name": "Progress", - "slug": "ui-progress" - }, - { - "url": "ui/spinners", - "name": "Spinners", - "slug": "ui-spinners" - }, - { - "url": "ui/tabs-pills", - "name": "Tabs & Pills", - "slug": "ui-tabs-pills" - }, - { - "url": "ui/toasts", - "name": "Toasts", - "slug": "ui-toasts" - }, - { - "url": "ui/tooltips-popovers", - "name": "Tooltips & Popovers", - "slug": "ui-tooltips-popovers" - }, - { - "url": "ui/typography", - "name": "Typography", - "slug": "ui-typography" + "name": "Esqueci a senha", + "slug": "auth-forgot-password-basic" } ] - }, - { - "name": "Extended UI", - "icon": "menu-icon icon-base bx bx-copy", - "slug": "extended", - "submenu": [ - { - "url": "extended/ui-perfect-scrollbar", - "name": "Perfect Scrollbar", - "slug": "extended-ui-perfect-scrollbar" - }, - { - "url": "extended/ui-text-divider", - "name": "Text Divider", - "slug": "extended-ui-text-divider" - } - ] - }, - { - "url": "icons/boxicons", - "icon": "menu-icon icon-base bx bx-crown", - "name": "Boxicons", - "slug": "icons-boxicons" - }, - { - "menuHeader": "Forms & Tables" - }, - { - "name": "Form Elements", - "icon": "menu-icon icon-base bx bx-detail", - "slug": "forms", - "submenu": [ - { - "url": "forms/basic-inputs", - "name": "Basic Inputs", - "slug": "forms-basic-inputs" - }, - { - "url": "forms/input-groups", - "name": "Input groups", - "slug": "forms-input-groups" - } - ] - }, - { - "name": "Form Layouts", - "icon": "menu-icon icon-base bx bx-detail", - "slug": "form-layouts", - "submenu": [ - { - "url": "form/layouts-vertical", - "name": "Vertical Form", - "slug": "form-layouts-vertical" - }, - { - "url": "form/layouts-horizontal", - "name": "Horizontal Form", - "slug": "form-layouts-horizontal" - } - ] - }, - { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/form/validation", - "icon": "menu-icon icon-base bx bx-list-check", - "name": "Form Validation", - "slug": "form-validation", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" - ] - }, - { - "url": "tables/basic", - "icon": "menu-icon icon-base bx bx-table", - "name": "Tables", - "slug": "tables-basic" - }, - { - "url": "https://demos.themeselection.com/sneat-bootstrap-html-laravel-admin-template/demo-1/tables/datatables-basic", - "icon": "menu-icon icon-base bx bx-grid", - "name": "Datatables", - "slug": "tables-datatables", - "target": "_blank", - "badge": [ - "label-primary fs-tiny", - "Pro" - ] - }, - { - "menuHeader": "Misc" - }, - { - "url": "https://github.com/themeselection/sneat-bootstrap-html-laravel-admin-template-free/issues", - "icon": "menu-icon icon-base bx bx-support", - "name": "Support", - "slug": "support", - "target": "_blank" - }, - { - "url": "https://themeselection.com/demo/sneat-bootstrap-html-admin-template/documentation/laravel-introduction.html", - "icon": "menu-icon icon-base bx bx-file", - "name": "Documentation", - "slug": "documentation", - "target": "_blank" } ] -} \ No newline at end of file +} diff --git a/resources/views/auth/confirm-password.blade.php b/resources/views/auth/confirm-password.blade.php new file mode 100644 index 00000000..3d381860 --- /dev/null +++ b/resources/views/auth/confirm-password.blade.php @@ -0,0 +1,27 @@ + +
+ {{ __('This is a secure area of the application. Please confirm your password before continuing.') }} +
+ +
+ @csrf + + +
+ + + + + +
+ +
+ + {{ __('Confirm') }} + +
+
+
diff --git a/resources/views/auth/forgot-password.blade.php b/resources/views/auth/forgot-password.blade.php new file mode 100644 index 00000000..cb32e08f --- /dev/null +++ b/resources/views/auth/forgot-password.blade.php @@ -0,0 +1,25 @@ + +
+ {{ __('Forgot your password? No problem. Just let us know your email address and we will email you a password reset link that will allow you to choose a new one.') }} +
+ + + + +
+ @csrf + + +
+ + + +
+ +
+ + {{ __('Email Password Reset Link') }} + +
+
+
diff --git a/resources/views/auth/login.blade.php b/resources/views/auth/login.blade.php new file mode 100644 index 00000000..78b684f7 --- /dev/null +++ b/resources/views/auth/login.blade.php @@ -0,0 +1,47 @@ + + + + +
+ @csrf + + +
+ + + +
+ + +
+ + + + + +
+ + +
+ +
+ +
+ @if (Route::has('password.request')) + + {{ __('Forgot your password?') }} + + @endif + + + {{ __('Log in') }} + +
+
+
diff --git a/resources/views/auth/register.blade.php b/resources/views/auth/register.blade.php new file mode 100644 index 00000000..a857242c --- /dev/null +++ b/resources/views/auth/register.blade.php @@ -0,0 +1,52 @@ + +
+ @csrf + + +
+ + + +
+ + +
+ + + +
+ + +
+ + + + + +
+ + +
+ + + + + +
+ +
+ + {{ __('Already registered?') }} + + + + {{ __('Register') }} + +
+
+
diff --git a/resources/views/auth/reset-password.blade.php b/resources/views/auth/reset-password.blade.php new file mode 100644 index 00000000..a6494cca --- /dev/null +++ b/resources/views/auth/reset-password.blade.php @@ -0,0 +1,39 @@ + +
+ @csrf + + + + + +
+ + + +
+ + +
+ + + +
+ + +
+ + + + + +
+ +
+ + {{ __('Reset Password') }} + +
+
+
diff --git a/resources/views/auth/verify-email.blade.php b/resources/views/auth/verify-email.blade.php new file mode 100644 index 00000000..eaf811d1 --- /dev/null +++ b/resources/views/auth/verify-email.blade.php @@ -0,0 +1,31 @@ + +
+ {{ __('Thanks for signing up! Before getting started, could you verify your email address by clicking on the link we just emailed to you? If you didn\'t receive the email, we will gladly send you another.') }} +
+ + @if (session('status') == 'verification-link-sent') +
+ {{ __('A new verification link has been sent to the email address you provided during registration.') }} +
+ @endif + +
+
+ @csrf + +
+ + {{ __('Resend Verification Email') }} + +
+
+ +
+ @csrf + + +
+
+
diff --git a/resources/views/components/application-logo.blade.php b/resources/views/components/application-logo.blade.php new file mode 100644 index 00000000..46579cf0 --- /dev/null +++ b/resources/views/components/application-logo.blade.php @@ -0,0 +1,3 @@ + + + diff --git a/resources/views/components/auth-session-status.blade.php b/resources/views/components/auth-session-status.blade.php new file mode 100644 index 00000000..c4bd6e23 --- /dev/null +++ b/resources/views/components/auth-session-status.blade.php @@ -0,0 +1,7 @@ +@props(['status']) + +@if ($status) +
merge(['class' => 'font-medium text-sm text-green-600']) }}> + {{ $status }} +
+@endif diff --git a/resources/views/components/danger-button.blade.php b/resources/views/components/danger-button.blade.php new file mode 100644 index 00000000..d17d2889 --- /dev/null +++ b/resources/views/components/danger-button.blade.php @@ -0,0 +1,3 @@ + diff --git a/resources/views/components/dropdown-link.blade.php b/resources/views/components/dropdown-link.blade.php new file mode 100644 index 00000000..e0f8ce1d --- /dev/null +++ b/resources/views/components/dropdown-link.blade.php @@ -0,0 +1 @@ +merge(['class' => 'block w-full px-4 py-2 text-start text-sm leading-5 text-gray-700 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 transition duration-150 ease-in-out']) }}>{{ $slot }} diff --git a/resources/views/components/dropdown.blade.php b/resources/views/components/dropdown.blade.php new file mode 100644 index 00000000..a46f7c83 --- /dev/null +++ b/resources/views/components/dropdown.blade.php @@ -0,0 +1,35 @@ +@props(['align' => 'right', 'width' => '48', 'contentClasses' => 'py-1 bg-white']) + +@php +$alignmentClasses = match ($align) { + 'left' => 'ltr:origin-top-left rtl:origin-top-right start-0', + 'top' => 'origin-top', + default => 'ltr:origin-top-right rtl:origin-top-left end-0', +}; + +$width = match ($width) { + '48' => 'w-48', + default => $width, +}; +@endphp + +
+
+ {{ $trigger }} +
+ + +
diff --git a/resources/views/components/input-error.blade.php b/resources/views/components/input-error.blade.php new file mode 100644 index 00000000..9e6da217 --- /dev/null +++ b/resources/views/components/input-error.blade.php @@ -0,0 +1,9 @@ +@props(['messages']) + +@if ($messages) +
    merge(['class' => 'text-sm text-red-600 space-y-1']) }}> + @foreach ((array) $messages as $message) +
  • {{ $message }}
  • + @endforeach +
+@endif diff --git a/resources/views/components/input-label.blade.php b/resources/views/components/input-label.blade.php new file mode 100644 index 00000000..1cc65e21 --- /dev/null +++ b/resources/views/components/input-label.blade.php @@ -0,0 +1,5 @@ +@props(['value']) + + diff --git a/resources/views/components/modal.blade.php b/resources/views/components/modal.blade.php new file mode 100644 index 00000000..70704c1a --- /dev/null +++ b/resources/views/components/modal.blade.php @@ -0,0 +1,78 @@ +@props([ + 'name', + 'show' => false, + 'maxWidth' => '2xl' +]) + +@php +$maxWidth = [ + 'sm' => 'sm:max-w-sm', + 'md' => 'sm:max-w-md', + 'lg' => 'sm:max-w-lg', + 'xl' => 'sm:max-w-xl', + '2xl' => 'sm:max-w-2xl', +][$maxWidth]; +@endphp + +
+
+
+
+ +
+ {{ $slot }} +
+
diff --git a/resources/views/components/nav-link.blade.php b/resources/views/components/nav-link.blade.php new file mode 100644 index 00000000..5c101a29 --- /dev/null +++ b/resources/views/components/nav-link.blade.php @@ -0,0 +1,11 @@ +@props(['active']) + +@php +$classes = ($active ?? false) + ? 'inline-flex items-center px-1 pt-1 border-b-2 border-indigo-400 text-sm font-medium leading-5 text-gray-900 focus:outline-none focus:border-indigo-700 transition duration-150 ease-in-out' + : 'inline-flex items-center px-1 pt-1 border-b-2 border-transparent text-sm font-medium leading-5 text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700 focus:border-gray-300 transition duration-150 ease-in-out'; +@endphp + +merge(['class' => $classes]) }}> + {{ $slot }} + diff --git a/resources/views/components/primary-button.blade.php b/resources/views/components/primary-button.blade.php new file mode 100644 index 00000000..d71f0b67 --- /dev/null +++ b/resources/views/components/primary-button.blade.php @@ -0,0 +1,3 @@ + diff --git a/resources/views/components/responsive-nav-link.blade.php b/resources/views/components/responsive-nav-link.blade.php new file mode 100644 index 00000000..43b91e7b --- /dev/null +++ b/resources/views/components/responsive-nav-link.blade.php @@ -0,0 +1,11 @@ +@props(['active']) + +@php +$classes = ($active ?? false) + ? 'block w-full ps-3 pe-4 py-2 border-l-4 border-indigo-400 text-start text-base font-medium text-indigo-700 bg-indigo-50 focus:outline-none focus:text-indigo-800 focus:bg-indigo-100 focus:border-indigo-700 transition duration-150 ease-in-out' + : 'block w-full ps-3 pe-4 py-2 border-l-4 border-transparent text-start text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out'; +@endphp + +merge(['class' => $classes]) }}> + {{ $slot }} + diff --git a/resources/views/components/secondary-button.blade.php b/resources/views/components/secondary-button.blade.php new file mode 100644 index 00000000..b32b69fc --- /dev/null +++ b/resources/views/components/secondary-button.blade.php @@ -0,0 +1,3 @@ + diff --git a/resources/views/components/text-input.blade.php b/resources/views/components/text-input.blade.php new file mode 100644 index 00000000..da1b12d8 --- /dev/null +++ b/resources/views/components/text-input.blade.php @@ -0,0 +1,3 @@ +@props(['disabled' => false]) + +merge(['class' => 'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm']) }}> diff --git a/resources/views/content/administrativo/auditoria/index.blade.php b/resources/views/content/administrativo/auditoria/index.blade.php new file mode 100644 index 00000000..5677460e --- /dev/null +++ b/resources/views/content/administrativo/auditoria/index.blade.php @@ -0,0 +1,100 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Auditoria') + +@section('content') +
+
+

Trilha de Auditoria

+

Eventos críticos de vendas, pedidos, faturamento e acessos.

+
+
+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ +
+
+
+ +
+
+ + + + + + + + + + + + + @forelse ($logs as $log) + + + + + + + + + @empty + + + + @endforelse + +
Data/HoraAçãoEntidadeUsuárioAntesDepois
{{ optional($log->created_at)->format('d/m/Y H:i:s') }}{{ $log->acao }}{{ $log->entidade_tipo }}#{{ $log->entidade_id }}{{ $log->usuario?->name ?? 'Sistema' }}{{ json_encode($log->dados_antes, JSON_UNESCAPED_UNICODE) }}{{ json_encode($log->dados_depois, JSON_UNESCAPED_UNICODE) }}
Nenhum log encontrado.
+
+ @if ($logs->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/administrativo/usuarios/index.blade.php b/resources/views/content/administrativo/usuarios/index.blade.php new file mode 100644 index 00000000..262d42dd --- /dev/null +++ b/resources/views/content/administrativo/usuarios/index.blade.php @@ -0,0 +1,121 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Usuarios e Acessos') + +@section('content') +
+
+

Gestao de Usuarios

+

Somente ADMIN pode ajustar nivel de acesso.

+
+ Matriz de Permissoes +
+ +@if (session('success')) +
{{ session('success') }}
+@endif + +
+
+
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + @forelse ($usuarios as $usuario) + + + + + + + @empty + + + + @endforelse + +
NomeEmailNivel AtualAtualizar Nivel
{{ $usuario->name }}{{ $usuario->email }}{{ $usuario->nivel_acesso ?? 'OPERADOR' }} + @perm('usuarios.manage') +
+ @csrf + @method('PUT') + + +
+ @else + Sem permissao para alterar. + @endperm +
Nenhum usuario encontrado.
+
+ @if ($usuarios->hasPages()) + + @endif +
+ +
+
+
Auditoria Recente de Acessos
+
+
+ + + + + + + + + + + + @forelse ($logsRecentes as $log) + + + + + + + + @empty + + + + @endforelse + +
DataAdminUsuarioDePara
{{ optional($log->created_at)->format('d/m/Y H:i') }}{{ $log->usuario?->name ?? 'Sistema' }}{{ $log->dados_depois['nome'] ?? ('#' . $log->entidade_id) }}{{ $log->dados_antes['nivel_acesso'] ?? '-' }}{{ $log->dados_depois['nivel_acesso'] ?? '-' }}
Sem alteracoes recentes de nivel de acesso.
+
+
+@endsection diff --git a/resources/views/content/administrativo/usuarios/permissoes.blade.php b/resources/views/content/administrativo/usuarios/permissoes.blade.php new file mode 100644 index 00000000..bbf1a927 --- /dev/null +++ b/resources/views/content/administrativo/usuarios/permissoes.blade.php @@ -0,0 +1,37 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Matriz de Permissoes') + +@section('content') +
+
+

Matriz de Permissoes

+

Visao central das permissoes por nivel de acesso.

+
+ Voltar +
+ +
+ @foreach ($matriz as $nivel => $permissoes) +
+
+
+
{{ $nivel }}
+
+
+ @if (in_array('*', $permissoes, true)) + Acesso total + @else +
    + @foreach ($permissoes as $permissao) +
  • {{ $permissao }}
  • + @endforeach +
+ @endif +
+
+
+ @endforeach +
+@endsection + diff --git a/resources/views/content/authentications/auth-forgot-password-basic.blade.php b/resources/views/content/authentications/auth-forgot-password-basic.blade.php index c9fb41b7..4f934217 100644 --- a/resources/views/content/authentications/auth-forgot-password-basic.blade.php +++ b/resources/views/content/authentications/auth-forgot-password-basic.blade.php @@ -23,15 +23,26 @@

Forgot Password? 🔒

Enter your email and we'll send you instructions to reset your password

-
+ + @if (session('status')) + + @endif + + + @csrf
- + + @error('email') +
{{ $message }}
+ @enderror
- + Back to login diff --git a/resources/views/content/authentications/auth-login-basic.blade.php b/resources/views/content/authentications/auth-login-basic.blade.php index 621098eb..05cb8824 100644 --- a/resources/views/content/authentications/auth-login-basic.blade.php +++ b/resources/views/content/authentications/auth-login-basic.blade.php @@ -21,28 +21,41 @@
-

Welcome to {{ config('variables.templateName') }}! 👋

-

Please sign-in to your account and start the adventure

+

Bem-vindo ao {{ config('variables.templateName') }}

+

Entre com sua conta para acessar o painel

-
+ @if (session('status')) + + @endif + + + @csrf
- - + + + @error('email') +
{{ $message }}
+ @enderror
- +
+ @error('password') +
{{ $message }}
+ @enderror
- +
- + Forgot Password?
@@ -54,7 +67,7 @@

New on our platform? - + Create an account

diff --git a/resources/views/content/authentications/auth-register-basic.blade.php b/resources/views/content/authentications/auth-register-basic.blade.php index c1bdcbc2..42d07672 100644 --- a/resources/views/content/authentications/auth-register-basic.blade.php +++ b/resources/views/content/authentications/auth-register-basic.blade.php @@ -21,40 +21,48 @@
-

Adventure starts here 🚀

-

Make your app management easy and fun!

+

Criar nova conta

+

Preencha os dados para acessar o sistema

- + + @csrf
- - + + + @error('name') +
{{ $message }}
+ @enderror
- + + @error('email') +
{{ $message }}
+ @enderror
-
+
- +
+ @error('password') +
{{ $message }}
+ @enderror
-
-
- - +
+ +
+ +
- +

Already have an account? - + Sign in instead

@@ -64,4 +72,4 @@
-@endsection \ No newline at end of file +@endsection diff --git a/resources/views/content/cadastros/categorias/_form.blade.php b/resources/views/content/cadastros/categorias/_form.blade.php new file mode 100644 index 00000000..4069c4dd --- /dev/null +++ b/resources/views/content/cadastros/categorias/_form.blade.php @@ -0,0 +1,29 @@ +@if ($errors->any()) +
Corrija os campos destacados.
+@endif + +
+
+
+
+ + + @error('nome') +
{{ $message }}
+ @enderror +
+
+ + +
+ ativo ?? true))> + +
+
+
+
+ + Cancelar +
+
+
diff --git a/resources/views/content/cadastros/categorias/create.blade.php b/resources/views/content/cadastros/categorias/create.blade.php new file mode 100644 index 00000000..69821a7b --- /dev/null +++ b/resources/views/content/cadastros/categorias/create.blade.php @@ -0,0 +1,11 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Nova Categoria') + +@section('content') +

Nova Categoria

+
+ @csrf + @include('content.cadastros.categorias._form') +
+@endsection diff --git a/resources/views/content/cadastros/categorias/edit.blade.php b/resources/views/content/cadastros/categorias/edit.blade.php new file mode 100644 index 00000000..28c6475b --- /dev/null +++ b/resources/views/content/cadastros/categorias/edit.blade.php @@ -0,0 +1,12 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Editar Categoria') + +@section('content') +

Editar Categoria

+
+ @csrf + @method('PUT') + @include('content.cadastros.categorias._form') +
+@endsection diff --git a/resources/views/content/cadastros/categorias/index.blade.php b/resources/views/content/cadastros/categorias/index.blade.php new file mode 100644 index 00000000..e4c3246c --- /dev/null +++ b/resources/views/content/cadastros/categorias/index.blade.php @@ -0,0 +1,81 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Categorias de Produto') + +@section('content') +
+

Categorias de Produto

+ @perm('cadastros_base.manage') + Nova Categoria + @endperm +
+ +@if (session('success')) +
{{ session('success') }}
+@endif +@if (session('error')) +
{{ session('error') }}
+@endif + +
+
+
+
+ + +
+
+ + +
+
+ + Limpar +
+
+
+
+ +
+
+ + + + + + + + + + @forelse ($categorias as $categoria) + + + + + + @empty + + + + @endforelse + +
NomeStatusAcoes
{{ $categoria->nome }}{{ $categoria->ativo ? 'Ativa' : 'Inativa' }} + @perm('cadastros_base.manage') + Editar +
+ @csrf + @method('DELETE') + +
+ @endperm +
Nenhuma categoria encontrada.
+
+ @if ($categorias->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/cadastros/tabelas-preco/_form.blade.php b/resources/views/content/cadastros/tabelas-preco/_form.blade.php new file mode 100644 index 00000000..b9eb4d39 --- /dev/null +++ b/resources/views/content/cadastros/tabelas-preco/_form.blade.php @@ -0,0 +1,54 @@ +@if ($errors->any()) +
Corrija os campos destacados.
+@endif + +
+
+
+
+ + + @error('nome') +
{{ $message }}
+ @enderror +
+
+ + + @error('codigo') +
{{ $message }}
+ @enderror +
+
+ + + @error('tipo') +
{{ $message }}
+ @enderror +
+
+ + + @error('prioridade') +
{{ $message }}
+ @enderror +
+
+ +
+ ativo ?? true))> + +
+
+
+ +
+ + Cancelar +
+
+
diff --git a/resources/views/content/cadastros/tabelas-preco/create.blade.php b/resources/views/content/cadastros/tabelas-preco/create.blade.php new file mode 100644 index 00000000..4b71df5c --- /dev/null +++ b/resources/views/content/cadastros/tabelas-preco/create.blade.php @@ -0,0 +1,11 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Nova Tabela de Preco') + +@section('content') +

Nova Tabela de Preco

+
+ @csrf + @include('content.cadastros.tabelas-preco._form') +
+@endsection diff --git a/resources/views/content/cadastros/tabelas-preco/edit.blade.php b/resources/views/content/cadastros/tabelas-preco/edit.blade.php new file mode 100644 index 00000000..58e0e650 --- /dev/null +++ b/resources/views/content/cadastros/tabelas-preco/edit.blade.php @@ -0,0 +1,12 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Editar Tabela de Preco') + +@section('content') +

Editar Tabela de Preco

+
+ @csrf + @method('PUT') + @include('content.cadastros.tabelas-preco._form') +
+@endsection diff --git a/resources/views/content/cadastros/tabelas-preco/index.blade.php b/resources/views/content/cadastros/tabelas-preco/index.blade.php new file mode 100644 index 00000000..ff664383 --- /dev/null +++ b/resources/views/content/cadastros/tabelas-preco/index.blade.php @@ -0,0 +1,96 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Tabelas de Preco') + +@section('content') +
+

Tabelas de Preco

+ @perm('cadastros_base.manage') + Nova Tabela + @endperm +
+ +@if (session('success')) +
{{ session('success') }}
+@endif +@if (session('error')) +
{{ session('error') }}
+@endif + +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + Limpar +
+
+
+
+ +
+
+ + + + + + + + + + + + + @forelse ($tabelas as $tabela) + + + + + + + + + @empty + + + + @endforelse + +
NomeCodigoTipoPrioridadeStatusAcoes
{{ $tabela->nome }}{{ $tabela->codigo }}{{ $tabela->tipo }}{{ $tabela->prioridade }}{{ $tabela->ativo ? 'Ativa' : 'Inativa' }} + @perm('cadastros_base.manage') + Editar +
+ @csrf + @method('DELETE') + +
+ @endperm +
Nenhuma tabela encontrada.
+
+ @if ($tabelas->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/cadastros/unidades/_form.blade.php b/resources/views/content/cadastros/unidades/_form.blade.php new file mode 100644 index 00000000..c37100ae --- /dev/null +++ b/resources/views/content/cadastros/unidades/_form.blade.php @@ -0,0 +1,43 @@ +@if ($errors->any()) +
Corrija os campos destacados.
+@endif + +
+
+
+
+ + + @error('sigla') +
{{ $message }}
+ @enderror +
+
+ + + @error('nome') +
{{ $message }}
+ @enderror +
+
+ + + @error('casas_decimais') +
{{ $message }}
+ @enderror +
+
+ + +
+ ativo ?? true))> + +
+
+
+
+ + Cancelar +
+
+
diff --git a/resources/views/content/cadastros/unidades/create.blade.php b/resources/views/content/cadastros/unidades/create.blade.php new file mode 100644 index 00000000..f4b00354 --- /dev/null +++ b/resources/views/content/cadastros/unidades/create.blade.php @@ -0,0 +1,11 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Nova Unidade de Medida') + +@section('content') +

Nova Unidade de Medida

+
+ @csrf + @include('content.cadastros.unidades._form') +
+@endsection diff --git a/resources/views/content/cadastros/unidades/edit.blade.php b/resources/views/content/cadastros/unidades/edit.blade.php new file mode 100644 index 00000000..353041f0 --- /dev/null +++ b/resources/views/content/cadastros/unidades/edit.blade.php @@ -0,0 +1,12 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Editar Unidade de Medida') + +@section('content') +

Editar Unidade de Medida

+
+ @csrf + @method('PUT') + @include('content.cadastros.unidades._form') +
+@endsection diff --git a/resources/views/content/cadastros/unidades/index.blade.php b/resources/views/content/cadastros/unidades/index.blade.php new file mode 100644 index 00000000..fdc4b668 --- /dev/null +++ b/resources/views/content/cadastros/unidades/index.blade.php @@ -0,0 +1,85 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Unidades de Medida') + +@section('content') +
+

Unidades de Medida

+ @perm('cadastros_base.manage') + Nova Unidade + @endperm +
+ +@if (session('success')) +
{{ session('success') }}
+@endif +@if (session('error')) +
{{ session('error') }}
+@endif + +
+
+
+
+ + +
+
+ + +
+
+ + Limpar +
+
+
+
+ +
+
+ + + + + + + + + + + + @forelse ($unidades as $unidade) + + + + + + + + @empty + + + + @endforelse + +
SiglaNomeCasas DecimaisStatusAcoes
{{ $unidade->sigla }}{{ $unidade->nome }}{{ $unidade->casas_decimais }}{{ $unidade->ativo ? 'Ativa' : 'Inativa' }} + @perm('cadastros_base.manage') + Editar +
+ @csrf + @method('DELETE') + +
+ @endperm +
Nenhuma unidade encontrada.
+
+ @if ($unidades->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/clientes/_form.blade.php b/resources/views/content/clientes/_form.blade.php new file mode 100644 index 00000000..154d8eb8 --- /dev/null +++ b/resources/views/content/clientes/_form.blade.php @@ -0,0 +1,267 @@ +@php + $isEdit = isset($cliente) && $cliente->exists; + $tipoPessoa = old('tipo_pessoa', $cliente->tipo_pessoa ?? 'PF'); + $selectedUf = old('uf', $cliente->uf ?? ''); +@endphp + +@if ($errors->any()) +
+ Corrija os campos destacados. +
+@endif + +
+
+
+
+
Dados Principais
+
+
+
+
+ + + @error('codigo') +
{{ $message }}
+ @enderror +
+
+ + + @error('tipo_pessoa') +
{{ $message }}
+ @enderror +
+
+ + + @error('nome') +
{{ $message }}
+ @enderror +
+ +
+ +
+ + + @error('cpf_cnpj') +
{{ $message }}
+ @enderror +
+
+
+ + + @error('rg_ie') +
{{ $message }}
+ @enderror +
+
+ + + @error('nome_fantasia') +
{{ $message }}
+ @enderror +
+
+
+
+ +
+
+
Endereco
+
+
+
+
+ + + @error('cep') +
{{ $message }}
+ @enderror +
+
+ + + @error('logradouro') +
{{ $message }}
+ @enderror +
+
+ + + @error('numero') +
{{ $message }}
+ @enderror +
+
+ + + @error('complemento') +
{{ $message }}
+ @enderror +
+
+ + + @error('bairro') +
{{ $message }}
+ @enderror +
+
+ + + @error('uf') +
{{ $message }}
+ @enderror +
+
+ + + @error('codigo_ibge') +
{{ $message }}
+ @enderror +
+
+ + + @error('cidade') +
{{ $message }}
+ @enderror +
+
+ + + @error('pais') +
{{ $message }}
+ @enderror +
+
+
+
+
+ +
+
+
+
Contatos
+
+
+
+
+ + + @error('telefone') +
{{ $message }}
+ @enderror +
+
+ + + @error('celular') +
{{ $message }}
+ @enderror +
+
+ + + @error('contato_nome') +
{{ $message }}
+ @enderror +
+
+ + + @error('email') +
{{ $message }}
+ @enderror +
+
+
+
+ +
+
+
Extra
+
+
+
+
+ + + @error('data_nascimento_fundacao') +
{{ $message }}
+ @enderror +
+
+ + + @error('sexo') +
{{ $message }}
+ @enderror +
+
+ + + @error('saldo_credito') +
{{ $message }}
+ @enderror +
+
+ + + @error('limite_prazo') +
{{ $message }}
+ @enderror +
+
+ + +
+ ativo ?? true))> + +
+
+
+
+
+
+ +
+
+
+
Observacoes
+
+
+ + @error('observacoes') +
{{ $message }}
+ @enderror +
+
+
+ +
+ + Cancelar +
+
diff --git a/resources/views/content/clientes/create.blade.php b/resources/views/content/clientes/create.blade.php new file mode 100644 index 00000000..6ec48db1 --- /dev/null +++ b/resources/views/content/clientes/create.blade.php @@ -0,0 +1,21 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Novo Cliente') + +@section('page-script') +@vite(['resources/assets/js/clientes-form.js']) +@endsection + +@section('content') +
+
+

Novo Cliente

+

Cadastre cliente pessoa fisica ou juridica.

+
+
+ +
+ @csrf + @include('content.clientes._form') +
+@endsection diff --git a/resources/views/content/clientes/edit.blade.php b/resources/views/content/clientes/edit.blade.php new file mode 100644 index 00000000..520e62e8 --- /dev/null +++ b/resources/views/content/clientes/edit.blade.php @@ -0,0 +1,22 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Editar Cliente') + +@section('page-script') +@vite(['resources/assets/js/clientes-form.js']) +@endsection + +@section('content') +
+
+

Editar Cliente

+

Atualize os dados cadastrais.

+
+
+ +
+ @csrf + @method('PUT') + @include('content.clientes._form') +
+@endsection diff --git a/resources/views/content/clientes/index.blade.php b/resources/views/content/clientes/index.blade.php new file mode 100644 index 00000000..6e2ea7ae --- /dev/null +++ b/resources/views/content/clientes/index.blade.php @@ -0,0 +1,130 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Clientes') + +@section('content') +
+
+

Clientes

+

Gerencie o cadastro de clientes PF e PJ.

+
+
+ + Exportar CSV + + @perm('clientes.manage') + + Novo Cliente + + @endperm +
+
+ +@if (session('success')) +
{{ session('success') }}
+@endif + +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + Limpar +
+
+
+
+ +
+
+ + + + + + + + + + + + + + + @forelse ($clientes as $cliente) + + + + + + + + + + + @empty + + + + @endforelse + +
CodigoNomeTipoDocumentoContatoCidade/UFSituacaoAcoes
{{ $cliente->codigo ?: '-' }} +
{{ $cliente->nome }}
+ @if ($cliente->nome_fantasia) + {{ $cliente->nome_fantasia }} + @endif +
+ {{ $cliente->tipo_pessoa }} + {{ $cliente->documento_formatado }} +
{{ $cliente->email ?: '-' }}
+ {{ $cliente->celular ?: ($cliente->telefone ?: '-') }} +
{{ $cliente->cidade ?: '-' }}{{ $cliente->uf ? '/'.$cliente->uf : '' }} + {{ $cliente->ativo ? 'Ativo' : 'Inativo' }} + + Ver + @perm('clientes.manage') + Editar +
+ @csrf + @method('DELETE') + +
+ @endperm +
Nenhum cliente encontrado.
+
+ @if ($clientes->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/clientes/show.blade.php b/resources/views/content/clientes/show.blade.php new file mode 100644 index 00000000..cd545177 --- /dev/null +++ b/resources/views/content/clientes/show.blade.php @@ -0,0 +1,93 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Detalhes do Cliente') + +@section('content') +
+
+

Cliente: {{ $cliente->nome }}

+

{{ $cliente->tipo_pessoa === 'PJ' ? 'Pessoa Juridica' : 'Pessoa Fisica' }}

+
+
+ @perm('clientes.manage') + Editar + @endperm + Voltar +
+
+ +@if (session('success')) +
{{ session('success') }}
+@endif + +
+
+
+
Dados Cadastrais
+
+
+
Codigo:
{{ $cliente->codigo ?: '-' }}
+
Tipo:
{{ $cliente->tipo_pessoa }}
+
Nome:
{{ $cliente->nome }}
+
{{ $cliente->tipo_pessoa === 'PJ' ? 'CNPJ' : 'CPF' }}:
{{ $cliente->documento_formatado }}
+
{{ $cliente->tipo_pessoa === 'PJ' ? 'IE' : 'RG' }}:
{{ $cliente->rg_ie ?: '-' }}
+
Nome Fantasia:
{{ $cliente->nome_fantasia ?: '-' }}
+
Data:
{{ optional($cliente->data_nascimento_fundacao)->format('d/m/Y') ?: '-' }}
+
Sexo:
{{ $cliente->sexo ?: '-' }}
+
+
+
+
+
Endereco
+
+
+
CEP:
{{ $cliente->cep ?: '-' }}
+
Logradouro:
{{ $cliente->logradouro ?: '-' }}
+
Numero:
{{ $cliente->numero ?: '-' }}
+
Complemento:
{{ $cliente->complemento ?: '-' }}
+
Bairro:
{{ $cliente->bairro ?: '-' }}
+
Cidade/UF:
{{ $cliente->cidade ?: '-' }}{{ $cliente->uf ? '/'.$cliente->uf : '' }}
+
Pais:
{{ $cliente->pais }}
+
Cod. IBGE:
{{ $cliente->codigo_ibge ?: '-' }}
+
+
+
+
+
+
+
Contato
+
+

Email:
{{ $cliente->email ?: '-' }}

+

Telefone:
{{ $cliente->telefone ?: '-' }}

+

Celular:
{{ $cliente->celular ?: '-' }}

+

Contato:
{{ $cliente->contato_nome ?: '-' }}

+
+
+
+
Financeiro
+
+

Saldo Credito:
R$ {{ number_format((float) $cliente->saldo_credito, 2, ',', '.') }}

+

Limite a Prazo:
R$ {{ number_format((float) $cliente->limite_prazo, 2, ',', '.') }}

+

Situacao:
+ {{ $cliente->ativo ? 'Ativo' : 'Inativo' }} +

+
+
+
+
Resumo Comercial
+
+

Documentos:
{{ number_format((int) ($resumoComercial['documentos_total'] ?? 0), 0, ',', '.') }}

+

Vendas Faturadas:
{{ number_format((int) ($resumoComercial['vendas_faturadas'] ?? 0), 0, ',', '.') }}

+

Ultima Venda:
{{ !empty($resumoComercial['ultima_venda']) ? \Illuminate\Support\Carbon::parse($resumoComercial['ultima_venda'])->format('d/m/Y H:i') : '-' }}

+

Contas em Aberto:
R$ {{ number_format((float) ($resumoComercial['receber_em_aberto'] ?? 0), 2, ',', '.') }}

+
+
+
+
Observacoes
+
+

{{ $cliente->observacoes ?: '-' }}

+
+
+
+
+@endsection diff --git a/resources/views/content/comercial/documentos/_form.blade.php b/resources/views/content/comercial/documentos/_form.blade.php new file mode 100644 index 00000000..f31d8955 --- /dev/null +++ b/resources/views/content/comercial/documentos/_form.blade.php @@ -0,0 +1,191 @@ +@php + $statusOptionsByTipo = $statusOptionsByTipo ?? []; + $regrasEdicao = $regrasEdicao ?? ['pode_editar' => true, 'permite_alterar_itens' => true, 'permite_alterar_cabecalho' => true, 'motivo' => null]; + $bloquearItens = $isEdit && !$regrasEdicao['permite_alterar_itens']; + $bloquearCabecalho = $isEdit && !$regrasEdicao['permite_alterar_cabecalho']; + $tipoAtual = old('tipo', $documento->tipo); + $statusOptions = $statusOptionsByTipo[$tipoAtual] ?? ['RASCUNHO']; + $statusAtual = old('status', $documento->status); + if (!in_array($statusAtual, $statusOptions, true)) { + $statusOptions[] = $statusAtual; + } + $clienteInicial = old('cliente_nome') ?: ($documento->cliente->nome ?? ''); + + $existingItens = old('itens'); + if ($existingItens === null && $isEdit) { + $existingItens = $documento->itens->map(fn($item) => [ + 'produto_id' => $item->produto_id, + 'produto_nome' => $item->descricao, + 'produto_sku' => $item->metadata['produto_sku'] ?? ($item->produto?->sku ?? ''), + 'produto_unidade' => $item->unidade_sigla, + 'quantidade' => $item->quantidade, + 'preco_unitario' => $item->preco_unitario, + ])->values()->all(); + } + + $existingItens = $existingItens ?: [[ + 'produto_id' => '', + 'produto_nome' => '', + 'produto_sku' => '', + 'produto_unidade' => 'UN', + 'quantidade' => 1, + 'preco_unitario' => 0, + ]]; +@endphp + +@if ($errors->any()) +
Revise os campos para continuar.
+@endif +@if ($isEdit && ($regrasEdicao['pode_editar'] ?? true) === false) +
{{ $regrasEdicao['motivo'] ?? 'Documento em modo somente leitura.' }}
+@endif + +
+
+
+
+
Itens do Documento
+ Pesquise por nome, SKU ou EAN e adicione rapidamente. +
+
+
+ + + +
+ +
+ + + + + + + + + + + + @foreach ($existingItens as $index => $item) + + + + + + + + @endforeach + +
ProdutoQtdPreco Unit.Subtotal
+ + + {{ $item['produto_unidade'] ?? 'UN' }} + + + + + + + + +
+
+ +
+ Regra ativa: somente em ORCAMENTO o preco unitario do item pode ser alterado livremente. Em PEDIDO/VENDA o ajuste deve ser no cabecalho (desconto/acrescimo/impostos). +
+
+
+
+ +
+
+
Cabecalho
+
+
+ + + @if ($isEdit) + + @endif +
+
+ + +
+
+ + + + @error('cliente_id') +
{{ $message }}
+ @enderror + + +
+
+ + +
+
+ + +
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
Subtotal:R$ 0,00
+
Total Liquido:R$ 0,00
+
+
+ +
+
Observacoes
+
+ +
+
+
+ +
+ + Cancelar +
+
+ + diff --git a/resources/views/content/comercial/documentos/analise.blade.php b/resources/views/content/comercial/documentos/analise.blade.php new file mode 100644 index 00000000..c9f007c0 --- /dev/null +++ b/resources/views/content/comercial/documentos/analise.blade.php @@ -0,0 +1,60 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Analise da Venda') + +@section('content') +
+
+

Analise Comercial - {{ $documento->numero }}

+

Comparativo custo de referencia vs venda com efeitos de desconto/acrescimo/imposto.

+
+ +
+ +
+
Subtotal Itens
R$ {{ number_format((float) $analise['subtotal_itens'], 2, ',', '.') }}
+
Desconto Cabecalho
R$ {{ number_format((float) $analise['desconto_rateado_total'], 2, ',', '.') }}
+
Acrescimo + Imposto
R$ {{ number_format((float) ($analise['acrescimo_rateado_total'] + $analise['imposto_rateado_total']), 2, ',', '.') }}
+
Margem Total
R$ {{ number_format((float) $analise['total_margem'], 2, ',', '.') }} ({{ number_format((float) $analise['margem_percentual_total'], 2, ',', '.') }}%)
+
+ +
+
+ + + + + + + + + + + + + + + + + @foreach ($analise['itens'] as $row) + + + + + + + + + + + + + @endforeach + +
ItemQtdReceita BrutaDesc. RateadoAcr. RateadoImp. RateadoCusto Ref Unit.Custo TotalReceita LiquidaMargem
{{ $row['item']->descricao }}{{ number_format((float) $row['item']->quantidade, 3, ',', '.') }}R$ {{ number_format((float) $row['receita_bruta'], 2, ',', '.') }}R$ {{ number_format((float) $row['desconto_rateado'], 2, ',', '.') }}R$ {{ number_format((float) $row['acrescimo_rateado'], 2, ',', '.') }}R$ {{ number_format((float) $row['imposto_rateado'], 2, ',', '.') }}R$ {{ number_format((float) $row['custo_ref_unitario'], 2, ',', '.') }}R$ {{ number_format((float) $row['custo_total'], 2, ',', '.') }}R$ {{ number_format((float) $row['receita'], 2, ',', '.') }}R$ {{ number_format((float) $row['margem'], 2, ',', '.') }} ({{ number_format((float) $row['margem_percentual'], 2, ',', '.') }}%)
+
+
+@endsection diff --git a/resources/views/content/comercial/documentos/create.blade.php b/resources/views/content/comercial/documentos/create.blade.php new file mode 100644 index 00000000..93b173f3 --- /dev/null +++ b/resources/views/content/comercial/documentos/create.blade.php @@ -0,0 +1,21 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Novo Documento') + +@section('page-script') +@vite(['resources/assets/js/documentos-form.js']) +@endsection + +@section('content') +
+
+

Novo Documento Comercial

+

Fluxo unificado: Orcamento -> Prevenda -> Pedido -> Venda -> Faturamento.

+
+
+ +
+ @csrf + @include('content.comercial.documentos._form') +
+@endsection diff --git a/resources/views/content/comercial/documentos/edit.blade.php b/resources/views/content/comercial/documentos/edit.blade.php new file mode 100644 index 00000000..2a3cedea --- /dev/null +++ b/resources/views/content/comercial/documentos/edit.blade.php @@ -0,0 +1,22 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Editar Documento') + +@section('page-script') +@vite(['resources/assets/js/documentos-form.js']) +@endsection + +@section('content') +
+
+

Editar {{ $documento->numero }}

+

Atualize itens e valores do cabecalho conforme a etapa comercial.

+
+
+ +
+ @csrf + @method('PUT') + @include('content.comercial.documentos._form') +
+@endsection diff --git a/resources/views/content/comercial/documentos/index.blade.php b/resources/views/content/comercial/documentos/index.blade.php new file mode 100644 index 00000000..2343b8ac --- /dev/null +++ b/resources/views/content/comercial/documentos/index.blade.php @@ -0,0 +1,295 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Vendas e Pedidos') + +@section('content') +
+
+

Nucleo Comercial

+

Orcamentos, pedidos, vendas, faturamento e analise comercial.

+
+
+ + Exportar CSV + + @perm('vendas.pdv.use') + + PDV Rapido + + @endperm + @perm('vendas.documentos.manage') + + Novo Documento + + @endperm +
+
+ +@if (session('success')) +
{{ session('success') }}
+@endif +@if (session('error')) +
{{ session('error') }}
+@endif +@if (session('warning')) +
{{ session('warning') }}
+@endif + +@php + $importFeedback = session('import_feedback'); +@endphp + +@perm('vendas.documentos.importar_legado') +
+
+
+
+
Importar Vendas Legadas (PDF)
+

Fluxo homologado para os modelos PDF enviados (ex.: 1.pdf e a1.pdf).

+
+
+
+ @csrf +
+ + + @error('arquivos') +
{{ $message }}
+ @enderror + @error('arquivos.*') +
{{ $message }}
+ @enderror +
+
+ + + Todos os PDFs da pasta selecionada serao importados. + @error('pasta_arquivos') +
{{ $message }}
+ @enderror + @error('pasta_arquivos.*') +
{{ $message }}
+ @enderror +
+
+ + + Use esta opcao para volume alto (evita erro 413/PostTooLarge). + @error('caminho_pasta') +
{{ $message }}
+ @enderror +
+
+ +
+
+ + @if (!empty($importFeedback)) +
+ @if (!empty($importFeedback['stats'])) +
+
Total{{ $importFeedback['stats']['total'] ?? 0 }}
+
Importados{{ $importFeedback['stats']['sucesso'] ?? 0 }}
+
Falhas{{ $importFeedback['stats']['falhas'] ?? 0 }}
+
Ignorados{{ $importFeedback['stats']['ignorados'] ?? 0 }}
+
Tempo de processamento{{ number_format((($importFeedback['stats']['tempo_ms'] ?? 0) / 1000), 2, ',', '.') }}s
+
+ @endif +
+
+
Importados
+
    + @forelse (($importFeedback['sucesso'] ?? []) as $item) +
  • + {{ $item['arquivo'] }} + {{ $item['numero'] }} +
  • + @empty +
  • Nenhum arquivo importado nesta execucao.
  • + @endforelse +
+
+
+
Falhas
+
    + @forelse (($importFeedback['falhas'] ?? []) as $item) +
  • +
    {{ $item['arquivo'] }}
    + {{ $item['erro'] }} +
  • + @empty +
  • Sem falhas na ultima importacao.
  • + @endforelse +
+
+
+
Ignorados (duplicidade)
+
    + @forelse (($importFeedback['ignorados'] ?? []) as $item) +
  • +
    {{ $item['arquivo'] }}
    + {{ $item['motivo'] }} +
  • + @empty +
  • Nenhum arquivo ignorado.
  • + @endforelse +
+
+
+ @endif +
+
+@endperm + +
+
+
+
+ Total de documentos +

{{ number_format($cards['total'], 0, ',', '.') }}

+
+
+
+
+
+
+ Orcamentos pendentes +

{{ number_format($cards['orcamentos_pendentes'], 0, ',', '.') }}

+
+
+
+
+
+
+ Aguardando faturamento +

{{ number_format($cards['aguardando_faturamento'], 0, ',', '.') }}

+
+
+
+
+
+
+ Faturados no mes +

{{ number_format($cards['faturados_mes'], 0, ',', '.') }}

+
+
+
+
+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + + + + + @forelse ($documentos as $documento) + + + + + + + + + + + @empty + + + + @endforelse + +
NumeroTipoClienteStatusDataTotalOrigemAcoes
{{ $documento->numero }}{{ $documento->tipo }}{{ $documento->cliente->nome }} + @php + $statusClass = match($documento->status) { + 'FATURADO' => 'success', + 'CANCELADO' => 'danger', + 'EM_SEPARACAO', 'AGUARDANDO_FATURAMENTO' => 'warning', + default => 'secondary' + }; + @endphp + {{ $documento->status }} + {{ optional($documento->data_emissao)->format('d/m/Y H:i') }}R$ {{ number_format((float) $documento->total_liquido, 2, ',', '.') }}{{ $documento->origem?->numero ?? '-' }} + Ver + Analise +
Nenhum documento encontrado.
+
+ @if ($documentos->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/comercial/documentos/show.blade.php b/resources/views/content/comercial/documentos/show.blade.php new file mode 100644 index 00000000..7376fe0f --- /dev/null +++ b/resources/views/content/comercial/documentos/show.blade.php @@ -0,0 +1,201 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', $documento->numero) + +@section('content') +
+
+

{{ $documento->numero }}

+

{{ $documento->tipo }} • {{ $documento->status }}

+
+
+ Analise + @perm('vendas.documentos.converter') + @if (($acoesFluxo['converter_pedido']['permitido'] ?? false) === true) +
+ @csrf + +
+ @else + + @endif + @endif + @perm('vendas.documentos.converter') + @if (($acoesFluxo['converter_venda']['permitido'] ?? false) === true) +
+ @csrf + +
+ @else + + @endif + @endif + @perm('vendas.documentos.faturar') + @if (($acoesFluxo['faturar']['permitido'] ?? false) === true) +
+ @csrf + +
+ @else + + @endif + @endif + @perm('vendas.documentos.cancelar') + @if (($podeGerenciarCancelamento ?? false) && !in_array($documento->status, ['FATURADO', 'CANCELADO'])) +
+ @csrf + @method('DELETE') + + +
+ @endif + @if (($podeGerenciarCancelamento ?? false) && $documento->status === 'CANCELADO') +
+ @csrf + + +
+ @endif + @endif + @perm('vendas.documentos.manage') + @if (($regrasEdicao['pode_editar'] ?? false) === true) + Editar + @endif + @endperm + Voltar +
+
+ +@if (session('success')) +
{{ session('success') }}
+@endif +@if ($errors->any()) +
{{ $errors->first() }}
+@endif +@if (($regrasEdicao['pode_editar'] ?? true) === false) +
{{ $regrasEdicao['motivo'] ?? 'Documento em modo somente leitura.' }}
+@endif +@if (($podeGerenciarCancelamento ?? false) === false) +
Cancelamento/Reabertura disponivel apenas para usuarios autorizados.
+@endif + +
+
+
+
Itens
+
+ + + + + + + + + + + + + @foreach ($documento->itens as $item) + + + + + + + + + @endforeach + +
#ProdutoQtdPreco Unit.SubtotalReserva
{{ $item->sequencia }}{{ $item->descricao }}{{ number_format((float) $item->quantidade, 3, ',', '.') }} {{ $item->unidade_sigla }}R$ {{ number_format((float) $item->preco_unitario, 2, ',', '.') }}R$ {{ number_format((float) $item->subtotal_liquido, 2, ',', '.') }} + @if ($item->reserva) + {{ $item->reserva->status }} + @else + - + @endif +
+
+
+ +
+
Eventos do Fluxo
+
+
    + @foreach ($documento->eventos as $evento) +
  • + +
    +
    +
    {{ $evento->acao }}
    + {{ optional($evento->data_evento)->format('d/m/Y H:i') }} +
    +

    {{ $evento->status_anterior ?: '-' }} -> {{ $evento->status_novo }}

    + Usuario: {{ $evento->usuario?->name ?? 'Sistema' }} + @if (!empty($evento->detalhes['motivo_cancelamento'])) +
    Motivo: {{ $evento->detalhes['motivo_cancelamento'] }}
    + @endif + @if (!empty($evento->detalhes['motivo_reabertura'])) +
    Motivo reabertura: {{ $evento->detalhes['motivo_reabertura'] }}
    + @endif +
    +
  • + @endforeach +
+
+
+
+ +
+
+
Resumo
+
+
Cliente{{ $documento->cliente->nome }}
+
Vendedor{{ $documento->vendedor->name }}
+
SubtotalR$ {{ number_format((float) $documento->subtotal, 2, ',', '.') }}
+
DescontoR$ {{ number_format((float) $documento->desconto_total, 2, ',', '.') }}
+
AcrescimoR$ {{ number_format((float) $documento->acrescimo_total, 2, ',', '.') }}
+
ImpostosR$ {{ number_format((float) $documento->impostos_total, 2, ',', '.') }}
+
+
TotalR$ {{ number_format((float) $documento->total_liquido, 2, ',', '.') }}
+ @if ($documento->faturamento) +
+
NF: {{ $documento->faturamento->numero_fiscal }}
+ @endif +
+
+ +
+
Indicadores Rapidos
+
+
ReceitaR$ {{ number_format((float) $analise['total_receita'], 2, ',', '.') }}
+
Custo ReferenciaR$ {{ number_format((float) $analise['total_custo_ref'], 2, ',', '.') }}
+
MargemR$ {{ number_format((float) $analise['total_margem'], 2, ',', '.') }}
+
+
+
+
+ + +@endsection diff --git a/resources/views/content/comercial/pdv/index.blade.php b/resources/views/content/comercial/pdv/index.blade.php new file mode 100644 index 00000000..6af66aeb --- /dev/null +++ b/resources/views/content/comercial/pdv/index.blade.php @@ -0,0 +1,116 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'PDV Rapido') + +@section('page-script') +@vite(['resources/assets/js/pdv.js']) +@endsection + +@section('content') +
+
+

Frente de Caixa (PDV)

+

Busca rapida por nome/EAN, carrinho dinamico e fechamento em um clique.

+
+ Voltar para vendas +
+ +@if (session('success')) +
{{ session('success') }}
+@endif +@if ($errors->any()) +
+ Não foi possível concluir a venda. +
{{ $errors->first() }}
+
+@endif + +
+ @csrf + + +
+
+
+
+
+ + + +
+
+ Itens: 0 + Volume: 0,000 + Atalhos: `F2` busca, `F4` finalizar, `F8` limpar +
+
+ + + + + + + + + + + +
ProdutoQtdPrecoSubtotal
+
+
+
+
+
+
+
+ + + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
SubtotalR$ 0,00
+
TotalR$ 0,00
+ + +
+
+
+
+
+ + +@endsection diff --git a/resources/views/content/compras/compras/_form.blade.php b/resources/views/content/compras/compras/_form.blade.php new file mode 100644 index 00000000..0676e47d --- /dev/null +++ b/resources/views/content/compras/compras/_form.blade.php @@ -0,0 +1,92 @@ +
+
+
+
+
Itens da Compra
+
+
+
+ + + + + + + + + + + + + + + + + + + + + +
ProdutoQtdPreço Unit.LoteValidade
+ +
+
+ +
+
+
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
Total itens0
+
Valor totalR$ 0,00
+
+
+
+
+ + Cancelar +
+
diff --git a/resources/views/content/compras/compras/create.blade.php b/resources/views/content/compras/compras/create.blade.php new file mode 100644 index 00000000..13ae59f4 --- /dev/null +++ b/resources/views/content/compras/compras/create.blade.php @@ -0,0 +1,20 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Nova Compra') + +@section('page-script') +@vite(['resources/assets/js/compra-form.js']) +@endsection + +@section('content') +

Nova Compra

+ +@if ($errors->any()) +
{{ $errors->first() }}
+@endif + +
+ @csrf + @include('content.compras.compras._form') +
+@endsection diff --git a/resources/views/content/compras/compras/index.blade.php b/resources/views/content/compras/compras/index.blade.php new file mode 100644 index 00000000..9f32da20 --- /dev/null +++ b/resources/views/content/compras/compras/index.blade.php @@ -0,0 +1,104 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Compras') + +@section('content') +
+
+

Compras

+

Entradas de mercadorias com geração de estoque e contas a pagar.

+
+
+ Exportar CSV + @perm('compras.compras.manage') + Nova Compra + @endperm +
+
+ +@if (session('success')) +
{{ session('success') }}
+@endif + +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + + + + @forelse ($compras as $compra) + + + + + + + + + + @empty + + + + @endforelse + +
NúmeroFornecedorDataStatusTotalConta a PagarAções
{{ $compra->numero }}{{ $compra->fornecedor->nome }}{{ optional($compra->data_compra)->format('d/m/Y H:i') }}{{ $compra->status }}R$ {{ number_format((float) $compra->valor_total, 2, ',', '.') }} + @if ($compra->contaPagar) + {{ $compra->contaPagar->status }} • R$ {{ number_format((float) $compra->contaPagar->valor_aberto, 2, ',', '.') }} + @else + - + @endif + + Ver +
Nenhuma compra encontrada.
+
+ @if ($compras->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/compras/compras/show.blade.php b/resources/views/content/compras/compras/show.blade.php new file mode 100644 index 00000000..cde3ae42 --- /dev/null +++ b/resources/views/content/compras/compras/show.blade.php @@ -0,0 +1,109 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', $compra->numero) + +@section('content') +
+
+

{{ $compra->numero }}

+

{{ $compra->fornecedor->nome }} • {{ $compra->status }}

+
+ Voltar +
+ +
+
Itens
{{ number_format((int) ($analitico['itens_total'] ?? 0), 0, ',', '.') }}
+
Qtd Total
{{ number_format((float) ($analitico['qtd_total'] ?? 0), 3, ',', '.') }}
+
Ticket Médio Item
R$ {{ number_format((float) ($analitico['ticket_medio_item'] ?? 0), 2, ',', '.') }}
+
Entradas Estoque
{{ number_format((float) ($analitico['qtd_entrada_estoque'] ?? 0), 3, ',', '.') }}
+
+ +
+
+
+
Itens
+
+ + + + + + + + + + + + + + @foreach ($compra->itens as $item) + + + + + + + + + + @endforeach + +
#ProdutoQtdPreço Unit.SubtotalLoteValidade
{{ $item->sequencia }}{{ $item->produto->nome }}{{ number_format((float) $item->quantidade, 3, ',', '.') }}R$ {{ number_format((float) $item->preco_unitario, 2, ',', '.') }}R$ {{ number_format((float) $item->subtotal, 2, ',', '.') }}{{ $item->numero_lote ?: '-' }}{{ optional($item->data_validade)->format('d/m/Y') ?: '-' }}
+
+
+
+
+
+
+
Fornecedor{{ $compra->fornecedor->nome }}
+
Filial{{ $compra->filial->nome }}
+
Data{{ optional($compra->data_compra)->format('d/m/Y H:i') }}
+
Status{{ $compra->status }}
+
+
Total compraR$ {{ number_format((float) $compra->valor_total, 2, ',', '.') }}
+ @if ($compra->contaPagar) +
Conta a pagar{{ $compra->contaPagar->status }}
+
AbertoR$ {{ number_format((float) $compra->contaPagar->valor_aberto, 2, ',', '.') }}
+
Vencimento{{ optional($compra->contaPagar->vencimento)->format('d/m/Y') }}
+ @endif +
+
+
+
+ +
+
Movimentações de Estoque da Compra
+
+ + + + + + + + + + + + + + @forelse ($movimentacoes as $mov) + + + + + + + + + + @empty + + + + @endforelse + +
DataProdutoTipoQtdSaldo ApósLote/SerialRef.
{{ optional($mov->created_at)->format('d/m/Y H:i') }}{{ $mov->produto->sku ?? '-' }} - {{ $mov->produto->nome ?? '-' }}{{ $mov->tipo }}{{ $mov->sinal > 0 ? '+' : '-' }}{{ number_format((float) $mov->quantidade, 3, ',', '.') }}{{ number_format((float) $mov->saldo_apos, 3, ',', '.') }}{{ $mov->lote ? $mov->lote->lote . ($mov->lote->serial ? ' / ' . $mov->lote->serial : '') : '-' }}{{ $mov->documento_ref ?: '-' }}
Sem movimentações de estoque vinculadas a esta compra.
+
+
+@endsection diff --git a/resources/views/content/compras/fornecedores/_form.blade.php b/resources/views/content/compras/fornecedores/_form.blade.php new file mode 100644 index 00000000..dd97b25f --- /dev/null +++ b/resources/views/content/compras/fornecedores/_form.blade.php @@ -0,0 +1,40 @@ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ ativo ?? true))> + +
+
+
+
+
+
+ + Cancelar +
diff --git a/resources/views/content/compras/fornecedores/create.blade.php b/resources/views/content/compras/fornecedores/create.blade.php new file mode 100644 index 00000000..1d61087c --- /dev/null +++ b/resources/views/content/compras/fornecedores/create.blade.php @@ -0,0 +1,11 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Novo Fornecedor') + +@section('content') +

Novo Fornecedor

+
+ @csrf + @include('content.compras.fornecedores._form') +
+@endsection diff --git a/resources/views/content/compras/fornecedores/edit.blade.php b/resources/views/content/compras/fornecedores/edit.blade.php new file mode 100644 index 00000000..acc36084 --- /dev/null +++ b/resources/views/content/compras/fornecedores/edit.blade.php @@ -0,0 +1,12 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Editar Fornecedor') + +@section('content') +

Editar Fornecedor

+
+ @csrf + @method('PUT') + @include('content.compras.fornecedores._form') +
+@endsection diff --git a/resources/views/content/compras/fornecedores/index.blade.php b/resources/views/content/compras/fornecedores/index.blade.php new file mode 100644 index 00000000..185f8c5b --- /dev/null +++ b/resources/views/content/compras/fornecedores/index.blade.php @@ -0,0 +1,101 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Fornecedores') + +@section('content') +
+
+

Fornecedores

+

Cadastro e gestão da base de compras.

+
+
+ Exportar CSV + @perm('compras.fornecedores.manage') + Novo Fornecedor + @endperm +
+
+ +@if (session('success')) +
{{ session('success') }}
+@endif + +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + + @forelse ($fornecedores as $fornecedor) + + + + + + + + @empty + + + + @endforelse + +
NomeCNPJContatoStatusAções
{{ $fornecedor->nome }}{{ $fornecedor->cnpj ?: '-' }}{{ $fornecedor->contato ?: '-' }} {{ $fornecedor->telefone ? '• '.$fornecedor->telefone : '' }}{{ $fornecedor->ativo ? 'ATIVO' : 'INATIVO' }} + @perm('compras.fornecedores.manage') + Editar +
+ @csrf + @method('DELETE') + +
+ @endperm +
Nenhum fornecedor encontrado.
+
+ @if ($fornecedores->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/estoque/alertas/index.blade.php b/resources/views/content/estoque/alertas/index.blade.php new file mode 100644 index 00000000..e39a145a --- /dev/null +++ b/resources/views/content/estoque/alertas/index.blade.php @@ -0,0 +1,109 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Alertas de Estoque') + +@section('content') +
+
+

Alertas de Estoque

+

Visão de ruptura e baixo estoque por produto. Filial referência: {{ $filialReferencia }} (estoque global).

+
+ @perm('estoque.movimentacoes.manage') + Registrar Movimentação + @endperm +
+ +
+
Itens monitorados

{{ number_format($cards['itens_monitorados'], 0, ',', '.') }}

+
Baixo estoque

{{ number_format($cards['baixo_estoque'], 0, ',', '.') }}

+
Ruptura

{{ number_format($cards['ruptura'], 0, ',', '.') }}

+
+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + + + + @forelse ($saldos as $saldo) + @php + $atual = (float) $saldo->quantidade_atual; + $reservado = (float) $saldo->quantidade_reservada; + $disponivel = $atual - $reservado; + $minimo = (float) $saldo->estoque_minimo; + $ruptura = $atual <= 0; + $baixo = !$ruptura && $atual <= $minimo; + @endphp + + + + + + + + + + @empty + + + + @endforelse + +
ProdutoCategoriaAtualReservadoDisponívelMínimoAlerta
+
{{ $saldo->produto->nome }}
+ {{ $saldo->produto->sku }} • {{ $saldo->produto->codigo_barras ?: '-' }} +
{{ $saldo->produto->categoria->nome ?? '-' }}{{ number_format($atual, 3, ',', '.') }}{{ number_format($reservado, 3, ',', '.') }}{{ number_format($disponivel, 3, ',', '.') }}{{ number_format($minimo, 3, ',', '.') }} + @if ($ruptura) + RUPTURA + @elseif ($baixo) + BAIXO ESTOQUE + @else + OK + @endif +
Nenhum alerta encontrado.
+
+ @if ($saldos->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/estoque/movimentacoes/create.blade.php b/resources/views/content/estoque/movimentacoes/create.blade.php new file mode 100644 index 00000000..327311e0 --- /dev/null +++ b/resources/views/content/estoque/movimentacoes/create.blade.php @@ -0,0 +1,147 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Nova Movimentacao') + +@section('page-script') +@vite(['resources/assets/js/movimentacoes-estoque-form.js']) +@endsection + +@section('content') +

Nova Movimentacao de Estoque

+ +@if ($errors->any()) +
Revise os campos destacados.
+@endif + +
+ @csrf +
+
+
+
+
+
+ + + @error('produto_id') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('tipo') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('ajuste_direcao') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('quantidade') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('origem') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('documento_ref') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('lote') +
{{ $message }}
+ @enderror +
+
+ + + @error('serial') +
{{ $message }}
+ @enderror +
+
+ + + @error('validade') +
{{ $message }}
+ @enderror +
+
+ + + @error('custo_unitario') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('observacao') +
{{ $message }}
+ @enderror +
+
+
+
+
+ +
+
+
+
Regras
+
    +
  • Entrada adiciona saldo.
  • +
  • Saida reduz saldo.
  • +
  • Ajuste exige direcao.
  • +
  • Produto com lote exige lote informado.
  • +
+
+
+
+ +
+ + Cancelar +
+
+
+@endsection diff --git a/resources/views/content/estoque/movimentacoes/index.blade.php b/resources/views/content/estoque/movimentacoes/index.blade.php new file mode 100644 index 00000000..70e1678f --- /dev/null +++ b/resources/views/content/estoque/movimentacoes/index.blade.php @@ -0,0 +1,91 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Movimentacoes de Estoque') + +@section('content') +
+

Movimentacoes de Estoque

+ @perm('estoque.movimentacoes.manage') + Nova Movimentacao + @endperm +
+ +@if (session('success')) +
{{ session('success') }}
+@endif + +
+
+
+
+ + +
+
+ + +
+
+ + Limpar +
+
+
+
+ +
+
+ + + + + + + + + + + + + + + @forelse ($movimentacoes as $mov) + + + + + + + + + + + @empty + + + + @endforelse + +
DataProdutoTipoOrigemLote/SerialQtdSaldo AposRef.
{{ optional($mov->created_at)->format('d/m/Y H:i') }}{{ $mov->produto->sku }} - {{ $mov->produto->nome }} + + {{ $mov->tipo }} + + {{ $mov->origem }}{{ $mov->lote ? $mov->lote->lote . ($mov->lote->serial ? ' / '.$mov->lote->serial : '') : '-' }}{{ $mov->sinal > 0 ? '+' : '-' }}{{ number_format((float) $mov->quantidade, 3, ',', '.') }}{{ number_format((float) $mov->saldo_apos, 3, ',', '.') }}{{ $mov->documento_ref ?: '-' }}
Sem movimentacoes registradas.
+
+ @if ($movimentacoes->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/financeiro/contas-pagar/index.blade.php b/resources/views/content/financeiro/contas-pagar/index.blade.php new file mode 100644 index 00000000..b32740c1 --- /dev/null +++ b/resources/views/content/financeiro/contas-pagar/index.blade.php @@ -0,0 +1,135 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Contas a Pagar') + +@section('content') +
+
+

Financeiro - Contas a Pagar

+

Controle de pagamentos de fornecedores e estornos.

+
+ Exportar CSV +
+ +@if (session('success')) +
{{ session('success') }}
+@endif +@if ($errors->any()) +
{{ $errors->first() }}
+@endif + +
+
Em aberto

R$ {{ number_format($cards['aberto_total'], 2, ',', '.') }}

+
Atrasado

R$ {{ number_format($cards['atrasado_total'], 2, ',', '.') }}

+
Pago no mês

R$ {{ number_format($cards['pago_mes'], 2, ',', '.') }}

+
+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + + + + @forelse ($contas as $conta) + + + + + + + + + + @empty + + + + @endforelse + +
CompraFornecedorVencimentoOriginalAbertoStatusAções
{{ $conta->compra->numero ?? ('#'.$conta->id) }}{{ $conta->fornecedor->nome ?? '-' }}{{ optional($conta->vencimento)->format('d/m/Y') }}R$ {{ number_format((float) $conta->valor_original, 2, ',', '.') }}R$ {{ number_format((float) $conta->valor_aberto, 2, ',', '.') }}{{ $conta->status }} + Ver + @perm('financeiro.contas_pagar.pagar') +
+
+ @csrf + + + + +
+
+ @endperm + @perm('financeiro.contas_pagar.estornar') +
+
+ @csrf + + + + +
+
+ @endperm +
Nenhuma conta a pagar encontrada.
+
+ @if ($contas->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/financeiro/contas-pagar/show.blade.php b/resources/views/content/financeiro/contas-pagar/show.blade.php new file mode 100644 index 00000000..d774f2e8 --- /dev/null +++ b/resources/views/content/financeiro/contas-pagar/show.blade.php @@ -0,0 +1,67 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Detalhe da Conta a Pagar') + +@section('content') +
+
+

Conta #{{ $conta->id }}

+

Compra: {{ $conta->compra->numero ?? '-' }} • Status: {{ $conta->status }}

+
+ +
+ +
+
+
+
Resumo
+
+

Fornecedor:
{{ $conta->fornecedor->nome ?? '-' }}

+

Vencimento:
{{ optional($conta->vencimento)->format('d/m/Y') ?: '-' }}

+

Valor Original:
R$ {{ number_format((float) $conta->valor_original, 2, ',', '.') }}

+

Valor Aberto:
R$ {{ number_format((float) $conta->valor_aberto, 2, ',', '.') }}

+

Status:
{{ $conta->status }}

+
+
+
+ +
+
+
Movimentações
+
+ + + + + + + + + + + + + @forelse ($conta->movimentos->sortByDesc('data_movimento') as $mov) + + + + + + + + + @empty + + + + @endforelse + +
DataTipoValorFormaUsuárioObservação
{{ optional($mov->data_movimento)->format('d/m/Y H:i') }}{{ $mov->tipo }}R$ {{ number_format((float) $mov->valor, 2, ',', '.') }}{{ $mov->forma_pagamento ?: '-' }}{{ $mov->usuario->name ?? 'Sistema' }}{{ $mov->observacao ?: '-' }}
Sem movimentações para esta conta.
+
+
+
+
+@endsection diff --git a/resources/views/content/financeiro/contas-receber/index.blade.php b/resources/views/content/financeiro/contas-receber/index.blade.php new file mode 100644 index 00000000..5b699469 --- /dev/null +++ b/resources/views/content/financeiro/contas-receber/index.blade.php @@ -0,0 +1,135 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Contas a Receber') + +@section('content') +
+
+

Financeiro - Contas a Receber

+

Baixa, estorno e conciliação rápida de recebimentos.

+
+ Exportar CSV +
+ +@if (session('success')) +
{{ session('success') }}
+@endif +@if ($errors->any()) +
{{ $errors->first() }}
+@endif + +
+
Em aberto

R$ {{ number_format($cards['aberto_total'], 2, ',', '.') }}

+
Atrasado

R$ {{ number_format($cards['atrasado_total'], 2, ',', '.') }}

+
Recebido no mês

R$ {{ number_format($cards['recebido_mes'], 2, ',', '.') }}

+
+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + + + + @forelse ($contas as $conta) + + + + + + + + + + @empty + + + + @endforelse + +
DocumentoClienteVencimentoOriginalAbertoStatusAções
{{ $conta->documento->numero ?? ('#'.$conta->id) }}{{ $conta->cliente->nome }}{{ optional($conta->vencimento)->format('d/m/Y') }}R$ {{ number_format((float) $conta->valor_original, 2, ',', '.') }}R$ {{ number_format((float) $conta->valor_aberto, 2, ',', '.') }}{{ $conta->status }} + Ver + @perm('financeiro.contas_receber.baixar') +
+
+ @csrf + + + + +
+
+ @endperm + @perm('financeiro.contas_receber.estornar') +
+
+ @csrf + + + + +
+
+ @endperm +
Nenhuma conta a receber encontrada.
+
+ @if ($contas->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/financeiro/contas-receber/show.blade.php b/resources/views/content/financeiro/contas-receber/show.blade.php new file mode 100644 index 00000000..4a1cb722 --- /dev/null +++ b/resources/views/content/financeiro/contas-receber/show.blade.php @@ -0,0 +1,67 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Detalhe da Conta a Receber') + +@section('content') +
+
+

Conta #{{ $conta->id }}

+

Documento: {{ $conta->documento->numero ?? '-' }} • Status: {{ $conta->status }}

+
+ +
+ +
+
+
+
Resumo
+
+

Cliente:
{{ $conta->cliente->nome ?? '-' }}

+

Vencimento:
{{ optional($conta->vencimento)->format('d/m/Y') ?: '-' }}

+

Valor Original:
R$ {{ number_format((float) $conta->valor_original, 2, ',', '.') }}

+

Valor Aberto:
R$ {{ number_format((float) $conta->valor_aberto, 2, ',', '.') }}

+

Status:
{{ $conta->status }}

+
+
+
+ +
+
+
Movimentações
+
+ + + + + + + + + + + + + @forelse ($conta->movimentos->sortByDesc('data_movimento') as $mov) + + + + + + + + + @empty + + + + @endforelse + +
DataTipoValorFormaUsuárioObservação
{{ optional($mov->data_movimento)->format('d/m/Y H:i') }}{{ $mov->tipo }}R$ {{ number_format((float) $mov->valor, 2, ',', '.') }}{{ $mov->forma_pagamento ?: '-' }}{{ $mov->usuario->name ?? 'Sistema' }}{{ $mov->observacao ?: '-' }}
Sem movimentações para esta conta.
+
+
+
+
+@endsection diff --git a/resources/views/content/produtos/_form.blade.php b/resources/views/content/produtos/_form.blade.php new file mode 100644 index 00000000..2aa88c3e --- /dev/null +++ b/resources/views/content/produtos/_form.blade.php @@ -0,0 +1,215 @@ +@php + $isEdit = isset($produto) && $produto->exists; + $precoCusto = old('preco_custo', $preco['preco_custo'] ?? 0); + $precoVenda = old('preco_venda', $preco['preco_venda'] ?? 0); +@endphp + +@if ($errors->any()) +
+ Revise os campos destacados para continuar. +
+@endif + +
+
+
+
+
Informacoes Gerais
+
+
+
+
+ + + @error('sku') +
{{ $message }}
+ @enderror +
+
+ + + @error('nome') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('categoria_id') +
{{ $message }}
+ @enderror +
+
+ + + @error('unidade_principal_id') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('codigo_barras') +
{{ $message }}
+ @enderror +
+
+ + + @error('marca') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('ncm') +
{{ $message }}
+ @enderror +
+
+ + + @error('cest') +
{{ $message }}
+ @enderror +
+ +
+ + + @error('descricao') +
{{ $message }}
+ @enderror +
+
+
+
+ +
+
+
Observacoes
+
+
+ + @error('observacoes') +
{{ $message }}
+ @enderror +
+
+
+ +
+
+
+
Preco e Estoque
+
+
+
+
+ + + @error('tabela_preco_id') +
{{ $message }}
+ @enderror +
+
+ + + @error('preco_custo') +
{{ $message }}
+ @enderror +
+
+ + + @error('preco_venda') +
{{ $message }}
+ @enderror +
+
+ + +
+
+ + + @error('estoque_minimo') +
{{ $message }}
+ @enderror +
+ @if (!$isEdit) +
+
+ Estoque inicial sera gravado como 0. +
+
+ @endif +
+
+
+ +
+
+
Regras
+
+
+ +
+ ativo ?? true))> + +
+ + +
+ permite_venda ?? true))> + +
+ + +
+ permite_compra ?? true))> + +
+ + +
+ controla_lote ?? false))> + +
+ + +
+ controla_validade ?? false))> + +
+
+
+
+ +
+ + Cancelar +
+
diff --git a/resources/views/content/produtos/create.blade.php b/resources/views/content/produtos/create.blade.php new file mode 100644 index 00000000..6d14ede6 --- /dev/null +++ b/resources/views/content/produtos/create.blade.php @@ -0,0 +1,21 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Novo Produto') + +@section('page-script') +@vite(['resources/assets/js/produtos-form.js']) +@endsection + +@section('content') +
+
+

Novo Produto

+

Cadastro com estrutura preparada para estoque e tabelas de preco.

+
+
+ +
+ @csrf + @include('content.produtos._form') +
+@endsection diff --git a/resources/views/content/produtos/edit.blade.php b/resources/views/content/produtos/edit.blade.php new file mode 100644 index 00000000..ea1c1c1f --- /dev/null +++ b/resources/views/content/produtos/edit.blade.php @@ -0,0 +1,22 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Editar Produto') + +@section('page-script') +@vite(['resources/assets/js/produtos-form.js']) +@endsection + +@section('content') +
+
+

Editar Produto

+

Atualize dados cadastrais, regras e tabela de preco.

+
+
+ +
+ @csrf + @method('PUT') + @include('content.produtos._form') +
+@endsection diff --git a/resources/views/content/produtos/index.blade.php b/resources/views/content/produtos/index.blade.php new file mode 100644 index 00000000..3bbd01e1 --- /dev/null +++ b/resources/views/content/produtos/index.blade.php @@ -0,0 +1,235 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Produtos') + +@section('content') +
+
+

Produtos

+

Cadastro, consulta e manutencao de produtos.

+
+
+ + Exportar CSV + + @perm('estoque.alertas.view') + + Alertas de Estoque + + @endperm + @perm('produtos.manage') + + Novo Produto + + @endperm +
+
+ +@if (session('success')) +
{{ session('success') }}
+@endif +@if (session('error')) +
{{ session('error') }}
+@endif + +
+
+
+
+ Total de itens +

{{ number_format($cards['total'], 0, ',', '.') }}

+
+
+
+
+
+
+ Ativos +

{{ number_format($cards['ativos'], 0, ',', '.') }}

+
+
+
+
+
+
+ Baixo estoque +

{{ number_format($cards['baixo_estoque'], 0, ',', '.') }}

+
+
+
+
+
+
+ Com preco cadastrado +

{{ number_format($cards['com_preco'], 0, ',', '.') }}

+
+
+
+
+
+
+ Margem média ref. +

{{ number_format((float) $cards['margem_media_ref'], 2, ',', '.') }}%

+
+
+
+
+
+
+ Cobertura média +

{{ number_format((float) $cards['cobertura_media_dias'], 1, ',', '.') }}d

+
+
+
+
+ +
+
+
+
+
Importar Produtos
+ Aceita CSV ou XLSX com colunas: nome, ean, marca, custo, preco_venda. +
+ @perm('produtos.manage') + + Baixar Template + + @endperm +
+ @perm('produtos.manage') +
+ @csrf +
+ + + @error('arquivo') +
{{ $message }}
+ @enderror +
+
+ +
+
+ @endperm +
+
+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + + + + + + + + @forelse ($produtos as $produto) + @php + $saldo = $produto->estoqueSaldo; + $estoqueAtual = (float) ($saldo->quantidade_atual ?? 0); + $estoqueMinimo = (float) ($saldo->estoque_minimo ?? 0); + $baixo = $estoqueAtual <= $estoqueMinimo; + @endphp + + + + + + + + + + + + + @empty + + + + @endforelse + +
SKUProdutoCategoriaUnidadePreco AtualMargem Ref.EstoqueCoberturaStatusAcoes
{{ $produto->sku }} +
{{ $produto->nome }}
+ {{ $produto->codigo_barras ?: '-' }} +
{{ $produto->categoria->nome }}{{ $produto->unidadePrincipal->sigla }}R$ {{ number_format((float) ($produto->preco_venda_atual ?? 0), 2, ',', '.') }}{{ number_format((float) ($produto->margem_ref_percentual ?? 0), 2, ',', '.') }}% +
{{ number_format($estoqueAtual, 3, ',', '.') }}
+ Min: {{ number_format($estoqueMinimo, 3, ',', '.') }} +
+ @if ($produto->cobertura_dias !== null) + {{ number_format((float) $produto->cobertura_dias, 1, ',', '.') }} dias + @else + Sem giro + @endif + + {{ $produto->ativo ? 'Ativo' : 'Inativo' }} + @if ($baixo) + Baixo estoque + @endif + + Ver + @perm('produtos.manage') + Editar +
+ @csrf + @method('DELETE') + +
+ @endperm +
Nenhum produto encontrado para os filtros aplicados.
+
+ @if ($produtos->hasPages()) + + @endif +
+@endsection diff --git a/resources/views/content/produtos/show.blade.php b/resources/views/content/produtos/show.blade.php new file mode 100644 index 00000000..b7a9dc5e --- /dev/null +++ b/resources/views/content/produtos/show.blade.php @@ -0,0 +1,87 @@ +@extends('layouts/contentNavbarLayout') + +@section('title', 'Detalhes do Produto') + +@section('content') +
+
+

{{ $produto->nome }}

+

SKU: {{ $produto->sku }}

+
+
+ @perm('produtos.manage') + Editar + @endperm + Voltar +
+
+ +@if (session('success')) +
{{ session('success') }}
+@endif + +@php + $saldo = $produto->estoqueSaldo; +@endphp + +
+
+
+
Dados do Produto
+
+
+
SKU
{{ $produto->sku }}
+
Nome
{{ $produto->nome }}
+
Codigo de Barras
{{ $produto->codigo_barras ?: '-' }}
+
Categoria
{{ $produto->categoria->nome }}
+
Unidade
{{ $produto->unidadePrincipal->sigla }} - {{ $produto->unidadePrincipal->nome }}
+
Marca
{{ $produto->marca ?: '-' }}
+
NCM
{{ $produto->ncm ?: '-' }}
+
CEST
{{ $produto->cest ?: '-' }}
+
Status
{{ $produto->ativo ? 'Ativo' : 'Inativo' }}
+
Descricao
{{ $produto->descricao ?: '-' }}
+
Observacoes
{{ $produto->observacoes ?: '-' }}
+
+
+
+
+ +
+
+
Estoque
+
+

Quantidade atual:
{{ number_format((float) ($saldo->quantidade_atual ?? 0), 3, ',', '.') }}

+

Estoque minimo:
{{ number_format((float) ($saldo->estoque_minimo ?? 0), 3, ',', '.') }}

+

+ Situacao:
+ @if ((float) ($saldo->quantidade_atual ?? 0) <= (float) ($saldo->estoque_minimo ?? 0)) + Baixo estoque + @else + Normal + @endif +

+
+
+ +
+
Tabelas de Preco
+
+ @forelse ($produto->precos->where('ativo', true) as $preco) +
+
{{ $preco->tabelaPreco->nome }}
+
Preco: R$ {{ number_format((float) $preco->preco, 2, ',', '.') }}
+ + Custo: R$ {{ number_format((float) ($preco->custo_referencia ?? 0), 2, ',', '.') }} + @if ($preco->margem_percentual !== null) + | Margem: {{ number_format((float) $preco->margem_percentual, 2, ',', '.') }}% + @endif + +
+ @empty +

Sem preco ativo cadastrado.

+ @endforelse +
+
+
+
+@endsection diff --git a/resources/views/dashboard.blade.php b/resources/views/dashboard.blade.php new file mode 100644 index 00000000..66028f2d --- /dev/null +++ b/resources/views/dashboard.blade.php @@ -0,0 +1,17 @@ + + +

+ {{ __('Dashboard') }} +

+
+ +
+
+
+
+ {{ __("You're logged in!") }} +
+
+
+
+
diff --git a/resources/views/errors/403.blade.php b/resources/views/errors/403.blade.php new file mode 100644 index 00000000..022cb675 --- /dev/null +++ b/resources/views/errors/403.blade.php @@ -0,0 +1,80 @@ + + + + + + 403 - Sem Permissão + + + +
+ Erro 403 +

Você não tem permissão para acessar esta área.

+

Se precisar desse acesso, solicite ao administrador do sistema. Você pode voltar para o painel principal ou retornar à página anterior.

+ +
+ + + diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php new file mode 100644 index 00000000..c5ff315f --- /dev/null +++ b/resources/views/layouts/app.blade.php @@ -0,0 +1,36 @@ + + + + + + + + {{ config('app.name', 'Laravel') }} + + + + + + + @vite(['resources/css/app.css', 'resources/js/app.js']) + + +
+ @include('layouts.navigation') + + + @isset($header) +
+
+ {{ $header }} +
+
+ @endisset + + +
+ {{ $slot }} +
+
+ + diff --git a/resources/views/layouts/guest.blade.php b/resources/views/layouts/guest.blade.php new file mode 100644 index 00000000..11feb470 --- /dev/null +++ b/resources/views/layouts/guest.blade.php @@ -0,0 +1,30 @@ + + + + + + + + {{ config('app.name', 'Laravel') }} + + + + + + + @vite(['resources/css/app.css', 'resources/js/app.js']) + + +
+
+ + + +
+ +
+ {{ $slot }} +
+
+ + diff --git a/resources/views/layouts/navigation.blade.php b/resources/views/layouts/navigation.blade.php new file mode 100644 index 00000000..c2d3a659 --- /dev/null +++ b/resources/views/layouts/navigation.blade.php @@ -0,0 +1,100 @@ + diff --git a/resources/views/layouts/sections/footer/footer.blade.php b/resources/views/layouts/sections/footer/footer.blade.php index 86425891..e8edf452 100644 --- a/resources/views/layouts/sections/footer/footer.blade.php +++ b/resources/views/layouts/sections/footer/footer.blade.php @@ -12,13 +12,9 @@ , made with ❤️ by {{ (!empty(config('variables.creatorName')) ? config('variables.creatorName') : '') }} - \ No newline at end of file + diff --git a/resources/views/layouts/sections/navbar/navbar-partial.blade.php b/resources/views/layouts/sections/navbar/navbar-partial.blade.php index 88bbf2fd..fd4f8858 100644 --- a/resources/views/layouts/sections/navbar/navbar-partial.blade.php +++ b/resources/views/layouts/sections/navbar/navbar-partial.blade.php @@ -32,65 +32,59 @@ - \ No newline at end of file + diff --git a/resources/views/profile/edit.blade.php b/resources/views/profile/edit.blade.php new file mode 100644 index 00000000..e0e1d387 --- /dev/null +++ b/resources/views/profile/edit.blade.php @@ -0,0 +1,29 @@ + + +

+ {{ __('Profile') }} +

+
+ +
+
+
+
+ @include('profile.partials.update-profile-information-form') +
+
+ +
+
+ @include('profile.partials.update-password-form') +
+
+ +
+
+ @include('profile.partials.delete-user-form') +
+
+
+
+
diff --git a/resources/views/profile/partials/delete-user-form.blade.php b/resources/views/profile/partials/delete-user-form.blade.php new file mode 100644 index 00000000..edeeb4a6 --- /dev/null +++ b/resources/views/profile/partials/delete-user-form.blade.php @@ -0,0 +1,55 @@ +
+
+

+ {{ __('Delete Account') }} +

+ +

+ {{ __('Once your account is deleted, all of its resources and data will be permanently deleted. Before deleting your account, please download any data or information that you wish to retain.') }} +

+
+ + {{ __('Delete Account') }} + + +
+ @csrf + @method('delete') + +

+ {{ __('Are you sure you want to delete your account?') }} +

+ +

+ {{ __('Once your account is deleted, all of its resources and data will be permanently deleted. Please enter your password to confirm you would like to permanently delete your account.') }} +

+ +
+ + + + + +
+ +
+ + {{ __('Cancel') }} + + + + {{ __('Delete Account') }} + +
+
+
+
diff --git a/resources/views/profile/partials/update-password-form.blade.php b/resources/views/profile/partials/update-password-form.blade.php new file mode 100644 index 00000000..eaca1acc --- /dev/null +++ b/resources/views/profile/partials/update-password-form.blade.php @@ -0,0 +1,48 @@ +
+
+

+ {{ __('Update Password') }} +

+ +

+ {{ __('Ensure your account is using a long, random password to stay secure.') }} +

+
+ +
+ @csrf + @method('put') + +
+ + + +
+ +
+ + + +
+ +
+ + + +
+ +
+ {{ __('Save') }} + + @if (session('status') === 'password-updated') +

{{ __('Saved.') }}

+ @endif +
+
+
diff --git a/resources/views/profile/partials/update-profile-information-form.blade.php b/resources/views/profile/partials/update-profile-information-form.blade.php new file mode 100644 index 00000000..5ae3d35d --- /dev/null +++ b/resources/views/profile/partials/update-profile-information-form.blade.php @@ -0,0 +1,64 @@ +
+
+

+ {{ __('Profile Information') }} +

+ +

+ {{ __("Update your account's profile information and email address.") }} +

+
+ +
+ @csrf +
+ +
+ @csrf + @method('patch') + +
+ + + +
+ +
+ + + + + @if ($user instanceof \Illuminate\Contracts\Auth\MustVerifyEmail && ! $user->hasVerifiedEmail()) +
+

+ {{ __('Your email address is unverified.') }} + + +

+ + @if (session('status') === 'verification-link-sent') +

+ {{ __('A new verification link has been sent to your email address.') }} +

+ @endif +
+ @endif +
+ +
+ {{ __('Save') }} + + @if (session('status') === 'profile-updated') +

{{ __('Saved.') }}

+ @endif +
+
+
diff --git a/resources/views/welcome.blade.php b/resources/views/welcome.blade.php new file mode 100644 index 00000000..df770da3 --- /dev/null +++ b/resources/views/welcome.blade.php @@ -0,0 +1,10 @@ + + + + + + {{ config('app.name', 'Laravel') }} + + + + diff --git a/routes/auth.php b/routes/auth.php new file mode 100644 index 00000000..ac05eebc --- /dev/null +++ b/routes/auth.php @@ -0,0 +1,62 @@ +group(function () { + Route::get('register', function () { + return redirect()->route('auth-register-basic'); + })->name('register'); + + Route::post('register', [RegisteredUserController::class, 'store']); + + Route::get('login', function () { + return redirect()->route('auth-login-basic'); + })->name('login'); + + Route::post('login', [AuthenticatedSessionController::class, 'store']); + + Route::get('forgot-password', function () { + return redirect()->route('auth-forgot-password-basic'); + })->name('password.request'); + + Route::post('forgot-password', [PasswordResetLinkController::class, 'store']) + ->name('password.email'); + + Route::get('reset-password/{token}', [NewPasswordController::class, 'create']) + ->name('password.reset'); + + Route::post('reset-password', [NewPasswordController::class, 'store']) + ->name('password.store'); +}); + +Route::middleware('auth')->group(function () { + Route::get('verify-email', EmailVerificationPromptController::class) + ->name('verification.notice'); + + Route::get('verify-email/{id}/{hash}', VerifyEmailController::class) + ->middleware(['signed', 'throttle:6,1']) + ->name('verification.verify'); + + Route::post('email/verification-notification', [EmailVerificationNotificationController::class, 'store']) + ->middleware('throttle:6,1') + ->name('verification.send'); + + Route::get('confirm-password', [ConfirmablePasswordController::class, 'show']) + ->name('password.confirm'); + + Route::post('confirm-password', [ConfirmablePasswordController::class, 'store']); + + Route::put('password', [PasswordController::class, 'update'])->name('password.update'); + + Route::post('logout', [AuthenticatedSessionController::class, 'destroy']) + ->name('logout'); +}); diff --git a/routes/web.php b/routes/web.php index be356e72..9752a946 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,109 +1,181 @@ name('dashboard-analytics'); - -// layout -Route::get('/layouts/without-menu', [WithoutMenu::class, 'index'])->name('layouts-without-menu'); -Route::get('/layouts/without-navbar', [WithoutNavbar::class, 'index'])->name('layouts-without-navbar'); -Route::get('/layouts/fluid', [Fluid::class, 'index'])->name('layouts-fluid'); -Route::get('/layouts/container', [Container::class, 'index'])->name('layouts-container'); -Route::get('/layouts/blank', [Blank::class, 'index'])->name('layouts-blank'); - -// pages -Route::get('/pages/account-settings-account', [AccountSettingsAccount::class, 'index'])->name('pages-account-settings-account'); -Route::get('/pages/account-settings-notifications', [AccountSettingsNotifications::class, 'index'])->name('pages-account-settings-notifications'); -Route::get('/pages/account-settings-connections', [AccountSettingsConnections::class, 'index'])->name('pages-account-settings-connections'); -Route::get('/pages/misc-error', [MiscError::class, 'index'])->name('pages-misc-error'); -Route::get('/pages/misc-under-maintenance', [MiscUnderMaintenance::class, 'index'])->name('pages-misc-under-maintenance'); - -// authentication -Route::get('/auth/login-basic', [LoginBasic::class, 'index'])->name('auth-login-basic'); -Route::get('/auth/register-basic', [RegisterBasic::class, 'index'])->name('auth-register-basic'); -Route::get('/auth/forgot-password-basic', [ForgotPasswordBasic::class, 'index'])->name('auth-reset-password-basic'); - -// cards -Route::get('/cards/basic', [CardBasic::class, 'index'])->name('cards-basic'); - -// User Interface -Route::get('/ui/accordion', [Accordion::class, 'index'])->name('ui-accordion'); -Route::get('/ui/alerts', [Alerts::class, 'index'])->name('ui-alerts'); -Route::get('/ui/badges', [Badges::class, 'index'])->name('ui-badges'); -Route::get('/ui/buttons', [Buttons::class, 'index'])->name('ui-buttons'); -Route::get('/ui/carousel', [Carousel::class, 'index'])->name('ui-carousel'); -Route::get('/ui/collapse', [Collapse::class, 'index'])->name('ui-collapse'); -Route::get('/ui/dropdowns', [Dropdowns::class, 'index'])->name('ui-dropdowns'); -Route::get('/ui/footer', [Footer::class, 'index'])->name('ui-footer'); -Route::get('/ui/list-groups', [ListGroups::class, 'index'])->name('ui-list-groups'); -Route::get('/ui/modals', [Modals::class, 'index'])->name('ui-modals'); -Route::get('/ui/navbar', [Navbar::class, 'index'])->name('ui-navbar'); -Route::get('/ui/offcanvas', [Offcanvas::class, 'index'])->name('ui-offcanvas'); -Route::get('/ui/pagination-breadcrumbs', [PaginationBreadcrumbs::class, 'index'])->name('ui-pagination-breadcrumbs'); -Route::get('/ui/progress', [Progress::class, 'index'])->name('ui-progress'); -Route::get('/ui/spinners', [Spinners::class, 'index'])->name('ui-spinners'); -Route::get('/ui/tabs-pills', [TabsPills::class, 'index'])->name('ui-tabs-pills'); -Route::get('/ui/toasts', [Toasts::class, 'index'])->name('ui-toasts'); -Route::get('/ui/tooltips-popovers', [TooltipsPopovers::class, 'index'])->name('ui-tooltips-popovers'); -Route::get('/ui/typography', [Typography::class, 'index'])->name('ui-typography'); - -// extended ui -Route::get('/extended/ui-perfect-scrollbar', [PerfectScrollbar::class, 'index'])->name('extended-ui-perfect-scrollbar'); -Route::get('/extended/ui-text-divider', [TextDivider::class, 'index'])->name('extended-ui-text-divider'); - -// icons -Route::get('/icons/boxicons', [Boxicons::class, 'index'])->name('icons-boxicons'); - -// form elements -Route::get('/forms/basic-inputs', [BasicInput::class, 'index'])->name('forms-basic-inputs'); -Route::get('/forms/input-groups', [InputGroups::class, 'index'])->name('forms-input-groups'); - -// form layouts -Route::get('/form/layouts-vertical', [VerticalForm::class, 'index'])->name('form-layouts-vertical'); -Route::get('/form/layouts-horizontal', [HorizontalForm::class, 'index'])->name('form-layouts-horizontal'); - -// tables -Route::get('/tables/basic', [TablesBasic::class, 'index'])->name('tables-basic'); \ No newline at end of file +use App\Http\Controllers\pages\AccountSettingsNotifications; +use App\Http\Controllers\produtos\ProdutoController; +use Illuminate\Support\Facades\Route; + +Route::middleware('guest')->group(function () { + Route::get('/auth/login-basic', [LoginBasic::class, 'index'])->name('auth-login-basic'); + Route::get('/auth/register-basic', [RegisterBasic::class, 'index'])->name('auth-register-basic'); + Route::get('/auth/forgot-password-basic', [ForgotPasswordBasic::class, 'index'])->name('auth-forgot-password-basic'); +}); + +Route::middleware('auth')->group(function () { + Route::middleware('perm:dashboard.view')->group(function () { + Route::get('/', [Analytics::class, 'index'])->name('dashboard-analytics'); + Route::get('/dashboard', [Analytics::class, 'index'])->name('dashboard'); + Route::get('/pages/account-settings-account', [AccountSettingsAccount::class, 'index'])->name('pages-account-settings-account'); + Route::get('/pages/account-settings-notifications', [AccountSettingsNotifications::class, 'index'])->name('pages-account-settings-notifications'); + Route::get('/pages/account-settings-connections', [AccountSettingsConnections::class, 'index'])->name('pages-account-settings-connections'); + }); + + Route::middleware('perm:usuarios.view')->group(function () { + Route::get('/usuarios', [UsuarioController::class, 'index'])->name('usuarios.index'); + Route::get('/usuarios/permissoes', [UsuarioController::class, 'permissoes'])->name('usuarios.permissoes'); + }); + + Route::middleware('perm:usuarios.manage')->group(function () { + Route::put('/usuarios/{user}/acesso', [UsuarioController::class, 'updateAcesso'])->name('usuarios.update-acesso'); + }); + + Route::middleware('perm:auditoria.view')->group(function () { + Route::get('/auditoria', [AuditoriaController::class, 'index'])->name('auditoria.index'); + Route::get('/auditoria/exportar-csv', [AuditoriaController::class, 'exportCsv'])->name('auditoria.export-csv'); + }); + + Route::middleware('perm:clientes.view')->group(function () { + Route::get('/clientes/exportar-csv', [ClienteController::class, 'exportCsv'])->name('clientes.export-csv'); + Route::resource('clientes', ClienteController::class)->only(['index', 'show']); + }); + + Route::middleware('perm:clientes.manage')->group(function () { + Route::get('/clientes/cnpj/{cnpj}', [ClienteController::class, 'buscarCnpj'])->name('clientes.buscar-cnpj'); + Route::get('/clientes/cidades/{uf}', [ClienteController::class, 'cidadesPorUf'])->name('clientes.cidades-uf'); + Route::resource('clientes', ClienteController::class)->except(['index', 'show']); + }); + + Route::middleware('perm:compras.fornecedores.view')->group(function () { + Route::get('/fornecedores/exportar-csv', [FornecedorController::class, 'exportCsv'])->name('fornecedores.export-csv'); + Route::get('/fornecedores', [FornecedorController::class, 'index'])->name('fornecedores.index'); + }); + + Route::middleware('perm:compras.fornecedores.manage')->group(function () { + Route::resource('fornecedores', FornecedorController::class)->parameters(['fornecedores' => 'fornecedor'])->except(['index', 'show']); + }); + + Route::middleware('perm:compras.compras.view')->group(function () { + Route::get('/compras/exportar-csv', [CompraController::class, 'exportCsv'])->name('compras.export-csv'); + Route::resource('compras', CompraController::class)->only(['index', 'show']); + }); + + Route::middleware('perm:compras.compras.manage')->group(function () { + Route::resource('compras', CompraController::class)->only(['create', 'store']); + }); + + Route::middleware('perm:produtos.view')->group(function () { + Route::get('produtos/exportar-csv', [ProdutoController::class, 'exportCsv'])->name('produtos.export-csv'); + Route::resource('produtos', ProdutoController::class)->only(['index', 'show']); + }); + + Route::middleware('perm:produtos.manage')->group(function () { + Route::get('produtos/importar/template', [ProdutoController::class, 'importTemplate'])->name('produtos.importar.template'); + Route::post('produtos/importar', [ProdutoController::class, 'import'])->name('produtos.importar'); + Route::resource('produtos', ProdutoController::class)->except(['index', 'show']); + }); + + Route::middleware('perm:cadastros_base.view')->group(function () { + Route::resource('categorias-produto', CategoriaProdutoController::class)->parameters(['categorias-produto' => 'categoria_produto'])->only(['index']); + Route::resource('unidades-medida', UnidadeMedidaController::class)->parameters(['unidades-medida' => 'unidade_medida'])->only(['index']); + Route::resource('tabelas-preco', TabelaPrecoController::class)->parameters(['tabelas-preco' => 'tabela_preco'])->only(['index']); + }); + + Route::middleware('perm:cadastros_base.manage')->group(function () { + Route::resource('categorias-produto', CategoriaProdutoController::class)->parameters(['categorias-produto' => 'categoria_produto'])->except(['index', 'show']); + Route::resource('unidades-medida', UnidadeMedidaController::class)->parameters(['unidades-medida' => 'unidade_medida'])->except(['index', 'show']); + Route::resource('tabelas-preco', TabelaPrecoController::class)->parameters(['tabelas-preco' => 'tabela_preco'])->except(['index', 'show']); + }); + + Route::middleware('perm:estoque.movimentacoes.view')->group(function () { + Route::resource('movimentacoes-estoque', MovimentacaoEstoqueController::class)->only(['index']); + }); + + Route::middleware('perm:estoque.movimentacoes.manage')->group(function () { + Route::get('movimentacoes-estoque/lotes/{produto}', [MovimentacaoEstoqueController::class, 'lotesPorProduto'])->name('movimentacoes-estoque.lotes'); + Route::resource('movimentacoes-estoque', MovimentacaoEstoqueController::class)->only(['create', 'store']); + }); + + Route::middleware('perm:estoque.alertas.view')->group(function () { + Route::get('estoque/alertas', [AlertaEstoqueController::class, 'index'])->name('estoque.alertas.index'); + }); + + Route::middleware('perm:financeiro.contas_receber.view')->group(function () { + Route::get('contas-receber', [ContaReceberController::class, 'index'])->name('contas-receber.index'); + Route::get('contas-receber/exportar-csv', [ContaReceberController::class, 'exportCsv'])->name('contas-receber.export-csv'); + Route::get('contas-receber/{conta}', [ContaReceberController::class, 'show'])->name('contas-receber.show'); + Route::get('contas-receber/{conta}/extrato/exportar-csv', [ContaReceberController::class, 'exportExtratoCsv'])->name('contas-receber.extrato.export-csv'); + }); + + Route::middleware('perm:financeiro.contas_receber.baixar')->group(function () { + Route::post('contas-receber/{conta}/baixar', [ContaReceberController::class, 'baixar'])->name('contas-receber.baixar'); + }); + Route::middleware('perm:financeiro.contas_receber.estornar')->post('contas-receber/{conta}/estornar', [ContaReceberController::class, 'estornar'])->name('contas-receber.estornar'); + + Route::middleware('perm:financeiro.contas_pagar.view')->group(function () { + Route::get('contas-pagar', [ContaPagarController::class, 'index'])->name('contas-pagar.index'); + Route::get('contas-pagar/exportar-csv', [ContaPagarController::class, 'exportCsv'])->name('contas-pagar.export-csv'); + Route::get('contas-pagar/{conta}', [ContaPagarController::class, 'show'])->name('contas-pagar.show'); + Route::get('contas-pagar/{conta}/extrato/exportar-csv', [ContaPagarController::class, 'exportExtratoCsv'])->name('contas-pagar.extrato.export-csv'); + }); + Route::middleware('perm:financeiro.contas_pagar.pagar')->group(function () { + Route::post('contas-pagar/{conta}/pagar', [ContaPagarController::class, 'pagar'])->name('contas-pagar.pagar'); + }); + Route::middleware('perm:financeiro.contas_pagar.estornar')->group(function () { + Route::post('contas-pagar/{conta}/estornar', [ContaPagarController::class, 'estornar'])->name('contas-pagar.estornar'); + }); + + Route::middleware('perm:vendas.pdv.use')->group(function () { + Route::get('pdv', [DocumentoComercialController::class, 'pdv'])->name('pdv.index'); + Route::post('pdv/finalizar', [DocumentoComercialController::class, 'pdvFinalizar'])->name('pdv.finalizar'); + }); + + Route::middleware('perm:vendas.documentos.converter')->group(function () { + Route::post('documentos-comerciais/{documento}/converter-pedido', [DocumentoComercialController::class, 'converterPedido'])->name('documentos-comerciais.converter-pedido'); + Route::post('documentos-comerciais/{documento}/converter-venda', [DocumentoComercialController::class, 'converterVenda'])->name('documentos-comerciais.converter-venda'); + }); + + Route::middleware('perm:vendas.documentos.faturar')->group(function () { + Route::post('documentos-comerciais/{documento}/faturar', [DocumentoComercialController::class, 'faturar'])->name('documentos-comerciais.faturar'); + }); + + Route::middleware('perm:vendas.documentos.cancelar')->group(function () { + Route::post('documentos-comerciais/{documento}/reabrir', [DocumentoComercialController::class, 'reabrir'])->name('documentos-comerciais.reabrir'); + }); + + Route::middleware('perm:vendas.documentos.importar_legado')->group(function () { + Route::post('documentos-comerciais/importar-pdf-legado', [DocumentoComercialController::class, 'importarPdfLegado'])->name('documentos-comerciais.importar-pdf-legado'); + }); + + Route::middleware('perm:vendas.documentos.view')->group(function () { + Route::get('documentos-comerciais/exportar-csv', [DocumentoComercialController::class, 'exportCsv'])->name('documentos-comerciais.export-csv'); + Route::resource('documentos-comerciais', DocumentoComercialController::class)->parameters(['documentos-comerciais' => 'documento'])->only(['index', 'show']); + Route::get('documentos-comerciais/{documento}/analise', [DocumentoComercialController::class, 'analise'])->name('documentos-comerciais.analise'); + Route::get('documentos-comerciais/{documento}/analise/exportar-csv', [DocumentoComercialController::class, 'exportAnaliseCsv'])->name('documentos-comerciais.analise.export-csv'); + }); + + Route::middleware('perm:vendas.documentos.manage')->group(function () { + Route::get('documentos-comerciais/produtos/busca', [DocumentoComercialController::class, 'buscarProdutos'])->name('documentos-comerciais.buscar-produtos'); + Route::get('documentos-comerciais/clientes/busca', [DocumentoComercialController::class, 'buscarClientes'])->name('documentos-comerciais.buscar-clientes'); + Route::resource('documentos-comerciais', DocumentoComercialController::class)->parameters(['documentos-comerciais' => 'documento'])->except(['index', 'show']); + }); +}); + +require __DIR__.'/auth.php'; diff --git a/tailwind.config.js b/tailwind.config.js new file mode 100644 index 00000000..c29eb1a1 --- /dev/null +++ b/tailwind.config.js @@ -0,0 +1,21 @@ +import defaultTheme from 'tailwindcss/defaultTheme'; +import forms from '@tailwindcss/forms'; + +/** @type {import('tailwindcss').Config} */ +export default { + content: [ + './vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php', + './storage/framework/views/*.php', + './resources/views/**/*.blade.php', + ], + + theme: { + extend: { + fontFamily: { + sans: ['Figtree', ...defaultTheme.fontFamily.sans], + }, + }, + }, + + plugins: [forms], +}; diff --git a/tests/Feature/Auth/AuthenticationTest.php b/tests/Feature/Auth/AuthenticationTest.php new file mode 100644 index 00000000..13dcb7ce --- /dev/null +++ b/tests/Feature/Auth/AuthenticationTest.php @@ -0,0 +1,54 @@ +get('/login'); + + $response->assertStatus(200); + } + + public function test_users_can_authenticate_using_the_login_screen(): void + { + $user = User::factory()->create(); + + $response = $this->post('/login', [ + 'email' => $user->email, + 'password' => 'password', + ]); + + $this->assertAuthenticated(); + $response->assertRedirect(route('dashboard', absolute: false)); + } + + public function test_users_can_not_authenticate_with_invalid_password(): void + { + $user = User::factory()->create(); + + $this->post('/login', [ + 'email' => $user->email, + 'password' => 'wrong-password', + ]); + + $this->assertGuest(); + } + + public function test_users_can_logout(): void + { + $user = User::factory()->create(); + + $response = $this->actingAs($user)->post('/logout'); + + $this->assertGuest(); + $response->assertRedirect('/'); + } +} diff --git a/tests/Feature/Auth/EmailVerificationTest.php b/tests/Feature/Auth/EmailVerificationTest.php new file mode 100644 index 00000000..705570b4 --- /dev/null +++ b/tests/Feature/Auth/EmailVerificationTest.php @@ -0,0 +1,58 @@ +unverified()->create(); + + $response = $this->actingAs($user)->get('/verify-email'); + + $response->assertStatus(200); + } + + public function test_email_can_be_verified(): void + { + $user = User::factory()->unverified()->create(); + + Event::fake(); + + $verificationUrl = URL::temporarySignedRoute( + 'verification.verify', + now()->addMinutes(60), + ['id' => $user->id, 'hash' => sha1($user->email)] + ); + + $response = $this->actingAs($user)->get($verificationUrl); + + Event::assertDispatched(Verified::class); + $this->assertTrue($user->fresh()->hasVerifiedEmail()); + $response->assertRedirect(route('dashboard', absolute: false).'?verified=1'); + } + + public function test_email_is_not_verified_with_invalid_hash(): void + { + $user = User::factory()->unverified()->create(); + + $verificationUrl = URL::temporarySignedRoute( + 'verification.verify', + now()->addMinutes(60), + ['id' => $user->id, 'hash' => sha1('wrong-email')] + ); + + $this->actingAs($user)->get($verificationUrl); + + $this->assertFalse($user->fresh()->hasVerifiedEmail()); + } +} diff --git a/tests/Feature/Auth/PasswordConfirmationTest.php b/tests/Feature/Auth/PasswordConfirmationTest.php new file mode 100644 index 00000000..ff85721e --- /dev/null +++ b/tests/Feature/Auth/PasswordConfirmationTest.php @@ -0,0 +1,44 @@ +create(); + + $response = $this->actingAs($user)->get('/confirm-password'); + + $response->assertStatus(200); + } + + public function test_password_can_be_confirmed(): void + { + $user = User::factory()->create(); + + $response = $this->actingAs($user)->post('/confirm-password', [ + 'password' => 'password', + ]); + + $response->assertRedirect(); + $response->assertSessionHasNoErrors(); + } + + public function test_password_is_not_confirmed_with_invalid_password(): void + { + $user = User::factory()->create(); + + $response = $this->actingAs($user)->post('/confirm-password', [ + 'password' => 'wrong-password', + ]); + + $response->assertSessionHasErrors(); + } +} diff --git a/tests/Feature/Auth/PasswordResetTest.php b/tests/Feature/Auth/PasswordResetTest.php new file mode 100644 index 00000000..aa503505 --- /dev/null +++ b/tests/Feature/Auth/PasswordResetTest.php @@ -0,0 +1,73 @@ +get('/forgot-password'); + + $response->assertStatus(200); + } + + public function test_reset_password_link_can_be_requested(): void + { + Notification::fake(); + + $user = User::factory()->create(); + + $this->post('/forgot-password', ['email' => $user->email]); + + Notification::assertSentTo($user, ResetPassword::class); + } + + public function test_reset_password_screen_can_be_rendered(): void + { + Notification::fake(); + + $user = User::factory()->create(); + + $this->post('/forgot-password', ['email' => $user->email]); + + Notification::assertSentTo($user, ResetPassword::class, function ($notification) { + $response = $this->get('/reset-password/'.$notification->token); + + $response->assertStatus(200); + + return true; + }); + } + + public function test_password_can_be_reset_with_valid_token(): void + { + Notification::fake(); + + $user = User::factory()->create(); + + $this->post('/forgot-password', ['email' => $user->email]); + + Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) { + $response = $this->post('/reset-password', [ + 'token' => $notification->token, + 'email' => $user->email, + 'password' => 'password', + 'password_confirmation' => 'password', + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect(route('login')); + + return true; + }); + } +} diff --git a/tests/Feature/Auth/PasswordUpdateTest.php b/tests/Feature/Auth/PasswordUpdateTest.php new file mode 100644 index 00000000..ca28c6c6 --- /dev/null +++ b/tests/Feature/Auth/PasswordUpdateTest.php @@ -0,0 +1,51 @@ +create(); + + $response = $this + ->actingAs($user) + ->from('/profile') + ->put('/password', [ + 'current_password' => 'password', + 'password' => 'new-password', + 'password_confirmation' => 'new-password', + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect('/profile'); + + $this->assertTrue(Hash::check('new-password', $user->refresh()->password)); + } + + public function test_correct_password_must_be_provided_to_update_password(): void + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->from('/profile') + ->put('/password', [ + 'current_password' => 'wrong-password', + 'password' => 'new-password', + 'password_confirmation' => 'new-password', + ]); + + $response + ->assertSessionHasErrorsIn('updatePassword', 'current_password') + ->assertRedirect('/profile'); + } +} diff --git a/tests/Feature/Auth/RegistrationTest.php b/tests/Feature/Auth/RegistrationTest.php new file mode 100644 index 00000000..1489d0e0 --- /dev/null +++ b/tests/Feature/Auth/RegistrationTest.php @@ -0,0 +1,31 @@ +get('/register'); + + $response->assertStatus(200); + } + + public function test_new_users_can_register(): void + { + $response = $this->post('/register', [ + 'name' => 'Test User', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + ]); + + $this->assertAuthenticated(); + $response->assertRedirect(route('dashboard', absolute: false)); + } +} diff --git a/tests/Feature/ProfileTest.php b/tests/Feature/ProfileTest.php new file mode 100644 index 00000000..252fdcc5 --- /dev/null +++ b/tests/Feature/ProfileTest.php @@ -0,0 +1,99 @@ +create(); + + $response = $this + ->actingAs($user) + ->get('/profile'); + + $response->assertOk(); + } + + public function test_profile_information_can_be_updated(): void + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->patch('/profile', [ + 'name' => 'Test User', + 'email' => 'test@example.com', + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect('/profile'); + + $user->refresh(); + + $this->assertSame('Test User', $user->name); + $this->assertSame('test@example.com', $user->email); + $this->assertNull($user->email_verified_at); + } + + public function test_email_verification_status_is_unchanged_when_the_email_address_is_unchanged(): void + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->patch('/profile', [ + 'name' => 'Test User', + 'email' => $user->email, + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect('/profile'); + + $this->assertNotNull($user->refresh()->email_verified_at); + } + + public function test_user_can_delete_their_account(): void + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->delete('/profile', [ + 'password' => 'password', + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect('/'); + + $this->assertGuest(); + $this->assertNull($user->fresh()); + } + + public function test_correct_password_must_be_provided_to_delete_account(): void + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->from('/profile') + ->delete('/profile', [ + 'password' => 'wrong-password', + ]); + + $response + ->assertSessionHasErrorsIn('userDeletion', 'password') + ->assertRedirect('/profile'); + + $this->assertNotNull($user->fresh()); + } +} diff --git a/tests/Feature/RbacRealRoutesTest.php b/tests/Feature/RbacRealRoutesTest.php new file mode 100644 index 00000000..0d77f1ab --- /dev/null +++ b/tests/Feature/RbacRealRoutesTest.php @@ -0,0 +1,46 @@ +actingAs(new User(['nivel_acesso' => 'OPERADOR'])); + + $response = $this->get('/usuarios/permissoes'); + + $response->assertOk(); + } + + public function test_operador_cannot_access_auditoria_route(): void + { + $this->actingAs(new User(['nivel_acesso' => 'OPERADOR'])); + + $response = $this->get('/auditoria'); + + $response->assertForbidden(); + } + + public function test_operador_cannot_import_legacy_pdf_route(): void + { + $this->actingAs(new User(['nivel_acesso' => 'OPERADOR'])); + + $response = $this->post('/documentos-comerciais/importar-pdf-legado', []); + + $response->assertForbidden(); + } + + public function test_gerente_can_reach_legacy_import_route_and_get_validation_redirect(): void + { + $this->actingAs(new User(['nivel_acesso' => 'GERENTE'])); + + $response = $this->post('/documentos-comerciais/importar-pdf-legado', []); + + $response->assertStatus(302); + } +} + diff --git a/tests/Feature/RbacRoutesTest.php b/tests/Feature/RbacRoutesTest.php new file mode 100644 index 00000000..46acdb00 --- /dev/null +++ b/tests/Feature/RbacRoutesTest.php @@ -0,0 +1,49 @@ +get('/_test/rbac/clientes-view', fn () => response('ok', 200)); + + Route::middleware(['web', 'auth', 'perm:auditoria.view']) + ->get('/_test/rbac/auditoria-view', fn () => response('ok', 200)); + } + + public function test_operador_can_access_route_with_allowed_permission(): void + { + $user = new User(['nivel_acesso' => 'OPERADOR']); + $this->actingAs($user); + + $response = $this->get('/_test/rbac/clientes-view'); + + $response->assertOk(); + } + + public function test_operador_cannot_access_route_without_permission(): void + { + $user = new User(['nivel_acesso' => 'OPERADOR']); + $this->actingAs($user); + + $response = $this->get('/_test/rbac/auditoria-view'); + + $response->assertForbidden(); + } + + public function test_guest_is_redirected_by_auth_middleware(): void + { + $response = $this->get('/_test/rbac/clientes-view'); + + $response->assertStatus(302); + } +} + diff --git a/tests/Unit/EnsurePermissionMiddlewareTest.php b/tests/Unit/EnsurePermissionMiddlewareTest.php new file mode 100644 index 00000000..838f4fe8 --- /dev/null +++ b/tests/Unit/EnsurePermissionMiddlewareTest.php @@ -0,0 +1,36 @@ +setUserResolver(fn () => new User(['nivel_acesso' => 'GERENTE'])); + + $middleware = new EnsurePermission(); + + $response = $middleware->handle($request, fn () => new Response('ok', 200), 'auditoria.view'); + + $this->assertSame(200, $response->getStatusCode()); + } + + public function test_middleware_blocks_user_without_permission(): void + { + $this->expectException(\Symfony\Component\HttpKernel\Exception\HttpException::class); + + $request = Request::create('/fake', 'GET'); + $request->setUserResolver(fn () => new User(['nivel_acesso' => 'OPERADOR'])); + + $middleware = new EnsurePermission(); + $middleware->handle($request, fn () => new Response('ok', 200), 'auditoria.view'); + } +} + diff --git a/tests/Unit/RbacPermissionTest.php b/tests/Unit/RbacPermissionTest.php new file mode 100644 index 00000000..6283c0c5 --- /dev/null +++ b/tests/Unit/RbacPermissionTest.php @@ -0,0 +1,28 @@ + 'ADMIN']); + + $this->assertTrue($user->hasPermission('usuarios.manage')); + $this->assertTrue($user->hasPermission('qualquer.permissao')); + } + + public function test_operador_has_expected_permissions_and_restrictions(): void + { + $user = new User(['nivel_acesso' => 'OPERADOR']); + + $this->assertTrue($user->hasPermission('clientes.view')); + $this->assertTrue($user->hasPermission('financeiro.contas_receber.baixar')); + $this->assertFalse($user->hasPermission('financeiro.contas_receber.estornar')); + $this->assertFalse($user->hasPermission('usuarios.manage')); + } +} + diff --git a/yarn.lock b/yarn.lock index a0dbd2ed..1d14c2f6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,6 +2,11 @@ # yarn lockfile v1 +"@alloc/quick-lru@^5.2.0": + version "5.2.0" + resolved "https://registry.yarnpkg.com/@alloc/quick-lru/-/quick-lru-5.2.0.tgz#7bf68b20c0a350f936915fcae06f58e32007ce30" + integrity sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw== + "@ampproject/remapping@^2.2.0": version "2.3.0" resolved "https://registry.yarnpkg.com/@ampproject/remapping/-/remapping-2.3.0.tgz#ed441b6fa600072520ce18b43d2c8cc8caecc7f4" @@ -1277,7 +1282,7 @@ wrap-ansi "^8.1.0" wrap-ansi-cjs "npm:wrap-ansi@^7.0.0" -"@jridgewell/gen-mapping@^0.3.12": +"@jridgewell/gen-mapping@^0.3.12", "@jridgewell/gen-mapping@^0.3.2": version "0.3.13" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz#6342a19f44347518c93e43b1ac69deb3c4656a1f" integrity sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA== @@ -1559,6 +1564,13 @@ resolved "https://registry.yarnpkg.com/@svgdotjs/svg.select.js/-/svg.select.js-4.0.2.tgz#80a10409e6c73206218690eac5c9f94f8c8909b5" integrity sha512-5gWdrvoQX3keo03SCmgaBbD+kFftq0F/f2bzCbNnpkkvW6tk4rl4MakORzFuNjvXPWwB4az9GwuvVxQVnjaK2g== +"@tailwindcss/forms@^0.5.2": + version "0.5.11" + resolved "https://registry.yarnpkg.com/@tailwindcss/forms/-/forms-0.5.11.tgz#e77039e96fa7b87c3d001a991f77f9418e666700" + integrity sha512-h9wegbZDPurxG22xZSoWtdzc41/OlNEUQERNqI/0fOwa2aVlWGu7C35E/x6LDyD3lgtztFSSjKZyuVM0hxhbgA== + dependencies: + mini-svg-data-uri "^1.2.3" + "@trysound/sax@0.2.0": version "0.2.0" resolved "https://registry.yarnpkg.com/@trysound/sax/-/sax-0.2.0.tgz#cccaab758af56761eb7bf37af6f03f326dd798ad" @@ -1613,6 +1625,18 @@ dependencies: "@types/node" "*" +"@vue/reactivity@~3.1.1": + version "3.1.5" + resolved "https://registry.yarnpkg.com/@vue/reactivity/-/reactivity-3.1.5.tgz#dbec4d9557f7c8f25c2635db1e23a78a729eb991" + integrity sha512-1tdfLmNjWG6t/CsPldh+foumYFo3cpyCHgBYQ34ylaMsJ+SNHQ1kApMIa8jN+i593zQuaw3AdWH0nJTARzCFhg== + dependencies: + "@vue/shared" "3.1.5" + +"@vue/shared@3.1.5": + version "3.1.5" + resolved "https://registry.yarnpkg.com/@vue/shared/-/shared-3.1.5.tgz#74ee3aad995d0a3996a6bb9533d4d280514ede03" + integrity sha512-oJ4F3TnvpXaQwZJNF3ZK+kLPHKarDmJjJ6jyzVNDKH9md1dptjC7lWR//jrGuLdek/U6iltWxqAnYOu8gCiOvA== + "@yr/monotone-cubic-spline@^1.0.3": version "1.0.3" resolved "https://registry.yarnpkg.com/@yr/monotone-cubic-spline/-/monotone-cubic-spline-1.0.3.tgz#7272d89f8e4f6fb7a1600c28c378cc18d3b577b9" @@ -1678,6 +1702,13 @@ ajv@^8.0.0, ajv@^8.0.1, ajv@^8.17.1, ajv@^8.9.0: json-schema-traverse "^1.0.0" require-from-string "^2.0.2" +alpinejs@^3.4.2: + version "3.15.8" + resolved "https://registry.yarnpkg.com/alpinejs/-/alpinejs-3.15.8.tgz#2817920fc8af4a63a8c6e57fc66aa71a5f6d8e89" + integrity sha512-zxIfCRTBGvF1CCLIOMQOxAyBuqibxSEwS6Jm1a3HGA9rgrJVcjEWlwLcQTVGAWGS8YhAsTRLVrtQ5a5QT9bSSQ== + dependencies: + "@vue/reactivity" "~3.1.1" + ansi-regex@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" @@ -1700,6 +1731,11 @@ ansi-styles@^6.1.0: resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.1.tgz#0e62320cf99c21afff3b3012192546aacbfb05c5" integrity sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug== +any-promise@^1.0.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/any-promise/-/any-promise-1.3.0.tgz#abc6afeedcea52e809cdc0376aed3ce39635d17f" + integrity sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A== + anymatch@~3.1.2: version "3.1.3" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.3.tgz#790c58b19ba1720a84205b57c618d5ad8524973e" @@ -1720,6 +1756,11 @@ apexcharts@~4.2.0: "@svgdotjs/svg.select.js" "^4.0.1" "@yr/monotone-cubic-spline" "^1.0.3" +arg@^5.0.2: + version "5.0.2" + resolved "https://registry.yarnpkg.com/arg/-/arg-5.0.2.tgz#c81433cc427c92c4dcf4865142dbca6f15acd59c" + integrity sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg== + argparse@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" @@ -1835,15 +1876,14 @@ atob@^2.1.2: resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9" integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== -autoprefixer@^10.4.21: - version "10.4.21" - resolved "https://registry.yarnpkg.com/autoprefixer/-/autoprefixer-10.4.21.tgz#77189468e7a8ad1d9a37fbc08efc9f480cf0a95d" - integrity sha512-O+A6LWV5LDHSJD3LjHYoNi4VLsj/Whi7k6zG12xTYaU4cQ8oxQGckXNX8cRHK5yOZ/ppVHe0ZBXGzSV9jXdVbQ== +autoprefixer@^10.4.2: + version "10.4.27" + resolved "https://registry.yarnpkg.com/autoprefixer/-/autoprefixer-10.4.27.tgz#51ea301a5c3c5f8642f8e564759c4f573be486f2" + integrity sha512-NP9APE+tO+LuJGn7/9+cohklunJsXWiaWEfV3si4Gi/XHDwVNgkwr1J3RQYFIvPy76GmJ9/bW8vyoU1LcxwKHA== dependencies: - browserslist "^4.24.4" - caniuse-lite "^1.0.30001702" - fraction.js "^4.3.7" - normalize-range "^0.1.2" + browserslist "^4.28.1" + caniuse-lite "^1.0.30001774" + fraction.js "^5.3.4" picocolors "^1.1.1" postcss-value-parser "^4.2.0" @@ -1915,6 +1955,11 @@ baseline-browser-mapping@^2.8.3: resolved "https://registry.yarnpkg.com/baseline-browser-mapping/-/baseline-browser-mapping-2.8.9.tgz#fd0b8543c4f172595131e94965335536b3101b75" integrity sha512-hY/u2lxLrbecMEWSB0IpGzGyDyeoMFQhCvZd2jGFSE5I17Fh01sYUBPCJtkWERw7zrac9+cIghxm/ytJa2X8iA== +baseline-browser-mapping@^2.9.0: + version "2.10.8" + resolved "https://registry.yarnpkg.com/baseline-browser-mapping/-/baseline-browser-mapping-2.10.8.tgz#23d1cea1a85b181c2b8660b6cfe626dc2fb15630" + integrity sha512-PCLz/LXGBsNTErbtB6i5u4eLpHeMfi93aUv5duMmj6caNu6IphS4q6UevDnL36sZQv9lrP11dbPKGMaXPwMKfQ== + batch@0.6.1: version "0.6.1" resolved "https://registry.yarnpkg.com/batch/-/batch-0.6.1.tgz#dc34314f4e679318093fc760272525f94bf25c16" @@ -2028,7 +2073,7 @@ browserslist@^4.23.1: node-releases "^2.0.14" update-browserslist-db "^1.1.0" -browserslist@^4.24.0, browserslist@^4.24.4, browserslist@^4.25.3: +browserslist@^4.24.0, browserslist@^4.25.3: version "4.26.2" resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.26.2.tgz#7db3b3577ec97f1140a52db4936654911078cef3" integrity sha512-ECFzp6uFOSB+dcZ5BK/IBaGWssbSYBHvuMeMt3MMFyhI0Z8SqGgEkBLARgpRH3hutIgPVsALcMwbDrJqPxQ65A== @@ -2039,6 +2084,17 @@ browserslist@^4.24.0, browserslist@^4.24.4, browserslist@^4.25.3: node-releases "^2.0.21" update-browserslist-db "^1.1.3" +browserslist@^4.28.1: + version "4.28.1" + resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.28.1.tgz#7f534594628c53c63101079e27e40de490456a95" + integrity sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA== + dependencies: + baseline-browser-mapping "^2.9.0" + caniuse-lite "^1.0.30001759" + electron-to-chromium "^1.5.263" + node-releases "^2.0.27" + update-browserslist-db "^1.2.0" + bs-recipes@1.3.4: version "1.3.4" resolved "https://registry.yarnpkg.com/bs-recipes/-/bs-recipes-1.3.4.tgz#0d2d4d48a718c8c044769fdc4f89592dc8b69585" @@ -2096,11 +2152,21 @@ callsites@^3.0.0: resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== -caniuse-lite@^1.0.30001640, caniuse-lite@^1.0.30001702, caniuse-lite@^1.0.30001741: +camelcase-css@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/camelcase-css/-/camelcase-css-2.0.1.tgz#ee978f6947914cc30c6b44741b6ed1df7f043fd5" + integrity sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA== + +caniuse-lite@^1.0.30001640, caniuse-lite@^1.0.30001741: version "1.0.30001746" resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001746.tgz#199d20f04f5369825e00ff7067d45d5dfa03aee7" integrity sha512-eA7Ys/DGw+pnkWWSE/id29f2IcPHVoE8wxtvE5JdvD2V28VTDPy1yEeo11Guz0sJ4ZeGRcm3uaTcAqK1LXaphA== +caniuse-lite@^1.0.30001759, caniuse-lite@^1.0.30001774: + version "1.0.30001780" + resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001780.tgz#0e413de292808868a62ed9118822683fa120a110" + integrity sha512-llngX0E7nQci5BPJDqoZSbuZ5Bcs9F5db7EtgfwBerX9XGtkkiO4NwfDDIRzHTTwcYC8vC7bmeUEPGrKlR/TkQ== + chalk@4.1.2, chalk@^4.0.0: version "4.1.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" @@ -2138,7 +2204,7 @@ cheerio@1.0.0: undici "^6.19.5" whatwg-mimetype "^4.0.0" -"chokidar@>=3.0.0 <4.0.0", chokidar@^3.5.1: +"chokidar@>=3.0.0 <4.0.0", chokidar@^3.5.1, chokidar@^3.6.0: version "3.6.0" resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.6.0.tgz#197c6cc669ef2a8dc5e7b4d97ee4e092c3eb0d5b" integrity sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw== @@ -2196,6 +2262,11 @@ commander@^2.2.0: resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== +commander@^4.0.0: + version "4.1.1" + resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" + integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== + commander@^7.2.0: version "7.2.0" resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" @@ -2488,6 +2559,11 @@ dev-ip@^1.0.1: resolved "https://registry.yarnpkg.com/dev-ip/-/dev-ip-1.0.1.tgz#a76a3ed1855be7a012bb8ac16cb80f3c00dc28f0" integrity sha512-LmVkry/oDShEgSZPNgqCIp2/TlqtExeGmymru3uCELnfyjY11IzpAproLYs+1X88fXO6DBoYP3ul2Xo2yz2j6A== +didyoumean@^1.2.2: + version "1.2.2" + resolved "https://registry.yarnpkg.com/didyoumean/-/didyoumean-1.2.2.tgz#989346ffe9e839b4555ecf5666edea0d3e8ad037" + integrity sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw== + dir-glob@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f" @@ -2495,6 +2571,11 @@ dir-glob@^3.0.1: dependencies: path-type "^4.0.0" +dlv@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/dlv/-/dlv-1.1.3.tgz#5c198a8a11453596e751494d49874bc7732f2e79" + integrity sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA== + doctrine@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" @@ -2570,6 +2651,11 @@ electron-to-chromium@^1.4.820, electron-to-chromium@^1.5.218: resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.5.227.tgz#c81b6af045b0d6098faed261f0bd611dc282d3a7" integrity sha512-ITxuoPfJu3lsNWUi2lBM2PaBPYgH3uqmxut5vmBxgYvyI4AlJ6P3Cai1O76mOrkJCBzq0IxWg/NtqOrpu/0gKA== +electron-to-chromium@^1.5.263: + version "1.5.321" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.5.321.tgz#57a80554e2e7fd65e3689d320f52a64723472d5d" + integrity sha512-L2C7Q279W2D/J4PLZLk7sebOILDSWos7bMsMNN06rK482umHUrh/3lM8G7IlHFOYip2oAg5nha1rCMxr/rs6ZQ== + emoji-regex@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" @@ -3009,7 +3095,7 @@ fast-diff@^1.1.2: resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.3.0.tgz#ece407fa550a64d638536cd727e129c61616e0f0" integrity sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw== -fast-glob@^3.2.9, fast-glob@^3.3.3: +fast-glob@^3.2.9, fast-glob@^3.3.2, fast-glob@^3.3.3: version "3.3.3" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.3.tgz#d06d585ce8dba90a16b0505c543c3ccfb3aeb818" integrity sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg== @@ -3054,7 +3140,7 @@ fd-slicer@~1.1.0: dependencies: pend "~1.2.0" -fdir@^6.4.4: +fdir@^6.4.4, fdir@^6.5.0: version "6.5.0" resolved "https://registry.yarnpkg.com/fdir/-/fdir-6.5.0.tgz#ed2ab967a331ade62f18d077dae192684d50d350" integrity sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg== @@ -3177,10 +3263,10 @@ form-data@^4.0.4: hasown "^2.0.2" mime-types "^2.1.12" -fraction.js@^4.3.7: - version "4.3.7" - resolved "https://registry.yarnpkg.com/fraction.js/-/fraction.js-4.3.7.tgz#06ca0085157e42fda7f9e726e79fefc4068840f7" - integrity sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew== +fraction.js@^5.3.4: + version "5.3.4" + resolved "https://registry.yarnpkg.com/fraction.js/-/fraction.js-5.3.4.tgz#8c0fcc6a9908262df4ed197427bdeef563e0699a" + integrity sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ== fresh@0.5.2, fresh@^0.5.2: version "0.5.2" @@ -3791,6 +3877,11 @@ jackspeak@^3.1.2: optionalDependencies: "@pkgjs/parseargs" "^0.11.0" +jiti@^1.21.7: + version "1.21.7" + resolved "https://registry.yarnpkg.com/jiti/-/jiti-1.21.7.tgz#9dd81043424a3d28458b193d965f0d18a2300ba9" + integrity sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A== + jquery@~3.7.1: version "3.7.1" resolved "https://registry.yarnpkg.com/jquery/-/jquery-3.7.1.tgz#083ef98927c9a6a74d05a6af02806566d16274de" @@ -3902,6 +3993,11 @@ levn@^0.4.1: prelude-ls "^1.2.1" type-check "~0.4.0" +lilconfig@^3.1.1, lilconfig@^3.1.3: + version "3.1.3" + resolved "https://registry.yarnpkg.com/lilconfig/-/lilconfig-3.1.3.tgz#a1bcfd6257f9585bf5ae14ceeebb7b559025e4c4" + integrity sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw== + limiter@^1.0.5: version "1.1.5" resolved "https://registry.yarnpkg.com/limiter/-/limiter-1.1.5.tgz#8f92a25b3b16c6131293a0cc834b4a838a2aa7c2" @@ -4069,6 +4165,11 @@ mime@1.6.0: resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg== +mini-svg-data-uri@^1.2.3: + version "1.4.4" + resolved "https://registry.yarnpkg.com/mini-svg-data-uri/-/mini-svg-data-uri-1.4.4.tgz#8ab0aabcdf8c29ad5693ca595af19dd2ead09939" + integrity sha512-r9deDe9p5FJUPZAk3A59wGH7Ii9YrjjWw0jmw/liSbHl2CHiyXj6FcDXDu2K3TjVAXqiJdaw3xxwlZZr9E6nHg== + minimatch@^3.0.2, minimatch@^3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" @@ -4153,6 +4254,15 @@ ms@2.1.3, ms@^2.1.1, ms@^2.1.3: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== +mz@^2.7.0: + version "2.7.0" + resolved "https://registry.yarnpkg.com/mz/-/mz-2.7.0.tgz#95008057a56cafadc2bc63dde7f9ff6955948e32" + integrity sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q== + dependencies: + any-promise "^1.0.0" + object-assign "^4.0.1" + thenify-all "^1.0.0" + nanoid@^3.3.11, nanoid@^3.3.7: version "3.3.11" resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.11.tgz#4f4f112cefbe303202f2199838128936266d185b" @@ -4178,16 +4288,16 @@ node-releases@^2.0.14, node-releases@^2.0.21: resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.21.tgz#f59b018bc0048044be2d4c4c04e4c8b18160894c" integrity sha512-5b0pgg78U3hwXkCM8Z9b2FJdPZlr9Psr9V2gQPESdGHqbntyFJKFW4r5TeWGFzafGY3hzs1JC62VEQMbl1JFkw== +node-releases@^2.0.27: + version "2.0.36" + resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.36.tgz#99fd6552aaeda9e17c4713b57a63964a2e325e9d" + integrity sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA== + normalize-path@^3.0.0, normalize-path@~3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== -normalize-range@^0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/normalize-range/-/normalize-range-0.1.2.tgz#2d10c06bdfd312ea9777695a4d28439456b75942" - integrity sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA== - nth-check@^2.0.1: version "2.1.1" resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-2.1.1.tgz#c9eab428effce36cd6b92c924bdb000ef1f1ed1d" @@ -4195,11 +4305,16 @@ nth-check@^2.0.1: dependencies: boolbase "^1.0.0" -object-assign@^4, object-assign@^4.1.1: +object-assign@^4, object-assign@^4.0.1, object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" integrity sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg== +object-hash@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/object-hash/-/object-hash-3.0.0.tgz#73f97f753e7baffc0e2cc9d6e079079744ac82e9" + integrity sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw== + object-inspect@^1.13.3, object-inspect@^1.13.4: version "1.13.4" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.4.tgz#8375265e21bc20d0fa582c22e1b13485d6e00213" @@ -4476,6 +4591,21 @@ picomatch@^4.0.2: resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.2.tgz#77c742931e8f3b8820946c76cd0c1f13730d1dab" integrity sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg== +picomatch@^4.0.3: + version "4.0.3" + resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.3.tgz#796c76136d1eead715db1e7bad785dedd695a042" + integrity sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q== + +pify@^2.3.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" + integrity sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog== + +pirates@^4.0.1: + version "4.0.7" + resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.7.tgz#643b4a18c4257c8a65104b73f3049ce9a0a15e22" + integrity sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA== + pkg-dir@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-7.0.0.tgz#8f0c08d6df4476756c5ff29b3282d0bab7517d11" @@ -4514,6 +4644,36 @@ possible-typed-array-names@^1.0.0: resolved "https://registry.yarnpkg.com/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz#93e3582bc0e5426586d9d07b79ee40fc841de4ae" integrity sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg== +postcss-import@^15.1.0: + version "15.1.0" + resolved "https://registry.yarnpkg.com/postcss-import/-/postcss-import-15.1.0.tgz#41c64ed8cc0e23735a9698b3249ffdbf704adc70" + integrity sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew== + dependencies: + postcss-value-parser "^4.0.0" + read-cache "^1.0.0" + resolve "^1.1.7" + +postcss-js@^4.0.1: + version "4.1.0" + resolved "https://registry.yarnpkg.com/postcss-js/-/postcss-js-4.1.0.tgz#003b63c6edde948766e40f3daf7e997ae43a5ce6" + integrity sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw== + dependencies: + camelcase-css "^2.0.1" + +"postcss-load-config@^4.0.2 || ^5.0 || ^6.0": + version "6.0.1" + resolved "https://registry.yarnpkg.com/postcss-load-config/-/postcss-load-config-6.0.1.tgz#6fd7dcd8ae89badcf1b2d644489cbabf83aa8096" + integrity sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g== + dependencies: + lilconfig "^3.1.1" + +postcss-nested@^6.2.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/postcss-nested/-/postcss-nested-6.2.0.tgz#4c2d22ab5f20b9cb61e2c5c5915950784d068131" + integrity sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ== + dependencies: + postcss-selector-parser "^6.1.1" + postcss-resolve-nested-selector@^0.1.6: version "0.1.6" resolved "https://registry.yarnpkg.com/postcss-resolve-nested-selector/-/postcss-resolve-nested-selector-0.1.6.tgz#3d84dec809f34de020372c41b039956966896686" @@ -4524,7 +4684,7 @@ postcss-safe-parser@^7.0.1: resolved "https://registry.yarnpkg.com/postcss-safe-parser/-/postcss-safe-parser-7.0.1.tgz#36e4f7e608111a0ca940fd9712ce034718c40ec0" integrity sha512-0AioNCJZ2DPYz5ABT6bddIqlhgwhpHZ/l65YAYo0BCIn0xiDpsnTHz0gnoTGk0OXZW0JRs+cDwL8u/teRdz+8A== -postcss-selector-parser@^6.1.1: +postcss-selector-parser@^6.1.1, postcss-selector-parser@^6.1.2: version "6.1.2" resolved "https://registry.yarnpkg.com/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz#27ecb41fb0e3b6ba7a1ec84fff347f734c7929de" integrity sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg== @@ -4540,7 +4700,7 @@ postcss-selector-parser@^7.1.0: cssesc "^3.0.0" util-deprecate "^1.0.2" -postcss-value-parser@^4.2.0: +postcss-value-parser@^4.0.0, postcss-value-parser@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz#723c09920836ba6d3e5af019f92bc0971c02e514" integrity sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ== @@ -4554,6 +4714,15 @@ postcss@^8.2.14: picocolors "^1.0.1" source-map-js "^1.2.0" +postcss@^8.4.31, postcss@^8.4.47: + version "8.5.8" + resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.5.8.tgz#6230ecc8fb02e7a0f6982e53990937857e13f399" + integrity sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg== + dependencies: + nanoid "^3.3.11" + picocolors "^1.1.1" + source-map-js "^1.2.1" + postcss@^8.5.3, postcss@^8.5.6: version "8.5.6" resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.5.6.tgz#2825006615a619b4f62a9e7426cc120b349a8f3c" @@ -4637,6 +4806,13 @@ react-is@^16.13.1: resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== +read-cache@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/read-cache/-/read-cache-1.0.0.tgz#e664ef31161166c9751cdbe8dbcf86b5fb58f774" + integrity sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA== + dependencies: + pify "^2.3.0" + readdirp@~3.6.0: version "3.6.0" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" @@ -4759,6 +4935,15 @@ resolve-url-loader@5.0.0: postcss "^8.2.14" source-map "0.6.1" +resolve@^1.1.7, resolve@^1.22.8: + version "1.22.11" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.11.tgz#aad857ce1ffb8bfa9b0b1ac29f1156383f68c262" + integrity sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ== + dependencies: + is-core-module "^2.16.1" + path-parse "^1.0.7" + supports-preserve-symlinks-flag "^1.0.0" + resolve@^1.14.2: version "1.22.8" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.8.tgz#b6c87a9f2aa06dfab52e3d70ac8cde321fa5a48d" @@ -5319,6 +5504,19 @@ stylelint@^16.8.0: table "^6.9.0" write-file-atomic "^5.0.1" +sucrase@^3.35.0: + version "3.35.1" + resolved "https://registry.yarnpkg.com/sucrase/-/sucrase-3.35.1.tgz#4619ea50393fe8bd0ae5071c26abd9b2e346bfe1" + integrity sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw== + dependencies: + "@jridgewell/gen-mapping" "^0.3.2" + commander "^4.0.0" + lines-and-columns "^1.1.6" + mz "^2.7.0" + pirates "^4.0.1" + tinyglobby "^0.2.11" + ts-interface-checker "^0.1.9" + supports-color@8.1.1: version "8.1.1" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" @@ -5382,6 +5580,34 @@ table@^6.9.0: string-width "^4.2.3" strip-ansi "^6.0.1" +tailwindcss@^3.1.0: + version "3.4.19" + resolved "https://registry.yarnpkg.com/tailwindcss/-/tailwindcss-3.4.19.tgz#af2a0a4ae302d52ebe078b6775e799e132500ee2" + integrity sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ== + dependencies: + "@alloc/quick-lru" "^5.2.0" + arg "^5.0.2" + chokidar "^3.6.0" + didyoumean "^1.2.2" + dlv "^1.1.3" + fast-glob "^3.3.2" + glob-parent "^6.0.2" + is-glob "^4.0.3" + jiti "^1.21.7" + lilconfig "^3.1.3" + micromatch "^4.0.8" + normalize-path "^3.0.0" + object-hash "^3.0.0" + picocolors "^1.1.1" + postcss "^8.4.47" + postcss-import "^15.1.0" + postcss-js "^4.0.1" + postcss-load-config "^4.0.2 || ^5.0 || ^6.0" + postcss-nested "^6.2.0" + postcss-selector-parser "^6.1.2" + resolve "^1.22.8" + sucrase "^3.35.0" + tar@^6.2.1: version "6.2.1" resolved "https://registry.yarnpkg.com/tar/-/tar-6.2.1.tgz#717549c541bc3c2af15751bea94b1dd068d4b03a" @@ -5394,11 +5620,33 @@ tar@^6.2.1: mkdirp "^1.0.3" yallist "^4.0.0" +thenify-all@^1.0.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/thenify-all/-/thenify-all-1.6.0.tgz#1a1918d402d8fc3f98fbf234db0bcc8cc10e9726" + integrity sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA== + dependencies: + thenify ">= 3.1.0 < 4" + +"thenify@>= 3.1.0 < 4": + version "3.3.1" + resolved "https://registry.yarnpkg.com/thenify/-/thenify-3.3.1.tgz#8932e686a4066038a016dd9e2ca46add9838a95f" + integrity sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw== + dependencies: + any-promise "^1.0.0" + tinyexec@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/tinyexec/-/tinyexec-0.3.2.tgz#941794e657a85e496577995c6eef66f53f42b3d2" integrity sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA== +tinyglobby@^0.2.11: + version "0.2.15" + resolved "https://registry.yarnpkg.com/tinyglobby/-/tinyglobby-0.2.15.tgz#e228dd1e638cea993d2fdb4fcd2d4602a79951c2" + integrity sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ== + dependencies: + fdir "^6.5.0" + picomatch "^4.0.3" + tinyglobby@^0.2.13: version "0.2.13" resolved "https://registry.yarnpkg.com/tinyglobby/-/tinyglobby-0.2.13.tgz#a0e46515ce6cbcd65331537e57484af5a7b2ff7e" @@ -5429,6 +5677,11 @@ tree-kill@1.2.2: resolved "https://registry.yarnpkg.com/tree-kill/-/tree-kill-1.2.2.tgz#4ca09a9092c88b73a7cdc5e8a01b507b0790a0cc" integrity sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A== +ts-interface-checker@^0.1.9: + version "0.1.13" + resolved "https://registry.yarnpkg.com/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz#784fd3d679722bc103b1b4b8030bcddb5db2a699" + integrity sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA== + tsconfig-paths@^3.15.0: version "3.15.0" resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz#5299ec605e55b1abb23ec939ef15edaf483070d4" @@ -5567,6 +5820,14 @@ update-browserslist-db@^1.1.0, update-browserslist-db@^1.1.3: escalade "^3.2.0" picocolors "^1.1.1" +update-browserslist-db@^1.2.0: + version "1.2.3" + resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz#64d76db58713136acbeb4c49114366cc6cc2e80d" + integrity sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w== + dependencies: + escalade "^3.2.0" + picocolors "^1.1.1" + uri-js@^4.2.2: version "4.4.1" resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e"