--
-- PostgreSQL database dump
--

\restrict londHmqT4llS8Wof4ZnceO2dyFhn4jiR5xbaszMgZpMczgr6aVW6xQJxeUdqJwa

-- Dumped from database version 16.10 (Debian 16.10-1.pgdg13+1)
-- Dumped by pg_dump version 16.10 (Debian 16.10-1.pgdg13+1)

SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;

--
-- Name: asistencia_delete_raw(bigint, text); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.asistencia_delete_raw(p_id_raw bigint, p_tz text DEFAULT 'America/Montevideo'::text) RETURNS jsonb
    LANGUAGE plpgsql
    AS $$
DECLARE
  v_id_usuario INT;
  v_ts         TIMESTAMPTZ;
  v_t0         TIMESTAMPTZ;
  v_t1         TIMESTAMPTZ;
  v_del_raw    INT;
  v_del        INT;
  v_ins        INT;
BEGIN
  SELECT id_usuario, ts INTO v_id_usuario, v_ts
  FROM public.asistencia_raw WHERE id_raw = p_id_raw;
  IF v_id_usuario IS NULL THEN
    RETURN jsonb_build_object('deleted',0,'msg','id_raw inexistente');
  END IF;

  v_t0 := v_ts - INTERVAL '1 day';
  v_t1 := v_ts + INTERVAL '1 day';

  -- borrar raw
  DELETE FROM public.asistencia_raw WHERE id_raw = p_id_raw;
  GET DIAGNOSTICS v_del_raw = ROW_COUNT;

  -- recomputar pares en ventana
  WITH tl AS (
    SELECT ar.ts,
           ROW_NUMBER() OVER (ORDER BY ar.ts) AS rn
    FROM public.asistencia_raw ar
    WHERE ar.id_usuario = v_id_usuario
      AND ar.ts BETWEEN v_t0 AND v_t1
  ),
  ready AS (
    SELECT (t1.ts AT TIME ZONE p_tz)::date AS fecha,
           t1.ts AS desde,
           t2.ts AS hasta,
           EXTRACT(EPOCH FROM (t2.ts - t1.ts))/60.0 AS dur_min
    FROM tl t1
    JOIN tl t2 ON t2.rn = t1.rn + 1
    WHERE (t1.rn % 2) = 1 AND t2.ts > t1.ts
  ),
  del AS (
    DELETE FROM public.asistencia_intervalo ai
    WHERE ai.id_usuario = v_id_usuario
      AND (ai.desde BETWEEN v_t0 AND v_t1 OR ai.hasta BETWEEN v_t0 AND v_t1)
    RETURNING 1
  ),
  ins AS (
    INSERT INTO public.asistencia_intervalo (id_usuario, fecha, desde, hasta, dur_min, origen)
    SELECT v_id_usuario, r.fecha, r.desde, r.hasta, r.dur_min, 'delete_adjust'
    FROM ready r
    ON CONFLICT (id_usuario, desde, hasta) DO NOTHING
    RETURNING 1
  )
  SELECT (SELECT COUNT(*) FROM del), (SELECT COUNT(*) FROM ins) INTO v_del, v_ins;

  RETURN jsonb_build_object('deleted',v_del_raw,'deleted_pairs',v_del,'inserted_pairs',v_ins);
END;
$$;


ALTER FUNCTION public.asistencia_delete_raw(p_id_raw bigint, p_tz text) OWNER TO manso;

--
-- Name: asistencia_get(text, date, date, text); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.asistencia_get(p_doc text, p_desde date, p_hasta date, p_tz text DEFAULT 'America/Montevideo'::text) RETURNS jsonb
    LANGUAGE sql
    AS $$
WITH u AS (
  SELECT id_usuario, documento, nombre, apellido
  FROM public.usuarios
  WHERE regexp_replace(documento,'^\s*0+','','g') = regexp_replace(p_doc,'^\s*0+','','g')
  LIMIT 1
),
r AS (
  SELECT ar.id_raw,
         (ar.ts AT TIME ZONE p_tz)::date                         AS fecha,
         to_char(ar.ts AT TIME ZONE p_tz,'HH24:MI:SS')           AS hora,
         COALESCE(ar.modo,'')                                    AS modo,
         COALESCE(ar.origen,'')                                  AS origen,
         ar.ts
  FROM public.asistencia_raw ar
  JOIN u USING (id_usuario)
  WHERE (ar.ts AT TIME ZONE p_tz)::date BETWEEN p_desde AND p_hasta
),
i AS (
  SELECT ai.id_intervalo,
         ai.fecha,
         to_char(ai.desde AT TIME ZONE p_tz,'HH24:MI:SS')        AS desde_hora,
         to_char(ai.hasta AT TIME ZONE p_tz,'HH24:MI:SS')        AS hasta_hora,
         ai.dur_min
  FROM public.asistencia_intervalo ai
  JOIN u USING (id_usuario)
  WHERE ai.fecha BETWEEN p_desde AND p_hasta
)
SELECT jsonb_build_object(
  'usuario', (SELECT to_jsonb(u.*) FROM u),
  'raw',     COALESCE((SELECT jsonb_agg(to_jsonb(r.*) ORDER BY r.ts) FROM r),'[]'::jsonb),
  'intervalos', COALESCE((SELECT jsonb_agg(to_jsonb(i.*) ORDER BY i.fecha, i.id_intervalo) FROM i),'[]'::jsonb)
);
$$;


ALTER FUNCTION public.asistencia_get(p_doc text, p_desde date, p_hasta date, p_tz text) OWNER TO manso;

--
-- Name: asistencia_update_raw(bigint, date, text, text, text); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.asistencia_update_raw(p_id_raw bigint, p_fecha date, p_hora text, p_modo text, p_tz text DEFAULT 'America/Montevideo'::text) RETURNS jsonb
    LANGUAGE plpgsql
    AS $$
DECLARE
  v_id_usuario INT;
  v_ts_old     TIMESTAMPTZ;
  v_ts_new     TIMESTAMPTZ;
  v_t0         TIMESTAMPTZ;
  v_t1         TIMESTAMPTZ;
  v_del        INT;
  v_ins        INT;
BEGIN
  -- leer estado previo
  SELECT id_usuario, ts INTO v_id_usuario, v_ts_old
  FROM public.asistencia_raw WHERE id_raw = p_id_raw;
  IF v_id_usuario IS NULL THEN
    RETURN jsonb_build_object('updated',0,'msg','id_raw inexistente');
  END IF;

  -- construir ts nuevo
  v_ts_new := make_timestamptz(
               EXTRACT(YEAR FROM p_fecha)::INT,
               EXTRACT(MONTH FROM p_fecha)::INT,
               EXTRACT(DAY FROM p_fecha)::INT,
               split_part(p_hora,':',1)::INT,
               split_part(p_hora,':',2)::INT,
               COALESCE(NULLIF(split_part(p_hora,':',3),''), '0')::INT,
               p_tz);

  -- aplicar update
  UPDATE public.asistencia_raw
  SET ts = v_ts_new,
      modo = COALESCE(p_modo, modo)
  WHERE id_raw = p_id_raw;

  -- ventana de recálculo
  v_t0 := LEAST(v_ts_old, v_ts_new) - INTERVAL '1 day';
  v_t1 := GREATEST(v_ts_old, v_ts_new) + INTERVAL '1 day';

  -- recomputar pares en la ventana: borrar los del rango y reinsertar
  WITH tl AS (
    SELECT ar.ts,
           ROW_NUMBER() OVER (ORDER BY ar.ts) AS rn
    FROM public.asistencia_raw ar
    WHERE ar.id_usuario = v_id_usuario
      AND ar.ts BETWEEN v_t0 AND v_t1
  ),
  ready AS (
    SELECT (t1.ts AT TIME ZONE p_tz)::date AS fecha,
           t1.ts AS desde,
           t2.ts AS hasta,
           EXTRACT(EPOCH FROM (t2.ts - t1.ts))/60.0 AS dur_min
    FROM tl t1
    JOIN tl t2 ON t2.rn = t1.rn + 1
    WHERE (t1.rn % 2) = 1 AND t2.ts > t1.ts
  ),
  del AS (
    DELETE FROM public.asistencia_intervalo ai
    WHERE ai.id_usuario = v_id_usuario
      AND (ai.desde BETWEEN v_t0 AND v_t1 OR ai.hasta BETWEEN v_t0 AND v_t1)
    RETURNING 1
  ),
  ins AS (
    INSERT INTO public.asistencia_intervalo (id_usuario, fecha, desde, hasta, dur_min, origen)
    SELECT v_id_usuario, r.fecha, r.desde, r.hasta, r.dur_min, 'edit_manual'
    FROM ready r
    ON CONFLICT (id_usuario, desde, hasta) DO NOTHING
    RETURNING 1
  )
  SELECT (SELECT COUNT(*) FROM del), (SELECT COUNT(*) FROM ins) INTO v_del, v_ins;

  RETURN jsonb_build_object('updated',1,'deleted_pairs',v_del,'inserted_pairs',v_ins);
END;
$$;


ALTER FUNCTION public.asistencia_update_raw(p_id_raw bigint, p_fecha date, p_hora text, p_modo text, p_tz text) OWNER TO manso;

