-- adaugare coloana DEV_ORDL.id_sucursala + upgrade SP_CREEAZA_COMANDA_PROTOTIP

-- Rulat conectat ca schema tinta (ex: MARIUSM_AUTO), O SINGURA DATA per schema

BEGIN
  IF PACK_MIGRARE.COLUMNEXIST('DEV_ORDL','ID_SUCURSALA')=0 THEN
    EXECUTE IMMEDIATE 'ALTER TABLE DEV_ORDL ADD (id_sucursala NUMBER(10))';
  END IF;
END;
/

CREATE OR REPLACE PROCEDURE SP_CREEAZA_COMANDA_PROTOTIP(
  p_tip             IN  NUMBER,
  p_id_masiniclient IN  NUMBER,
  p_solicitari      IN  VARCHAR2,
  p_id_firma        IN  NUMBER,
  p_id_sucursala    IN  NUMBER DEFAULT NULL,
  p_id_ordl         OUT NUMBER,
  p_nrord           OUT VARCHAR2
) AS
  v_id_lucrare  NUMBER;
  v_seq         NUMBER;
  v_exists      NUMBER;
  v_now         DATE := SYSDATE;
BEGIN
  v_seq   := SEQ_NR_LUCRARE.NEXTVAL;
  p_nrord := 'P' || LPAD(p_id_firma, 2, '0') || '-' || v_seq;

  SELECT COUNT(*) INTO v_exists
    FROM NOM_LUCRARI
   WHERE sters = 0 AND nrord = p_nrord;
  IF v_exists > 0 THEN
    RAISE_APPLICATION_ERROR(-20001,
      'Mai exista o comanda cu numarul ' || p_nrord);
  END IF;

  INSERT INTO NOM_LUCRARI (nrord, id_mod)
    VALUES (p_nrord, 1200)
    RETURNING id_lucrare INTO v_id_lucrare;

  INSERT INTO DEV_ORDL (
    an, luna,
    id_lucrare,
    datai, dataoraad,
    id_util_ad,
    id_masiniclient,
    id_tip,
    solicitari_client,
    id_sucursala
  ) VALUES (
    EXTRACT(YEAR FROM v_now), EXTRACT(MONTH FROM v_now),
    v_id_lucrare,
    v_now, v_now,
    0,
    p_id_masiniclient,
    p_tip,
    p_solicitari,
    p_id_sucursala
  ) RETURNING id_ordl INTO p_id_ordl;
END SP_CREEAZA_COMANDA_PROTOTIP;
/

exec pack_migrare.UpdateVersiune('ff_2026_04_12_01_AUTO'); commit;
