templates/base.html.twig line 1

Open in your IDE?
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <base href="">
  5.     <title>Agrovit Facturas | {{ titlePage|default('Bienvenido') }}  </title>
  6.     <meta charset="utf-8"/>
  7.     <meta name="description" content="una descripcion "/>
  8.     <meta name="keywords" content="palabras claves "/>
  9.     <meta name="viewport" content="width=device-width, initial-scale=1"/>
  10.     <meta property="og:locale" content="en_US"/>
  11.     <meta property="og:type" content="article"/>
  12.     <meta property="og:title" content="Laboratorio IANSA"/>
  13.     <meta property="og:url" content="https://keenthemes.com/metronic"/>
  14.     <meta property="og:site_name" content="Facturas | IAnalytics"/>
  15.     <link rel="icon" href="{{ asset('media/logo.png') }}">
  16.     <link rel="shortcut icon" href="#"/>
  17.     <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700"/>
  18.     <link href="{{ asset('plugins/datatables/dataTables.bootstrap4.css') }}" rel="stylesheet"/>
  19.     <link href="{{ asset('plugins/global/plugins.bundle.css') }}" rel="stylesheet" type="text/css"/>
  20.     <link href="{{ asset('css/style.bundle.css') }}" rel="stylesheet" type="text/css"/>
  21.     <link href="{{ asset('css/iansaLab.css') }} " rel="stylesheet" type="text/css"/>
  22.     {% set headerImg = 'media/patterns/banners1.jpg' %}
  23.     {% set headerImg2 = 'media/patterns/banners1Black.jpg' %}
  24.     {% set mosaico = 'media/svg/wave-bg-dark.svg' %}
  25.     {% set modeStyle = '' %}
  26.     {% set logoLab = 'media/logo.png' %}
  27.     <style>
  28.         .email-dropdown-menu {
  29.             display: none;
  30.             position: absolute;
  31.             background-color: #ffffff;
  32.             border-radius: 6px; /* Bordes redondeados */
  33.             box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  34.             z-index: 1000; /* Asegúrate de que la z-index es suficientemente alta para superponer otros elementos */
  35.         }
  36.         .dark-mode-toggle-container {
  37.             display: flex;
  38.             align-items: center;
  39.             gap: 10px; /* Espacio entre el texto y el switch */
  40.         }
  41.         .switch {
  42.             position: relative;
  43.             display: inline-block;
  44.             width: 60px;
  45.             height: 34px;
  46.         }
  47.         .switch input {
  48.             opacity: 0;
  49.             width: 0;
  50.             height: 0;
  51.         }
  52.         .slider {
  53.             position: absolute;
  54.             cursor: pointer;
  55.             top: 0;
  56.             left: 0;
  57.             right: 0;
  58.             bottom: 0;
  59.             background-color: #ccc;
  60.             transition: .4s;
  61.         }
  62.         .slider:before {
  63.             position: absolute;
  64.             content: "";
  65.             height: 26px;
  66.             width: 26px;
  67.             left: 4px;
  68.             bottom: 4px;
  69.             background-color: white;
  70.             transition: .4s;
  71.         }
  72.         input:checked + .slider {
  73.             background-color: #2196F3;
  74.         }
  75.         input:checked + .slider:before {
  76.             transform: translateX(26px);
  77.         }
  78.         .slider.round {
  79.             border-radius: 34px;
  80.         }
  81.         .slider.round:before {
  82.             border-radius: 50%;
  83.         }
  84.     </style>
  85.     {% block stylesheets %}
  86.     {% endblock %}
  87. </head>
  88. <body id="kt_body" style="background-image: url({{ asset(headerImg) }});background-blend-mode: multiply; background-size: auto !important;" class="header-fixed header-tablet-and-mobile-fixed toolbar-enabled  dark-mode">
  89. <div class="d-flex flex-column flex-root">
  90.     <!--begin::Page-->
  91.     <div class="page d-flex flex-row flex-column-fluid">
  92.         <!--begin::Wrapper-->
  93.         <div class="wrapper d-flex flex-column flex-row-fluid" id="kt_wrapper">
  94.             <!--begin::Header-->
  95.             <div id="kt_header" class="header align-items-stretch" data-kt-sticky="true" data-kt-sticky-name="header"
  96.                  data-kt-sticky-offset="{default: '200px', lg: '300px'}"
  97.                  style="background-color:rgb(255 255 255 / 0%);border-bottom:0">
  98.                 <!--begin::Container-->
  99.                 <div class="container-fluid d-flex align-items-center">
  100.                     <div class="d-flex topbar align-items-center d-lg-none ms-n2 me-3" title="Show aside menu">
  101.                         <div class="btn btn-icon btn-active-light-primary btn-custom w-30px h-30px w-md-40px h-md-40px"
  102.                              id="kt_header_menu_mobile_toggle">
  103.                             <!--begin::Svg Icon | path: icons/duotune/abstract/abs015.svg-->
  104.                             <span class="svg-icon svg-icon-1">
  105.                                 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
  106.                                      fill="none">
  107.                                     <path d="M21 7H3C2.4 7 2 6.6 2 6V4C2 3.4 2.4 3 3 3H21C21.6 3 22 3.4 22 4V6C22 6.6 21.6 7 21 7Z"
  108.                                           fill="currentColor"/>
  109.                                     <path opacity="0.3"
  110.                                           d="M21 14H3C2.4 14 2 13.6 2 13V11C2 10.4 2.4 10 3 10H21C21.6 10 22 10.4 22 11V13C22 13.6 21.6 14 21 14ZM22 20V18C22 17.4 21.6 17 21 17H3C2.4 17 2 17.4 2 18V20C2 20.6 2.4 21 3 21H21C21.6 21 22 20.6 22 20Z"
  111.                                           fill="currentColor"/>
  112.                                 </svg>
  113.                             </span>
  114.                             <!--end::Svg Icon-->
  115.                         </div>
  116.                     </div>
  117.                     <!--begin::Header Logo-->
  118.                     <div class="header-logo me-5 me-md-8 flex-grow-1 flex-lg-grow-0">
  119.                         <a href="{{ path('app_dash') }}">
  120.                             <img alt="Logo" src="{{ asset(logoLab) }}" class="logo-default h-200px"/>
  121.                             <img alt="Logo" src="{{ asset(logoLab) }}" class="logo-sticky h-200px"/>
  122.                         </a>
  123.                     </div>
  124.                     <div class="d-flex align-items-stretch justify-content-between flex-lg-grow-1">
  125.                         <!--begin::Navbar-->
  126.                         <div class="d-flex align-items-stretch mx-auto" id="kt_header_nav">
  127.                             <div class="header-menu align-items-stretch" data-kt-drawer="true"
  128.                                  data-kt-drawer-name="header-menu" data-kt-drawer-activate="{default: true, lg: false}"
  129.                                  data-kt-drawer-overlay="true"
  130.                                  data-kt-drawer-width="{default:'200px', '300px': '250px'}"
  131.                                  data-kt-drawer-direction="start" data-kt-drawer-toggle="#kt_header_menu_mobile_toggle"
  132.                                  data-kt-swapper="true" data-kt-swapper-mode="prepend"
  133.                                  data-kt-swapper-parent="{default: '#kt_body', lg: '#kt_header_nav'}">
  134.                                 <!--begin::Menu-->
  135.                                 <div class="menu menu-lg-rounded menu-column menu-lg-row menu-state-bg menu-title-gray-700 menu-state-icon-primary menu-state-bullet-primary menu-arrow-gray-400 fw-bold my-5 my-lg-0 align-items-stretch"
  136.                                      id="#kt_header_menu" data-kt-menu="true">
  137.                                     <div data-kt-menu-trigger="click" data-kt-menu-placement="bottom-start"
  138.                                          class="menu-item here show menu-lg-down-accordion me-lg-1">
  139.                                         {% if is_granted('ROLE_SUPER_ADMIN') or is_granted('ROLE_ADMIN') %}
  140.                                             <div class="menu-item menu-here-bg menu-lg-down me-0 me-lg-2 ">
  141.                                                 <!--begin:Menu link-->
  142.                                                 <a class="btn btn-outline-light {{ startActive|default('') }} py-3 text-black menuHead"
  143.                                                    href="{{ path('app_start') }}">Inicio
  144.                                                 </a>
  145.                                             </div>
  146.                                             <div class="menu-item menu-here-bg menu-lg-down me-0 me-lg-2 ">
  147.                                                 <!--begin:Menu link-->
  148.                                                 <a class="btn btn-outline-light {{ ventaActive|default('') }} py-3 text-black menuHead"
  149.                                                    href="{{ path('app_sales') }}"> Ventas
  150.                                                 </a>
  151.                                             </div>
  152.                                             <div class="menu-item menu-here-bg menu-lg-down me-0 me-lg-2 ">
  153.                                                 <!--begin:Menu link-->
  154.                                                 <a class="btn btn-outline-light {{ compraActive|default('') }} py-3 text-black menuHead"
  155.                                                    href="{{ path('app_purchases') }}"> Compras
  156.                                                 </a>
  157.                                             </div>
  158.                                             <div class="menu-item menu-here-bg menu-lg-down me-0 me-lg-2 ">
  159.                                                 <!--begin:Menu link-->
  160.                                                 <a class="btn btn-outline-light {{ ordenesActive|default('') }} py-3 text-black menuHead"
  161.                                                    href="{{ path('app_orders') }}"> Ordenes
  162.                                                 </a>
  163.                                             </div>
  164.     
  165.                                         {% endif %}
  166.                                         {% if is_granted('ROLE_SUPER_ADMIN') or is_granted('ROLE_ADMIN') or is_granted('ROLE_SALESMAN') %}
  167.                                             <div class="menu-item menu-here-bg menu-lg-down me-0 me-lg-2 ">
  168.                                                 <!--begin:Menu link-->
  169.                                                 <a class="btn btn-outline-light {{ comicionActive|default('') }} py-3 text-black menuHead"
  170.                                                    href="{{ path('app_commissions') }}">Comisiones
  171.                                                 </a>
  172.                                             </div>
  173.                                             <div class="menu-item menu-here-bg menu-lg-down me-0 me-lg-2 ">
  174.                                                 <!--begin:Menu link-->
  175.                                                 <a class="btn btn-outline-light {{ reportingActive|default('') }} py-3 text-black menuHead"
  176.                                                    href="{{ path('app_reporting') }}">Reportes
  177.                                                 </a>
  178.                                             </div>
  179.                                         {% endif %}
  180.                                         {% if is_granted('ROLE_ADMIN') %}
  181.                                             <div class="menu-item menu-here-bg menu-lg-down me-0  dropdown">
  182.                                                 <a class="btn btn-outline-light menuHead py-3 text-black dropdown-toggle"
  183.                                                    href="#" role="button" id="generalMenuDropdownTwo"
  184.                                                    data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
  185.                                                 >Administración</a>
  186.                                                 <div class="dropdown-menu" aria-labelledby="generalMenuDropdownTwo"
  187.                                                      style="max-height: 30vh; overflow-y: auto;">
  188.                                                     <a class="btn btn-outline-light py-3 menuList {{ UserActive|default('') }}"
  189.                                                        href="{{ path('app_user') }}">{{ 'Users'|trans }}</a>
  190.                                                     <a class="btn btn-outline-light py-3 menuList {{ SalesmanActive|default('') }}"
  191.                                                        href="{{ path('app_salesman_index') }}">{{ 'Salesman'|trans }}</a>
  192.                                                     <a class="btn btn-outline-light py-3 menuList {{ OrganizationActive|default('') }}"
  193.                                                        href="{{ path('app_organization_index') }}">{{ 'Organization'|trans }}</a>
  194.                                                     <a class="btn btn-outline-light py-3 menuList {{ CategoryActive|default('') }}"
  195.                                                        href="{{ path('app_category_index') }}">{{ 'Categories'|trans }}</a>
  196.                                                     <a class="btn btn-outline-light py-3 menuList {{ ProductActive|default('') }}"
  197.                                                        href="{{ path('app_product_index') }}">{{ 'Products'|trans }}</a>
  198.                                                     <a class="btn btn-outline-light py-3 menuList {{ PaymentActive|default('') }}"
  199.                                                        href="{{ path('app_payment_index') }}">{{ 'Payment'|trans }}
  200.                                                         Facturas de Ventas</a>
  201.                                                     <a class="btn btn-outline-light py-3 menuList {{ CommissionSettingActive|default('') }}"
  202.                                                        href="{{ path('app_commission_setting_index') }}">{{ 'Commission Setting'|trans }}</a>
  203.                                                 </div>
  204.                                             </div>
  205.                                         {% endif %}
  206.                                         {% if is_granted('ROLE_SUPER_ADMIN') %}
  207.                                             <div class="menu-item menu-here-bg menu-lg-down me-0 me-lg-2 ">
  208.                                                 <a href="#"
  209.                                                    class="btn btn-outline-light email-dropdown-toggle  py-3 text-black menuHead">
  210.                                                     Menu <span class="caret">&#9662;</span> </a>
  211.                                                 <div class="email-dropdown-menu">
  212.                                                     <div class="menu-item menu-here-bg menu-lg-down me-0  dropdown">
  213.                                                         <a class="btn btn-outline-light menuHead py-3 text-black dropdown-toggle"
  214.                                                            href="#" role="button" id="generalMenuDropdown"
  215.                                                            data-bs-toggle="dropdown" aria-haspopup="true"
  216.                                                            aria-expanded="false"
  217.                                                         >Administración General</a>
  218.                                                         <div class="dropdown-menu" aria-labelledby="generalMenuDropdown"
  219.                                                              style="max-height: 30vh; overflow-y: auto;">
  220.                                                             <a class="btn btn-outline-light py-3 menuList {{ UserActive|default('') }}"
  221.                                                                href="{{ path('app_user') }}">{{ 'Users'|trans }}</a>
  222.                                                             <a class="btn btn-outline-light py-3 menuList {{ RoleActive|default('') }}"
  223.                                                                href="{{ path('app_role_index') }}">Roles</a>
  224.                                                             <a class="btn btn-outline-light py-3 menuList {{ CategoryActive|default('') }}"
  225.                                                                href="{{ path('app_category_index') }}">{{ 'Categories'|trans }}</a>
  226.                                                             <a class="btn btn-outline-light py-3 menuList {{ ProductActive|default('') }}"
  227.                                                                href="{{ path('app_product_index') }}">{{ 'Products'|trans }}</a>
  228.                                                             <a class="btn btn-outline-light py-3 menuList {{ InvoiceActive|default('') }}"
  229.                                                                href="{{ path('app_invoice_index') }}">{{ 'Invoice'|trans }}</a>
  230.                                                             <a class="btn btn-outline-light py-3 menuList {{ OrganizationActive|default('') }}"
  231.                                                                href="{{ path('app_organization_index') }}">{{ 'Organization'|trans }}</a>
  232.                                                             <a class="btn btn-outline-light py-3 menuList {{ PaymentActive|default('') }}"
  233.                                                                href="{{ path('app_payment_index') }}">{{ 'Payment'|trans }}</a>
  234.                                                             <a class="btn btn-outline-light py-3 menuList {{ InvoiceItemActive|default('') }}"
  235.                                                                href="{{ path('app_invoice_item_index') }}">{{ 'Invoice Item'|trans }}</a>
  236.                                                             <a class="btn btn-outline-light py-3 menuList {{ InvoiceStatusActive|default('') }}"
  237.                                                                href="{{ path('app_invoice_status_index') }}">{{ 'Invoice Status'|trans }}</a>
  238.                                                             <a class="btn btn-outline-light py-3 menuList {{ StoreActive|default('') }}"
  239.                                                                href="{{ path('app_store_index') }}">{{ 'Store'|trans }}</a>
  240.                                                             <a class="btn btn-outline-light py-3 menuList {{ AddressActive|default('') }}"
  241.                                                                href="{{ path('app_address_index') }}">{{ 'Address'|trans }}</a>
  242.                                                             <a class="btn btn-outline-light py-3 menuList {{ AddressOrganizationActive|default('') }}"
  243.                                                                href="{{ path('app_address_organization_index') }}">{{ 'AddressOrganization'|trans }}</a>
  244.                                                             <a class="btn btn-outline-light py-3 menuList {{ AddressSalesmanActive|default('') }}"
  245.                                                                href="{{ path('app_address_salesman_index') }}">{{ 'AddressSalesman'|trans }}</a>
  246.                                                             <a class="btn btn-outline-light py-3 menuList {{ QuoteActive|default('') }}"
  247.                                                                href="{{ path('app_quote_index') }}">{{ 'Quote'|trans }}</a>
  248.                                                             <a class="btn btn-outline-light py-3 menuList {{ CommissionSettingActive|default('') }}"
  249.                                                                href="{{ path('app_commission_setting_index') }}">{{ 'Commission Setting'|trans }}</a>
  250.                                                             <a class="btn btn-outline-light py-3 menuList {{ SalesmanCommissionActive|default('') }}"
  251.                                                                href="{{ path('app_salesman_commission_index') }}">{{ 'Commission Salesman'|trans }}</a>
  252.                                                             <a class="btn btn-outline-light py-3 menuList {{ SalesmanActive|default('') }}"
  253.                                                                href="{{ path('app_salesman_index') }}">{{ 'Salesman'|trans }}</a>
  254.                                                             <a class="btn btn-outline-light py-3 menuList {{ PaymentPlanActive|default('') }}"
  255.                                                                href="{{ path('app_payment_plan_index') }}">{{ 'PaymentPlan'|trans }}</a>
  256.                                                             <a class="btn btn-outline-light py-3 menuList {{ PayQuoteActive|default('') }}"
  257.                                                                href="{{ path('app_pay_quote_index') }}">{{ 'PayQuote'|trans }}</a>
  258.                                                             <a class="btn btn-outline-light py-3 menuList {{ StockActive|default('') }}"
  259.                                                                href="{{ path('app_stock_index') }}">{{ 'Stock'|trans }}</a>
  260.                                                             <a class="btn btn-outline-light py-3 menuList {{ PurchaseActive|default('') }}"
  261.                                                                href="{{ path('app_purchase_index') }}">{{ 'Purchase'|trans }}</a>
  262.                                                             <a class="btn btn-outline-light py-3 menuList {{ PurchaseItemActive|default('') }}"
  263.                                                                href="{{ path('app_purchase_item_index') }}">{{ 'Purchase Item'|trans }}</a>
  264.                                                         </div>
  265.                                                     </div>
  266.                                                     <div class="menu-item menu-here-bg menu-lg-down me-0 dropdown">
  267.                                                         <a class="btn btn-outline-light menuHead py-3 text-black dropdown-toggle"
  268.                                                            href="#" role="button" id="typeMenuDropdown"
  269.                                                            data-bs-toggle="dropdown" aria-haspopup="true"
  270.                                                            aria-expanded="false"
  271.                                                         >Administración Tipos</a>
  272.                                                         <div class="dropdown-menu" aria-labelledby="typeMenuDropdown">
  273.                                                             <a class="btn btn-outline-light py-3 menuList {{ StatusTypeActive|default('') }}"
  274.                                                                href="{{ path('app_status_type_index') }}">Estados</a>
  275.                                                             <a class="btn btn-outline-light py-3 menuList {{ ParameterTypeActive|default('') }}"
  276.                                                                href="{{ path('app_parameter_type_index') }}">{{ 'Parameter Type'|trans }}</a>
  277.                                                             <a class="btn btn-outline-light py-3 menuList {{ ParameterActive|default('') }}"
  278.                                                                href="{{ path('app_parameter_index') }}">{{ 'Parameter'|trans }}</a>
  279.                                                             <a class="btn btn-outline-light py-3 menuList {{ PaymentTypeActive|default('') }}"
  280.                                                                href="{{ path('app_payment_type_index') }}">Forma de Pago</a>
  281.                                                             <a class="btn btn-outline-light py-3 menuList {{ CurrencyTypeActive|default('') }}"
  282.                                                                href="{{ path('app_currency_type_index') }}">Tipo
  283.                                                                 Moneda</a>
  284.                                                             <a class="btn btn-outline-light py-3 menuList {{ MethodPayTypeActive|default('') }}"
  285.                                                                href="{{ path('app_method_pay_type_index') }}">{{ 'Method Pay Type'|trans }}</a>
  286.                                                             <a class="btn btn-outline-light py-3 menuList {{ PlanTypeActive|default('') }}"
  287.                                                                href="{{ path('app_plan_type_index') }}">{{ 'Plan Type'|trans }}</a>
  288.                                                             <a class="btn btn-outline-light py-3 menuList {{ OrganizationTypeActive|default('') }}"
  289.                                                                href="{{ path('app_organization_type_index') }}">{{ 'Organization Type'|trans }}</a>
  290.                                                             <a class="btn btn-outline-light py-3 menuList {{ AddressTypeActive|default('') }}"
  291.                                                                href="{{ path('app_address_type_index') }}">{{ 'Address Type'|trans }}</a>
  292.                                                             <a class="btn btn-outline-light py-3 menuList {{ CommissionTypeActive|default('') }}"
  293.                                                                href="{{ path('app_commission_type_index') }}">{{ 'Commission Type'|trans }}</a>
  294.                                                         </div>
  295.                                                     </div>
  296.                                                 </div>
  297.                                             </div>
  298.                                         {% endif %}
  299.                                     </div>
  300.                                 </div>
  301.                                 <!--end::Menu-->
  302.                             </div>
  303.                         </div>
  304.                         <!--begin::Toolbar wrapper-->
  305.                         <div class="topbar d-flex align-items-stretch flex-shrink-0">
  306.                             <!--begin::Search-->
  307.                             <!--end::Theme mode-->
  308.                             <!--begin::User-->
  309.                             <div class="d-flex align-items-center me-n3 ms-1 ms-lg-3" style="padding-left: 10px" id="kt_header_user_menu_toggle">
  310.                                 {% if app.user %}
  311.                                     <!--begin::Menu wrapper-->
  312.                                     <div class="btn btn-icon btn-active-light-primary btn btn-icon btn-active-light-primary btn-custom w-30px h-30px w-md-40px h-md-40px"
  313.                                          style="padding-right: 15px"
  314.                                          data-kt-menu-trigger="click" data-kt-menu-attach="parent"
  315.                                          data-kt-menu-placement="bottom-end">
  316.                                         {% if app.user.avatar == null %}
  317.                                             <img class="h-50px w-50px rounded"
  318.                                                  src="{{ url('profile_avatar', { 'id': app.user.avatar|default('none') } ) }}"
  319.                                                  alt=""/>
  320.                                         {% else %}
  321.                                             <img alt="Logo" class="h-50px w-50px rounded"
  322.                                                  src="data:image/png;base64,{{ app.user.avatar|default('none') }}"/>
  323.                                         {% endif %}
  324.                                     </div>
  325.                                     <!--begin::User account menu-->
  326.                                     <div class="menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-800 menu-state-bg menu-state-primary fw-bold py-4 fs-6 w-275px"
  327.                                          data-kt-menu="true">
  328.                                         <!--begin::Menu item-->
  329.                                         <div class="menu-item px-3">
  330.                                             <div class="menu-content d-flex align-items-center px-3">
  331.                                                 <!--begin::Avatar-->
  332.                                                 <div class="symbol symbol-50px me-5">
  333.                                                     {% if app.user.avatar == null %}
  334.                                                         <img class="h-30px w-30px rounded"
  335.                                                              src="{{ url('profile_avatar', { 'id': app.user.avatar|default('none') } ) }}"
  336.                                                              alt=""/>
  337.                                                     {% else %}
  338.                                                         <img alt="Logo"
  339.                                                              src="data:image/png;base64,{{ app.user.avatar|default('none') }}"/>
  340.                                                     {% endif %}
  341.                                                 </div>
  342.                                                 <!--end::Avatar-->
  343.                                                 <!--begin::Username-->
  344.                                                 <div class="d-flex flex-column">
  345.                                                     <a href="{{ path('profile_user', {'id': app.user.id}) }}"
  346.                                                        class="fw-bold text-muted text-hover-primary fs-7">{{ app.user.email }}</a>
  347.                                                 </div>
  348.                                                 <!--end::Username-->
  349.                                             </div>
  350.                                         </div>
  351.                                         <!--end::Menu item-->
  352.                                         <!--begin::Menu separator-->
  353.                                         <div class="separator my-2"></div>
  354.                                         <!--end::Menu separator-->
  355.                                         <!--begin::Menu item-->
  356.                                         <div class="menu-item px-5">
  357.                                             <a href="{{ path('profile_user', {'id': app.user.id}) }}"
  358.                                                class="menu-link px-5">Mi Perfil</a>
  359.                                         </div>
  360.                                         <div class="separator my-2"></div>
  361.                                     <div class="dark-mode-toggle-container">
  362.                                         <span style="margin-left: 11%">Modo oscuro</span>
  363.                                         <label class="switch">
  364.                                             <input type="checkbox" id="darkModeToggle">
  365.                                             <span class="slider round"></span>
  366.                                         </label>
  367.                                     </div>
  368.                                     <div class="separator my-2"></div>
  369.                                     <div class="menu-item px-5">
  370.                                             <a href="{{ path('app_logout') }}" class="menu-link px-5">Cerrar Sesión</a>
  371.                                         </div>
  372.                                     </div>
  373.                                     <!--end::User account menu-->
  374.                                     <!--end::Menu wrapper-->
  375.                                 {% else %}
  376.                                 {% endif %}
  377.                             </div>
  378.                             <!--end::User -->
  379.                             <!--begin::Aside mobile toggle-->
  380.                             <!--end::Aside mobile toggle-->
  381.                         </div>
  382.                         <!--end::Toolbar wrapper-->
  383.                     </div>
  384.                 </div>
  385.                 <!--end::Container-->
  386.             </div>
  387.             <!--end::Header-->
  388.             <!--begin::Toolbar-->
  389.             {% if showToolbar|default(1) %}
  390.                 <div class="toolbar " id="kt_toolbar">
  391.                     <!--begin::Container-->
  392.                     <div id="kt_toolbar_container" class="container-xxl d-flex flex-stack flex-wrap">
  393.                         <div class="page-title d-flex flex-column me-3" style="z-index: 10">
  394.                             <h1 class="p-3" style="color: #12484a">{% block title %} {% endblock %} </h1>
  395.                             <ul class="breadcrumb breadcrumb-separatorless fw-bold fs-7 my-1">
  396.                                 {% block breadcrumb %}
  397.                                 {% endblock %}
  398.                             </ul>
  399.                         </div>
  400.                         <!--end::Page title-->
  401.                         <!--begin::Actions-->
  402.                         <div class="d-flex align-items-center py-3 py-md-1">
  403.                             {% block breadBottom %}
  404.                             {% endblock %}
  405.                         </div>
  406.                         <!--end::Actions-->
  407.                     </div>
  408.                     <!--end::Container-->
  409.                 </div>
  410.             {% else %}
  411.                 <!--begin::Actions-->
  412.                 <div class="mb-5">
  413.                 </div>
  414.             {% endif %}
  415.             <!--end::Toolbar-->
  416.             <!--begin::Container-->
  417.             <div id="kt_content_container" class="d-flex flex-column-fluid align-items-start container-fluid">
  418.                 <!--begin::Post-->
  419.                 <div class="content flex-row-fluid" id="kt_content">
  420.                     <div class="row">
  421.                         <!--begin::Col-->
  422.                         <div class="col-md-12">
  423.                             <div class="row">
  424.                                 <div class="col-md-12">
  425.                                     {% if app.request.attributes.get('_route') != 'app_start' and app.request.attributes.get('_route') != 'profile_user' and app.request.attributes.get('_route') != 'load_user' %}
  426.                                     <div class="card card-bordered" style="padding: 25px;">
  427.                                         <div class="card-body">
  428.                                             <div class="table-responsive">
  429.                                                 {% endif %}
  430.                                                 {% block body %}
  431.                                                 {% endblock %}
  432.                                                 {% if app.request.attributes.get('_route') != 'app_start' %}
  433.                                             </div>
  434.                                         </div>
  435.                                     </div>
  436.                                     {% endif %}
  437.                                 </div>
  438.                             </div>
  439.                         </div>
  440.                         <!--end::Col-->
  441.                     </div>
  442.                 </div>
  443.                 <!--end::Post-->
  444.             </div>
  445.             <!--end::Container-->
  446.             <!--begin::Footer-->
  447.             <div class="footer py-4 d-flex flex-lg-column" id="kt_footer">
  448.                 <!--begin::Container-->
  449.                 <div class="container-xxl d-flex flex-column flex-md-row align-items-center justify-content-between">
  450.                     <!--begin::Copyright-->
  451.                     <div class="text-dark order-2 order-md-1">
  452.                         <span class="text-muted fw-bold me-1"></span>
  453.                         <a href="https://ianalytics.cl" target="_blank" class=" text-hover-primary"
  454.                            style="color: #12484a">iAnalytics</a>
  455.                     </div>
  456.                 </div>
  457.                 <!--end::Container-->
  458.             </div>
  459.             <!--end::Footer-->
  460.         </div>
  461.         <!--end::Wrapper-->
  462.     </div>
  463.     <!--end::Page-->
  464. </div>
  465. <div class="modal fade payModal" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false"
  466.      tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  467.     <div class="modal-dialog modal-lg">
  468.         <form id="payForm" action="" method="post">
  469.             <div class="modal-content">
  470.                 <div class="modal-header" style="background-color: #107c69;">
  471.                     <h1 class="modal-title fs-5 text-white" id="staticBackdropLabel">Pagar Factura</h1>
  472.                     <button type="button" class="btn-close text-white" data-bs-dismiss="modal"
  473.                             aria-label="Close"></button>
  474.                 </div>
  475.                 <div class="modal-body p2">
  476.                     <div class="container text-center">
  477.                         <div>
  478.                             <label for="customer" class="label-form">Seleccione una Factura:</label>
  479.                             <input class="form-control" type="text" id="customer" name="customer">
  480.                         </div>
  481.                         <div>
  482.                             <label for="product" class="label-form">Tipo de Pago:</label>
  483.                             <input class="form-control" type="text" id="product" name="product">
  484.                         </div>
  485.                         <div>
  486.                             <label for="quantity" class="label-form">Cuotas:</label>
  487.                             <input class="form-control" type="number" id="quantity" name="quantity">
  488.                         </div>
  489.                         <div>
  490.                             <label for="pay" class="label-form">Abonar:</label>
  491.                             <input class="form-control" type="number" id="pay" name="pay">
  492.                         </div>
  493.                         <div>
  494.                             <label for="total" class="label-form">Total:</label>
  495.                             <input class="form-control" type="text" id="total" name="total">
  496.                         </div>
  497.                     </div>
  498.                 </div>
  499.                 <div class="modal-footer">
  500.                     <button type="button" style="background-color: #ce3e61" class="btn text-white"
  501.                             data-bs-dismiss="modal">Cancelar
  502.                     </button>
  503.                     <button type="submit" style="background-color: #107c69" class="btn text-white">Pagar</button>
  504.                 </div>
  505.             </div>
  506.         </form>
  507.     </div>
  508. </div>
  509. <div class="modal fade invoiceModal" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false"
  510.      tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  511.     <div class="modal-dialog modal-lg">
  512.         {% set currentRoute = app.request.attributes.get('_route') %}
  513.         {% set formAction = 'app_invoice_create' %}
  514.         {% if currentRoute == 'app_sales' %}
  515.             {% set formAction = 'app_invoice_create' %}
  516.         {% elseif currentRoute == 'app_purchases' %}
  517.             {% set formAction = 'app_purchase_create' %}
  518.             {% elseif currentRoute == 'app_orders' %}
  519.             {% set formAction = 'app_preinvoice_create' %}
  520.             {% elseif currentRoute == 'app_orders' %}
  521.             {% set formAction = 'edit_preinvoice' %}
  522.         {% endif %}
  523.         <form id="invoiceForm" action="{{ path(formAction) }}" method="POST">
  524.             <div class="modal-content">
  525.                 <div class="modal-header" id="divColor">
  526.                     <h1 class="modal-title fs-5 text-white" id="titleModal"></h1>
  527.                     <button type="button" class="btn-close text-white" data-bs-dismiss="modal"
  528.                             aria-label="Cerrar"></button>
  529.                 </div>
  530.                 <div class="modal-body p2">
  531.                     <div class="container">
  532.                         <div class="row">
  533.                             <div class="col-md-12">
  534.                                 <div class="form-group">
  535.                                     <label for="poNumber">N° Orden de Compra</label>
  536.                                     <input type="text" class="form-control" id="poNumber" name="poNumber" placeholder="Ingrese su numero de orden">
  537.                                 </div>
  538.                             </div>
  539.                         </div>
  540.                         <div class="row">
  541.                             <div class="col-md-6">
  542.                                 <div class="form-group">
  543.                                     <label for="hostNum" class="label-form">N° Factura<i
  544.                                                 style="color:red;">*</i></label>
  545.                                     <input type="number" class="form-control mb-4" id="hostNum" name="hostNum" min="1"
  546.                                            required>
  547.                                 </div>
  548.                             </div>
  549.                             <div class="{% if currentRoute == 'app_orders' %}col-md-12{% else %}col-md-6{% endif %}">
  550.                                 <div class="form-group">
  551.                                     <label for="date" class="label-form">Fecha de Emisión<i
  552.                                                 style="color:red;">*</i></label>
  553.                                     <input type="date" class="form-control mb-4" id="date" name="date" required>
  554.                                 </div>
  555.                             </div>
  556.                         </div>
  557.                         <div class="row">
  558.                             <div class="{% if currentRoute == 'app_purchases'%}col-md-12{% elseif currentRoute == 'app_orders' %}col-md-12 {% else %}col-md-6{% endif %}">
  559.                                 <div class="form-group">
  560.                                     <label for="endDate" class="label-form">Fecha Vencimiento Factura<i
  561.                                                 style="color:red;">*</i></label>
  562.                                     <input type="date" class="form-control mb-4" id="endDate" name="endDate" required>
  563.                                 </div>
  564.                             </div>
  565.                             <div class="col-md-6">
  566.                                 <div class="form-group">
  567.                                     <label for="salesman" class="label-form">Vendedor<i style="color:red;">*</i></label>
  568.                                     <select class="form-control optionSelect" id="salesman" name="salesman"
  569.                                             data-control="select2" required>
  570.                                     </select>
  571.                                 </div>
  572.                             </div>
  573.                         </div>
  574.                         <div class="row">
  575.                             <div class="{% if currentRoute == 'app_purchases' %}col-md-12{% else %}col-md-6{% endif %}">
  576.                                 <div class="form-group">
  577.                                     <label for="organization" class="label-form" id="titleOrganization"></label>
  578.                                     <select class="form-control optionSelect" id="organization" name="organization"
  579.                                             data-control="select2" autocomplete="off" required>
  580.                                     </select>
  581.                                 </div>
  582.                             </div>
  583.                             <div class="col-md-6">
  584.                                 <div class="form-group">
  585.                                     <label for="payMethod" class="label-form">Condición de pago<i style="color:red;">*</i></label>
  586.                                     <select class="form-control optionSelect" id="payMethod" name="payMethod"
  587.                                             data-control="select2" required>
  588.                                     </select>
  589.                                 </div>
  590.                             </div>
  591.                             <div class="col-md-12">
  592.                                 <div class="form-group">
  593.                                     <label for="payType" class="label-form">Forma de pago<i style="color:red;">*</i></label>
  594.                                     <select class="form-control optionSelect" id="payType" name="payType"
  595.                                             data-control="select2" required>
  596.                                     </select>
  597.                                 </div>
  598.                             </div>
  599.                         </div>
  600.                         <div class="form-group{% if currentRoute == 'app_purchases' %}col-md-12{% else %}col-md-6{% endif %}">
  601.                             <label for="planType" class="label-form">Plan de pago</label>
  602.                             <select class="form-control optionSelect" id="planType" name="planType"
  603.                                     data-control="select2" required>
  604.                             </select>
  605.                         </div>
  606.                         <input type="hidden" id="selectedProductsList" name="selectedProductsList">
  607.                         <div class="row">
  608.                             <div class="col-md-12">
  609.                                 <div class="form-group">
  610.                                     <label for="productSearch" class="p-2" style="color: #12484a">Productos:<i
  611.                                                 style="color:red;">*</i></label>
  612.                                     <input type="text" id="productSearch" placeholder="Buscar">
  613.                                     <div id="products" class="mt-4"
  614.                                          style="max-height: 350px !important;overflow-y: scroll;margin-bottom: 2px;">
  615.                                     </div>
  616.                                 </div>
  617.                             </div>
  618.                         </div>
  619.                         <div class="col-md-12">
  620.                             <label for="observation" class="form-label">Observaciones:</label>
  621.                             <textarea class="form-control" name="observation" id="observation" rows="3" placeholder="Ingresar observaciones"></textarea>
  622.                         </div>
  623.                         <input type="hidden" name="preinvoices" id="preinvoicesInput" value="">
  624.                     </div>
  625.                 </div>
  626.                 <div class="modal-footer" style="display: flex; justify-content: space-between; align-items: center;">
  627.                     <div class="form-group">
  628.                         <label for="totalInvoice" class="p-2"
  629.                                style="color: #12484a;font-weight: bolder;font-size: x-large;" id="totalInvoiceTitle">Total:</label>
  630.                         <input hidden="hidden" name="totalInvoice" id="totalInvoice">
  631.                     </div>
  632.                     <div>
  633.                         <button type="button" style="background-color: #ce3e61" class="btn text-white"
  634.                                 data-bs-dismiss="modal">Cancelar
  635.                         </button>
  636.                         <button type="submit" style="background-color: #107c69" class="btn text-white btn-create"
  637.                                 id="createInvoice">Crear
  638.                         </button>
  639.                         
  640.                         <button type="button" style="background-color: #0d6efd" class="btn text-white btn-sm mt-1 btn-saveChanges" id="saveChangesButton" style="display: none;">
  641.                             Guardar Cambios
  642.                         </button>
  643.                     </div>
  644.                 </div>
  645.             </div>
  646.         </form>
  647.     </div>
  648. </div>
  649. <div class="modal fade purchasePrint" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false"
  650.      tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  651.     <div class="modal-dialog modal-lg">
  652.         <div class="modal-content">
  653.             <div class="modal-header" id="divColor">
  654.                 <h1 class="modal-title fs-5 " id="titleModalPrint">Detalle Factura</h1>
  655.                 <button type="button" class="btn-close text-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
  656.             </div>
  657.             <div class="modal-body p2">
  658.                 <div class="container">
  659.                     <div class="form-group">
  660.                         <iframe id="iframe" style="width: 100%; height: 900px; border: none;"></iframe>
  661.                     </div>
  662.                 </div>
  663.             </div>
  664.         </div>
  665.     </div>
  666. </div>
  667. <div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
  668.     <div class="modal-dialog">
  669.         <div class="modal-content">
  670.             <div class="modal-header">
  671.                 <h5 class="modal-title" id="paymentModalLabel">Registrar Pago</h5>
  672.                 <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  673.             </div>
  674.             <div class="modal-body">
  675.                 <form id="paymentForm">
  676.                     <div class="mb-3">
  677.                         <label for="paymentType" class="form-label">Tipo de Pago</label>
  678.                         <select class="form-select" id="paymentType" name="paymentType" required>
  679.                         </select>
  680.                     </div>
  681.                     <input type="hidden" id="invoiceId" name="invoiceId">
  682.                     <button type="submit" class="btn btn-primary">Registrar Pago</button>
  683.                 </form>
  684.             </div>
  685.         </div>
  686.     </div>
  687. </div>
  688. <script src="{{ asset('plugins/global/plugins.bundle.js') }}  "></script>
  689. <script src="{{ asset('js/scripts.bundle.js') }} "></script>
  690. <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
  691. <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
  692. <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
  693. <script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
  694. <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  695. <script>console.log("Ruta actual: {{ currentRoute }}");</script>
  696. {% if is_granted('ROLE_SUPER_ADMIN') %}
  697.     <script>
  698.         
  699.         document.addEventListener('DOMContentLoaded', function () {
  700.             let toggle = document.querySelector('.email-dropdown-toggle');
  701.             let menu = document.querySelector('.email-dropdown-menu');
  702.             let subMenus = document.querySelectorAll('.dropdown-menu');
  703.             toggle.addEventListener('click', function (event) {
  704.                 event.stopPropagation();
  705.                 menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
  706.             });
  707.             subMenus.forEach(function (subMenu) {
  708.                 subMenu.addEventListener('click', function (event) {
  709.                     event.stopPropagation();
  710.                 });
  711.             });
  712.             window.addEventListener('click', function (event) {
  713.                 if (menu.style.display === 'block' && !menu.contains(event.target) && !toggle.contains(event.target)) {
  714.                     menu.style.display = 'none';
  715.                 }
  716.             });
  717.         });
  718.     </script>
  719. {% endif %}
  720. <script>
  721.     function handleAction(url, confirmMessage) {
  722.         Swal.fire({
  723.             title: '¿Estás seguro?',
  724.             text: confirmMessage,
  725.             icon: 'warning',
  726.             showCancelButton: true,
  727.             confirmButtonColor: '#3085d6',
  728.             cancelButtonColor: '#d33',
  729.             confirmButtonText: 'Sí, proceder!',
  730.             cancelButtonText: 'Cancelar'
  731.         }).then((result) => {
  732.             if (result.isConfirmed) {
  733.                 if (url.includes('deactivate')) {
  734.                     $.ajax({
  735.                         url: url,
  736.                         method: 'POST',
  737.                         success: function (response) {
  738.                             if (response.success) {
  739.                                 Swal.fire(
  740.                                     'Eliminado!',
  741.                                     'Factura Eliminada.',
  742.                                     'success'
  743.                                 );
  744.                                 $(`button[data-id="${response.id}"]`).closest('tr').remove();
  745.                             } else {
  746.                                 Swal.fire(
  747.                                     'Error!',
  748.                                     'No se pudo eliminar la factura.',
  749.                                     'error'
  750.                                 );
  751.                             }
  752.                         },
  753.                         error: function () {
  754.                             Swal.fire(
  755.                                 'Error!',
  756.                                 'Ocurrió un error al intentar eliminar la factura.',
  757.                                 'error'
  758.                             );
  759.                         }
  760.                     });
  761.                 } else {
  762.                     window.location.href = url;
  763.                 }
  764.             }
  765.         });
  766.     }
  767.     $(document).on('click', '.printPurchase', function (event) {
  768.         event.preventDefault();
  769.         let orderId = $(this).data('id');
  770.         let urlPrint = "{{ path('view_purchase_detail', { 'id': 'replace_id' }) }}".replace('replace_id', orderId);
  771.         $('#iframe').attr('src', urlPrint);
  772.         $('.purchasePrint').modal('show');
  773.     });
  774.     $(document).on('click', '.printInvoice', function (event) {
  775.         event.preventDefault();
  776.         let orderId = $(this).data('id');
  777.         let urlPrint = "{{ path('view_invoice_detail', { 'id': 'replace_id' }) }}".replace('replace_id', orderId);
  778.         $('#iframe').attr('src', urlPrint);
  779.         $('.purchasePrint').modal('show');
  780.     });
  781.     $(document).on('click', '.printPreinvoice', function (event) {
  782.         event.preventDefault();
  783.         $('#titleModalPrint').text('Detalle Orden de Compra')
  784.         let orderId = $(this).data('id');
  785.         console.log(orderId + 'id recuperado')
  786.         let urlPrint = "{{ path('view_preinvoice_detail', { 'id': 'replace_id' }) }}".replace('replace_id', orderId);
  787.         $('#iframe').attr('src', urlPrint);
  788.         $('.purchasePrint').modal('show');
  789.     });
  790.     $(document).ready(function () {
  791.         $.extend(true, $.fn.dataTable.defaults, {
  792.             language: {
  793.                 url: '//cdn.datatables.net/plug-ins/2.0.8/i18n/es-MX.json'
  794.             }
  795.         });
  796.         $('.btn').each(function () {
  797.             if ($(this).text().trim() === 'Guardar' || $(this).text().trim() === 'Actualizar') {
  798.                 $(this).addClass('btn-sm  btn-success');
  799.                 $(this).css('margin-top', '5px');
  800.             }
  801.             if ($(this).text().trim() === 'Eliminar' || $(this).text().trim() === 'Cancelar') {
  802.                 $(this).addClass('btn-sm btn-danger');
  803.                 $(this).css('margin-top', '5px');
  804.             }
  805.             if ($(this).text().trim() === 'Crear' || $(this).text().trim() === 'Guardar cambios') {
  806.                 $(this).addClass('btn-sm');
  807.                 $(this).css('margin-top', '5px');
  808.             }
  809.         });
  810.         $("a").each(function () {
  811.             if ($(this).text().trim() === 'Volver' || $(this).text().trim() === 'Ver') {
  812.                 $(this).addClass('btn btn-sm btn-secondary');
  813.                 $(this).css('margin-top', '5px');
  814.             }
  815.             if ($(this).text().trim() === 'Editar' || $(this).text().trim() === 'Editar admin') {
  816.                 $(this).addClass('btn btn-sm  btn-primary');
  817.                 $(this).css('margin-top', '5px');
  818.             }
  819.             if ($(this).text().trim() === 'Crear nuevo' || $(this).text().trim() === 'Crear nuevo admin') {
  820.                 $(this).addClass('btn btn-sm text-white');
  821.                 $(this).css('background-color', '#3f4254');
  822.                 $(this).css('margin-top', '5px');
  823.             }
  824.         });
  825.         $('.optionSelect').each(function () {
  826.             $(this).select2({
  827.                 dropdownParent: $('.invoiceModal .modal-body'),
  828.                 width: '100%',
  829.             });
  830.         });
  831.     });
  832.     let ivaParameter;
  833.     let dolarParameter;
  834.     $(document).ready(function () {
  835.         function checkAndUpdateDollarPrice() {
  836.             $.ajax({
  837.                 url: '{{ path('check_dollar_update') }}',
  838.                 type: 'GET',
  839.                 dataType: 'json',
  840.                 success: function (data) {
  841.                     if (data.status === 'updated') {
  842.                         console.log('Precio del dólar actualizado:', data['dollarPrice']);
  843.                         
  844.                         dolarParameter = parseFloat(data['dollarPrice']).toFixed(3);
  845.                         $('#dolar').val('$' + dolarParameter); 
  846.         
  847.                     } else {
  848.                         console.log('No se requiere actualización. Precio actual del dólar:', data['dollarPrice']);
  849.                         
  850.                         dolarParameter = parseFloat(data['dollarPrice']).toFixed(3);
  851.                         $('#dolar').val('$' + dolarParameter); 
  852.                         console.log(dolarParameter);
  853.                     }
  854.                 },
  855.                 error: function (jqXHR, textStatus, errorThrown) {
  856.                     console.error('Error checking dollar price:', textStatus, errorThrown);
  857.                 }
  858.             });
  859.         }
  860.         
  861.         function checkAndUpdateIva() {
  862.             $.ajax({
  863.                 url: '{{ path('check_iva_update') }}',
  864.                 type: 'GET',
  865.                 dataType: 'json',
  866.                 success: function (data) {
  867.                     ivaParameter = data['iva'];
  868.                     console.log('iva', ivaParameter)
  869.                 },
  870.                 error: function (jqXHR, textStatus, errorThrown) {
  871.                     console.error('Error checking iva price:', textStatus, errorThrown);
  872.                 }
  873.             });
  874.         }
  875.         checkAndUpdateDollarPrice();
  876.         checkAndUpdateIva();
  877.     });
  878.     $(document).on("click", ".payBtn", function () {
  879.         $(".payModal").modal('show');
  880.     });
  881.     let typeProduct;
  882.     $(document).on("click", ".invoiceBtn", function () {
  883.         adittionalData(2, false)
  884.         typeProduct = 2;
  885.         $('#titleModal').text('Ventas');
  886.         $('#titleOrganization').html('Cliente asociado<i style="color:red;">*</i>');
  887.         //$('#endDate').closest('.form-group').remove();
  888.         $('#poNumber').closest('.form-group').remove();
  889.         $('#divColor').css('background-color', '#107c69');
  890.         $('.btn-saveChanges').hide();
  891.         $(".invoiceModal").modal('show');
  892.         setTimeout(function () {
  893.             calculateInvoice();
  894.         }, 300);
  895.     });
  896.     $(document).on("click", ".purchaseBtn", function () {
  897.         adittionalData(1, false)
  898.         typeProduct = 1;
  899.         $('#titleModal').text('Compras');
  900.         $('#titleOrganization').html('Proveedor asociado<i style="color:red;">*</i>');
  901.         $('#salesman').closest('.form-group').remove();
  902.         $('#payMethod').closest('.form-group').remove();
  903.         $('#planType').closest('.form-group').remove();
  904.         $('#poNumber').closest('.form-group').remove();
  905.         $('#divColor').css('background-color', '#bd2d50');
  906.         $('.btn-saveChanges').hide();
  907.         $(".invoiceModal").modal('show');
  908.         setTimeout(function () {
  909.             calculateInvoice();
  910.         }, 300);
  911.     });
  912.     $(document).on("click", ".orderBtn", function () {
  913.         adittionalData(1, false)
  914.         typeProduct = 1;
  915.         $('#titleModal').text('Orden de Compra');
  916.         $('#titleOrganization').html('Proveedor asociado<i style="color:red;">*</i>');
  917.         $('#hostNum').closest('.form-group').remove();
  918.         $('#salesman').closest('.form-group').remove();
  919.         $('#payMethod').closest('.form-group').remove();
  920.         $('#divColor').css('background-color', '#bd2d54');
  921.         $('.btn-saveChanges').hide();
  922.         $(".invoiceModal").modal('show');
  923.         setTimeout(function () {
  924.             calculateInvoice();
  925.         }, 300);
  926.     });
  927.     
  928.     $(document).on('change', '.form-check-input.productsOption', function () {
  929.         let index = parseInt($(this).attr('id').split('_')[1]);
  930.         let quantityInput = $(`#quantity_${index}`);
  931.         let priceInput = $(`#price_${index}`);
  932.         if ($(this).is(":checked")) {
  933.             quantityInput.show();
  934.             priceInput.show();
  935.         } else {
  936.             quantityInput.hide();
  937.             priceInput.hide();
  938.         }
  939.         calculateInvoice()
  940.     });
  941.     $(document).on("click", "#statusSwitch", function () {
  942.         let isChecked = $(this).prop('checked');
  943.         if (isChecked) {
  944.             $(this).next('.form-check-label').text('estado: Activo');
  945.             $('#statusSwitch').prop('checked', true);
  946.         } else {
  947.             $(this).next('.form-check-label').text('estado: Inactivo');
  948.             $('#statusSwitch').prop('checked', false);
  949.         }
  950.     });
  951.     $(document).on('input', '.quantity', function () {
  952.         let inputValue = $(this).val().trim();
  953.         let stockavailable = $(this).data('stockavailable');
  954.         if (isNaN(inputValue) || inputValue === "") {
  955.             $(this).val(0);
  956.             inputValue = 0;
  957.         }
  958.         let quantity = parseInt(inputValue);
  959.         if (quantity < 1) {
  960.             quantity = 1;
  961.         } else if (quantity > stockavailable) {
  962.             quantity = stockavailable;
  963.         }
  964.         $(this).val(quantity);
  965.         calculateInvoice();
  966.     });
  967.     document.addEventListener('DOMContentLoaded', function () {
  968.         let numInputs = document.querySelectorAll('.numInputs');
  969.         numInputs.forEach(function (input) {
  970.             input.addEventListener('input', function () {
  971.                 let inputValue = this.value;
  972.                 if (!/^\d*\.?\d*$/.test(inputValue)) {
  973.                     this.value = inputValue.slice(0, -1);
  974.                 }
  975.             });
  976.         });
  977.     });
  978.     {% for flashMessage in app.session.flashbag.get('error') %}
  979.     Swal.fire({
  980.         text: "{{ flashMessage }}",
  981.         icon: "error",
  982.         timer: 2000,
  983.         showConfirmButton: false,
  984.         showCancelButton: false,
  985.     });
  986.     {% endfor %}
  987.     {% for flashMessage in app.session.flashbag.get('success') %}
  988.     Swal.fire({
  989.         text: "{{ flashMessage }}",
  990.         icon: "success",
  991.         timer: 2000,
  992.         showConfirmButton: false,
  993.         showCancelButton: false,
  994.     });
  995.     {% endfor %}
  996.     {% for flashMessage in app.session.flashbag.get('info') %}
  997.     Swal.fire({
  998.         text: "{{ flashMessage }}",
  999.         icon: "info",
  1000.         timer: 2000,
  1001.         showConfirmButton: false,
  1002.         showCancelButton: false,
  1003.     });
  1004.     {% endfor %}
  1005.     toastr.options = {
  1006.         "closeButton": false,
  1007.         "debug": false,
  1008.         "newestOnTop": false,
  1009.         "progressBar": true,
  1010.         "positionClass": "toastr-top-right",
  1011.         "preventDuplicates": false,
  1012.         "onclick": null,
  1013.         "showDuration": "300",
  1014.         "hideDuration": "1000",
  1015.         "timeOut": "5000",
  1016.         "extendedTimeOut": "1000",
  1017.         "showEasing": "swing",
  1018.         "hideEasing": "linear",
  1019.         "showMethod": "fadeIn",
  1020.         "hideMethod": "fadeOut"
  1021.     };
  1022.     {% set excluded_routes = ['app_start', 'app_sales', 'app_purchases', 'app_orders', 'app_commissions'] %}
  1023.     {% if app.request.attributes.get('_route') not in excluded_routes %}
  1024.     $(document).ready(function () {
  1025.         let table = $('.table');
  1026.         if (!table.find('tbody tr').text().includes('No existen registros')) {
  1027.             table.DataTable({
  1028.                 order: [[0, "desc"]],
  1029.                 columnDefs: [
  1030.                     {type: 'num', targets: 0}
  1031.                 ]
  1032.             });
  1033.             table.addClass('table-row-bordered gy-5 stylish-table mb-0 mt-2');
  1034.             $('.table tr').addClass('fw-semibold fs-6 text-center');
  1035.         } else {
  1036.             console.log("La tabla está vacía o contiene el mensaje de que no existen registros");
  1037.         }
  1038.     });
  1039.     {% endif %}
  1040.     function validateForm(currentForm) {
  1041.         if (currentForm.id === 'paymentForm') {
  1042.             return false;
  1043.         }
  1044.         if (currentForm.id === 'organizationForm') {
  1045.             let rut = $('#rutInput').val();
  1046.             let orgType = $('#orgType').val();
  1047.             rut = formatearRUT(rut);
  1048.             let isValidRUT = validateRUT(rut);
  1049.             let isRUTExist = verificarRUTExistente(rut, orgType);
  1050.             if (isValidRUT && isRUTExist) {
  1051.                 Swal.fire({
  1052.                     title: 'Error de Validación',
  1053.                     text: 'El RUT ingresado es inválido o ya existe.',
  1054.                     icon: 'error',
  1055.                     confirmButtonColor: '#3085d6',
  1056.                     confirmButtonText: 'OK'
  1057.                 });
  1058.                 return false;
  1059.             }
  1060.         }
  1061.         if (currentForm.id === 'salesmanForm') {
  1062.             let rut = $('#rutInput').val();
  1063.             rut = formatearRUT(rut);
  1064.             let isValidRUT = validateRUT(rut);
  1065.             let isRUTExist = verificarRUTExistente(rut, '0');
  1066.             if (isValidRUT && isRUTExist) {
  1067.                 Swal.fire({
  1068.                     title: 'Error de Validación',
  1069.                     text: 'El RUT ingresado es inválido o ya existe.',
  1070.                     icon: 'error',
  1071.                     confirmButtonColor: '#3085d6',
  1072.                     confirmButtonText: 'OK'
  1073.                 });
  1074.                 return false;
  1075.             }
  1076.         }
  1077.         if (currentForm.id === 'invoiceForm') {
  1078.             let allFilled = true;
  1079.             let emptyFields = [];
  1080.             let invalidSelects = [];
  1081.             $(currentForm).find('input[required], select[required], textarea[required]').each(function () {
  1082.                 if (!$(this).val().trim() || ($(this).is('select') && ($(this).val() === '0' || $(this).val() === null))) {
  1083.                     allFilled = false;
  1084.                     let label = $('label[for="' + $(this).attr('id') + '"]').text() || $(this).attr('id');
  1085.                     emptyFields.push(label);
  1086.                     if ($(this).is('select')) {
  1087.                         invalidSelects.push(label);
  1088.                     }
  1089.                 }
  1090.             });
  1091.             if (!allFilled) {
  1092.                 let fieldNames = emptyFields.join(', ');
  1093.                 let message = 'Por favor, completa los siguientes campos antes de enviar: ' + fieldNames;
  1094.                 Swal.fire({
  1095.                     title: 'Campos incompletos',
  1096.                     text: message,
  1097.                     icon: 'warning',
  1098.                     confirmButtonColor: '#3085d6',
  1099.                     confirmButtonText: 'OK'
  1100.                 });
  1101.                 return false;
  1102.             }
  1103.             if ($('.productsOption:checked').length === 0) {
  1104.                 Swal.fire({
  1105.                     icon: 'error',
  1106.                     title: 'Error',
  1107.                     text: 'Debe seleccionar al menos un producto.'
  1108.                 });
  1109.                 return false;
  1110.             }
  1111.         }
  1112.         let allFilled = true;
  1113.         let emptyFields = [];
  1114.         $(currentForm).find('input, textarea, select').each(function () {
  1115.             if ($(this).attr('type') !== 'file' && $(this).prop('required') && ($(this).val().trim() === '')) {
  1116.                 allFilled = false;
  1117.                 let id = $(this).attr('id');
  1118.                 let label = $("label[for='" + id + "']").text();
  1119.                 emptyFields.push(label);
  1120.             }
  1121.         });
  1122.         if (!allFilled) {
  1123.             let fieldNames = emptyFields.join(', ');
  1124.             Swal.fire({
  1125.                 title: 'Campos incompletos',
  1126.                 text: 'Por favor, completa los siguientes campos antes de enviar: ' + fieldNames,
  1127.                 icon: 'warning',
  1128.                 confirmButtonColor: '#3085d6',
  1129.                 confirmButtonText: 'OK'
  1130.             });
  1131.             return false;
  1132.         }
  1133.         return true;
  1134.     }
  1135.     $(document).ready(function () {
  1136.         let forms = $('form');
  1137.         if (forms.length > 0) {
  1138.             forms.on('submit', function (e) {
  1139.                 e.preventDefault();
  1140.                 let currentForm = this;
  1141.                 let isSubmitting = $(currentForm).data('isSubmitting');
  1142.                 if (isSubmitting) {
  1143.                     return;
  1144.                 }
  1145.                 if (validateForm(currentForm)) {
  1146.                     Swal.fire({
  1147.                         title: '¿Estás Seguro?',
  1148.                         text: "¡No podrás revertir esta acción!",
  1149.                         icon: 'warning',
  1150.                         showCancelButton: true,
  1151.                         confirmButtonColor: '#3085d6',
  1152.                         cancelButtonColor: '#d33',
  1153.                         confirmButtonText: 'Confirmar',
  1154.                         cancelButtonText: 'Cancelar'
  1155.                     }).then((result) => {
  1156.                         if (result.isConfirmed) {
  1157.                             $(currentForm).data('isSubmitting', true);
  1158.                             currentForm.submit();
  1159.                         }
  1160.                     });
  1161.                 }
  1162.             });
  1163.         }
  1164.     });
  1165.     let selectedProducts = {};
  1166.     let products;
  1167.     let unitActualSale;
  1168.     let cant = false;
  1169.     function adittionalData(type, act) {
  1170.         $.ajax({
  1171.             url: `{{ path('app_additional_data_invoice') }}?type=${type}`,
  1172.             method: 'GET',
  1173.             success: function (response) {
  1174.                 $('#totalInvoiceTitle').text("Total:");
  1175.                 let organizations = response.result.organization;
  1176.                 products = response.result['products'];
  1177.                 let sellers = response.result.salesman;
  1178.                 let planTypes = response.result.planType;
  1179.                 let paymentMethods = response.result['methodPayment'];
  1180.                 let paymentTypes = response.result['payTypes'];
  1181.                 let selectPlanType = $('#planType');
  1182.                 let selectSalesman = $('#salesman');
  1183.                 let selectOrganization = $('#organization');
  1184.                 let selectPayMethod = $('#payMethod');
  1185.                 let selectPayType = $('#payType');
  1186.                 $("#products").empty();
  1187.                 if (!act) {
  1188.                     selectOrganization.empty();
  1189.                     selectSalesman.empty();
  1190.                     selectPayMethod.empty();
  1191.                     selectPlanType.empty();
  1192.                     selectPayType.empty();
  1193.                     selectOrganization.html("<option value='0'>No Especifíca</option>");
  1194.                     selectSalesman.html("<option value='0'>No Especifíca</option>");
  1195.                     selectPayMethod.html("<option value='0'>No Especifíca</option>");
  1196.                     selectPlanType.html("<option value='null'>No Especifíca</option>");
  1197.                     $.each(organizations, function (i, organization) {
  1198.                         let option = $("<option></option>");
  1199.                         option.attr('value', organization.id);
  1200.                         option.attr('data-agent_legal_name', organization['agent_legal_name']);
  1201.                         option.attr('data-organization_type', organization.name);
  1202.                         option.text(organization['business_name']);
  1203.                         $("#organization").append(option);
  1204.                     });
  1205.                     $.each(sellers, function (i, salesman) {
  1206.                         let option = $("<option></option>");
  1207.                         option.attr('value', salesman.id);
  1208.                         option.attr('data-salesman_dni', salesman['salesman_dni']);
  1209.                         option.text(salesman['salesman_name']);
  1210.                         $("#salesman").append(option);
  1211.                     });
  1212.                     $.each(planTypes, function (i, planType) {
  1213.                         let option = $("<option></option>");
  1214.                         option.attr('value', planType.id);
  1215.                         option.text(planType.name + " - Cuotas: " + planType['quote_num']);
  1216.                         $("#planType").append(option);
  1217.                     });
  1218.                     $.each(paymentMethods, function (i, paymentMethod) {
  1219.                         let option = $("<option></option>");
  1220.                         option.attr('value', paymentMethod.id);
  1221.                         option.text(paymentMethod.name);
  1222.                         $("#payMethod").append(option);
  1223.                     });
  1224.                     $.each(paymentTypes, function (i, paymentType) {
  1225.                         let option = $("<option></option>");
  1226.                         option.attr('value', paymentType.id);
  1227.                         option.text(paymentType.name);
  1228.                         $("#payType").append(option);
  1229.                     });
  1230.                 }
  1231.                 renderProducts(products, type);
  1232.                 $('#productSearch').on('input', function () {
  1233.                     let searchTerm = $(this).val().toLowerCase();
  1234.                     let filteredProducts = products.filter(product => {
  1235.                         let productName = product['product_name'];
  1236.                         return productName && productName.toLowerCase().includes(searchTerm);
  1237.                     });
  1238.                     renderProducts(filteredProducts, type);
  1239.                 });
  1240.             }
  1241.         });
  1242.     }
  1243.     function renderProducts(productsList, type) {
  1244.         $('#products').empty();
  1245.         $.each(productsList, function (i, product) {
  1246.             if(!product['quantity_available'] || product['quantity_available'] <= 0){
  1247.                 return
  1248.             }
  1249.             let divCheck = $(`<div class="form-check mb-2 mt-4"></div>`);
  1250.             let productId = product.id;
  1251.             let checkbox = $(`<input class="form-check-input productsOption" type="checkbox" id="product_${productId}" name="products[${i}][id]" value="${product.id}">`);
  1252.             let productName = $(`<span id="product_name_${productId}" title="">${product['product_name']} - Stock Disponible: ${product['quantity_available']}</span>`);
  1253.             let inputContainer = $('<div class="input-container" style="margin-top: 10px;width: 650px;"></div>');
  1254.             let quantityInput = $(`<div class="col-6" id="divQuantity_${productId}" style="display:none;">Cantidad: <input type="number" class="form-control mb-2 quantity" id="quantity_${productId}" name="products[${i}][quantity]" value="1" placeholder="Cantidad"></div>`);
  1255.             let dolarInput = $(`<div class="col-6" id="divDolar_${productId}" style="display:none;">Dolar Producto: <input type="text" id="dolar_${productId}" name="products[${i}][dolar]" value="$${dolarParameter}" placeholder="Dolar"></div>`);
  1256.             
  1257.             let priceInput = $(`<div class="col-3" id="divPrice_${productId}"  style="display:none;">Precio Distribuidor: <input type="text" id="price_${productId}" name="products[${i}][price]" ></div>`);
  1258.             priceInput.find('input').val(product['unit_price_amount']);
  1259.             
  1260.             let ivaUni = $(`<div class="col-3" id="divIva_${productId}"  style="display:none;">Monto IVA: <input type="text" class="form-control mb-2" id="supplier_unit_amount_${productId}" name="products[${i}][supplier_unit_amount]" readonly></div>`);
  1261.             let netoUni = $(`<div class="col-3" id="divNeto_${productId}"  style="display:none;">Valor Neto: <input type="text" class="form-control mb-2" id="item_amount_${productId}" name="products[${i}][item_amount]" readonly></div>`);
  1262.             let brutoUni = $(`<div class="col-3" id="divBruto_${productId}"  style="display:none;">Total: <input type="text" class="form-control mb-2" id="supplier_tax_amount_${productId}" name="products[${i}][supplier_tax_amount]" readonly></div>`);
  1263.             let priceInputTwo = $(`<div class="col-3" style="display:none;">Valor Unitario: <input type="text" id="priceSale_${productId}" name="products[${i}][priceSale]" ></div>`);
  1264.             priceInputTwo.find('input').val(product['sale_price_amount']);
  1265.             let iva = $('<div class="col-3" style="display:none;">Monto IVA : <input type="text" class="form-control mb-2" id="tax_amount_' + productId + '" name="products[' + i + '][tax_amount]" readonly></div>');
  1266.             let neto = $('<div class="col-3" style="display:none;">Valor Neto : <input type="text" class="form-control mb-2" id="net_amount_' + productId + '" name="products[' + i + '][net_amount]" readonly></div>');
  1267.             let totalP = $('<div class="col-3" style="display:none;">Total : <input type="text" class="form-control mb-2" id="gross_margin_pct_' + productId + '" name="products[' + i + '][gross_margin_pct]" readonly></div>');
  1268.             if (type === 2) {
  1269.                 inputContainer.append($('<div class="row" style="display: flex;justify-content: space-between;">').append(quantityInput).append(dolarInput).append(priceInputTwo).append(neto).append(iva).append(totalP));
  1270.             } else {
  1271.                 inputContainer.append($('<div class="row" style="display: flex;justify-content: space-between;">').append(quantityInput).append(dolarInput).append(quantityInput).append(dolarInput).append(priceInput).append(netoUni).append(ivaUni).append(brutoUni));
  1272.             }
  1273.             
  1274.             divCheck.append(checkbox);
  1275.             divCheck.append(productName);
  1276.             divCheck.append(inputContainer);
  1277.             let saleUnitInput = $('<input type="hidden" id="sale_unit_' + productId + '" name="products[' + i + '][sale_unit]" value="' + product['currency_type_sale'] + '">');
  1278.             let purchaseUnitInput = $('<input type="hidden" id="purchase_unit_' + productId + '" name="products[' + i + '][purchase_unit]" value="' + product['currency_type_unit'] + '">');
  1279.             divCheck.append(saleUnitInput, purchaseUnitInput);
  1280.             console.log('restore1')
  1281.             if (selectedProducts[productId]) {
  1282.                 var currentRoute = '{{ app.request.attributes.get('_route') }}';
  1283.                 checkbox.prop('checked', true);
  1284.                 quantityInput.show().find('input').val(selectedProducts[productId].quantity);
  1285.                 dolarInput.show().find('input').val('$' + selectedProducts[productId].dolarInput);
  1286.                 if (currentRoute === 'app_sales') {
  1287.                     if (selectedProducts[productId].currency_type_sale_actual === '1') {
  1288.                         console.log('usdVneta')
  1289.                         let formatPriceSale = selectedProducts[productId].priceSale.replace(',', '.');
  1290.                         priceInputTwo.show().find('input').val(formatCurrency(Math.round(formatPriceSale * selectedProducts[productId].dolarInput)));
  1291.                     } else if (selectedProducts[productId].currency_type_sale_actual === '2') {
  1292.                         console.log('clpVenta')
  1293.                         console.log(selectedProducts[productId]['priceSale'])
  1294.                         priceInputTwo.show().find('input').val(formatCurrency(selectedProducts[productId]['priceSale']));
  1295.                     }
  1296.                     totalP.show().find('input').val(formatCurrency(selectedProducts[productId]['grossMarginPct']));
  1297.                     iva.show().find('input').val(formatCurrency(selectedProducts[productId]['taxAmount']));
  1298.                     neto.show().find('input').val(formatCurrency(selectedProducts[productId]['netAmount']));
  1299.                 } else {
  1300.                     if (selectedProducts[productId].currency_type_unit_actual === '1') {
  1301.                         console.log('usdCopra')
  1302.                         let formatPrice =selectedProducts[productId].price.replace(',', '.');
  1303.                         priceInput.show().find('input').val(formatCurrency(Math.round(formatPrice * selectedProducts[productId].dolarInput)));
  1304.                     } else if (selectedProducts[productId].currency_type_unit_actual === '2') {
  1305.                         console.log('clpCopra')
  1306.                         priceInput.show().find('input').val(formatCurrency(selectedProducts[productId].price));
  1307.                     }
  1308.                     netoUni.show().find('input').val(formatCurrency(selectedProducts[productId]['item_amount']));
  1309.                     ivaUni.show().find('input').val(formatCurrency(selectedProducts[productId]['supplier_unit_amount']));
  1310.                     brutoUni.show().find('input').val(formatCurrency(selectedProducts[productId]['supplier_tax_amount']));
  1311.                 }
  1312.             }
  1313.             dolarInput.find('input').on('input', function () {
  1314.                 let valor = $(this).val().replace(/,/g, '.');
  1315.                 valor = valor.replace(/[^0-9.]/g, '');
  1316.                 if (valor.length > 9) {
  1317.                     valor = valor.substring(0, 9);
  1318.                 }
  1319.                 let parts = valor.split('.');
  1320.                 if (parts.length > 2) {
  1321.                     valor = parts[0] + '.' + parts.slice(1).join('');
  1322.                 }
  1323.                 if (parts.length > 1 && parts[1].length > 3) {
  1324.                     parts[1] = parts[1].substring(0, 3);
  1325.                     valor = parts.join('.');
  1326.                 }
  1327.                 $(this).val('$'+valor);
  1328.                 updateProductPrices(productId);
  1329.             });
  1330.             quantityInput.find('input').on('input', function () {
  1331.                 let valor = $(this).val();
  1332.                 if (valor.length > 6) {
  1333.                     valor = valor.substring(0, 6);
  1334.                     $(this).val(valor);
  1335.                     return false;
  1336.                 }
  1337.                 if (valor === '' || valor === 'Na' || valor <= 0) {
  1338.                     $(this).val(1);
  1339.                     return false;
  1340.                 }
  1341.                 updateProductPrices(productId);
  1342.             });
  1343.             priceInput.find('input').on('input', function () {
  1344.                 let valor = $(this).val();
  1345.                 valor = valor.replace(/[^0-9,]/g, '');
  1346.                 let parts = valor.split(',');
  1347.                 if (parts.length > 2) {
  1348.                     valor = parts[0] + ',' + parts.slice(1).join('');
  1349.                 }
  1350.                 if (parts.length > 1 && parts[1].length > 3) {
  1351.                     parts[1] = parts[1].substring(0, 3);
  1352.                     valor = parts.join('.');
  1353.                 }
  1354.                 let integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.');
  1355.                 if (parts.length > 1) {
  1356.                     valor = integerPart + ',' + parts[1];
  1357.                 } else {
  1358.                     valor = integerPart;
  1359.                 }
  1360.                 if (valor.length > 15) {
  1361.                     valor = valor.substring(0, 15);
  1362.                     $(this).val(valor);
  1363.                     return false;
  1364.                 }
  1365.                 $(this).val(valor);
  1366.             });
  1367.             priceInput.find('input').on('change', function () {
  1368.                 let newPrice = priceInput.find('input').val();
  1369.                 if (newPrice === '') {
  1370.                     updateProductPrices(productId);
  1371.                     Swal.fire('Cancelado!', 'No se han realizado cambios y el precio original ha sido restaurado.', 'info');
  1372.                     return;
  1373.                 }
  1374.                 Swal.fire({
  1375.                     title: 'Actualizar Precio',
  1376.                     text: '¿Quieres actualizar el precio globalmente, temporalmente o cancelar la actualización?',
  1377.                     icon: 'warning',
  1378.                     showCancelButton: true,
  1379.                     showDenyButton: true,
  1380.                     confirmButtonText: 'Globalmente',
  1381.                     denyButtonText: 'Temporalmente',
  1382.                     cancelButtonText: 'Cancelar',
  1383.                     reverseButtons: true
  1384.                 }).then((result) => {
  1385.                     if (result.isConfirmed || result.isDenied) {
  1386.                         let isGlobal = result.isConfirmed;
  1387.                         Swal.fire({
  1388.                             title: 'Seleccionar Unidad',
  1389.                             text: 'Selecciona el tipo de unidad:',
  1390.                             icon: 'question',
  1391.                             showCancelButton: true,
  1392.                             confirmButtonText: 'USD',
  1393.                             cancelButtonText: 'CLP',
  1394.                             reverseButtons: true
  1395.                         }).then((unitResult) => {
  1396.                             let unit = unitResult.isConfirmed ? '1' : '2'; // USD = 1, CLP = 2
  1397.                             if (unit === '2') {
  1398.                                 newPrice = parseCurrency(newPrice);
  1399.                             } else {
  1400.                                 newPrice = newPrice.replace('.', '');
  1401.                             }
  1402.                             selectedProducts[productId].currency_type_unit_actual = unit;
  1403.                             selectedProducts[productId].price = newPrice;
  1404.                             if (isGlobal) {
  1405.                                 selectedProducts[productId].priceOrg = newPrice;
  1406.                                 updateGlobalPrice(productId, newPrice, 1, unit);
  1407.                                 updateProductPrices(productId);
  1408.                                 Swal.fire('Actualizado!', 'El precio se actualizará globalmente.', 'success');
  1409.                             } else {
  1410.                                 updateProductPrices(productId);
  1411.                                 Swal.fire('Temporal', 'El precio se actualizará solo temporalmente.', 'info');
  1412.                             }
  1413.                         });
  1414.                     } else if (result.dismiss === Swal.DismissReason.cancel) {
  1415.                         updateProductPrices(productId);
  1416.                         Swal.fire('Cancelado!', 'No se han realizado cambios y el precio original ha sido restaurado.', 'info');
  1417.                     }
  1418.                 });
  1419.             });
  1420.             priceInputTwo.find('input').on('input', function () {
  1421.                 let valor = $(this).val();
  1422.                 // Eliminar caracteres no permitidos, permitiendo números y comas
  1423.                 valor = valor.replace(/[^0-9,]/g, '');
  1424.                 // Permitir solo una coma
  1425.                 let parts = valor.split(',');
  1426.                 if (parts.length > 2) {
  1427.                     valor = parts[0] + ',' + parts.slice(1).join('');
  1428.                 }
  1429.                 if (parts.length > 1 && parts[1].length > 2) {
  1430.                     parts[1] = parts[1].substring(0, 2);
  1431.                     valor = parts.join('.');
  1432.                 }
  1433.                 // Formatear la parte entera con puntos como separadores de miles
  1434.                 let integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.');
  1435.                 if (parts.length > 1) {
  1436.                     valor = integerPart + ',' + parts[1];
  1437.                 } else {
  1438.                     valor = integerPart;
  1439.                 }
  1440.                 if (valor.length > 15) {
  1441.                     valor = valor.substring(0, 15);
  1442.                     $(this).val(valor);
  1443.                     return false;
  1444.                 }
  1445.                 $(this).val(valor);
  1446.                 console.log(valor);
  1447.             });
  1448.             priceInputTwo.find('input').on('change', function () {
  1449.                 let newPrice = priceInputTwo.find('input').val();
  1450.                 if (newPrice === '') {
  1451.                     updateProductPrices(productId);
  1452.                     Swal.fire('Cancelado!', 'No se han realizado cambios y el precio original ha sido restaurado.', 'info');
  1453.                     return;
  1454.                 }
  1455.                 Swal.fire({
  1456.                     title: 'Actualizar Precio',
  1457.                     text: '¿Quieres actualizar el precio globalmente, temporalmente o cancelar la actualización?',
  1458.                     icon: 'warning',
  1459.                     showCancelButton: true,
  1460.                     showDenyButton: true,
  1461.                     confirmButtonText: 'Globalmente',
  1462.                     denyButtonText: 'Temporalmente',
  1463.                     cancelButtonText: 'Cancelar',
  1464.                     reverseButtons: true
  1465.                 }).then((result) => {
  1466.                     if (result.isConfirmed || result.isDenied) {
  1467.                         let isGlobal = result.isConfirmed;
  1468.                         Swal.fire({
  1469.                             title: 'Seleccionar Unidad',
  1470.                             text: 'Selecciona el tipo de unidad:',
  1471.                             icon: 'question',
  1472.                             showCancelButton: true,
  1473.                             confirmButtonText: 'USD',
  1474.                             cancelButtonText: 'CLP',
  1475.                             reverseButtons: true
  1476.                         }).then((unitResult) => {
  1477.                             let unit = unitResult.isConfirmed ? '1' : '2'; // USD = 1, CLP = 2
  1478.                             if (unit === '2') {
  1479.                                 newPrice = parseCurrency(newPrice);
  1480.                             } else {
  1481.                                 newPrice = newPrice.replace('.', '');
  1482.                             }
  1483.                             selectedProducts[productId].currency_type_sale_actual = unit;
  1484.                             selectedProducts[productId].priceSale = newPrice;
  1485.                             if (isGlobal) {
  1486.                                 selectedProducts[productId].priceOrg = newPrice;
  1487.                                 updateGlobalPrice(productId, newPrice, 2, unit);
  1488.                                 updateProductPrices(productId);
  1489.                                 Swal.fire('Actualizado!', 'El precio se actualizará globalmente.', 'success');
  1490.                             } else {
  1491.                                 updateProductPrices(productId);
  1492.                                 Swal.fire('Temporal', 'El precio se actualizará solo temporalmente.', 'info');
  1493.                             }
  1494.                         });
  1495.                     } else if (result.dismiss === Swal.DismissReason.cancel)  {
  1496.                         updateProductPrices(productId);
  1497.                         Swal.fire('Cancelado!', 'No se han realizado cambios y el precio original ha sido restaurado.', 'info');
  1498.                     }
  1499.                 });
  1500.             });
  1501.             checkbox.on('change', function () {
  1502.                 if ($(this).is(':checked')) {
  1503.                     quantityInput.show();
  1504.                     priceInput.show();
  1505.                     priceInputTwo.show();
  1506.                     totalP.show();
  1507.                     iva.show();
  1508.                     neto.show();
  1509.                     brutoUni.show();
  1510.                     ivaUni.show();
  1511.                     netoUni.show();
  1512.                     dolarInput.show();
  1513.                     updateProductPrices(productId);
  1514.                 } else {
  1515.                     quantityInput.hide();
  1516.                     priceInput.hide();
  1517.                     $(`#price_${productId}`).val(selectedProducts[productId].priceOrg);
  1518.                     $(`#purchase_unit_${productId}`).val(selectedProducts[productId].currency_type_unit_actual);
  1519.                     priceInputTwo.hide();
  1520.                     $(`#priceSale_${productId}`).val(selectedProducts[productId].priceOrg);
  1521.                     $(`#sale_unit_${productId}`).val(selectedProducts[productId].currency_type_sale_actual);
  1522.                     totalP.hide();
  1523.                     iva.hide();
  1524.                     neto.hide();
  1525.                     brutoUni.hide();
  1526.                     ivaUni.hide();
  1527.                     dolarInput.hide();
  1528.                     netoUni.hide();
  1529.                     delete selectedProducts[productId];
  1530.                 }
  1531.             });
  1532.             $("#products").append(divCheck);
  1533.         });
  1534.         calculateInvoice();
  1535.     }
  1536.     
  1537.     
  1538.     function updateProductPrices(productId) {
  1539.         var currentRoute = '{{ app.request.attributes.get('_route') }}';
  1540.         let dolarInput = $(`#dolar_${productId}`).val();
  1541.         let quantity = parseInt($(`#quantity_${productId}`).val());
  1542.         dolarInput = dolarInput.replace(/^\$+/g, '');
  1543.         console.log('calculops');
  1544.         console.log(dolarInput);
  1545.         console.log(selectedProducts[productId]);
  1546.         console.log(currentRoute)
  1547.         let priceOriginalInput;
  1548.         let unitAct = 0;
  1549.         let priceAct = 0;
  1550.         if (currentRoute === 'app_purchases') {
  1551.             if (selectedProducts[productId] === undefined) {
  1552.                 unitAct = $(`#purchase_unit_${productId}`).val();
  1553.                 priceAct = $(`#price_${productId}`).val();
  1554.                 priceOriginalInput = priceAct;
  1555.             } else {
  1556.                 console.log(selectedProducts[productId]);
  1557.                 unitAct = selectedProducts[productId].currency_type_unit_actual;
  1558.                 priceAct = selectedProducts[productId].price;
  1559.                 priceOriginalInput = selectedProducts[productId].priceOrg;
  1560.             }
  1561.         
  1562.             console.log(priceAct + ' probando precio');
  1563.         
  1564.             let netAmountUnit = 0;
  1565.             let taxAmountUnit = 0;
  1566.             let totalUnit = 0;
  1567.             let pricePurchase;
  1568.         
  1569.            
  1570.             if (unitAct === '1') {
  1571.                 console.log('usd');
  1572.                 priceAct = parseFloat(priceAct.replace(',', '.'));
  1573.                 console.log(priceAct);
  1574.                 console.log(dolarInput);
  1575.               
  1576.           
  1577.                 pricePurchase = priceAct * dolarInput;
  1578.                 netAmountUnit = pricePurchase * quantity;
  1579.                 taxAmountUnit = netAmountUnit * ivaParameter;
  1580.                 totalUnit = netAmountUnit + taxAmountUnit;
  1581.                 
  1582.                 
  1583.         
  1584.                 console.log(pricePurchase + ' valor en CLP');
  1585.                 console.log(netAmountUnit + ' monto neto');
  1586.                 console.log(taxAmountUnit + ' monto IVA');
  1587.             } else if (unitAct === '2') {
  1588.                 console.log('clp');
  1589.         
  1590.                 
  1591.                 pricePurchase = parseFloat(priceAct);
  1592.                 netAmountUnit = pricePurchase * quantity;
  1593.                 taxAmountUnit = netAmountUnit * ivaParameter;
  1594.                 totalUnit = netAmountUnit + taxAmountUnit;
  1595.                 console.log(taxAmountUnit + 'iva')
  1596.             }
  1597.         
  1598.             $(`#price_${productId}`).val(formatCurrency(Math.round(pricePurchase)));
  1599.             $(`#item_amount_${productId}`).val(formatCurrency(Math.round(netAmountUnit)));
  1600.             $(`#supplier_unit_amount_${productId}`).val(formatCurrency(Math.ceil(taxAmountUnit)));
  1601.             $(`#supplier_tax_amount_${productId}`).val(formatCurrency(Math.round(totalUnit)));
  1602.         
  1603.             console.log('guardando');
  1604.         
  1605.            
  1606.            
  1607.             selectedProducts[productId] = {
  1608.                 quantity: quantity,
  1609.                 price: parseFloat(priceAct),
  1610.                 currency_type_unit_actual: unitAct,
  1611.                 priceOrg: priceOriginalInput,
  1612.                 dolarInput: dolarInput,
  1613.                 supplier_unit_amount: Math.ceil(taxAmountUnit),
  1614.                 item_amount: Math.round(netAmountUnit),
  1615.                 supplier_tax_amount: Math.round(totalUnit)
  1616.             };
  1617.            
  1618.         }
  1619.         
  1620.         if (currentRoute === 'app_sales') {
  1621.             if (selectedProducts[productId] === undefined) {
  1622.                 unitAct = $(`#sale_unit_${productId}`).val();
  1623.                 priceAct = $(`#priceSale_${productId}`).val();
  1624.                 priceOriginalInput = priceAct;
  1625.             } else {
  1626.                 console.log(selectedProducts[productId])
  1627.                 unitAct = selectedProducts[productId].currency_type_sale_actual;
  1628.                 priceAct = selectedProducts[productId].priceSale;
  1629.                 priceOriginalInput = selectedProducts[productId].priceOrg;
  1630.             }
  1631.             console.log(priceAct);
  1632.             console.log(unitAct);
  1633.             let netAmountUnit = 0;
  1634.             let taxAmountUnit = 0;
  1635.             let totalUnit = 0;
  1636.             let pricePurchase;
  1637.             if (unitAct === '1') {
  1638.                 console.log('usd')
  1639.                 pricePurchase = priceAct.replace(',','.') * dolarInput;
  1640.                 netAmountUnit = pricePurchase * quantity;
  1641.                 taxAmountUnit = netAmountUnit * ivaParameter;
  1642.                 totalUnit = netAmountUnit + taxAmountUnit;
  1643.             } else if (unitAct === '2') {
  1644.                 console.log('clp')
  1645.                 pricePurchase = priceAct;
  1646.                 netAmountUnit = pricePurchase * quantity;
  1647.                 taxAmountUnit = netAmountUnit * ivaParameter;
  1648.                 totalUnit = netAmountUnit + taxAmountUnit;
  1649.             }
  1650.                 $(`#price_${productId}`).val(formatCurrency(Math.round(pricePurchase)));
  1651.                 $(`#gross_margin_pct_${productId}`).val(formatCurrency(Math.round(totalUnit)));
  1652.                 $(`#tax_amount_${productId}`).val(formatCurrency(Math.trunc(taxAmountUnit)));
  1653.                 $(`#net_amount_${productId}`).val(formatCurrency(Math.round(netAmountUnit)));
  1654.                 console.log(taxAmountUnit)
  1655.             console.log('guardando')
  1656.             selectedProducts[productId] = {
  1657.                 quantity: quantity,
  1658.                 currency_type_sale_actual: unitAct,
  1659.                 priceOrg: priceOriginalInput,
  1660.                 priceSale: priceAct,
  1661.                 taxAmount: Math.trunc(taxAmountUnit),
  1662.                 netAmount: Math.round(netAmountUnit),
  1663.                 dolarInput: dolarInput,
  1664.                 grossMarginPct: Math.round(totalUnit),
  1665.             };
  1666.         }
  1667.         if (currentRoute === 'app_orders') {
  1668.             if (selectedProducts[productId] === undefined) {
  1669.                 unitAct = $(`#purchase_unit_${productId}`).val();
  1670.                 priceAct = $(`#price_${productId}`).val();
  1671.                 priceOriginalInput = priceAct;
  1672.             } else {
  1673.                 console.log(selectedProducts[productId])
  1674.                 unitAct = selectedProducts[productId].currency_type_unit_actual;
  1675.                 priceAct = selectedProducts[productId].price;
  1676.                 priceOriginalInput = selectedProducts[productId].priceOrg;
  1677.             }
  1678.             console.log(priceAct,  'precio magico');
  1679.             console.log(unitAct);
  1680.             let netAmountUnit = 0;
  1681.             let taxAmountUnit = 0;
  1682.             let totalUnit = 0;
  1683.             let pricePurchase;
  1684.             if (unitAct === '1') {
  1685.                 console.log('usd')
  1686.                 pricePurchase = priceAct.replace(',','.') * dolarInput;
  1687.                 netAmountUnit = pricePurchase * quantity;
  1688.                 taxAmountUnit = netAmountUnit * ivaParameter;
  1689.                 totalUnit = netAmountUnit + taxAmountUnit;
  1690.             } else if (unitAct === '2') {
  1691.                 console.log('clp')
  1692.                 pricePurchase = priceAct;
  1693.                 netAmountUnit = pricePurchase * quantity;
  1694.                 taxAmountUnit = netAmountUnit * ivaParameter;
  1695.                 totalUnit = netAmountUnit + taxAmountUnit;
  1696.             }
  1697.             $(`#price_${productId}`).val((parseFloat(pricePurchase).toFixed(3)));
  1698.             $(`#item_amount_${productId}`).val(formatCurrency(Math.round(netAmountUnit)));
  1699.             $(`#supplier_unit_amount_${productId}`).val(formatCurrency(Math.ceil(taxAmountUnit)));
  1700.             $(`#supplier_tax_amount_${productId}`).val(formatCurrency(Math.round(totalUnit)));
  1701.             console.log('guardando')
  1702.             selectedProducts[productId] = {
  1703.                 quantity: quantity,
  1704.                 price: priceAct,
  1705.                 currency_type_unit_actual: unitAct,
  1706.                 priceOrg: priceOriginalInput,
  1707.                 dolarInput: dolarInput,
  1708.                 supplier_unit_amount: Math.ceil(taxAmountUnit),
  1709.                 item_amount: Math.round(netAmountUnit),
  1710.                 supplier_tax_amount: Math.round(totalUnit)
  1711.             };
  1712.             
  1713.         }
  1714.         setTimeout(function () {
  1715.             calculateInvoice();
  1716.         }, 300);
  1717.     }
  1718.     function updateGlobalPrice(productId, newPrice, type, unit) {
  1719.         console.log(unit)
  1720.         if(unit === '1' ){
  1721.             newPrice = newPrice.replace(',','.');
  1722.         }
  1723.         $.ajax({
  1724.             type: 'POST',
  1725.             url: '{{ path('update_global_price') }}',
  1726.             data: {
  1727.                 id: productId,
  1728.                 price: newPrice,
  1729.                 type: type,
  1730.                 unit: unit
  1731.             },
  1732.             success: function (response) {
  1733.                 console.log(response.message);
  1734.             },
  1735.             error: function (xhr, status, error) {
  1736.                 console.error('Error al actualizar el precio global:', error);
  1737.             }
  1738.         });
  1739.     }
  1740.     function calculateInvoice() {
  1741.         let currentRoute = "{{ app.request.attributes.get('_route') }}";
  1742.         let total = 0;
  1743.         for (let productId in selectedProducts) {
  1744.             let product = selectedProducts[productId];
  1745.             let itemAmount;
  1746.             if (currentRoute === 'app_sales') {
  1747.                 itemAmount =product.grossMarginPct || 0;
  1748.             } else {
  1749.                 itemAmount = product.supplier_tax_amount || 0;
  1750.             }
  1751.             total += itemAmount;
  1752.         }
  1753.         $('#totalInvoiceTitle').text("Total: " + formatCurrency(total));
  1754.         $('#totalInvoice').val(total);
  1755.         $('#selectedProductsList').val(JSON.stringify(selectedProducts));
  1756.         console.log(selectedProducts, 'productos seleccionados')
  1757.     }
  1758.     function formatCurrency(value, decimals = 0) {
  1759.         return new Intl.NumberFormat('es-CL', {
  1760.             style: 'currency',
  1761.             currency: 'CLP',
  1762.             minimumFractionDigits: decimals,
  1763.             maximumFractionDigits: decimals
  1764.         }).format(value);
  1765.     }
  1766.     function parseCurrency(value) {
  1767.         // Remover los puntos de separador de miles
  1768.         value = value.replace(/\./g, "");
  1769.         // Reemplazar la coma como separador decimal por un punto
  1770.         value = value.replace(/,/g, ".");
  1771.         // Convertir a float
  1772.         return parseFloat(value);
  1773.     }
  1774.     function formatPriceCLP(price) {
  1775.         // Convertir a número flotante y luego a una cadena para asegurar el formato
  1776.         price = parseFloat(price.replace(/,/g, '.')).toFixed(3).toString();
  1777.         // Separar la parte entera y decimal
  1778.         let parts = price.split('.');
  1779.         let integerPart = parts[0];
  1780.         let decimalPart = parts.length > 1 ? parts[1] : '';
  1781.         // Formatear la parte entera con puntos como separadores de miles
  1782.         integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
  1783.         // Combinar las partes nuevamente
  1784.         return integerPart;
  1785.     }
  1786.     $(document).ready(function () {
  1787.         $('#payType').closest('.form-group').hide();
  1788.         $('#planType').closest('.form-group').hide();
  1789.         $('#payMethod').change(function() {
  1790.             var selectedValue = $(this).val();
  1791.             console.log(selectedValue)
  1792.             if (selectedValue == '1') {
  1793.                 console.log('selectedValue')
  1794.                 $('#payType').closest('.form-group').hide();
  1795.                 $('#planType').closest('.form-group').show();
  1796.             } else if (selectedValue == '2') {
  1797.                 $('#payType').closest('.form-group').show();
  1798.                 $('#planType').closest('.form-group').hide();
  1799.             } else {
  1800.                 $('#payType').closest('.form-group').hide();
  1801.                 $('#planType').closest('.form-group').hide();
  1802.             }
  1803.         });
  1804.         $('#hostNum').on('input', function () {
  1805.             let valor = $(this).val();
  1806.             // Eliminar cualquier carácter que no sea un número
  1807.             valor = valor.replace(/[^0-9]/g, '');
  1808.             // Si el valor es menor o igual a 0, establecerlo en 1
  1809.             if (valor === '' || valor <= 0) {
  1810.                 $(this).val(1);
  1811.             } else {
  1812.                 $(this).val(valor);
  1813.             }
  1814.         });
  1815.         $('#orgType,#rutInput').on('input', function () {
  1816.             let rut = $('#rutInput');
  1817.             let orgType = $('#orgType').val();
  1818.             if (orgType === undefined) {
  1819.                 orgType = 0;
  1820.             }
  1821.             let rutF = formatearRUT(rut.val());
  1822.             rut.val(rutF);
  1823.             let isValid = validateRUT(rut);
  1824.             if (isValid) {
  1825.                 $('#rutValidation').html('&#10004;').css('color', 'green');
  1826.                 verificarRUTExistente(rut, orgType);
  1827.             } else {
  1828.                 $('#rutValidation').html('&#10008;').css('color', 'red');
  1829.             }
  1830.         });
  1831.     });
  1832.     function validateRUT(rut) {
  1833.         rut = rut.replace(/[^0-9kK]/g, '');
  1834.         if (rut.length < 2) return false;
  1835.         let dv = rut.slice(-1).toUpperCase();
  1836.         let rutNumero = parseInt(rut.slice(0, -1), 10);
  1837.         let m = 0;
  1838.         let s = 1;
  1839.         while (rutNumero > 0) {
  1840.             s = (s + rutNumero % 10 * (9 - m++ % 6)) % 11;
  1841.             rutNumero = Math.floor(rutNumero / 10);
  1842.         }
  1843.         return (dv === (s ? s - 1 : 'K'));
  1844.     }
  1845.     function formatearRUT(rut) {
  1846.         rut = rut.replace(/[^\dkK]+/g, '');
  1847.         let reversed = rut.split('').reverse().join('');
  1848.         let dv = reversed.charAt(0).toUpperCase();
  1849.         let digits = reversed.substring(1);
  1850.         let formattedRUT = dv + '-';
  1851.         for (let i = 0; i < digits.length; i++) {
  1852.             formattedRUT += digits.charAt(i);
  1853.             if (i % 3 === 2 && i !== digits.length - 1) {
  1854.                 formattedRUT += '.';
  1855.             }
  1856.         }
  1857.         return formattedRUT.split('').reverse().join('');
  1858.     }
  1859.     function verificarRUTExistente(rut, orgType) {
  1860.         let url = '{{ path('valid_rut', {'rut': 'PLACEHOLDER', 'orgType': 'PLACEHOLDER_ORG'})|raw }}';
  1861.         url = url.replace('PLACEHOLDER', encodeURIComponent(rut)).replace('PLACEHOLDER_ORG', encodeURIComponent(orgType));
  1862.         let exist = false;
  1863.         $.ajax({
  1864.             type: 'GET',
  1865.             url: url,
  1866.             async: false,
  1867.             success: function (response) {
  1868.                 if (response.exists) {
  1869.                     $('#patenteOn').prop('hidden', false);
  1870.                     $('#patenteOff').prop('hidden', true);
  1871.                     exist = true;
  1872.                 } else {
  1873.                     $('#patenteOn').prop('hidden', true);
  1874.                     $('#patenteOff').prop('hidden', false);
  1875.                     exist = false;
  1876.                 }
  1877.             }
  1878.         });
  1879.         return exist;
  1880.     }
  1881. </script>
  1882. <script>
  1883.     function openPaymentModal(invoiceId) {
  1884.         $('#invoiceId').val(invoiceId);
  1885.         $('#paymentModal').modal('show');
  1886.         // Llenar las opciones del tipo de pago
  1887.         $.ajax({
  1888.             url: '{{ path('app_get_payment_types') }}',
  1889.             method: 'GET',
  1890.             success: function (response) {
  1891.                 $('#paymentType').empty();
  1892.                 response.forEach(function (type) {
  1893.                     $('#paymentType').append(new Option(type.name, type.id));
  1894.                 });
  1895.             }
  1896.         });
  1897.     }
  1898.     $('#paymentForm').submit(function (event) {
  1899.         event.preventDefault();
  1900.         const paymentType = $('#paymentType').val();
  1901.         const invoiceId = $('#invoiceId').val();
  1902.         $.ajax({
  1903.             url: '{{ path('app_register_payment') }}',
  1904.             method: 'POST',
  1905.             data: {
  1906.                 paymentType: paymentType,
  1907.                 invoiceId: invoiceId
  1908.             },
  1909.             success: function (response) {
  1910.                 if (response.success) {
  1911.                     $('#paymentModal').modal('hide');
  1912.                     Swal.fire(
  1913.                         'Actualizado!',
  1914.                         'Pago realizado.',
  1915.                         'success'
  1916.                     ).then((result) => {
  1917.                         if (result.isConfirmed) {
  1918.                             location.reload();
  1919.                         }
  1920.                     });
  1921.                 }
  1922.             }
  1923.         });
  1924.     });
  1925.     //Editar Preinvoices
  1926.     $(document).on("click", ".editOrderBtn", function () {
  1927.         const preinvoiceId = $(this).data("id");
  1928.         const url = `/admin/preinvoice/${preinvoiceId}/edit`;
  1929.  
  1930.         $('#invoiceForm').data('preinvoice-id', preinvoiceId);
  1931.         $('#invoiceForm').attr('action', `/admin/preinvoice/${preinvoiceId}/update`);
  1932.         
  1933.     
  1934.         adittionalData(1, false);
  1935.         typeProduct = 1;
  1936.         selectedProducts = {}; 
  1937.         
  1938.         $('#invoiceForm').attr('action', url.replace('/edit', '')); 
  1939.         $('#titleModal').text('Editar Orden de Compra');
  1940.         $('#titleOrganization').html('Proveedor Asociado<i style="color:red;">*</i>');
  1941.         $('#hostNum').closest('.form-group').remove();
  1942.         $('#salesman').closest('.form-group').remove();
  1943.         $('#payMethod').closest('.form-group').remove();
  1944.         $('#divColor').css('background-color', '#bd2d54');
  1945.         $('.btn-saveChanges').show();
  1946.         $('.btn-create').hide();
  1947.     
  1948.         $.ajax({
  1949.             url: url,
  1950.             method: "GET",
  1951.             success: function (response) {
  1952.                 console.log("Respuesta recibida:", response);
  1953.     
  1954.                 
  1955.                 $('#poNumber').val(response.poNumber);
  1956.                 $('#date').val(response.date);
  1957.                 $('#endDate').val(response.endDate);
  1958.                 $('#organization').val(response.organization).trigger('change');
  1959.                 $('#planType').val(response.planType).trigger('change');
  1960.                 $('#observation').val(response.observation);
  1961.         ;
  1962.                 
  1963.                 if (response.products && typeof response.products === "object") {
  1964.                     const products = response.products;
  1965.                 
  1966.                     Object.keys(products).forEach((productId) => {
  1967.                         const product = products[productId];
  1968.                         const checkbox = $(`#product_${productId}`);
  1969.                 
  1970.                         if (checkbox.length) {
  1971.                             checkbox.prop("checked", true); 
  1972.                             checkbox.trigger("change");
  1973.                             $(`#price_${productId}`).val(product.price);
  1974.                             $(`#dolar_${productId}`).val(product.dolarInput || '');
  1975.                             $(`#item_amount_${productId}`).val(product.item_amount);
  1976.                             $(`#supplier_unit_amount_${productId}`).val(parseFloat(product.supplier_unit_amount));
  1977.                             $(`#supplier_tax_amount_${productId}`).val(product.supplier_tax_amount);
  1978.                             $(`#quantity_${productId}`).val(product.quantity || '');
  1979.                             updateProductPrices(productId);
  1980.                         
  1981.                         } else {
  1982.                             console.warn(`Checkbox con ID product_${productId} no encontrado en el DOM.`);
  1983.                         }
  1984.                         
  1985.                     });
  1986.                 } else {
  1987.                     console.error("products no es un objeto válido:", response.products);
  1988.                 }
  1989.                 setTimeout(function () {
  1990.                     calculateInvoice();
  1991.                 }, 300);
  1992.     
  1993.                 $('#totalInvoice').val(response.total);
  1994.     
  1995.                 $(".invoiceModal").modal("show");
  1996.     
  1997.               
  1998.             },
  1999.             error: function (xhr) {
  2000.                 console.error("Error al cargar datos:", xhr.responseText);
  2001.                 Swal.fire("Error", "No se pudieron cargar los datos.", "error");
  2002.             },
  2003.         });
  2004.     });
  2005.     
  2006.     
  2007.     $(document).ready(function () {
  2008.         
  2009.         const urlParams = new URLSearchParams(window.location.search);
  2010.         let preinvoices = [];
  2011.         for (const [key,value] of urlParams.entries()){
  2012.             if(key.startsWith('preinvoices')){
  2013.                 preinvoices.push(value)
  2014.             }
  2015.         }
  2016.             console.log(preinvoices, 'Id de ordenes de compra');
  2017.         if (preinvoices.length > 0) {
  2018.             adittionalData(1, false);
  2019.             typeProduct = 1;
  2020.             selectedProducts = {}; 
  2021.         
  2022.         
  2023.             $('#titleModal').text('Factura de Compra');
  2024.             $('#titleOrganization').html('Proveedor Asociado<i style="color:red;">*</i>');
  2025.             $('#poNumber').closest('.form-group').remove();
  2026.             $('#salesman').closest('.form-group').remove();
  2027.             $('#payMethod').closest('.form-group').remove();
  2028.             $('#divColor').css('background-color', '#bd2d54');
  2029.             $('.btn-saveChanges').hide();
  2030.             
  2031.             $.ajax({
  2032.                 url: `{{ path('purchase_consolidated') }}`,
  2033.                 method: "POST",
  2034.                 contentType: 'application/json',
  2035.                 data: JSON.stringify({preinvoices}),
  2036.                 success: function (response) {
  2037.                     if(response.status){
  2038.                         console.log("Datos cargados:", response);
  2039.                         $('#preinvoicesInput').val(JSON.stringify(preinvoices));
  2040.                         $('#organization').val(response.data.organization).trigger('change');
  2041.                         $('planType').val(response.planType).trigger('change');
  2042.                         $('observation').val(response.observation);
  2043.                         $('#totalInvoice').val(response.data.total);
  2044.                         Object.keys(response.data.products).forEach(productId => {
  2045.                             const product = response.data.products[productId];
  2046.     
  2047.                             const checkbox = $(`#product_${productId}`);
  2048.                 
  2049.                             if (checkbox.length) {
  2050.                                 checkbox.prop("checked", true); 
  2051.                                 checkbox.trigger("change");
  2052.                                 $(`#price_${productId}`).val(product.price);
  2053.                                 $(`#dolar_${productId}`).val(product.dolarInput || '');
  2054.                                 $(`#item_amount_${productId}`).val(product.item_amount);
  2055.                                 $(`#supplier_unit_amount_${productId}`).val(parseFloat(product.supplier_unit_amount));
  2056.                                 $(`#supplier_tax_amount_${productId}`).val(product.supplier_tax_amount);
  2057.                                 $(`#quantity_${productId}`).val(product.quantity || '');
  2058.                                 updateProductPrices(productId);
  2059.                             
  2060.                             } else {
  2061.                                 console.warn(`Checkbox con ID product_${productId} no encontrado en el DOM.`);
  2062.                             }
  2063.     
  2064.                             
  2065.                         });
  2066.                     }
  2067.                 
  2068.                     setTimeout(function () {
  2069.                         calculateInvoice();
  2070.                     }, 300);
  2071.         
  2072.                     $('#totalInvoice').val(response.total);
  2073.                     // Mostrar el modal
  2074.                     $(".invoiceModal").modal("show");
  2075.                 },
  2076.                 error: function (xhr) {
  2077.                     console.error("Error al cargar los datos:", xhr.responseText);
  2078.                     Swal.fire("Error", "No se pudieron cargar los datos de la orden.", "error");
  2079.                 },
  2080.             });
  2081.         } else {
  2082.             console.error("No se encontró preinvoiceId en la URL.");
  2083.         }
  2084.     });
  2085.     $(document).ready(function () {
  2086.         const urlParams = new URLSearchParams(window.location.search);
  2087.     
  2088.         const preinvoiceIds = [];
  2089.         for (const [key, value] of urlParams.entries()) {
  2090.             if (key.startsWith('preinvoices')) {
  2091.                 preinvoiceIds.push(value); 
  2092.             }
  2093.         }
  2094.         if (preinvoiceIds.length > 0) {
  2095.             $('.invoiceModal').modal('show');
  2096.             $('.invoiceModal').on('hidden.bs.modal', function () {
  2097.                 history.replaceState(null, '', '/purchases');
  2098.                 window.location.href = '/purchases';
  2099.             });
  2100.         }
  2101.     });
  2102. </script>
  2103. <script>
  2104.     $(document).ready(function() {
  2105.         // Función para aplicar el modo oscuro
  2106.         function enableDarkMode() {
  2107.             $('#kt_body').css('background-image', 'url({{ asset(headerImg2) }})');
  2108.             $('.menu-here-bg .text-black').removeClass('text-black').addClass('modeDark');
  2109.             localStorage.setItem('darkMode', 'enabled');
  2110.         }
  2111.         // Función para desactivar el modo oscuro
  2112.         function disableDarkMode() {
  2113.             $('#kt_body').css('background-image', 'url({{ asset(headerImg) }})');
  2114.             $('.menu-here-bg .modeDark').removeClass('modeDark').addClass('text-black');
  2115.             localStorage.setItem('darkMode', 'disabled');
  2116.         }
  2117.         // Recuperar el estado del modo oscuro del almacenamiento local
  2118.         if (localStorage.getItem('darkMode') === 'enabled') {
  2119.             $('#darkModeToggle').prop('checked', true);
  2120.             enableDarkMode();
  2121.         } else {
  2122.             disableDarkMode();
  2123.         }
  2124.         // Cambiar el modo oscuro al cambiar el switch
  2125.         $('#darkModeToggle').change(function() {
  2126.             if ($(this).is(':checked')) {
  2127.                 enableDarkMode();
  2128.             } else {
  2129.                 disableDarkMode();
  2130.             }
  2131.         });
  2132.     });
  2133. </script>
  2134. {% block javascripts %}
  2135. {% endblock %}
  2136. </body>
  2137. </html>