--
-- Name: delete_compra(integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.delete_compra(p_id_compra integer) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
  DELETE FROM public.deta_comp_materias WHERE id_compra = p_id_compra;
  DELETE FROM public.deta_comp_producto WHERE id_compra = p_id_compra;
  DELETE FROM public.compras WHERE id_compra = p_id_compra;
END;
$$;


ALTER FUNCTION public.delete_compra(p_id_compra integer) OWNER TO manso;

--
-- Name: f_abrir_comanda(integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.f_abrir_comanda(p_id integer) RETURNS jsonb
    LANGUAGE plpgsql
    AS $$
DECLARE r jsonb;
BEGIN
  UPDATE public.comandas
     SET estado    = 'abierta',
         fec_cierre = NULL
   WHERE id_comanda = p_id;

  IF NOT FOUND THEN
    RETURN NULL;
  END IF;

  SELECT to_jsonb(v) INTO r
    FROM public.v_comandas_resumen v
   WHERE v.id_comanda = p_id;

  RETURN r;
END;
$$;


ALTER FUNCTION public.f_abrir_comanda(p_id integer) OWNER TO manso;

--
-- Name: f_cerrar_comanda(integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.f_cerrar_comanda(p_id integer) RETURNS jsonb
    LANGUAGE plpgsql
    AS $$
DECLARE r jsonb;
BEGIN
  UPDATE public.comandas
     SET estado    = 'cerrada',
         fec_cierre = COALESCE(fec_cierre, NOW())
   WHERE id_comanda = p_id;

  IF NOT FOUND THEN
    RETURN NULL;
  END IF;

  SELECT to_jsonb(v) INTO r
    FROM public.v_comandas_resumen v
   WHERE v.id_comanda = p_id;

  RETURN r;
END;
$$;


ALTER FUNCTION public.f_cerrar_comanda(p_id integer) OWNER TO manso;

--
-- Name: f_comanda_detalle_json(integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.f_comanda_detalle_json(p_id_comanda integer) RETURNS jsonb
    LANGUAGE sql
    AS $$
WITH base AS (
  SELECT
    c.id_comanda,
    c.fec_creacion,
    c.estado,
    c.observaciones,
    u.id_usuario,
    u.nombre   AS usuario_nombre,
    u.apellido AS usuario_apellido,
    m.id_mesa,
    m.numero   AS mesa_numero,
    m.apodo    AS mesa_apodo,
    d.id_producto,
    p.nombre   AS producto_nombre,
    d.cantidad,
    d.pre_unitario,
    (d.cantidad * d.pre_unitario) AS subtotal
  FROM public.comandas c
  JOIN public.usuarios  u ON u.id_usuario = c.id_usuario
  JOIN public.mesas     m ON m.id_mesa     = c.id_mesa
  LEFT JOIN public.deta_comandas d ON d.id_comanda = c.id_comanda
  LEFT JOIN public.productos     p ON p.id_producto = d.id_producto
  WHERE c.id_comanda = p_id_comanda
),
hdr AS (
  -- 1 sola fila con los datos de cabecera
  SELECT DISTINCT
    id_comanda, fec_creacion, estado, observaciones,
    id_usuario, usuario_nombre, usuario_apellido,
    id_mesa, mesa_numero, mesa_apodo
  FROM base
),
agg_items AS (
  SELECT
    COALESCE(
      jsonb_agg(
        jsonb_build_object(
          'producto_id',   b.id_producto,
          'producto',      b.producto_nombre,
          'cantidad',      b.cantidad,
          'pre_unitario',  b.pre_unitario,
          'subtotal',      b.subtotal
        )
        ORDER BY b.producto_nombre NULLS LAST
      ) FILTER (WHERE b.id_producto IS NOT NULL),
      '[]'::jsonb
    ) AS items
  FROM base b
),
tot AS (
  SELECT
    COUNT(*) FILTER (WHERE id_producto IS NOT NULL) AS items,
    COALESCE(SUM(subtotal), 0)::numeric            AS total
  FROM base
)
SELECT
  CASE
    WHEN EXISTS (SELECT 1 FROM hdr) THEN
      jsonb_build_object(
        'id_comanda',   h.id_comanda,
        'fec_creacion', h.fec_creacion,
        'estado',       h.estado,
        'observaciones',h.observaciones,
        'usuario', jsonb_build_object(
          'id_usuario',      h.id_usuario,
          'nombre',          h.usuario_nombre,
          'apellido',        h.usuario_apellido
        ),
        'mesa', jsonb_build_object(
          'id_mesa',         h.id_mesa,
          'numero',          h.mesa_numero,
          'apodo',           h.mesa_apodo
        ),
        'items',   i.items,
        'totales', jsonb_build_object(
          'items', t.items,
          'total', t.total
        )
      )
    ELSE NULL
  END
FROM hdr h, agg_items i, tot t;
$$;


ALTER FUNCTION public.f_comanda_detalle_json(p_id_comanda integer) OWNER TO manso;

--
-- Name: f_comanda_detalle_rows(integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.f_comanda_detalle_rows(p_id_comanda integer) RETURNS TABLE(id_comanda integer, fec_creacion timestamp without time zone, estado text, observaciones text, id_usuario integer, usuario_nombre text, usuario_apellido text, id_mesa integer, mesa_numero integer, mesa_apodo text, producto_id integer, producto_nombre text, cantidad numeric, pre_unitario numeric, subtotal numeric, items integer, total numeric)
    LANGUAGE sql
    AS $$
WITH base AS (
  SELECT
    c.id_comanda, c.fec_creacion, c.estado, c.observaciones,
    u.id_usuario, u.nombre AS usuario_nombre, u.apellido AS usuario_apellido,
    m.id_mesa, m.numero AS mesa_numero, m.apodo AS mesa_apodo,
    d.id_producto, p.nombre AS producto_nombre,
    d.cantidad, d.pre_unitario,
    (d.cantidad * d.pre_unitario) AS subtotal
  FROM public.comandas c
  JOIN public.usuarios u ON u.id_usuario = c.id_usuario
  JOIN public.mesas    m ON m.id_mesa     = c.id_mesa
  LEFT JOIN public.deta_comandas d ON d.id_comanda = c.id_comanda
  LEFT JOIN public.productos     p ON p.id_producto = d.id_producto
  WHERE c.id_comanda = p_id_comanda
),
tot AS (
  SELECT
    COUNT(*) FILTER (WHERE id_producto IS NOT NULL) AS items,
    COALESCE(SUM(subtotal), 0) AS total
  FROM base
)
SELECT
  b.id_comanda, b.fec_creacion, b.estado, b.observaciones,
  b.id_usuario, b.usuario_nombre, b.usuario_apellido,
  b.id_mesa, b.mesa_numero, b.mesa_apodo,
  b.id_producto, b.producto_nombre,
  b.cantidad, b.pre_unitario, b.subtotal,
  t.items, t.total
FROM base b CROSS JOIN tot t
ORDER BY b.producto_nombre NULLS LAST;
$$;


ALTER FUNCTION public.f_comanda_detalle_rows(p_id_comanda integer) OWNER TO manso;

SET default_tablespace = '';

SET default_table_access_method = heap;

--
-- Name: comandas; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.comandas (
    id_comanda integer NOT NULL,
    id_usuario integer NOT NULL,
    id_mesa integer NOT NULL,
    fec_creacion timestamp without time zone DEFAULT now() NOT NULL,
    estado text NOT NULL,
    observaciones text,
    fec_cierre timestamp with time zone,
    CONSTRAINT comandas_estado_check CHECK ((estado = ANY (ARRAY['abierta'::text, 'cerrada'::text, 'pagada'::text, 'anulada'::text])))
);


ALTER TABLE public.comandas OWNER TO manso;

--
-- Name: COLUMN comandas.fec_cierre; Type: COMMENT; Schema: public; Owner: manso
--

COMMENT ON COLUMN public.comandas.fec_cierre IS 'Fecha/hora de cierre de la comanda (NULL si está abierta)';


--
-- Name: deta_comandas; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.deta_comandas (
    id_det_comanda integer NOT NULL,
    id_comanda integer NOT NULL,
    id_producto integer NOT NULL,
    cantidad numeric(12,3) NOT NULL,
    pre_unitario numeric(12,2) NOT NULL,
    observaciones text,
    CONSTRAINT deta_comandas_cantidad_check CHECK ((cantidad > (0)::numeric)),
    CONSTRAINT deta_comandas_pre_unitario_check CHECK ((pre_unitario >= (0)::numeric))
);


ALTER TABLE public.deta_comandas OWNER TO manso;

--
-- Name: mesas; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.mesas (
    id_mesa integer NOT NULL,
    numero integer NOT NULL,
    apodo text NOT NULL,
    estado text DEFAULT 'libre'::text NOT NULL,
    CONSTRAINT mesas_estado_check CHECK ((estado = ANY (ARRAY['libre'::text, 'ocupada'::text, 'reservada'::text])))
);


ALTER TABLE public.mesas OWNER TO manso;

--
-- Name: usuarios; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.usuarios (
    id_usuario integer NOT NULL,
    documento text,
    img_perfil character varying(255) DEFAULT 'img_perfil.png'::character varying NOT NULL,
    nombre text NOT NULL,
    apellido text NOT NULL,
    correo text,
    telefono text,
    fec_nacimiento date,
    activo boolean DEFAULT true
);


ALTER TABLE public.usuarios OWNER TO manso;

--
-- Name: v_comandas_resumen; Type: VIEW; Schema: public; Owner: manso
--

CREATE VIEW public.v_comandas_resumen AS
 WITH items AS (
         SELECT d.id_comanda,
            count(*) AS items,
            sum((d.cantidad * d.pre_unitario)) AS total
           FROM public.deta_comandas d
          GROUP BY d.id_comanda
        )
 SELECT c.id_comanda,
    c.fec_creacion,
    c.estado,
    c.observaciones,
    u.id_usuario,
    u.nombre AS usuario_nombre,
    u.apellido AS usuario_apellido,
    m.id_mesa,
    m.numero AS mesa_numero,
    m.apodo AS mesa_apodo,
    COALESCE(i.items, (0)::bigint) AS items,
    COALESCE(i.total, (0)::numeric) AS total,
    c.fec_cierre,
        CASE
            WHEN (c.fec_cierre IS NOT NULL) THEN round((EXTRACT(epoch FROM (c.fec_cierre - (c.fec_creacion)::timestamp with time zone)) / 60.0), 1)
            ELSE NULL::numeric
        END AS duracion_min
   FROM (((public.comandas c
     JOIN public.usuarios u ON ((u.id_usuario = c.id_usuario)))
     JOIN public.mesas m ON ((m.id_mesa = c.id_mesa)))
     LEFT JOIN items i ON ((i.id_comanda = c.id_comanda)));


ALTER VIEW public.v_comandas_resumen OWNER TO manso;

--
-- Name: f_comandas_resumen(text, integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.f_comandas_resumen(p_estado text DEFAULT NULL::text, p_limit integer DEFAULT 200) RETURNS SETOF public.v_comandas_resumen
    LANGUAGE sql
    AS $$
  SELECT *
  FROM public.v_comandas_resumen
  WHERE (p_estado IS NULL OR estado = p_estado)
  ORDER BY id_comanda DESC
  LIMIT p_limit;
$$;


ALTER FUNCTION public.f_comandas_resumen(p_estado text, p_limit integer) OWNER TO manso;

--
-- Name: find_usuarios_por_documentos(jsonb); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.find_usuarios_por_documentos(p_docs jsonb) RETURNS jsonb
    LANGUAGE sql
    AS $$
WITH docs AS (
  SELECT DISTINCT
         regexp_replace(value::text, '^\s*0+', '', 'g') AS doc_clean,
         value::text                                  AS original
  FROM jsonb_array_elements_text(COALESCE(p_docs,'[]'))
),
rows AS (
  SELECT d.original                             AS documento,
         u.nombre,
         u.apellido,
         (u.id_usuario IS NOT NULL)             AS found
  FROM docs d
  LEFT JOIN public.usuarios u
    ON regexp_replace(u.documento, '^\s*0+', '', 'g') = d.doc_clean
)
SELECT COALESCE(
  jsonb_object_agg(
    documento,
    jsonb_build_object(
      'nombre',   COALESCE(nombre, ''),
      'apellido', COALESCE(apellido, ''),
      'found',    found
    )
  ),
  '{}'::jsonb
)
FROM rows;
$$;


ALTER FUNCTION public.find_usuarios_por_documentos(p_docs jsonb) OWNER TO manso;

--
-- Name: get_compra(integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.get_compra(p_id_compra integer) RETURNS jsonb
    LANGUAGE sql
    AS $$
WITH cab AS (
  SELECT c.id_compra, c.id_proveedor, c.fec_compra, c.total
  FROM public.compras c
  WHERE c.id_compra = p_id_compra
),
dm AS (
  SELECT 'MAT'::text AS tipo, d.id_mat_prima AS id,
         d.cantidad, d.pre_unitario AS precio
  FROM public.deta_comp_materias d WHERE d.id_compra = p_id_compra
),
dp AS (
  SELECT 'PROD'::text AS tipo, d.id_producto AS id,
         d.cantidad, d.pre_unitario AS precio
  FROM public.deta_comp_producto d WHERE d.id_compra = p_id_compra
),
det AS (
  SELECT jsonb_agg(to_jsonb(x.*)) AS detalles
  FROM (
    SELECT * FROM dm
    UNION ALL
    SELECT * FROM dp
  ) x
)
SELECT jsonb_build_object(
  'id_compra', (SELECT id_compra FROM cab),
  'id_proveedor',(SELECT id_proveedor FROM cab),
  'fec_compra', to_char((SELECT fec_compra FROM cab),'YYYY-MM-DD HH24:MI:SS'),
  'total', (SELECT total FROM cab),
  'detalles', COALESCE((SELECT detalles FROM det),'[]'::jsonb)
);
$$;


ALTER FUNCTION public.get_compra(p_id_compra integer) OWNER TO manso;

--
-- Name: get_materia_prima(integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.get_materia_prima(p_id integer) RETURNS jsonb
    LANGUAGE sql
    AS $$
SELECT jsonb_build_object(
  'materia', to_jsonb(mp),
  'proveedores', COALESCE(
    (
      SELECT jsonb_agg(
               jsonb_build_object(
                 'id_proveedor', pr.id_proveedor,
                 'raz_social', pr.raz_social,
                 'rut', pr.rut,
                 'contacto', pr.contacto,
                 'direccion', pr.direccion
               )
             )
      FROM public.prov_mate_prima pmp
      JOIN public.proveedores pr ON pr.id_proveedor = pmp.id_proveedor
      WHERE pmp.id_mat_prima = mp.id_mat_prima
    ),
    '[]'::jsonb
  )
)
FROM public.mate_primas mp
WHERE mp.id_mat_prima = p_id;
$$;


ALTER FUNCTION public.get_materia_prima(p_id integer) OWNER TO manso;

--
-- Name: get_producto(integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.get_producto(p_id integer) RETURNS jsonb
    LANGUAGE sql
    AS $$
SELECT jsonb_build_object(
  'producto', to_jsonb(p),       -- el registro completo del producto en JSONB
  'receta', COALESCE(
    (
      SELECT jsonb_agg(
               jsonb_build_object(
                 'id_mat_prima', rp.id_mat_prima,
                 'qty_por_unidad', rp.qty_por_unidad,
                 'nombre', mp.nombre,
                 'unidad', mp.unidad
               )
             )
      FROM receta_producto rp
      LEFT JOIN mate_primas mp USING (id_mat_prima)
      WHERE rp.id_producto = p.id_producto
    ),
    '[]'::jsonb
  )
)
FROM productos p
WHERE p.id_producto = p_id;
$$;


ALTER FUNCTION public.get_producto(p_id integer) OWNER TO manso;

--
-- Name: import_asistencia(jsonb, text, text); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.import_asistencia(p_registros jsonb, p_origen text, p_tz text DEFAULT 'America/Montevideo'::text) RETURNS jsonb
    LANGUAGE plpgsql
    AS $_$
DECLARE
  v_ins_raw   INT;
  v_ins_pairs INT;
  v_miss      JSONB;
BEGIN
  WITH
  -- 1) JSON -> filas
  j AS (
    SELECT
      regexp_replace(elem->>'doc','^\s*0+','','g')::TEXT AS doc_clean,
      (elem->>'isoDate')::DATE                            AS d,
      elem->>'time'                                       AS time_str,
      NULLIF(elem->>'mode','')                            AS modo
    FROM jsonb_array_elements(COALESCE(p_registros,'[]')) elem
  ),
  -- 2) Vincular a usuarios
  u AS (
    SELECT j.*, u.id_usuario
    FROM j
    LEFT JOIN public.usuarios u
      ON regexp_replace(u.documento,'^\s*0+','','g') = j.doc_clean
  ),
  -- 3) Documentos faltantes
  miss AS (
    SELECT jsonb_agg(doc_clean) AS missing
    FROM u WHERE id_usuario IS NULL
  ),
  -- 4) TS determinista en TZ del negocio
  parsed AS (
    SELECT
      u.id_usuario,
      u.modo,
      make_timestamptz(
        EXTRACT(YEAR  FROM u.d)::INT,
        EXTRACT(MONTH FROM u.d)::INT,
        EXTRACT(DAY   FROM u.d)::INT,
        split_part(u.time_str,':',1)::INT,
        split_part(u.time_str,':',2)::INT,
        COALESCE(NULLIF(split_part(u.time_str,':',3),''),'0')::INT,
        p_tz
      ) AS ts_calc
    FROM u
    WHERE u.id_usuario IS NOT NULL
  ),
  -- 5) Ventana por usuario (±1 día de lo importado)
  win AS (
    SELECT id_usuario,
           (MIN(ts_calc) - INTERVAL '1 day') AS t0,
           (MAX(ts_calc) + INTERVAL '1 day') AS t1
    FROM parsed
    GROUP BY id_usuario
  ),
  -- 6) Lo existente en BD dentro de la ventana
  existing AS (
    SELECT ar.id_usuario, ar.ts
    FROM public.asistencia_raw ar
    JOIN win w ON w.id_usuario = ar.id_usuario
              AND ar.ts BETWEEN w.t0 AND w.t1
  ),
  -- 7) CANDIDATE = existente ∪ archivo (sin duplicados)
  candidate AS (
    SELECT id_usuario, ts FROM existing
    UNION                                   -- ¡clave para evitar doble click!
    SELECT id_usuario, ts_calc AS ts FROM parsed
  ),
  -- 8) Paridad previa (cuántas marcas había ANTES de la ventana)
  before_cnt AS (
    SELECT w.id_usuario, COUNT(*)::int AS cnt
    FROM win w
    JOIN public.asistencia_raw ar
      ON ar.id_usuario = w.id_usuario
     AND ar.ts < w.t0
    GROUP BY w.id_usuario
  ),
  -- 9) Línea de tiempo candidata y pares (1→2, 3→4…), jornada = día local del inicio
  timeline AS (
    SELECT
      c.id_usuario,
      c.ts,
      ROW_NUMBER() OVER (PARTITION BY c.id_usuario ORDER BY c.ts) AS rn
    FROM candidate c
  ),
  ready AS (
    SELECT
      t1.id_usuario,
      (t1.ts AT TIME ZONE p_tz)::date AS fecha,
      t1.ts AS desde,
      t2.ts AS hasta,
      EXTRACT(EPOCH FROM (t2.ts - t1.ts))/60.0 AS dur_min
    FROM timeline t1
    JOIN timeline t2
      ON t2.id_usuario = t1.id_usuario
     AND t2.rn = t1.rn + 1
    LEFT JOIN before_cnt b ON b.id_usuario = t1.id_usuario
    WHERE ((COALESCE(b.cnt,0) + t1.rn) % 2) = 1   -- t1 es IN global
      AND t2.ts > t1.ts
  ),
  -- 10) INSERT crudo (dedupe)
  ins_raw AS (
    INSERT INTO public.asistencia_raw (id_usuario, ts, modo, origen)
    SELECT id_usuario, ts_calc,
           NULLIF(modo,'')::text,   -- puede quedar NULL para auto-etiquetado
           p_origen
    FROM parsed
    ON CONFLICT (id_usuario, ts) DO NOTHING
    RETURNING 1
  ),
  -- 11) Auto-etiquetar IN/OUT en BD para filas con modo vacío/'1' (tras insertar)
  before_cnt2 AS (
    SELECT w.id_usuario, COUNT(*)::int AS cnt
    FROM win w
    JOIN public.asistencia_raw ar
      ON ar.id_usuario = w.id_usuario
     AND ar.ts < w.t0
    GROUP BY w.id_usuario
  ),
  tl2 AS (
    SELECT
      ar.id_usuario, ar.ts,
      ROW_NUMBER() OVER (PARTITION BY ar.id_usuario ORDER BY ar.ts) AS rn
    FROM public.asistencia_raw ar
    JOIN win w ON w.id_usuario = ar.id_usuario
              AND ar.ts BETWEEN w.t0 AND w.t1
  ),
  label2 AS (
    SELECT
      t.id_usuario,
      t.ts,
      CASE WHEN ((COALESCE(b.cnt,0) + t.rn) % 2) = 1 THEN 'IN' ELSE 'OUT' END AS new_mode
    FROM tl2 t
    LEFT JOIN before_cnt2 b ON b.id_usuario = t.id_usuario
  ),
  set_mode AS (
    UPDATE public.asistencia_raw ar
       SET modo = l.new_mode
      FROM label2 l
     WHERE ar.id_usuario = l.id_usuario
       AND ar.ts         = l.ts
       AND (ar.modo IS NULL OR btrim(ar.modo) = '' OR ar.modo ~ '^\s*1\s*$')
    RETURNING 1
  ),
  -- 12) INSERT pares (dedupe) calculados desde CANDIDATE (ya tiene todo el contexto)
  ins_pairs AS (
    INSERT INTO public.asistencia_intervalo (id_usuario, fecha, desde, hasta, dur_min, origen)
    SELECT id_usuario, fecha, desde, hasta, dur_min, p_origen
    FROM ready
    ON CONFLICT (id_usuario, desde, hasta) DO NOTHING
    RETURNING 1
  )
  SELECT
    (SELECT COUNT(*) FROM ins_raw),
    (SELECT COUNT(*) FROM ins_pairs),
    (SELECT COALESCE(missing,'[]'::jsonb) FROM miss)
  INTO v_ins_raw, v_ins_pairs, v_miss;

  RETURN jsonb_build_object(
    'inserted_raw',   v_ins_raw,
    'inserted_pairs', v_ins_pairs,
    'missing_docs',   v_miss
  );
END;
$_$;


ALTER FUNCTION public.import_asistencia(p_registros jsonb, p_origen text, p_tz text) OWNER TO manso;

--
-- Name: report_asistencia(date, date); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.report_asistencia(p_desde date, p_hasta date) RETURNS TABLE(documento text, nombre text, apellido text, fecha date, desde_hora text, hasta_hora text, dur_min numeric)
    LANGUAGE sql
    AS $$
  SELECT
    u.documento, u.nombre, u.apellido,
    ai.fecha,
    to_char(ai.desde AT TIME ZONE 'America/Montevideo','HH24:MI:SS') AS desde_hora,
    to_char(ai.hasta AT TIME ZONE 'America/Montevideo','HH24:MI:SS') AS hasta_hora,
    ai.dur_min
  FROM public.asistencia_intervalo ai
  JOIN public.usuarios u USING (id_usuario)
  WHERE ai.fecha BETWEEN p_desde AND p_hasta
  ORDER BY u.documento, ai.fecha, ai.desde;
$$;


ALTER FUNCTION public.report_asistencia(p_desde date, p_hasta date) OWNER TO manso;

--
-- Name: report_gastos(integer); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.report_gastos(p_year integer) RETURNS jsonb
    LANGUAGE sql STABLE
    AS $$
WITH mdata AS (
  SELECT date_trunc('month', c.fec_compra)::date AS m,
         SUM(c.total)::numeric AS importe
  FROM public.compras c
  WHERE EXTRACT(YEAR FROM c.fec_compra) = p_year
  GROUP BY 1
),
mm AS (
  SELECT EXTRACT(MONTH FROM m)::int AS mes, importe
  FROM mdata
)
SELECT jsonb_build_object(
  'year', p_year,
  'total', COALESCE((SELECT SUM(importe) FROM mdata), 0),
  'avg',   COALESCE((SELECT AVG(importe) FROM mdata), 0),
  'months',
    (SELECT jsonb_agg(
       jsonb_build_object(
         'mes', gs,
         'nombre', to_char(to_date(gs::text,'MM'),'Mon'),
         'importe', COALESCE(mm.importe,0)
       )
       ORDER BY gs
     )
     FROM generate_series(1,12) gs
     LEFT JOIN mm ON mm.mes = gs)
);
$$;


ALTER FUNCTION public.report_gastos(p_year integer) OWNER TO manso;

--
-- Name: report_tickets_year(integer, text); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.report_tickets_year(p_year integer, p_tz text DEFAULT 'America/Montevideo'::text) RETURNS jsonb
    LANGUAGE sql STABLE
    AS $$
WITH bounds AS (
  SELECT
    make_timestamp(p_year,   1, 1, 0,0,0)  AS d0,
    make_timestamp(p_year+1, 1, 1, 0,0,0)  AS d1,
    make_timestamptz(p_year,   1, 1, 0,0,0, p_tz) AS t0,
    make_timestamptz(p_year+1, 1, 1, 0,0,0, p_tz) AS t1
),
base AS (
  SELECT
    c.id_comanda,
    CASE WHEN c.fec_cierre IS NOT NULL
         THEN (c.fec_cierre AT TIME ZONE p_tz)
         ELSE c.fec_creacion
    END AS fec_local,
    v.total
  FROM public.comandas c
  JOIN public.vw_ticket_total v ON v.id_comanda = c.id_comanda
  JOIN bounds b ON TRUE
  WHERE
    (c.fec_cierre IS NOT NULL AND c.fec_cierre  >= b.t0 AND c.fec_cierre  < b.t1)
    OR
    (c.fec_cierre IS     NULL AND c.fec_creacion >= b.d0 AND c.fec_creacion < b.d1)
),
m AS (
  SELECT
    EXTRACT(MONTH FROM fec_local)::int AS mes,
    COUNT(*)::int                      AS cant,
    SUM(total)::numeric                AS importe,
    AVG(total)::numeric                AS avg
  FROM base
  GROUP BY 1
),
ytd AS (
  SELECT COUNT(*)::int AS total_ytd,
         AVG(total)::numeric AS avg_ticket,
         SUM(total)::numeric AS to_date
  FROM base
)
SELECT jsonb_build_object(
  'year', p_year,
  'total_ytd', (SELECT total_ytd FROM ytd),
  'avg_ticket', (SELECT avg_ticket FROM ytd),
  'to_date',    (SELECT to_date FROM ytd),
  'months',
    (SELECT jsonb_agg(
       jsonb_build_object(
         'mes', mes,
         'nombre', to_char(to_date(mes::text,'MM'),'Mon'),
         'cant', cant,
         'importe', importe,
         'avg', avg
       )
       ORDER BY mes
     )
     FROM m)
);
$$;


ALTER FUNCTION public.report_tickets_year(p_year integer, p_tz text) OWNER TO manso;

--
-- Name: save_compra(integer, integer, timestamp with time zone, jsonb); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.save_compra(p_id_compra integer, p_id_proveedor integer, p_fec_compra timestamp with time zone, p_detalles jsonb) RETURNS TABLE(id_compra integer, total numeric)
    LANGUAGE plpgsql
    AS $$
DECLARE
  v_id    INT;
  v_total numeric := 0;
BEGIN
  IF COALESCE(jsonb_array_length(p_detalles),0) = 0 THEN
    RAISE EXCEPTION 'No hay renglones en la compra';
  END IF;

  -- Cabecera (insert/update)
  IF p_id_compra IS NULL THEN
    INSERT INTO public.compras (id_proveedor, fec_compra, total)
    VALUES (p_id_proveedor, COALESCE(p_fec_compra, now()), 0)
    RETURNING public.compras.id_compra INTO v_id;
  ELSE
    UPDATE public.compras c
       SET id_proveedor = p_id_proveedor,
           fec_compra   = COALESCE(p_fec_compra, c.fec_compra)
     WHERE c.id_compra = p_id_compra
    RETURNING c.id_compra INTO v_id;

    -- Reemplazamos los renglones
    DELETE FROM public.deta_comp_materias d WHERE d.id_compra = v_id;
    DELETE FROM public.deta_comp_producto  p WHERE p.id_compra = v_id;
  END IF;

  -- Materias primas (sin CTE: parseo JSON inline)
  INSERT INTO public.deta_comp_materias (id_compra, id_mat_prima, cantidad, pre_unitario)
  SELECT
    v_id,
    x.id,
    x.cantidad,
    x.precio
  FROM jsonb_to_recordset(COALESCE(p_detalles, '[]'::jsonb))
       AS x(tipo text, id int, cantidad numeric, precio numeric)
  WHERE UPPER(TRIM(x.tipo)) = 'MAT';

  -- Productos (sin CTE)
  INSERT INTO public.deta_comp_producto (id_compra, id_producto, cantidad, pre_unitario)
  SELECT
    v_id,
    x.id,
    x.cantidad,
    x.precio
  FROM jsonb_to_recordset(COALESCE(p_detalles, '[]'::jsonb))
       AS x(tipo text, id int, cantidad numeric, precio numeric)
  WHERE UPPER(TRIM(x.tipo)) = 'PROD';

  -- Recalcular total (calificado) y redondear a ENTERO
  SELECT
    COALESCE( (SELECT SUM(dcm.cantidad*dcm.pre_unitario)
               FROM public.deta_comp_materias dcm
               WHERE dcm.id_compra = v_id), 0)
  + COALESCE( (SELECT SUM(dcp.cantidad*dcp.pre_unitario)
               FROM public.deta_comp_producto dcp
               WHERE dcp.id_compra = v_id), 0)
  INTO v_total;

  UPDATE public.compras c
     SET total = round(v_total, 0)
   WHERE c.id_compra = v_id;

  RETURN QUERY SELECT v_id, round(v_total, 0);
END;
$$;


ALTER FUNCTION public.save_compra(p_id_compra integer, p_id_proveedor integer, p_fec_compra timestamp with time zone, p_detalles jsonb) OWNER TO manso;

--
-- Name: save_materia_prima(integer, text, text, boolean, jsonb); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.save_materia_prima(p_id_mat_prima integer, p_nombre text, p_unidad text, p_activo boolean, p_proveedores jsonb DEFAULT '[]'::jsonb) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
DECLARE
  v_id INT;
BEGIN
  IF p_id_mat_prima IS NULL THEN
    INSERT INTO public.mate_primas (nombre, unidad, activo)
    VALUES (p_nombre, p_unidad, COALESCE(p_activo, TRUE))
    RETURNING mate_primas.id_mat_prima INTO v_id;
  ELSE
    UPDATE public.mate_primas mp
       SET nombre = p_nombre,
           unidad = p_unidad,
           activo = COALESCE(p_activo, TRUE)
     WHERE mp.id_mat_prima = p_id_mat_prima;
    v_id := p_id_mat_prima;
  END IF;

  -- Sincronizar proveedores: borrar todos y re-crear a partir de JSONB
  DELETE FROM public.prov_mate_prima pmp WHERE pmp.id_mat_prima = v_id;

  INSERT INTO public.prov_mate_prima (id_proveedor, id_mat_prima)
  SELECT (e->>0)::INT    AS id_proveedor,    -- elementos JSON como enteros (array simple)
         v_id            AS id_mat_prima
  FROM jsonb_array_elements(COALESCE(p_proveedores, '[]'::jsonb)) AS e
  WHERE (e->>0) ~ '^\d+$'; -- solo enteros

  RETURN v_id;
END;
$_$;


ALTER FUNCTION public.save_materia_prima(p_id_mat_prima integer, p_nombre text, p_unidad text, p_activo boolean, p_proveedores jsonb) OWNER TO manso;

--
-- Name: save_producto(integer, text, text, numeric, boolean, integer, jsonb); Type: FUNCTION; Schema: public; Owner: manso
--

CREATE FUNCTION public.save_producto(p_id_producto integer, p_nombre text, p_img_producto text, p_precio numeric, p_activo boolean, p_id_categoria integer, p_receta jsonb DEFAULT '[]'::jsonb) RETURNS integer
    LANGUAGE plpgsql
    AS $_$
DECLARE
  v_id INT;
BEGIN
  IF p_id_producto IS NULL THEN
    INSERT INTO public.productos (nombre, img_producto, precio, activo, id_categoria)
    VALUES (p_nombre, p_img_producto, p_precio, COALESCE(p_activo, TRUE), p_id_categoria)
    RETURNING productos.id_producto INTO v_id;
  ELSE
    UPDATE public.productos p
       SET nombre       = p_nombre,
           img_producto = p_img_producto,
           precio       = p_precio,
           activo       = COALESCE(p_activo, TRUE),
           id_categoria = p_id_categoria
     WHERE p.id_producto = p_id_producto;
    v_id := p_id_producto;
  END IF;

  -- Limpia receta actual
  DELETE FROM public.receta_producto rp WHERE rp.id_producto = v_id;

  -- Inserta SOLO ítems válidos (id entero positivo y cantidad > 0), redondeo a 3 decimales
  INSERT INTO public.receta_producto (id_producto, id_mat_prima, qty_por_unidad)
  SELECT 
    v_id,
    (rec->>'id_mat_prima')::INT,
    ROUND((rec->>'qty_por_unidad')::NUMERIC, 3)
  FROM jsonb_array_elements(COALESCE(p_receta, '[]'::jsonb)) AS rec
  WHERE
    (rec->>'id_mat_prima') ~ '^\d+$'
    AND (rec->>'id_mat_prima')::INT > 0
    AND (rec->>'qty_por_unidad') ~ '^\d+(\.\d+)?$'
    AND (rec->>'qty_por_unidad')::NUMERIC > 0;

  RETURN v_id;
END;
$_$;


ALTER FUNCTION public.save_producto(p_id_producto integer, p_nombre text, p_img_producto text, p_precio numeric, p_activo boolean, p_id_categoria integer, p_receta jsonb) OWNER TO manso;

--
-- Name: asistencia_intervalo; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.asistencia_intervalo (
    id_intervalo bigint NOT NULL,
    id_usuario integer NOT NULL,
    fecha date NOT NULL,
    desde timestamp with time zone NOT NULL,
    hasta timestamp with time zone NOT NULL,
    dur_min numeric(10,2) NOT NULL,
    origen text,
    created_at timestamp with time zone DEFAULT now() NOT NULL,
    CONSTRAINT chk_ai_orden CHECK ((hasta > desde))
);


ALTER TABLE public.asistencia_intervalo OWNER TO manso;

--
-- Name: asistencia_intervalo_id_intervalo_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.asistencia_intervalo_id_intervalo_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.asistencia_intervalo_id_intervalo_seq OWNER TO manso;

--
-- Name: asistencia_intervalo_id_intervalo_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.asistencia_intervalo_id_intervalo_seq OWNED BY public.asistencia_intervalo.id_intervalo;


--
-- Name: asistencia_raw; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.asistencia_raw (
    id_raw bigint NOT NULL,
    id_usuario integer NOT NULL,
    ts timestamp with time zone NOT NULL,
    modo text,
    origen text,
    created_at timestamp with time zone DEFAULT now() NOT NULL
);


ALTER TABLE public.asistencia_raw OWNER TO manso;

--
-- Name: asistencia_raw_id_raw_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.asistencia_raw_id_raw_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.asistencia_raw_id_raw_seq OWNER TO manso;

--
-- Name: asistencia_raw_id_raw_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.asistencia_raw_id_raw_seq OWNED BY public.asistencia_raw.id_raw;


--
-- Name: asistencia_resumen_diario; Type: VIEW; Schema: public; Owner: manso
--

CREATE VIEW public.asistencia_resumen_diario AS
 SELECT ai.id_usuario,
    u.documento,
    u.nombre,
    u.apellido,
    ai.fecha,
    sum(ai.dur_min) AS minutos_dia,
    round((sum(ai.dur_min) / 60.0), 2) AS horas_dia,
    count(*) AS pares_dia
   FROM (public.asistencia_intervalo ai
     JOIN public.usuarios u USING (id_usuario))
  GROUP BY ai.id_usuario, u.documento, u.nombre, u.apellido, ai.fecha
  ORDER BY ai.id_usuario, ai.fecha;


ALTER VIEW public.asistencia_resumen_diario OWNER TO manso;

--
-- Name: categorias; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.categorias (
    id_categoria integer NOT NULL,
    nombre text NOT NULL,
    visible boolean DEFAULT true
);


ALTER TABLE public.categorias OWNER TO manso;

--
-- Name: categorias_id_categoria_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.categorias_id_categoria_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.categorias_id_categoria_seq OWNER TO manso;

--
-- Name: categorias_id_categoria_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.categorias_id_categoria_seq OWNED BY public.categorias.id_categoria;


--
-- Name: clientes; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.clientes (
    id_cliente integer NOT NULL,
    nombre text NOT NULL,
    correo text,
    telefono text,
    fec_nacimiento date,
    activo boolean DEFAULT true
);


ALTER TABLE public.clientes OWNER TO manso;

--
-- Name: clientes_id_cliente_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.clientes_id_cliente_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.clientes_id_cliente_seq OWNER TO manso;

--
-- Name: clientes_id_cliente_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.clientes_id_cliente_seq OWNED BY public.clientes.id_cliente;


--
-- Name: comandas_id_comanda_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.comandas_id_comanda_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.comandas_id_comanda_seq OWNER TO manso;

--
-- Name: comandas_id_comanda_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.comandas_id_comanda_seq OWNED BY public.comandas.id_comanda;


--
-- Name: compras; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.compras (
    id_compra integer NOT NULL,
    id_proveedor integer NOT NULL,
    fec_compra timestamp without time zone NOT NULL,
    total numeric(14,2)
);


ALTER TABLE public.compras OWNER TO manso;

--
-- Name: compras_id_compra_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.compras_id_compra_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.compras_id_compra_seq OWNER TO manso;

--
-- Name: compras_id_compra_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.compras_id_compra_seq OWNED BY public.compras.id_compra;


--
-- Name: deta_comandas_id_det_comanda_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.deta_comandas_id_det_comanda_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.deta_comandas_id_det_comanda_seq OWNER TO manso;

--
-- Name: deta_comandas_id_det_comanda_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.deta_comandas_id_det_comanda_seq OWNED BY public.deta_comandas.id_det_comanda;


--
-- Name: deta_comp_materias; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.deta_comp_materias (
    id_compra integer NOT NULL,
    id_mat_prima integer NOT NULL,
    cantidad numeric(12,3) NOT NULL,
    pre_unitario numeric(12,2) NOT NULL,
    CONSTRAINT deta_comp_materias_cantidad_check CHECK ((cantidad > (0)::numeric)),
    CONSTRAINT deta_comp_materias_pre_unitario_check CHECK ((pre_unitario >= (0)::numeric))
);


ALTER TABLE public.deta_comp_materias OWNER TO manso;

--
-- Name: deta_comp_producto; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.deta_comp_producto (
    id_compra integer NOT NULL,
    id_producto integer NOT NULL,
    cantidad numeric(12,3) NOT NULL,
    pre_unitario numeric(12,2) NOT NULL,
    CONSTRAINT deta_comp_producto_cantidad_check CHECK ((cantidad > (0)::numeric)),
    CONSTRAINT deta_comp_producto_pre_unitario_check CHECK ((pre_unitario >= (0)::numeric))
);


ALTER TABLE public.deta_comp_producto OWNER TO manso;

--
-- Name: mate_primas; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.mate_primas (
    id_mat_prima integer NOT NULL,
    nombre text NOT NULL,
    unidad text NOT NULL,
    activo boolean DEFAULT true
);


ALTER TABLE public.mate_primas OWNER TO manso;

--
-- Name: mate_primas_id_mat_prima_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.mate_primas_id_mat_prima_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.mate_primas_id_mat_prima_seq OWNER TO manso;

--
-- Name: mate_primas_id_mat_prima_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.mate_primas_id_mat_prima_seq OWNED BY public.mate_primas.id_mat_prima;


--
-- Name: mesas_id_mesa_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.mesas_id_mesa_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.mesas_id_mesa_seq OWNER TO manso;

--
-- Name: mesas_id_mesa_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.mesas_id_mesa_seq OWNED BY public.mesas.id_mesa;


--
-- Name: productos; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.productos (
    id_producto integer NOT NULL,
    nombre text NOT NULL,
    img_producto character varying(255) DEFAULT 'img/productos/img_producto.png'::character varying NOT NULL,
    precio integer NOT NULL,
    activo boolean DEFAULT true,
    id_categoria integer NOT NULL,
    CONSTRAINT productos_precio_check CHECK (((precio)::numeric >= (0)::numeric)),
    CONSTRAINT productos_precio_nn CHECK ((precio >= 0))
);


ALTER TABLE public.productos OWNER TO manso;

--
-- Name: productos_id_producto_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.productos_id_producto_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.productos_id_producto_seq OWNER TO manso;

--
-- Name: productos_id_producto_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.productos_id_producto_seq OWNED BY public.productos.id_producto;


--
-- Name: prov_mate_prima; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.prov_mate_prima (
    id_proveedor integer NOT NULL,
    id_mat_prima integer NOT NULL
);


ALTER TABLE public.prov_mate_prima OWNER TO manso;

--
-- Name: prov_producto; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.prov_producto (
    id_proveedor integer NOT NULL,
    id_producto integer NOT NULL
);


ALTER TABLE public.prov_producto OWNER TO manso;

--
-- Name: proveedores; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.proveedores (
    id_proveedor integer NOT NULL,
    rut text,
    raz_social text NOT NULL,
    direccion text,
    contacto text
);


ALTER TABLE public.proveedores OWNER TO manso;

--
-- Name: proveedores_id_proveedor_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.proveedores_id_proveedor_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.proveedores_id_proveedor_seq OWNER TO manso;

--
-- Name: proveedores_id_proveedor_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.proveedores_id_proveedor_seq OWNED BY public.proveedores.id_proveedor;


--
-- Name: receta_producto; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.receta_producto (
    id_producto integer NOT NULL,
    id_mat_prima integer NOT NULL,
    qty_por_unidad numeric(12,3) NOT NULL,
    CONSTRAINT receta_producto_qty_por_unidad_check CHECK ((qty_por_unidad > (0)::numeric))
);


ALTER TABLE public.receta_producto OWNER TO manso;

--
-- Name: roles; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.roles (
    id_rol integer NOT NULL,
    nombre text NOT NULL
);


ALTER TABLE public.roles OWNER TO manso;

--
-- Name: roles_id_rol_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.roles_id_rol_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.roles_id_rol_seq OWNER TO manso;

--
-- Name: roles_id_rol_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.roles_id_rol_seq OWNED BY public.roles.id_rol;


--
-- Name: usua_roles; Type: TABLE; Schema: public; Owner: manso
--

CREATE TABLE public.usua_roles (
    id_usuario integer NOT NULL,
    id_rol integer NOT NULL,
    fec_asignacion timestamp without time zone DEFAULT now(),
    autor integer,
    activo boolean DEFAULT true
);


ALTER TABLE public.usua_roles OWNER TO manso;

--
-- Name: usuarios_id_usuario_seq; Type: SEQUENCE; Schema: public; Owner: manso
--

CREATE SEQUENCE public.usuarios_id_usuario_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER SEQUENCE public.usuarios_id_usuario_seq OWNER TO manso;

--
-- Name: usuarios_id_usuario_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: manso
--

ALTER SEQUENCE public.usuarios_id_usuario_seq OWNED BY public.usuarios.id_usuario;


--
-- Name: v_comandas_detalle_base; Type: VIEW; Schema: public; Owner: manso
--

CREATE VIEW public.v_comandas_detalle_base AS
 SELECT c.id_comanda,
    c.fec_creacion,
    c.fec_cierre,
    c.estado,
    c.observaciones,
    u.id_usuario,
    u.nombre AS usuario_nombre,
    u.apellido AS usuario_apellido,
    m.id_mesa,
    m.numero AS mesa_numero,
    m.apodo AS mesa_apodo,
    d.id_producto,
    p.nombre AS producto_nombre,
    d.cantidad,
    d.pre_unitario,
    (d.cantidad * d.pre_unitario) AS subtotal
   FROM ((((public.comandas c
     JOIN public.usuarios u ON ((u.id_usuario = c.id_usuario)))
     JOIN public.mesas m ON ((m.id_mesa = c.id_mesa)))
     LEFT JOIN public.deta_comandas d ON ((d.id_comanda = c.id_comanda)))
     LEFT JOIN public.productos p ON ((p.id_producto = d.id_producto)));


ALTER VIEW public.v_comandas_detalle_base OWNER TO manso;

--
-- Name: v_comandas_detalle_items; Type: VIEW; Schema: public; Owner: manso
--

CREATE VIEW public.v_comandas_detalle_items AS
 SELECT d.id_comanda,
    d.id_det_comanda,
    d.id_producto,
    p.nombre AS producto_nombre,
    d.cantidad,
    d.pre_unitario,
    (d.cantidad * d.pre_unitario) AS subtotal,
    d.observaciones
   FROM (public.deta_comandas d
     JOIN public.productos p ON ((p.id_producto = d.id_producto)));


ALTER VIEW public.v_comandas_detalle_items OWNER TO manso;

--
-- Name: v_comandas_detalle_json; Type: VIEW; Schema: public; Owner: manso
--

CREATE VIEW public.v_comandas_detalle_json AS
 SELECT id_comanda,
    jsonb_build_object('id_comanda', id_comanda, 'fec_creacion', fec_creacion, 'fec_cierre', fec_cierre, 'estado', estado, 'observaciones', observaciones, 'usuario', jsonb_build_object('id_usuario', id_usuario, 'nombre', usuario_nombre, 'apellido', usuario_apellido), 'mesa', jsonb_build_object('id_mesa', id_mesa, 'numero', mesa_numero, 'apodo', mesa_apodo), 'items', COALESCE(( SELECT jsonb_agg(jsonb_build_object('producto_id', b.id_producto, 'producto', b.producto_nombre, 'cantidad', b.cantidad, 'pre_unitario', b.pre_unitario, 'subtotal', b.subtotal) ORDER BY b.producto_nombre) AS jsonb_agg
           FROM public.v_comandas_detalle_base b
          WHERE ((b.id_comanda = h.id_comanda) AND (b.id_producto IS NOT NULL))), '[]'::jsonb), 'totales', jsonb_build_object('items', COALESCE(( SELECT count(*) AS count
           FROM public.v_comandas_detalle_base b
          WHERE ((b.id_comanda = h.id_comanda) AND (b.id_producto IS NOT NULL))), (0)::bigint), 'total', COALESCE(( SELECT sum(b.subtotal) AS sum
           FROM public.v_comandas_detalle_base b
          WHERE (b.id_comanda = h.id_comanda)), (0)::numeric))) AS data
   FROM ( SELECT DISTINCT v_comandas_detalle_base.id_comanda,
            v_comandas_detalle_base.fec_creacion,
            v_comandas_detalle_base.fec_cierre,
            v_comandas_detalle_base.estado,
            v_comandas_detalle_base.observaciones,
            v_comandas_detalle_base.id_usuario,
            v_comandas_detalle_base.usuario_nombre,
            v_comandas_detalle_base.usuario_apellido,
            v_comandas_detalle_base.id_mesa,
            v_comandas_detalle_base.mesa_numero,
            v_comandas_detalle_base.mesa_apodo
           FROM public.v_comandas_detalle_base) h;


ALTER VIEW public.v_comandas_detalle_json OWNER TO manso;

--
-- Name: vw_compras; Type: VIEW; Schema: public; Owner: manso
--

CREATE VIEW public.vw_compras AS
 SELECT c.id_compra,
    c.id_proveedor,
    p.raz_social AS proveedor,
    c.fec_compra,
    c.total
   FROM (public.compras c
     JOIN public.proveedores p USING (id_proveedor))
  ORDER BY c.fec_compra DESC, c.id_compra DESC;


ALTER VIEW public.vw_compras OWNER TO manso;

--
-- Name: vw_ticket_total; Type: VIEW; Schema: public; Owner: manso
--

CREATE VIEW public.vw_ticket_total AS
 WITH lineas AS (
         SELECT c.id_comanda,
            COALESCE(c.fec_cierre, (c.fec_creacion)::timestamp with time zone) AS fec_ticket,
            (COALESCE(dc.pre_unitario, (p.precio)::numeric, (0)::numeric))::numeric(14,2) AS pu,
            (COALESCE(dc.cantidad, (1)::numeric))::numeric(14,3) AS qty
           FROM ((public.comandas c
             JOIN public.deta_comandas dc ON ((dc.id_comanda = c.id_comanda)))
             LEFT JOIN public.productos p ON ((p.id_producto = dc.id_producto)))
        )
 SELECT id_comanda,
    fec_ticket,
    (sum((qty * pu)))::numeric(14,2) AS total
   FROM lineas
  GROUP BY id_comanda, fec_ticket;


ALTER VIEW public.vw_ticket_total OWNER TO manso;

--
-- Name: asistencia_intervalo id_intervalo; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.asistencia_intervalo ALTER COLUMN id_intervalo SET DEFAULT nextval('public.asistencia_intervalo_id_intervalo_seq'::regclass);


--
-- Name: asistencia_raw id_raw; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.asistencia_raw ALTER COLUMN id_raw SET DEFAULT nextval('public.asistencia_raw_id_raw_seq'::regclass);


--
-- Name: categorias id_categoria; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.categorias ALTER COLUMN id_categoria SET DEFAULT nextval('public.categorias_id_categoria_seq'::regclass);


--
-- Name: clientes id_cliente; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.clientes ALTER COLUMN id_cliente SET DEFAULT nextval('public.clientes_id_cliente_seq'::regclass);


--
-- Name: comandas id_comanda; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.comandas ALTER COLUMN id_comanda SET DEFAULT nextval('public.comandas_id_comanda_seq'::regclass);


--
-- Name: compras id_compra; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.compras ALTER COLUMN id_compra SET DEFAULT nextval('public.compras_id_compra_seq'::regclass);


--
-- Name: deta_comandas id_det_comanda; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comandas ALTER COLUMN id_det_comanda SET DEFAULT nextval('public.deta_comandas_id_det_comanda_seq'::regclass);


--
-- Name: mate_primas id_mat_prima; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.mate_primas ALTER COLUMN id_mat_prima SET DEFAULT nextval('public.mate_primas_id_mat_prima_seq'::regclass);


--
-- Name: mesas id_mesa; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.mesas ALTER COLUMN id_mesa SET DEFAULT nextval('public.mesas_id_mesa_seq'::regclass);


--
-- Name: productos id_producto; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.productos ALTER COLUMN id_producto SET DEFAULT nextval('public.productos_id_producto_seq'::regclass);


--
-- Name: proveedores id_proveedor; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.proveedores ALTER COLUMN id_proveedor SET DEFAULT nextval('public.proveedores_id_proveedor_seq'::regclass);


--
-- Name: roles id_rol; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.roles ALTER COLUMN id_rol SET DEFAULT nextval('public.roles_id_rol_seq'::regclass);


--
-- Name: usuarios id_usuario; Type: DEFAULT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.usuarios ALTER COLUMN id_usuario SET DEFAULT nextval('public.usuarios_id_usuario_seq'::regclass);


--
-- Data for Name: asistencia_intervalo; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.asistencia_intervalo (id_intervalo, id_usuario, fecha, desde, hasta, dur_min, origen, created_at) FROM stdin;
83	1	2025-08-29	2025-08-30 01:19:38+00	2025-08-30 01:26:19+00	6.68	delete_adjust	2025-08-30 04:42:43.597798+00
84	1	2025-08-29	2025-08-30 02:30:00+00	2025-08-30 02:46:40+00	16.67	delete_adjust	2025-08-30 04:42:43.597798+00
85	1	2025-08-30	2025-08-30 03:13:31+00	2025-08-30 03:36:03+00	22.53	delete_adjust	2025-08-30 04:42:43.597798+00
86	1	2025-08-30	2025-08-30 04:10:00+00	2025-08-30 04:12:00+00	2.00	delete_adjust	2025-08-30 04:42:43.597798+00
87	1	2025-08-30	2025-08-30 04:24:08+00	2025-08-30 04:38:56+00	14.80	delete_adjust	2025-08-30 04:42:43.597798+00
88	1	2025-08-30	2025-08-30 05:01:55+00	2025-08-30 05:10:00+00	8.08	delete_adjust	2025-08-30 04:42:43.597798+00
89	1	2025-08-27	2025-08-27 04:34:55+00	2025-08-27 06:35:08+00	120.22	AGL_001.txt	2025-08-30 04:43:13.749738+00
90	1	2025-08-29	2025-08-30 00:12:34+00	2025-08-30 00:47:24+00	34.83	AGL_001.txt	2025-08-30 04:43:13.749738+00
97	2	2025-01-02	2025-01-02 12:12:00+00	2025-01-02 14:48:00+00	156.00	manual_form	2025-08-30 04:45:59.234439+00
99	2	2025-01-02	2025-01-02 20:50:00+00	2025-01-03 02:48:00+00	358.00	manual_form	2025-08-30 04:46:45.672304+00
108	1	2025-01-01	2025-01-01 10:00:00+00	2025-01-01 16:00:00+00	360.00	manual_form	2025-09-01 21:03:36.046072+00
\.


--
-- Data for Name: asistencia_raw; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.asistencia_raw (id_raw, id_usuario, ts, modo, origen, created_at) FROM stdin;
1	1	2025-08-30 05:10:00+00	OUT	manual_form	2025-08-30 04:11:08.227836+00
2	1	2025-08-30 04:10:00+00	IN	manual_form	2025-08-30 04:11:08.227836+00
3	1	2025-08-30 04:12:00+00	OUT	manual_form	2025-08-30 04:12:30.456958+00
4	1	2025-08-30 02:30:00+00	IN	manual_form	2025-08-30 04:12:30.456958+00
22	1	2025-08-30 01:19:38+00	IN	AGL_001.txt	2025-08-30 04:32:09.754679+00
21	1	2025-08-30 01:26:19+00	OUT	AGL_001.txt	2025-08-30 04:32:09.754679+00
20	1	2025-08-30 02:46:40+00	OUT	AGL_001.txt	2025-08-30 04:32:09.754679+00
19	1	2025-08-30 03:13:31+00	IN	AGL_001.txt	2025-08-30 04:32:09.754679+00
18	1	2025-08-30 03:36:03+00	OUT	AGL_001.txt	2025-08-30 04:32:09.754679+00
17	1	2025-08-30 04:38:56+00	OUT	AGL_001.txt	2025-08-30 04:32:09.754679+00
16	1	2025-08-30 05:01:55+00	IN	AGL_001.txt	2025-08-30 04:32:09.754679+00
15	1	2025-08-30 04:24:08+00	IN	AGL_001.txt	2025-08-30 04:32:09.754679+00
71	2	2025-01-02 14:48:00+00	OUT	manual_form	2025-08-30 04:45:59.234439+00
72	2	2025-01-02 12:12:00+00	IN	manual_form	2025-08-30 04:45:59.234439+00
73	2	2025-01-03 02:48:00+00	OUT	manual_form	2025-08-30 04:46:45.672304+00
74	2	2025-01-02 20:50:00+00	IN	manual_form	2025-08-30 04:46:45.672304+00
60	1	2025-08-27 04:34:55+00	IN	AGL_001.txt	2025-08-30 04:43:13.749738+00
59	1	2025-08-27 06:35:08+00	OUT	AGL_001.txt	2025-08-30 04:43:13.749738+00
70	1	2025-08-30 00:12:34+00	IN	AGL_001.txt	2025-08-30 04:43:13.749738+00
69	1	2025-08-30 00:47:24+00	OUT	AGL_001.txt	2025-08-30 04:43:13.749738+00
87	1	2025-01-01 16:00:00+00	OUT	manual_form	2025-09-01 21:03:36.046072+00
88	1	2025-01-01 10:00:00+00	IN	manual_form	2025-09-01 21:03:36.046072+00
\.


--
-- Data for Name: categorias; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.categorias (id_categoria, nombre, visible) FROM stdin;
1	Cafetería	t
2	Café	t
3	Bar	t
4	Tragos y Refrescos	t
\.


--
-- Data for Name: clientes; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.clientes (id_cliente, nombre, correo, telefono, fec_nacimiento, activo) FROM stdin;
1	Familia	\N	\N	\N	t
\.


--
-- Data for Name: comandas; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.comandas (id_comanda, id_usuario, id_mesa, fec_creacion, estado, observaciones, fec_cierre) FROM stdin;
2	3	14	2025-08-25 18:47:57.398972	cerrada	\N	\N
49	1	14	2025-08-29 16:53:42.617246	cerrada	Auto blanco	2025-08-29 16:56:44.184737+00
4	1	1	2025-08-25 19:07:51.695426	cerrada	Pedido para una familia grande.	\N
3	1	1	2025-08-25 19:07:37.584356	cerrada	Pedido para una familia grande.	\N
1	3	14	2025-08-25 18:46:18.834688	cerrada	\N	\N
48	3	14	2025-08-29 16:53:06.77149	cerrada	Grande huevo	2025-08-29 16:56:45.225257+00
47	3	14	2025-08-29 16:52:22.556665	cerrada	Grande huevo	2025-08-29 16:56:46.440835+00
8	3	14	2025-08-29 02:57:22.46956	cerrada	\N	2025-08-29 03:47:50.750949+00
7	1	14	2025-08-29 02:56:29.755449	cerrada	\N	2025-08-29 04:31:33.254769+00
6	2	6	2025-08-25 19:09:25.280339	cerrada	\N	2025-08-29 04:32:29.813119+00
46	3	14	2025-08-29 16:51:23.011327	cerrada	Grande huevo	2025-08-29 16:56:47.457248+00
5	1	1	2025-08-25 19:08:08.596438	cerrada	\N	2025-08-29 04:35:24.52745+00
10	1	3	2025-08-29 04:41:51.354916	cerrada	\N	2025-08-29 04:48:01.548441+00
12	3	14	2025-08-29 04:48:53.292023	cerrada	\N	2025-08-29 05:17:41.133298+00
19	3	14	2025-08-29 05:49:56.258621	cerrada	\N	2025-08-29 05:50:10.286428+00
18	3	14	2025-08-29 05:49:13.120391	cerrada	\N	2025-08-29 05:50:11.319667+00
17	3	14	2025-08-29 05:46:54.548073	cerrada	oBSERVACIOOONNN	2025-08-29 05:50:12.331972+00
16	2	8	2025-08-29 05:46:23.763257	cerrada	oBSERVACIOOONNN	2025-08-29 05:50:13.37213+00
15	2	8	2025-08-29 05:46:18.69042	cerrada	oBSERVACIOOONNN	2025-08-29 05:50:14.334797+00
14	3	14	2025-08-29 05:19:28.908216	cerrada	jdwkjklqwndv	2025-08-29 05:50:15.26329+00
13	3	14	2025-08-29 04:58:36.159791	cerrada	hola	2025-08-29 05:50:16.511989+00
11	1	4	2025-08-29 04:48:36.541902	cerrada	\N	2025-08-29 05:50:17.832327+00
9	1	1	2025-08-29 04:37:56.310221	cerrada	Olaaa	2025-08-29 05:50:19.084017+00
20	3	14	2025-08-29 05:50:25.106438	cerrada	\N	2025-08-29 05:50:30.321838+00
29	2	6	2025-08-29 06:06:44.812528	cerrada	\N	2025-08-29 06:08:16.181067+00
28	3	14	2025-08-29 06:06:13.297627	cerrada	\N	2025-08-29 06:08:17.69094+00
27	1	1	2025-08-29 06:03:10.757812	cerrada	\N	2025-08-29 06:08:18.986658+00
26	1	8	2025-08-29 06:02:25.460776	cerrada	\N	2025-08-29 06:08:20.296605+00
25	1	8	2025-08-29 06:01:26.571144	cerrada	Sin gluten	2025-08-29 06:08:22.898867+00
24	1	1	2025-08-29 05:58:17.922202	cerrada	\N	2025-08-29 06:08:24.187839+00
23	1	1	2025-08-29 05:57:35.418369	cerrada	Observacionesssqaishfoiadhfohsdf	2025-08-29 06:08:25.558933+00
22	3	14	2025-08-29 05:54:44.675905	cerrada	\N	2025-08-29 06:08:27.55245+00
21	3	14	2025-08-29 05:51:54.451937	cerrada	\N	2025-08-29 06:08:29.094665+00
31	1	14	2025-08-29 16:10:31.619565	cerrada	TestObs,.-.-.	2025-08-29 16:13:11.693159+00
30	1	4	2025-08-29 14:46:00.062522	cerrada	123	2025-08-29 16:13:14.63311+00
52	1	12	2025-08-29 16:55:21.360321	cerrada	grande el huevo	2025-08-29 16:56:40.145463+00
51	1	14	2025-08-29 16:54:44.410546	cerrada	auto blanco	2025-08-29 16:56:41.279442+00
50	1	14	2025-08-29 16:54:08.307324	cerrada	auto blanco	2025-08-29 16:56:42.968122+00
45	3	14	2025-08-29 16:51:08.371592	cerrada	Grande huevo	2025-08-29 16:56:48.831883+00
44	3	14	2025-08-29 16:50:54.483409	cerrada	Grande huevo	2025-08-29 16:56:49.85665+00
43	1	14	2025-08-29 16:50:11.083248	cerrada	Grande huevo	2025-08-29 16:56:51.165809+00
41	1	13	2025-08-29 16:27:13.691181	cerrada	Mesa normal	2025-08-29 16:56:52.301133+00
42	3	12	2025-08-29 16:27:47.766143	cerrada	Mesa normal	2025-08-29 16:56:53.405482+00
40	1	14	2025-08-29 16:26:43.787724	cerrada	Observación huevo	2025-08-29 16:56:54.62857+00
39	3	14	2025-08-29 16:26:09.754868	cerrada	Observación del huevo	2025-08-29 16:56:55.865184+00
38	3	14	2025-08-29 16:25:43.366429	cerrada	Observación del huevo	2025-08-29 16:56:57.13223+00
37	1	14	2025-08-29 16:25:01.413168	cerrada	Observación del huevo	2025-08-29 16:56:58.590021+00
36	1	14	2025-08-29 16:24:23.587871	cerrada	Observación del huevo	2025-08-29 16:56:59.863697+00
35	3	14	2025-08-29 16:23:33.26689	cerrada	Observación del huevo	2025-08-29 16:57:01.082691+00
34	3	14	2025-08-29 16:23:27.385911	cerrada	Observación del huevo	2025-08-29 16:57:02.429882+00
33	1	5	2025-08-29 16:16:28.527735	cerrada	Esta es una observación	2025-08-29 16:57:03.761533+00
32	1	5	2025-08-29 16:15:54.377397	cerrada	Esta es una observación	2025-08-29 16:57:05.939418+00
53	3	8	2025-09-01 20:21:27.553491	abierta	\N	\N
54	3	14	2025-09-01 21:16:30.760241	abierta	Ana	\N
55	3	11	2025-09-02 00:22:18.600045	abierta	\N	\N
\.


--
-- Data for Name: compras; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.compras (id_compra, id_proveedor, fec_compra, total) FROM stdin;
36	4	2025-07-29 08:02:33.489822	3806.00
37	1	2025-06-28 06:27:33.489822	2944.00
38	2	2025-08-22 22:23:33.489822	2866.00
39	2	2025-07-27 10:50:33.489822	7774.00
40	4	2025-08-03 21:28:33.489822	2373.00
41	1	2025-06-13 08:23:33.489822	1556.00
42	4	2025-07-29 02:30:33.489822	5941.00
43	4	2025-07-27 04:39:33.489822	3570.00
44	4	2025-07-10 04:43:33.489822	2648.00
45	1	2025-07-05 00:59:33.489822	11349.00
46	3	2025-07-04 18:17:33.489822	1671.00
47	3	2025-07-11 02:42:33.489822	2423.00
48	3	2025-07-16 14:47:33.489822	7851.00
49	3	2025-07-21 01:24:33.489822	4888.00
50	1	2025-06-05 13:46:33.489822	4985.00
51	3	2025-08-02 20:32:33.489822	144.00
52	1	2025-07-27 10:08:33.489822	1840.00
53	2	2025-08-22 08:01:33.489822	3398.00
55	2	2025-07-14 10:16:33.489822	632.00
56	2	2025-07-14 20:17:33.489822	6882.00
57	1	2025-06-17 15:01:33.489822	2974.00
58	2	2025-06-19 15:29:33.489822	2644.00
60	2	2025-06-09 15:01:33.489822	1436.00
61	3	2025-08-09 00:54:33.489822	6453.00
62	1	2025-08-26 16:17:33.489822	5450.00
63	1	2025-08-05 08:39:33.489822	8873.00
64	1	2025-07-19 12:38:33.489822	4093.00
65	1	2025-06-23 09:31:33.489822	666.00
59	1	2025-08-29 16:42:00	3248.00
54	2	2025-08-26 04:37:00	2483.00
\.


--
-- Data for Name: deta_comandas; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.deta_comandas (id_det_comanda, id_comanda, id_producto, cantidad, pre_unitario, observaciones) FROM stdin;
1	1	52	4.000	130.00	\N
2	2	40	1.000	250.00	\N
3	2	49	1.000	230.00	\N
4	2	24	3.000	100.00	\N
5	6	51	5.000	230.00	\N
6	6	33	2.000	550.00	\N
7	7	52	3.000	130.00	\N
8	8	33	3.000	550.00	\N
9	9	37	3.000	320.00	\N
10	10	52	1.000	130.00	\N
11	11	47	3.000	280.00	\N
12	11	43	1.000	230.00	\N
13	11	45	1.000	280.00	\N
14	11	44	1.000	150.00	\N
15	11	24	2.000	100.00	\N
16	12	28	1.000	100.00	\N
17	12	31	13.000	100.00	\N
18	13	51	2.000	230.00	\N
19	13	52	2.000	130.00	\N
20	14	52	1.000	130.00	\N
21	15	52	1.000	130.00	\N
22	15	51	1.000	230.00	\N
23	16	51	1.000	230.00	\N
24	16	52	1.000	130.00	\N
25	17	46	1.000	150.00	\N
26	18	47	1.000	280.00	\N
27	19	51	1.000	230.00	\N
28	19	48	1.000	230.00	\N
29	20	52	1.000	130.00	\N
30	20	49	1.000	230.00	\N
31	20	51	1.000	230.00	\N
32	22	49	1.000	230.00	\N
33	23	52	1.000	130.00	\N
34	23	48	1.000	230.00	\N
35	23	51	1.000	230.00	\N
36	23	50	1.000	230.00	\N
37	24	52	1.000	130.00	\N
38	24	51	1.000	230.00	\N
39	25	47	1.000	280.00	\N
40	25	49	1.000	230.00	\N
41	25	50	1.000	230.00	\N
42	26	50	1.000	230.00	\N
43	26	49	1.000	230.00	\N
44	27	50	3.000	230.00	\N
45	27	49	3.000	230.00	\N
46	28	51	1.000	230.00	\N
47	28	52	1.000	130.00	\N
48	28	45	1.000	280.00	\N
49	28	50	1.000	230.00	\N
50	29	48	2.000	230.00	\N
51	29	49	6.000	230.00	\N
52	29	47	2.000	280.00	\N
54	30	20	3.000	140.00	\N
53	30	16	1.000	100.00	\N
55	30	17	1.000	150.00	\N
56	31	51	1.000	230.00	\N
57	31	23	1.000	180.00	\N
58	31	52	2.000	140.00	\N
59	31	33	1.000	550.00	\N
60	33	9	2.000	120.00	\N
61	33	18	1.000	80.00	\N
62	33	2	1.000	60.00	\N
63	34	3	1.000	60.00	\N
64	34	21	1.000	180.00	\N
65	34	33	1.000	550.00	\N
66	34	23	2.000	180.00	\N
67	36	33	1.000	550.00	\N
68	36	49	1.000	230.00	\N
69	36	3	1.000	60.00	\N
70	36	6	1.000	50.00	\N
71	36	11	1.000	120.00	\N
72	37	3	1.000	60.00	\N
73	37	6	1.000	50.00	\N
74	37	49	1.000	230.00	\N
75	38	38	4.000	250.00	\N
76	38	33	1.000	550.00	\N
77	38	50	1.000	230.00	\N
78	38	10	1.000	120.00	\N
79	38	52	1.000	140.00	\N
80	38	9	1.000	120.00	\N
81	39	33	1.000	550.00	\N
82	39	38	4.000	250.00	\N
83	40	52	1.000	140.00	\N
84	40	29	1.000	80.00	\N
85	40	46	1.000	150.00	\N
86	40	49	1.000	230.00	\N
87	40	10	1.000	120.00	\N
88	40	11	6.000	120.00	\N
89	41	4	1.000	250.00	\N
90	41	8	1.000	120.00	\N
91	42	46	1.000	150.00	\N
92	42	49	1.000	230.00	\N
93	42	44	1.000	150.00	\N
94	43	33	1.000	550.00	\N
95	43	25	1.000	180.00	\N
96	43	16	1.000	100.00	\N
97	43	24	1.000	100.00	\N
98	43	47	2.000	280.00	\N
99	44	46	1.000	150.00	\N
100	45	46	1.000	150.00	\N
101	46	46	1.000	150.00	\N
102	47	51	1.000	230.00	\N
103	48	50	1.000	230.00	\N
104	49	47	1.000	280.00	\N
105	49	33	2.000	550.00	\N
106	51	33	1.000	550.00	\N
107	51	47	1.000	280.00	\N
108	52	24	1.000	100.00	\N
109	52	25	1.000	180.00	\N
110	52	16	1.000	100.00	\N
111	53	52	10.000	130.00	\N
112	53	23	11.000	180.00	\N
113	53	33	10.000	550.00	\N
114	54	50	2.000	230.00	\N
115	54	52	2.000	130.00	\N
116	55	33	2.000	550.00	\N
117	55	52	2.000	130.00	\N
\.


--
-- Data for Name: deta_comp_materias; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.deta_comp_materias (id_compra, id_mat_prima, cantidad, pre_unitario) FROM stdin;
36	5	1.019	322.00
36	9	1.370	80.00
36	10	5.755	232.00
38	3	7.311	392.00
39	1	6.840	447.00
39	10	7.533	397.00
40	9	2.636	283.00
40	8	8.262	151.00
41	7	3.794	410.00
43	3	5.017	293.00
44	4	8.652	306.00
45	6	9.781	426.00
46	7	3.017	422.00
48	1	0.735	511.00
48	3	5.249	373.00
49	1	9.816	498.00
50	1	2.517	459.00
50	7	2.785	239.00
50	2	3.788	392.00
52	6	7.542	244.00
53	3	4.332	522.00
55	6	4.937	128.00
56	5	6.062	45.00
57	9	1.806	465.00
57	5	4.283	275.00
57	7	1.861	402.00
57	3	4.002	52.00
58	1	3.379	471.00
60	2	0.588	216.00
61	10	13.011	327.00
62	10	4.719	405.00
62	9	4.646	295.00
62	1	3.242	338.00
63	6	8.843	457.00
63	7	6.086	270.00
63	8	6.852	394.00
63	1	1.678	147.00
65	1	4.788	139.00
59	9	1.000	590.00
54	3	2.000	157.00
54	6	2.000	376.00
54	9	4.000	67.00
\.


--
-- Data for Name: deta_comp_producto; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.deta_comp_producto (id_compra, id_producto, cantidad, pre_unitario) FROM stdin;
36	31	8.500	35.00
36	33	8.224	211.00
37	19	2.839	238.00
37	51	5.961	162.00
37	36	8.570	152.00
39	12	2.329	515.00
39	2	2.859	184.00
40	13	1.521	63.00
40	2	2.897	98.00
42	50	8.152	516.00
42	15	8.067	215.00
43	26	2.209	314.00
43	14	5.892	179.00
43	33	2.023	174.00
45	40	9.248	434.00
45	27	5.979	530.00
46	46	2.919	87.00
46	32	0.658	219.00
47	17	7.792	225.00
47	34	2.923	229.00
48	2	8.937	268.00
48	14	8.415	371.00
50	9	1.573	516.00
50	14	1.940	447.00
51	41	1.598	90.00
53	40	1.525	416.00
53	38	2.629	191.00
56	1	5.752	412.00
56	42	9.845	378.00
56	7	2.073	250.00
58	14	6.745	156.00
60	34	9.698	135.00
61	26	3.828	460.00
61	22	1.325	330.00
62	8	8.369	105.00
62	27	0.812	238.00
63	13	0.730	332.00
64	46	9.524	257.00
64	22	1.355	431.00
64	47	6.969	99.00
64	43	2.123	175.00
59	39	6.000	443.00
54	16	3.000	383.00
\.


--
-- Data for Name: mate_primas; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.mate_primas (id_mat_prima, nombre, unidad, activo) FROM stdin;
2	Huevo	u	t
3	Harina	gr	t
4	Avena	gr	t
1	Capsulas	u	t
9	Queso Azul San Ignacio	gr	t
10	Panceta	gr	t
8	Sal	gr	t
7	Sobres de Azucar	u	t
6	Azucar	gr	t
5	Bondiola cocida	gr	t
\.


--
-- Data for Name: mesas; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.mesas (id_mesa, numero, apodo, estado) FROM stdin;
1	1	Living princial	libre
2	2	Ventanal izquierdo	libre
3	3	Primer mesa contra la baranda	libre
4	4	Ventanal derecho	libre
5	5	Segunda mesa contra la baranda	libre
6	6	Junto a Juana	libre
7	7	Mostrador/Barra	libre
8	8	Booth derecho	libre
9	9	Booth izquierdo	libre
10	10	Living secundario	libre
11	11	Zona del Pool	libre
12	12	Cowork	libre
13	13	Mesa del fuego	libre
14	14	Takeaway	libre
\.


--
-- Data for Name: productos; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.productos (id_producto, nombre, img_producto, precio, activo, id_categoria) FROM stdin;
17	Cheesecake	img/productos/img_producto.png	250	t	1
2	Alfajores de Maicena	img/productos/img_producto.png	60	t	1
3	Alfajores sin TACC	img/productos/img_producto.png	60	t	1
4	Sandwich tostado LyC	img/productos/img_producto.png	250	t	1
5	Sandwich tostado JyQ	img/productos/img_producto.png	250	t	1
6	Scones	img/productos/img_producto.png	50	t	1
7	Medialunas	img/productos/img_producto.png	80	t	1
8	Medialunas Rellenas	img/productos/img_producto.png	120	t	1
9	Cookies de Avena	img/productos/img_producto.png	120	t	1
10	Cookies de chocolate	img/productos/img_producto.png	120	t	1
11	Brownies con helado	img/productos/img_producto.png	120	t	1
12	Budín de banana	img/productos/img_producto.png	150	t	1
13	Budín de naranja	img/productos/img_producto.png	150	t	1
14	Tostadas	img/productos/img_producto.png	100	t	1
15	Tarteletas	img/productos/img_producto.png	150	t	1
16	Chocobomba	img/productos/img_producto.png	100	t	1
18	Carajillo Oriental	img/productos/img_producto.png	80	t	2
20	Latte	img/productos/img_producto.png	140	t	2
21	Latte de DDL	img/productos/img_producto.png	180	t	2
22	Latte de chocolate semi amargo	img/productos/img_producto.png	180	t	2
23	Latte de vainilla	img/productos/img_producto.png	180	t	2
24	Expresso	img/productos/img_producto.png	100	t	2
25	Expresso doble	img/productos/img_producto.png	180	t	2
26	Cortado	img/productos/img_producto.png	100	t	2
27	Lágrima	img/productos/img_producto.png	100	t	2
28	Americano	img/productos/img_producto.png	100	t	2
29	Té	img/productos/img_producto.png	80	t	2
30	Té con leche	img/productos/img_producto.png	100	t	2
31	Submarino	img/productos/img_producto.png	100	t	2
32	Muzzarela clásica	img/productos/img_producto.png	450	t	3
34	Margarita	img/productos/img_producto.png	500	t	3
35	Calzone	img/productos/img_producto.png	450	t	3
36	Fritas	img/productos/img_producto.png	250	t	3
37	Aros de cebolla	img/productos/img_producto.png	320	t	3
38	Papas con cheddar	img/productos/img_producto.png	250	t	3
41	Tostones	img/productos/img_producto.png	250	t	3
42	Corona chica	img/productos/img_producto.png	150	t	4
43	Corona grande	img/productos/img_producto.png	230	t	4
44	Patricia Dunkel (lata)	img/productos/img_producto.png	150	t	4
45	Patricia Dunkel (grande)	img/productos/img_producto.png	280	t	4
46	Zillertal (lata)	img/productos/img_producto.png	150	t	4
47	Zillertal (grande)	img/productos/img_producto.png	280	t	4
48	Patagonia Weisse	img/productos/img_producto.png	230	t	4
19	Cappuccino	img/productos/img_producto.png	140	t	2
50	Patagonia Bohemian	img/productos/img_producto.png	230	t	4
49	Patagonia 24.7	img/productos/img_producto.png	230	t	4
1	Desayuno americano para dos	img/productos/img_producto.png	800	t	1
51	Patagonia Amber Lager	img/productos/img_producto.png	240	t	4
33	Una Vaina Bien	img/productos/img_producto.png	550	t	3
40	Tequeños	img/productos/img_producto.png	250	f	3
52	Monster	img/productos/img_producto.png	140	t	4
39	Pastelitos	img/productos/img_producto.png	250	t	3
\.


--
-- Data for Name: prov_mate_prima; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.prov_mate_prima (id_proveedor, id_mat_prima) FROM stdin;
3	2
2	3
2	4
3	1
2	9
3	10
2	8
3	7
2	6
3	5
\.


--
-- Data for Name: prov_producto; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.prov_producto (id_proveedor, id_producto) FROM stdin;
\.


--
-- Data for Name: proveedores; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.proveedores (id_proveedor, rut, raz_social, direccion, contacto) FROM stdin;
1	217795000011	Emilupe S.R.L.	\N	091049216
2	216450470015	Finesa Trading S.A.	\N	094426877
3	\N	Otro	\N	\N
4	\N	Gara Gardo S en C	\N	\N
\.


--
-- Data for Name: receta_producto; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.receta_producto (id_producto, id_mat_prima, qty_por_unidad) FROM stdin;
28	1	1.000
19	1	1.000
50	7	1.000
49	8	1.000
17	2	2.000
17	3	21.500
1	2	1.000
1	10	10.000
51	6	1.000
33	3	60.000
33	2	25.000
52	5	1.000
39	10	1.000
39	3	1.000
\.


--
-- Data for Name: roles; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.roles (id_rol, nombre) FROM stdin;
1	Dueño
2	Cocinero
3	Barista
4	Barman
5	Bachero
6	Mozo
\.


--
-- Data for Name: usua_roles; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.usua_roles (id_usuario, id_rol, fec_asignacion, autor, activo) FROM stdin;
1	1	2025-08-25 14:39:39.204513	1	t
1	3	2025-08-25 14:39:39.204513	1	t
2	3	2025-08-25 14:39:39.204513	1	t
2	4	2025-08-25 14:39:39.204513	1	t
3	2	2025-08-25 14:39:39.204513	1	t
\.


--
-- Data for Name: usuarios; Type: TABLE DATA; Schema: public; Owner: manso
--

COPY public.usuarios (id_usuario, documento, img_perfil, nombre, apellido, correo, telefono, fec_nacimiento, activo) FROM stdin;
1	52809684	img_perfil.png	Mateo	Saldain	mateosaldain02@gmail.com	\N	2002-08-11	t
2	55683627	img_perfil.png	Cristopher	Moreno	\N	\N	2001-08-11	t
3	49953084	img_perfil.png	Bruno	Correa	\N	\N	1999-08-19	t
\.


--
-- Name: asistencia_intervalo_id_intervalo_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.asistencia_intervalo_id_intervalo_seq', 108, true);


--
-- Name: asistencia_raw_id_raw_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.asistencia_raw_id_raw_seq', 88, true);


--
-- Name: categorias_id_categoria_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.categorias_id_categoria_seq', 4, true);


--
-- Name: clientes_id_cliente_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.clientes_id_cliente_seq', 1, true);


--
-- Name: comandas_id_comanda_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.comandas_id_comanda_seq', 55, true);


--
-- Name: compras_id_compra_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.compras_id_compra_seq', 66, true);


--
-- Name: deta_comandas_id_det_comanda_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.deta_comandas_id_det_comanda_seq', 117, true);


--
-- Name: mate_primas_id_mat_prima_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.mate_primas_id_mat_prima_seq', 10, true);


--
-- Name: mesas_id_mesa_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.mesas_id_mesa_seq', 14, true);


--
-- Name: productos_id_producto_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.productos_id_producto_seq', 52, true);


--
-- Name: proveedores_id_proveedor_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.proveedores_id_proveedor_seq', 4, true);


--
-- Name: roles_id_rol_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.roles_id_rol_seq', 6, true);


--
-- Name: usuarios_id_usuario_seq; Type: SEQUENCE SET; Schema: public; Owner: manso
--

SELECT pg_catalog.setval('public.usuarios_id_usuario_seq', 3, true);


--
-- Name: asistencia_intervalo asistencia_intervalo_id_usuario_desde_hasta_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.asistencia_intervalo
    ADD CONSTRAINT asistencia_intervalo_id_usuario_desde_hasta_key UNIQUE (id_usuario, desde, hasta);


--
-- Name: asistencia_intervalo asistencia_intervalo_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.asistencia_intervalo
    ADD CONSTRAINT asistencia_intervalo_pkey PRIMARY KEY (id_intervalo);


--
-- Name: asistencia_raw asistencia_raw_id_usuario_ts_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.asistencia_raw
    ADD CONSTRAINT asistencia_raw_id_usuario_ts_key UNIQUE (id_usuario, ts);


--
-- Name: asistencia_raw asistencia_raw_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.asistencia_raw
    ADD CONSTRAINT asistencia_raw_pkey PRIMARY KEY (id_raw);


--
-- Name: categorias categorias_nombre_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.categorias
    ADD CONSTRAINT categorias_nombre_key UNIQUE (nombre);


--
-- Name: categorias categorias_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.categorias
    ADD CONSTRAINT categorias_pkey PRIMARY KEY (id_categoria);


--
-- Name: clientes clientes_correo_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.clientes
    ADD CONSTRAINT clientes_correo_key UNIQUE (correo);


--
-- Name: clientes clientes_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.clientes
    ADD CONSTRAINT clientes_pkey PRIMARY KEY (id_cliente);


--
-- Name: clientes clientes_telefono_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.clientes
    ADD CONSTRAINT clientes_telefono_key UNIQUE (telefono);


--
-- Name: comandas comandas_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.comandas
    ADD CONSTRAINT comandas_pkey PRIMARY KEY (id_comanda);


--
-- Name: compras compras_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.compras
    ADD CONSTRAINT compras_pkey PRIMARY KEY (id_compra);


--
-- Name: deta_comandas deta_comandas_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comandas
    ADD CONSTRAINT deta_comandas_pkey PRIMARY KEY (id_det_comanda);


--
-- Name: deta_comp_materias deta_comp_materias_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comp_materias
    ADD CONSTRAINT deta_comp_materias_pkey PRIMARY KEY (id_compra, id_mat_prima);


--
-- Name: deta_comp_producto deta_comp_producto_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comp_producto
    ADD CONSTRAINT deta_comp_producto_pkey PRIMARY KEY (id_compra, id_producto);


--
-- Name: mate_primas mate_primas_nombre_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.mate_primas
    ADD CONSTRAINT mate_primas_nombre_key UNIQUE (nombre);


--
-- Name: mate_primas mate_primas_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.mate_primas
    ADD CONSTRAINT mate_primas_pkey PRIMARY KEY (id_mat_prima);


--
-- Name: mesas mesas_apodo_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.mesas
    ADD CONSTRAINT mesas_apodo_key UNIQUE (apodo);


--
-- Name: mesas mesas_numero_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.mesas
    ADD CONSTRAINT mesas_numero_key UNIQUE (numero);


--
-- Name: mesas mesas_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.mesas
    ADD CONSTRAINT mesas_pkey PRIMARY KEY (id_mesa);


--
-- Name: productos productos_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.productos
    ADD CONSTRAINT productos_pkey PRIMARY KEY (id_producto);


--
-- Name: prov_mate_prima prov_mate_prima_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.prov_mate_prima
    ADD CONSTRAINT prov_mate_prima_pkey PRIMARY KEY (id_proveedor, id_mat_prima);


--
-- Name: prov_producto prov_producto_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.prov_producto
    ADD CONSTRAINT prov_producto_pkey PRIMARY KEY (id_proveedor, id_producto);


--
-- Name: proveedores proveedores_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.proveedores
    ADD CONSTRAINT proveedores_pkey PRIMARY KEY (id_proveedor);


--
-- Name: proveedores proveedores_rut_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.proveedores
    ADD CONSTRAINT proveedores_rut_key UNIQUE (rut);


--
-- Name: receta_producto receta_producto_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.receta_producto
    ADD CONSTRAINT receta_producto_pkey PRIMARY KEY (id_producto, id_mat_prima);


--
-- Name: roles roles_nombre_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.roles
    ADD CONSTRAINT roles_nombre_key UNIQUE (nombre);


--
-- Name: roles roles_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.roles
    ADD CONSTRAINT roles_pkey PRIMARY KEY (id_rol);


--
-- Name: usua_roles usua_roles_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.usua_roles
    ADD CONSTRAINT usua_roles_pkey PRIMARY KEY (id_usuario, id_rol);


--
-- Name: usuarios usuarios_documento_key; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.usuarios
    ADD CONSTRAINT usuarios_documento_key UNIQUE (documento);


--
-- Name: usuarios usuarios_pkey; Type: CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.usuarios
    ADD CONSTRAINT usuarios_pkey PRIMARY KEY (id_usuario);


--
-- Name: compras_fec_compra_idx; Type: INDEX; Schema: public; Owner: manso
--

CREATE INDEX compras_fec_compra_idx ON public.compras USING btree (fec_compra);


--
-- Name: idx_asist_int_usuario_fecha; Type: INDEX; Schema: public; Owner: manso
--

CREATE INDEX idx_asist_int_usuario_fecha ON public.asistencia_intervalo USING btree (id_usuario, fecha);


--
-- Name: idx_asist_raw_usuario_ts; Type: INDEX; Schema: public; Owner: manso
--

CREATE INDEX idx_asist_raw_usuario_ts ON public.asistencia_raw USING btree (id_usuario, ts);


--
-- Name: idx_detalle_comanda_comanda; Type: INDEX; Schema: public; Owner: manso
--

CREATE INDEX idx_detalle_comanda_comanda ON public.deta_comandas USING btree (id_comanda);


--
-- Name: idx_detalle_comanda_producto; Type: INDEX; Schema: public; Owner: manso
--

CREATE INDEX idx_detalle_comanda_producto ON public.deta_comandas USING btree (id_producto);


--
-- Name: ix_comandas_fec_cierre; Type: INDEX; Schema: public; Owner: manso
--

CREATE INDEX ix_comandas_fec_cierre ON public.comandas USING btree (fec_cierre);


--
-- Name: ix_comandas_id; Type: INDEX; Schema: public; Owner: manso
--

CREATE INDEX ix_comandas_id ON public.comandas USING btree (id_comanda);


--
-- Name: ix_deta_comandas_id_comanda; Type: INDEX; Schema: public; Owner: manso
--

CREATE INDEX ix_deta_comandas_id_comanda ON public.deta_comandas USING btree (id_comanda);


--
-- Name: ix_deta_comandas_id_producto; Type: INDEX; Schema: public; Owner: manso
--

CREATE INDEX ix_deta_comandas_id_producto ON public.deta_comandas USING btree (id_producto);


--
-- Name: asistencia_intervalo asistencia_intervalo_id_usuario_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.asistencia_intervalo
    ADD CONSTRAINT asistencia_intervalo_id_usuario_fkey FOREIGN KEY (id_usuario) REFERENCES public.usuarios(id_usuario) ON DELETE CASCADE;


--
-- Name: asistencia_raw asistencia_raw_id_usuario_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.asistencia_raw
    ADD CONSTRAINT asistencia_raw_id_usuario_fkey FOREIGN KEY (id_usuario) REFERENCES public.usuarios(id_usuario) ON DELETE CASCADE;


--
-- Name: comandas comandas_id_mesa_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.comandas
    ADD CONSTRAINT comandas_id_mesa_fkey FOREIGN KEY (id_mesa) REFERENCES public.mesas(id_mesa);


--
-- Name: comandas comandas_id_usuario_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.comandas
    ADD CONSTRAINT comandas_id_usuario_fkey FOREIGN KEY (id_usuario) REFERENCES public.usuarios(id_usuario);


--
-- Name: compras compras_id_proveedor_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.compras
    ADD CONSTRAINT compras_id_proveedor_fkey FOREIGN KEY (id_proveedor) REFERENCES public.proveedores(id_proveedor);


--
-- Name: deta_comandas deta_comandas_id_comanda_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comandas
    ADD CONSTRAINT deta_comandas_id_comanda_fkey FOREIGN KEY (id_comanda) REFERENCES public.comandas(id_comanda) ON DELETE CASCADE;


--
-- Name: deta_comandas deta_comandas_id_producto_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comandas
    ADD CONSTRAINT deta_comandas_id_producto_fkey FOREIGN KEY (id_producto) REFERENCES public.productos(id_producto);


--
-- Name: deta_comp_materias deta_comp_materias_id_compra_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comp_materias
    ADD CONSTRAINT deta_comp_materias_id_compra_fkey FOREIGN KEY (id_compra) REFERENCES public.compras(id_compra) ON DELETE CASCADE;


--
-- Name: deta_comp_materias deta_comp_materias_id_mat_prima_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comp_materias
    ADD CONSTRAINT deta_comp_materias_id_mat_prima_fkey FOREIGN KEY (id_mat_prima) REFERENCES public.mate_primas(id_mat_prima);


--
-- Name: deta_comp_producto deta_comp_producto_id_compra_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comp_producto
    ADD CONSTRAINT deta_comp_producto_id_compra_fkey FOREIGN KEY (id_compra) REFERENCES public.compras(id_compra) ON DELETE CASCADE;


--
-- Name: deta_comp_producto deta_comp_producto_id_producto_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.deta_comp_producto
    ADD CONSTRAINT deta_comp_producto_id_producto_fkey FOREIGN KEY (id_producto) REFERENCES public.productos(id_producto);


--
-- Name: productos productos_id_categoria_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.productos
    ADD CONSTRAINT productos_id_categoria_fkey FOREIGN KEY (id_categoria) REFERENCES public.categorias(id_categoria);


--
-- Name: prov_mate_prima prov_mate_prima_id_mat_prima_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.prov_mate_prima
    ADD CONSTRAINT prov_mate_prima_id_mat_prima_fkey FOREIGN KEY (id_mat_prima) REFERENCES public.mate_primas(id_mat_prima);


--
-- Name: prov_mate_prima prov_mate_prima_id_proveedor_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.prov_mate_prima
    ADD CONSTRAINT prov_mate_prima_id_proveedor_fkey FOREIGN KEY (id_proveedor) REFERENCES public.proveedores(id_proveedor) ON DELETE CASCADE;


--
-- Name: prov_producto prov_producto_id_producto_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.prov_producto
    ADD CONSTRAINT prov_producto_id_producto_fkey FOREIGN KEY (id_producto) REFERENCES public.productos(id_producto);


--
-- Name: prov_producto prov_producto_id_proveedor_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.prov_producto
    ADD CONSTRAINT prov_producto_id_proveedor_fkey FOREIGN KEY (id_proveedor) REFERENCES public.proveedores(id_proveedor) ON DELETE CASCADE;


--
-- Name: receta_producto receta_producto_id_mat_prima_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.receta_producto
    ADD CONSTRAINT receta_producto_id_mat_prima_fkey FOREIGN KEY (id_mat_prima) REFERENCES public.mate_primas(id_mat_prima);


--
-- Name: receta_producto receta_producto_id_producto_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.receta_producto
    ADD CONSTRAINT receta_producto_id_producto_fkey FOREIGN KEY (id_producto) REFERENCES public.productos(id_producto) ON DELETE CASCADE;


--
-- Name: usua_roles usua_roles_autor_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.usua_roles
    ADD CONSTRAINT usua_roles_autor_fkey FOREIGN KEY (autor) REFERENCES public.usuarios(id_usuario);


--
-- Name: usua_roles usua_roles_id_rol_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.usua_roles
    ADD CONSTRAINT usua_roles_id_rol_fkey FOREIGN KEY (id_rol) REFERENCES public.roles(id_rol);


--
-- Name: usua_roles usua_roles_id_usuario_fkey; Type: FK CONSTRAINT; Schema: public; Owner: manso
--

ALTER TABLE ONLY public.usua_roles
    ADD CONSTRAINT usua_roles_id_usuario_fkey FOREIGN KEY (id_usuario) REFERENCES public.usuarios(id_usuario) ON DELETE CASCADE;


--
-- PostgreSQL database dump complete
--

\unrestrict londHmqT4llS8Wof4ZnceO2dyFhn4jiR5xbaszMgZpMczgr6aVW6xQJxeUdqJwa

