execute PROCEDURE NOWA_WERSJA(#ID_APTEKI#,130.64);

SET TERM ^ ;
EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'KONTRAHENCI' and rf.RDB$FIELD_NAME = 'POWIAZANY')) then 
 execute statement 'alter table KONTRAHENCI ADD POWIAZANY char(1)';  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'KONTRAHENCI' and rf.RDB$FIELD_NAME = 'ZAGRANICZNY')) then 
 execute statement 'alter table kontrahenci add ZAGRANICZNY char(1)';  
END^

EXECUTE block as BEGIN
if (exists(select 1 from RDB$TRIGGERS where RDB$TRIGGER_NAME='KONTRAHENCI_PESEL')) then 
 execute statement 'drop TRIGGER KONTRAHENCI_PESEL';
END^

EXECUTE block as BEGIN
if (exists(select 1 from rdb$functions where rdb$function_name='DATA_BIEZ')) then 
 execute statement 'drop EXTERNAL FUNCTION DATA_BIEZ';
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'FAKT_ZB' and rf.RDB$FIELD_NAME = 'ZAKSIEGOWANA')) then 
 execute statement 'ALTER TABLE FAKT_ZB ADD ZAKSIEGOWANA char(1)';  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'OGOLNE' and rf.RDB$FIELD_NAME = 'OF_IMIE')) then 
 begin
 execute statement 'ALTER table OGOLNE ADD OF_IMIE VARCHAR(50)';  
 execute statement 'ALTER table OGOLNE ADD OF_NAZWISKO VARCHAR(50)'; 
 execute statement 'ALTER table OGOLNE ADD OF_DATA DATE';  
 end
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'POST_ZL' and rf.RDB$FIELD_NAME = 'POST_POD')) then 
begin
  execute statement 'ALTER TABLE POST_ZL ADD POST_POD VARCHAR(20)';   
  DELETE from SYNCLOGIN WHERE ID_SYNC=10 and IFUPDDATE > '14.12.2020' and #ID_APTEKI# <> 1; --hl7 w wersji 130.08
end 
END^

/* nie wszedzie przeszlo w 130 */
EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'BLPR' and rf.RDB$FIELD_NAME = 'KOD_CN'))
 then begin
 execute statement 'alter table BLPR ADD KOD_CN VARCHAR(50)';   
 UPDATE OGOLNE o set o.BLOZ_DATA = NULL where o.id_apteki=#ID_APTEKI#;
 end
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'ZDST' and rf.RDB$FIELD_NAME = 'DATA_ZAMKN')) then 
begin
 execute statement 'ALTER TABLE ZDST ADD DATA_ZAMKN DATE'; 

end 
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'OGOLNE' and rf.RDB$FIELD_NAME = 'ID_KS')) then 
 execute statement 'alter table ogolne ADD id_ks int';  
END^


EXECUTE block as BEGIN
if (exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'USERS' and rf.RDB$FIELD_NAME = 'OSTRZEZENIA')) then 
 execute statement 'ALTER TABLE USERS DROP OSTRZEZENIA';  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'ZDST' and rf.RDB$FIELD_NAME = 'ID_ZAM')) then 
 begin
 execute statement 'ALTER TABLE ZDST ADD id_zam INTEGER';  
 execute statement 'ALTER TABLE ZDST ADD CONSTRAINT FK_ZDST_ZAMINFO FOREIGN KEY (ID_ZAM,ID_APTEKI) REFERENCES ZAMINFO (ID_ZAM,ID_APTEKI) ON DELETE SET NULL';
 end
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'WNIOSKI_UMOWY' and rf.RDB$FIELD_NAME = 'KOD_UMOWY_DRUK')) then 
 execute statement 'ALTER TABLE WNIOSKI_UMOWY ADD KOD_UMOWY_DRUK VARCHAR(30)';  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'EPRUF_RAPORTY' and rf.RDB$FIELD_NAME = 'IFINSUSER')) then 
 begin
 execute statement 'Alter table EPRUF_RAPORTY add IFINSUSER varchar(20) default USER';  
 execute statement "Alter table EPRUF_RAPORTY add IFINSDATE TIMESTAMP default 'NOW'";
 execute statement "ALTER TABLE OGOLNE ADD EPRUF_RAP_LAST VARCHAR(40)"; 
 end
END^

EXECUTE block as BEGIN
if (exists(select 1 from RDB$TRIGGERS where RDB$TRIGGER_NAME='UPDB_DOSTAWY')) then 
 execute statement 'drop TRIGGER UPDB_DOSTAWY';
END^


EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'KONTRAHENCI' and rf.RDB$FIELD_NAME = 'SPRAWDZONY')) then 
 execute statement "alter table KONTRAHENCI add SPRAWDZONY char(1) default 'N'";  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'SPRZEDAZDEL' and rf.RDB$FIELD_NAME = 'ID_OSOZ')) then 
 execute statement "ALTER TABLE SPRZEDAZDEL ADD ID_OSOZ Varchar(20)";  
END^

EXECUTE block as BEGIN
if (exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'BRAKDEF' and rf.RDB$FIELD_NAME = 'ZALOZYL')) then 
 begin
 execute statement "update brakdef set ifinsdate=zalozono,ifinsuser=zalozyl,ifupddate=ifupddate+0.00000001 where ifinsdate is null and zalozono is not null";   
 execute statement "ALTER TABLE BRAKDEF DROP ZALOZYL";  
 execute statement "ALTER TABLE BRAKDEF DROP ZALOZONO";   
 end
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'SYNCCBT')) then 
 execute statement "CREATE TABLE SYNCCBT
(
  ID_APTEKI apteka,  
  ID_CBT Integer ,
  k3 Char(7),
  k6 Varchar(14),
  k7 Varchar(30),
  k15 Varchar(3),
  k22 Varchar(5),
  k24 Varchar(4),
  IFUPDDATE Timestamp DEFAULT 'NOW',
  PRIMARY KEY (ID_CBT,ID_APTEKI)
)";  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'CBT_ZAPYTANIA')) then 
 execute statement "CREATE TABLE CBT_ZAPYTANIA (
  ID_CBT INTEGER NOT NULL,
  ID_APTEKI INTEGER NOT NULL,
  KOMENTARZ VARCHAR(1024),
  ILOSC INTEGER DEFAULT 1,
  IFUPDDATE TIMESTAMP DEFAULT 'NOW',
  IFUPDUSER VARCHAR(10) DEFAULT USER,
  IFINSUSER VARCHAR(20) DEFAULT USER,
  IFINSDATE TIMESTAMP DEFAULT 'NOW' NOT NULL ,
  PRIMARY KEY (ID_CBT,ID_APTEKI,IFINSDATE)
)";  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'DERMO')) then 
 execute statement "CREATE TABLE DERMO(ID_APTEKI Integer NOT NULL,
LISTA Varchar(2000),
PRIMARY KEY (ID_APTEKI))";
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$INDEX_SEGMENTS where RDB$INDEX_NAME='ZAMPAK_ZB')) then 
 execute statement 'CREATE INDEX ZAMPAK_ZB on ZAMPAK(id_zbiorcze)';
END^ 

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'RZDST' and rf.RDB$FIELD_NAME = 'WN_IDP')) then 
 execute statement "ALTER TABLE RZDST ADD WN_IDP Integer";  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'OGOLNE' and rf.RDB$FIELD_NAME = 'NAPR_DTZAMK')) then 
 execute statement 'alter table ogolne ADD NAPR_DTZAMK timestamp';  
END^

EXECUTE block as 
declare st varchar(50);
BEGIN
 for select rdb$constraint_name from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$relation_name = 'VAT7ATR'
   and not exists(SELECT f.RDB$FIELD_NAME from RDB$RELATION_FIELDS f WHERE f.RDB$RELATION_NAME = 'VAT7ATR' AND f.RDB$FIELD_NAME = 'DT_OD') into st do
 begin	
  execute statement 'ALTER TABLE VAT7ATR DROP CONSTRAINT ' || st;
  execute statement 'ALTER table VAT7ATR ADD DT_OD DATE';
  execute statement 'ALTER table VAT7ATR ADD DT_DO DATE';
 end
END ^
commit^

EXECUTE block as BEGIN --fb3
if (exists(select 1 from VAT7ATR where DT_OD is null) and (SELECT rdb$get_context('SYSTEM', 'ENGINE_VERSION') from rdb$database)>'3') then 
 begin
  execute statement "UPDATE VAT7ATR set DT_OD = '01.01.2010',dt_do = '31.12.2100' where DT_OD is null";
  execute statement "UPDATE VAT7ATR set dt_do = '31.12.2021' where id in (14,15,26)";
  execute statement "ALTER TABLE VAT7ATR ALTER DT_OD SET not NULL";
  execute statement "ALTER TABLE VAT7ATR ALTER DT_DO SET not NULL";
 end
END ^

EXECUTE block as BEGIN --fb2
if (exists(select 1 from VAT7ATR where DT_OD is null) and (SELECT rdb$get_context('SYSTEM', 'ENGINE_VERSION') from rdb$database)<'3') then 
 begin
  execute statement "UPDATE VAT7ATR set DT_OD = '01.01.2010',dt_do = '31.12.2100' where DT_OD is null";
  execute statement "UPDATE VAT7ATR set dt_do = '31.12.2021' where id in (14,15,26)";
  execute statement "UPDATE RDB$RELATION_FIELDS SET RDB$NULL_FLAG = 1 WHERE RDB$RELATION_NAME = 'VAT7ATR' and RDB$FIELD_NAME = 'DT_OD'";
  execute statement "UPDATE RDB$RELATION_FIELDS SET RDB$NULL_FLAG = 1 WHERE RDB$RELATION_NAME = 'VAT7ATR' and RDB$FIELD_NAME = 'DT_DO'";  
 end
END ^
commit^

EXECUTE block as BEGIN
if (not exists(select 1 from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$relation_name = 'VAT7ATR')
       and (select count(*) from (select 1 a from MON$ATTACHMENTS where lower(mon$remote_process) similar to '%apteka_.exe%|%ekspedycja.exe%' 
       group by substring (MON$REMOTE_ADDRESS from 1 for iif(position('/',MON$REMOTE_ADDRESS)=0,16,position('/',MON$REMOTE_ADDRESS)))||round(MON$TIMESTAMP-cast('today' as timestamp),3)||right(MON$REMOTE_PROCESS,10)))=1 
    ) then	execute statement 'ALTER TABLE VAT7ATR ADD PRIMARY KEY (ID,DT_OD,DT_DO)';  
END ^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'OGOLNE' and rf.RDB$FIELD_NAME = 'DOSTAWY_VAT')) then 
 execute statement 'ALTER TABLE OGOLNE ADD DOSTAWY_VAT CHAR(1)';  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$INDEX_SEGMENTS where RDB$INDEX_NAME='EPRUF_L_EAN')) then 
 execute statement 'CREATE INDEX EPRUF_L_EAN on EPRUF_LEKI(ean)';
END^ 

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'EPRUF_LEKI' and rf.RDB$FIELD_NAME = 'IFUPDDATE')) then 
 begin
 execute statement 'alter table EPRUF_LEKI add IFUPDDATE TIMESTAMP DEFAULT ''NOW''';   
 execute statement 'alter table EPRUF_LEKI add IFINSDATE TIMESTAMP DEFAULT ''NOW''';  
 execute statement 'alter table EPRUF_LEKI add ID_APTEKI APTEKA'; 
 execute statement 'alter table EPRUF_LEKI add DTSPR TIMESTAMP';  
 DELETE from SYNCLOGIN WHERE ID_SYNC=10 and IFUPDDATE > '6.7.22' and #ID_APTEKI# <> 1 
  and exists(select*from ogolne where id_apteki=#ID_APTEKI# and EPRUF_USL_LAST is not null) ; --EPRUF_LEKI w wersji 130.421
 end
END^

EXECUTE block as BEGIN
if (exists(select 1 from RDB$TRIGGERS where RDB$TRIGGER_NAME='CT_EPRUF_LEKI')) then  
 execute statement 'drop TRIGGER CT_EPRUF_LEKI';   
END^


EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'RAP_GIF' and rf.RDB$FIELD_NAME = 'IDZB')) then 
  begin
 execute statement 'ALTER TABLE RAP_GIF ADD IDZB INTEGER';  
 execute statement 'alter table RAP_GIF add IFUPDDATE TIMESTAMP DEFAULT ''NOW''';  
 execute statement 'alter table RAP_GIF add ID_APTEKI APTEKA';  
 execute statement 'ALTER TABLE DOSTAWCY ADD ZORZ_MASKA Varchar(80)';   
 execute statement 'alter table odmowy add gif_txt VARCHAR(1024)';
 execute statement 'alter table odmowy add gif_def VARCHAR(1)';
  end
END^

EXECUTE block as declare ap apteka; BEGIN
if (exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'KA_PRODUCT_CODE') and ap not in (10042,10053)) then 
 execute statement 'drop view KA_PRODUCT_CODE'; 
if (exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'KIESZEN_OFERTA') and ap not in (10042,10053)) then 
 execute statement 'drop view KIESZEN_OFERTA'; 
if (exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'LEKI_SK') and ap not in (10042,10053)) then 
 execute statement 'drop view LEKI_SK'; 
if (exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'V_RZDSTK')) then 
 execute statement 'drop view V_RZDSTK';  
END^

EXECUTE block as BEGIN
if (exists(select 1 from RDB$procedures where RDB$procedure_NAME='NOWA_WERSJA_PO')) then 
 execute statement 'drop procedure NOWA_WERSJA_PO';
END^

EXECUTE block as BEGIN
if (not exists(SELECT*FROM RDB$RELATION_FIELDS RF JOIN RDB$FIELDS F ON (F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE)
              WHERE RF.RDB$RELATION_NAME = 'WWW_ODBIORY' and rf.RDB$FIELD_NAME = 'ID_ODBIOR' and F.RDB$FIELD_LENGTH=20)) then
begin
execute statement 'Drop PROCEDURE NOWE_ZAM';
execute statement 'Drop TABLE WWW_ODBIORY_CENY';
execute statement 'drop TABLE WWW_ODBIORY';
end
END^
commit^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'WWW_ODBIORY')) then 
  begin
 execute statement 'alter table TRANZAKCJE add KSEF_REF VARCHAR(44)';
 execute statement 'alter table TOWARY_ZMIANY add DNI_MIN integer';
 execute statement 'alter table TOWARY_ZMIANY add DNI_MAX integer';
 execute statement 'alter table OGOLNE add aptus_pass VARCHAR(40)';
 execute statement 'alter table OGOLNE add aptus_user VARCHAR(40)';
 execute statement 'alter table OGOLNE add aptus_zam INTEGER';
 execute statement 'alter table OGOLNE add aptus_url VARCHAR(100)';
 execute statement 'ALTER table kzam alter COLUMN ID_ODBIOR type VARCHAR(20)';
 execute statement 'alter table kzam add id2 VARCHAR(20)';
 execute statement 'alter table kzam add nm2 VARCHAR(50)';
 execute statement 'alter table sprzedaz add ID_WYDAL integer';
 execute statement 'CREATE TABLE WWW_ODBIORY
(
  ID_APTEKI INTEGER NOT NULL,
  ID_ODBIOR VARCHAR(20) NOT NULL,
  NM_ODBIOR VARCHAR(100) NOT NULL,
  AKTYWNY VARCHAR(1),
  RECEPTY VARCHAR(1),
  PRIMARY KEY (ID_APTEKI,ID_ODBIOR)
)';
 execute statement 'CREATE TABLE WWW_ODBIORY_CENY
(
  ID_APTEKI INTEGER NOT NULL,
  ID_ODBIOR VARCHAR(20) NOT NULL,
  CN_OD DOUBLE PRECISION NOT NULL,
  CN_DO DOUBLE PRECISION NOT NULL,
  WG_OD DOUBLE PRECISION NOT NULL,
  WG_DO DOUBLE PRECISION NOT NULL,
  OPLATA DOUBLE PRECISION,
  ID_TOWARY INTEGER,
  PRIMARY KEY (ID_APTEKI,ID_ODBIOR,CN_OD,WG_OD)
)';
 execute statement 'ALTER TABLE WWW_ODBIORY_CENY ADD CONSTRAINT FK_WWW_ODBIORY_CENY
  FOREIGN KEY (ID_APTEKI,ID_ODBIOR) REFERENCES WWW_ODBIORY (ID_APTEKI,ID_ODBIOR) ON UPDATE CASCADE ON DELETE CASCADE';
end
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'TOWARY_WNIOSKI')) then 
  begin
 execute statement 'CREATE TABLE TOWARY_WNIOSKI
(
  ID_APTEKI INTEGER NOT NULL,
  ID_TOWARY INTEGER NOT NULL,
  ID_UMOWY VARCHAR(100) Not null,
  ID_PROD INTEGER NOT NULL,  
  IFUPDDATE TIMESTAMP DEFAULT ''NOW'',
  IFUPDUSER VARCHAR(10) DEFAULT USER,
  IFINSUSER VARCHAR(20) DEFAULT USER,
  IFINSDATE TIMESTAMP DEFAULT ''NOW'',
  CONSTRAINT TOWARY_WNIOSKI_PK PRIMARY KEY (ID_TOWARY,ID_APTEKI,ID_UMOWY,ID_PROD)
)';
 execute statement 'ALTER TABLE TOWARY_WNIOSKI ADD CONSTRAINT FK_TOWARY_WNIOSKI_TOWARY
  FOREIGN KEY (ID_TOWARY,ID_APTEKI) REFERENCES TOWARY (ID_TOWARY,ID_APTEKI) ON UPDATE CASCADE ON DELETE CASCADE';
 execute statement 'CREATE INDEX TOWARY_WNIOSKI_SYNC ON TOWARY_WNIOSKI (ID_APTEKI,IFUPDDATE)';
 execute statement 'CREATE INDEX TOWARY_WNIOSKI_WNID ON TOWARY_WNIOSKI (ID_PROD,ID_APTEKI)';
  end
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'PROD_HANDL' and rf.RDB$FIELD_NAME = 'KOD_PROD')) then 
  begin
 execute statement 'ALTER table PROD_HANDL add KOD_PROD INTEGER';  
 execute statement 'alter table WNIOSKI_UMOWY add id_kom INTEGER';  
 execute statement 'ALTER table RECEPTA add wnumowa VARCHAR(30)';  
 
 execute statement 'CREATE TABLE PAKIET_ZAOP
( ID_UMOWY VARCHAR(100) NOT NULL,
  ID_PAKIET INTEGER NOT NULL,
  ID_PROD INTEGER NOT NULL,
  CENA DOUBLE PRECISION,  
  CONSTRAINT PAKIET_ZAOP_PK PRIMARY KEY (ID_UMOWY,ID_PROD,ID_PAKIET)
)';   
 execute statement 'ALTER TABLE PAKIET_ZAOP ADD CONSTRAINT FK_PAKIET_ZAOP_WNIOSKI_UMOWY
  FOREIGN KEY (ID_UMOWY) REFERENCES WNIOSKI_UMOWY (KOD) ON DELETE CASCADE';
 execute statement 'CREATE TABLE PLANY_MIES
(
  ID_UMOWY VARCHAR(100) NOT NULL,
  MIESIAC INTEGER NOT NULL,
  ID_KOM INTEGER NOT NULL,
  ID_PAKIET INTEGER NOT NULL,
  ZAKRES VARCHAR(20) NOT NULL,
  WYROZNIK INTEGER NOT NULL,  
  CONSTRAINT PLANY_MIES_PK PRIMARY KEY (ID_UMOWY,MIESIAC,ID_KOM,ID_PAKIET,ZAKRES)
)';
 execute statement 'ALTER TABLE PLANY_MIES ADD CONSTRAINT FK_PLANY_MIES_WNIOSKI_UMOWY
  FOREIGN KEY (ID_UMOWY) REFERENCES WNIOSKI_UMOWY (KOD) ON DELETE CASCADE';
  end
END^

EXECUTE block as BEGIN
if (exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'PAKIET_ZAOP' and rf.RDB$FIELD_NAME = 'ID_APTEKI')) then 
  begin 
 execute statement 'drop TRIGGER UPDB_PAKIET_ZAOP';
 execute statement 'drop TRIGGER UPDB_PLANY_MIES';
 execute statement 'ALTER TABLE PAKIET_ZAOP DROP ID_APTEKI';
 execute statement 'ALTER TABLE PAKIET_ZAOP DROP IFUPDDATE';
 execute statement 'ALTER TABLE PAKIET_ZAOP DROP IFUPDUSER';
 execute statement 'ALTER TABLE PLANY_MIES DROP ID_APTEKI';
 execute statement 'ALTER TABLE PLANY_MIES DROP IFUPDDATE';
 execute statement 'ALTER TABLE PLANY_MIES DROP IFUPDUSER';  
 execute statement 'alter table PAKIET_ZAOP DROP CONSTRAINT PAKIET_ZAOP_PK';
 execute statement 'alter table PAKIET_ZAOP add CONSTRAINT PAKIET_ZAOP_PK PRIMARY KEY (ID_UMOWY,ID_PROD,ID_PAKIET)';  
 execute statement 'CREATE INDEX TOWARY_WNIOSKI_WNID1 ON TOWARY_WNIOSKI (ID_UMOWY,ID_APTEKI)';
   end
END^

EXECUTE block as
declare st varchar(50);
BEGIN
   if (not exists(select 1 from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$constraint_name = 'PROD_HANDL_PK')
       and (select count(*) from (select 1 a from MON$ATTACHMENTS where lower(mon$remote_process) similar to '%apteka_.exe%|%ekspedycja.exe%' 
       group by substring (MON$REMOTE_ADDRESS from 1 for iif(position('/',MON$REMOTE_ADDRESS)=0,16,position('/',MON$REMOTE_ADDRESS)))||round(MON$TIMESTAMP-cast('today' as timestamp),3)||right(MON$REMOTE_PROCESS,10)))=1 
    ) then
begin   
  for select rdb$constraint_name from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$relation_name = 'PROD_HANDL'
    AND rdb$constraint_name CONTAINING 'INTEG' into st do
  BEGIN
    execute statement 'alter table PROD_HANDL drop constraint ' || st;
    execute statement 'alter table PROD_HANDL add CONSTRAINT PROD_HANDL_PK PRIMARY KEY (ID_PROD,ID_UMOWY)';
    execute statement 'drop INDEX TOWARY_WNIOSKI_WNID';
    execute statement 'CREATE INDEX TOWARY_WNIOSKI_WNID ON TOWARY_WNIOSKI (ID_PROD,ID_APTEKI)';
  end
end  
END ^


EXECUTE block as 
BEGIN
if (not exists(select 1 from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$constraint_name = 'OSOZ_TOWARY_PK') 
       and (select count(*) from (select 1 a from MON$ATTACHMENTS where lower(mon$remote_process) similar to '%apteka_.exe%|%ekspedycja.exe%' 
       group by substring (MON$REMOTE_ADDRESS from 1 for iif(position('/',MON$REMOTE_ADDRESS)=0,16,position('/',MON$REMOTE_ADDRESS)))||round(MON$TIMESTAMP-cast('today' as timestamp),3)||right(MON$REMOTE_PROCESS,10)))=1 
    ) then
 begin 
 if(exists(select 1 from OSOZ_TOWARY)) then rdb$set_context('USER_SESSION', 'k1o','1' );
 execute statement 'DELETE from OSOZ_TOWARY';  
 end
END ^
commit^

EXECUTE block as
declare st varchar(50);
BEGIN
if (not exists(select 1 from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$constraint_name = 'OSOZ_TOWARY_PK') 
       and (select count(*) from (select 1 a from MON$ATTACHMENTS where lower(mon$remote_process) similar to '%apteka_.exe%|%ekspedycja.exe%' 
       group by substring (MON$REMOTE_ADDRESS from 1 for iif(position('/',MON$REMOTE_ADDRESS)=0,16,position('/',MON$REMOTE_ADDRESS)))||round(MON$TIMESTAMP-cast('today' as timestamp),3)||right(MON$REMOTE_PROCESS,10)))=1 
    ) then
begin
  for select rdb$constraint_name from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$relation_name = 'OSOZ_TOWARY'
    AND rdb$constraint_name CONTAINING 'INTEG' into st do
  BEGIN
    execute statement 'alter table OSOZ_TOWARY drop constraint ' || st;
    execute statement 'alter table OSOZ_TOWARY add CONSTRAINT OSOZ_TOWARY_PK PRIMARY KEY (BLOZ7,RODZAJ)';
    execute statement 'CREATE TRIGGER OSOZ_TOWARY_BU FOR OSOZ_TOWARY
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
   if (new.OD_DNIA > old.OD_DNIA) THEN
     new.OD_DNIA = old.OD_DNIA;
   if (new.DO_DNIA < old.DO_DNIA) THEN
     new.DO_DNIA = old.DO_DNIA;  
END';  
  end
end

END ^

commit^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'RZDST' and rf.RDB$FIELD_NAME = 'ID_OSOZ')) then 
  execute statement 'ALTER table RZDST add ID_OSOZ VARCHAR(20)';
END^


EXECUTE block as 
declare tb varchar(50);
declare pl varchar(50);
BEGIN
 for select RDB$FIELD_NAME, RDB$RELATION_NAME from RDB$RELATION_FIELDS where rdb$base_field is null and upper(rdb$default_source)='DEFAULT "NOW"' into pl,tb do
   execute statement 'ALTER TABLE '|| tb ||' ALTER COLUMN '|| pl ||' set DEFAULT ''NOW''';
END ^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$INDEX_SEGMENTS where RDB$INDEX_NAME='EP_STATUS')) then 
 execute statement 'CREATE INDEX EP_STATUS ON Eprzyjecia (STATUS)';
END^ 


EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'EPRUF_RAPORTY' and rf.RDB$FIELD_NAME = 'IFUPDDATE')) then 
 begin
 execute statement 'Alter table EPRUF_RAPORTY add IFUPDUSER varchar(20) default USER';  
 execute statement 'Alter table EPRUF_RAPORTY add IFUPDDATE TIMESTAMP default ''NOW'''; 
 end
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'RECEPTURA' and rf.RDB$FIELD_NAME = 'DT_WAZN')) then 
 execute statement 'ALTER TABLE RECEPTURA add DT_WAZN DATE';   
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'OPAKOWANIA' and rf.RDB$FIELD_NAME = 'ALERTY')) then 
 execute statement 'alter table OPAKOWANIA add ALERTY varchar(512)';   
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'PROD_ZPOSP_GRUPY')) then 
 execute statement 'CREATE TABLE PROD_ZPOSP_GRUPY
(
  KOD_SRODKA VARCHAR(16) NOT NULL,
  DATA_OD TIMESTAMP NOT NULL,
  DATA_DO TIMESTAMP NOT NULL,
  IFUPDDATE TIMESTAMP DEFAULT ''NOW'',
  ID_APTEKI APTEKA,
  CONSTRAINT PK_PROD_ZPOSP_GRUPY PRIMARY KEY (KOD_SRODKA,DATA_OD,DATA_DO)
)';   
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'NEUCA_REK')) then 
begin
 execute statement 'CREATE TABLE NEUCA_REK
(
  ID_NEUCA_REK INTEGER NOT NULL,
  NAZWA VARCHAR(256),
  OPIS VARCHAR(512),
  KOLOR INTEGER,
  DT_OD TIMESTAMP,
  DT_DO TIMESTAMP,
  AKTYWNA CHAR(1),
  CONSTRAINT PK_NEUCA_REK PRIMARY KEY (ID_NEUCA_REK)
)';   
 execute statement 'CREATE TABLE NEUCA_REK_ZAW
(
  ID_NEUCA_REK INTEGER NOT NULL,
  ID_NEUCA_REK_ZAW INTEGER NOT NULL,
  NR INTEGER,
  ID_NEUCA INTEGER,
  BLOZ INTEGER,
  EAN VARCHAR(15),
  ID_TOWARY INTEGER,
  ID_CBT INTEGER,
  CONSTRAINT PK_NEUCA_REK_ZAW PRIMARY KEY (ID_NEUCA_REK,ID_NEUCA_REK_ZAW)
)';   
 execute statement 'ALTER TABLE NEUCA_REK_ZAW ADD CONSTRAINT FK_NEUCA_REK_ZAW_NEUCA_REK
  FOREIGN KEY (ID_NEUCA_REK) REFERENCES NEUCA_REK (ID_NEUCA_REK) ON UPDATE CASCADE ON DELETE CASCADE';
 execute statement 'CREATE INDEX IDX_NEUCA_REK_ZAW1 ON NEUCA_REK_ZAW (ID_TOWARY)';
 execute statement 'CREATE TABLE NEUCA_CENY
(
  ID_NEUCA_CENY INTEGER NOT NULL,
  NAZWA VARCHAR(256),
  OPIS VARCHAR(512),
  PRIORYTET INTEGER,
  DT_OD TIMESTAMP,
  DT_DO TIMESTAMP,
  AKTYWNA CHAR(1),
  NADPISUJ CHAR(1),
  CONSTRAINT PK_NEUCA_CENY PRIMARY KEY (ID_NEUCA_CENY)
)';
 execute statement 'CREATE TABLE NEUCA_CENY_ZAW
(
  ID_NEUCA_CENY INTEGER NOT NULL,
  ID_NEUCA_CENY_ZAW INTEGER NOT NULL,
  NR INTEGER,
  ID_NEUCA INTEGER,
  BLOZ INTEGER,
  EAN VARCHAR(15),
  ID_TOWARY INTEGER,
  ID_CBT INTEGER,
  CENA DOUBLE PRECISION,
  CONSTRAINT PK_NEUCA_CENY_ZAW PRIMARY KEY (ID_NEUCA_CENY,ID_NEUCA_CENY_ZAW)
)';
 execute statement 'ALTER TABLE NEUCA_CENY_ZAW ADD CONSTRAINT FK_NEUCA_CENY_ZAW_NEUCA_CENY
  FOREIGN KEY (ID_NEUCA_CENY) REFERENCES NEUCA_CENY (ID_NEUCA_CENY) ON UPDATE CASCADE ON DELETE CASCADE';
 execute statement 'CREATE INDEX IDX_NEUCA_CENY_ZAW1 ON NEUCA_CENY_ZAW (ID_TOWARY)';
end
END^


EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'BRAKI' and rf.RDB$FIELD_NAME = 'ANULOWANE')) then 
begin
 execute statement 'alter table BRAKI add ANULOWANE char(1)';   
 execute statement 'alter table BRAKI add POWIADOM char(1)';   
end 
END^


/* nie dodaje do ostrzezen przy 130.53 czyli starsze zainstaluje, a od 130.50 w locie nie. Docelowo uzupelnic - dokleic do kolejnego skryptu indeksow */
EXECUTE block as BEGIN
if (not exists(select * from rdb$indices i left join rdb$index_segments s on i.rdb$index_name = s.rdb$index_name 
             left join rdb$relation_constraints rc on rc.rdb$index_name = i.rdb$index_name
             where rc.rdb$constraint_type = 'PRIMARY KEY' and rc.rdb$relation_name = 'PLANY_MIES' and s.rdb$field_name='ZAKRES')
       and (select count(*) from (select 1 a from MON$ATTACHMENTS where lower(mon$remote_process) similar to '%apteka_.exe%|%ekspedycja.exe%' 
       group by substring (MON$REMOTE_ADDRESS from 1 for iif(position('/',MON$REMOTE_ADDRESS)=0,16,position('/',MON$REMOTE_ADDRESS)))||round(MON$TIMESTAMP-cast('today' as timestamp),3)||right(MON$REMOTE_PROCESS,10)))=1 
    ) then	begin
    execute statement 'alter table plany_mies drop CONSTRAINT PLANY_MIES_PK';  
    execute statement 'alter table plany_mies Add CONSTRAINT PLANY_MIES_PK PRIMARY KEY (ID_UMOWY,MIESIAC,ID_KOM,ID_PAKIET,ZAKRES)';
            end
END ^

EXECUTE block as
declare st varchar(50);
BEGIN
  if (not exists(select 1 from RDB$RELATION_FIELDS where RDB$RELATION_NAME = 'OFERTY_CENY' and RDB$FIELD_NAME = 'ID_POZ_PROM')) then   
  begin
    execute statement 'ALTER table OFERTY_CENY add ID_POZ_PROM VARCHAR(10) default -1  not null';
    execute statement 'ALTER TABLE PRIOR_ZAMT ADD ID_P_PROM Varchar(10)';
    execute statement 'ALTER TABLE ZAM_POZ ADD ID_P_PROM Varchar(10)';
  end
END ^

EXECUTE block as
declare st varchar(50);
BEGIN
  select rdb$constraint_name from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$relation_name = 'OFERTY_CENY' into st;
  if (st <> 'OFERTY_CENY_PK'
  and (select count(*) from (select 1 a from MON$ATTACHMENTS where lower(mon$remote_process) similar to '%apteka_.exe%|%ekspedycja.exe%' 
       group by substring (MON$REMOTE_ADDRESS from 1 for iif(position('/',MON$REMOTE_ADDRESS)=0,16,position('/',MON$REMOTE_ADDRESS)))||round(MON$TIMESTAMP-cast('today' as timestamp),3)||right(MON$REMOTE_PROCESS,10)))=1 
  ) then
  begin
    if(exists(select 1 from oferty)) then rdb$set_context('USER_SESSION', 'k2o','1' );
    execute statement 'Delete from oferty';
    execute statement 'ALTER TABLE OFERTY_CENY DROP CONSTRAINT ' || st;
    execute statement 'ALTER TABLE OFERTY_CENY ADD CONSTRAINT OFERTY_CENY_PK  PRIMARY KEY (ID_DOSTAWCY,KOD,ID_POZ_PROM)';
  end
END ^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$INDEX_SEGMENTS where RDB$INDEX_NAME='TOWARY_EANR')) then 
 execute statement 'CREATE INDEX TOWARY_EANR on towary (ean_ref,id_apteki)';
END^ 

EXECUTE block as BEGIN
if (exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'TOWARY_WNIOSKI' and rf.RDB$FIELD_NAME = 'AKTYWNY')) then 
 execute statement 'ALTER TABLE TOWARY_WNIOSKI DROP AKTYWNY';  
END^

EXECUTE block as BEGIN
if (not exists(select 1 from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = 'SMOPL' and rf.RDB$FIELD_NAME = 'IFUPDDATE')) then 
 begin
 execute statement 'alter table SMOPL add IFUPDDATE TIMESTAMP DEFAULT ''NOW''';   
 execute statement 'CREATE INDEX SMOPL_SYNC ON SMOPL (ID_APTEKI,IFUPDDATE);';  
 end
END^

SET TERM ; ^
/*  koniec tablic */

ALTER TABLE HL7 ALTER COLUMN OPIS TYPE VARCHAR(300);
ALTER table EZLECENIA ALTER COLUMN dane_we type VARCHAR(20000);
ALTER table EZLECENIA ALTER COLUMN dane_wy type VARCHAR(20000);
ALTER TABLE ZDST ALTER COLUMN ID_OSOZ type VARCHAR(12);
ALTER TABLE KZAM ALTER LOGIN TYPE Varchar(100);
ALTER TABLE KZAM ALTER NM2 TYPE Varchar(100);
alter table prod_handl alter COLUMN kod_prod type VARCHAR(20);

commit;

SET TERM ^ ;

Create or ALTER PROCEDURE WN_KODY_UM (
    IAP INTEGER,
    ITW INTEGER,
    IDL INTEGER,
    DTA TIMESTAMP,
    KWN VARCHAR(20) )
RETURNS (
    KODSR VARCHAR(20) )
AS
DECLARE bylo int;
BEGIN
  if (IDL <> 21) THEN
  BEGIN
    KODSR = '';
    SUSPEND;
    exit;
  END
  if (CHARACTER_LENGTH(KWN) > 3) THEN
  BEGIN
    KODSR = kwn;
    SUSPEND;
    exit;
  END
  bylo = 0;
  for select DISTINCT PROD_HANDL.KOD_SR
   from TOWARY_WNIOSKI  
   left JOIN PROD_HANDL on TOWARY_WNIOSKI.ID_UMOWY = PROD_HANDL.ID_UMOWY and TOWARY_WNIOSKI.ID_PROD=PROD_HANDL.ID_PROD
   LEFT JOIN WNIOSKI_UMOWY u on TOWARY_WNIOSKI.ID_UMOWY=u.KOD
   where TOWARY_WNIOSKI.ID_APTEKI=:iap and TOWARY_WNIOSKI.ID_TOWARY=:itw and :dta BETWEEN u.OD_DNIA and u.DO_DNIA
   order by 1 into KODSR do 
   BEGIN
     bylo = 1;
     suspend;
   end
  if (bylo = 0) THEN
  BEGIN
    KODSR = '';
    SUSPEND;
  end    
end
^

ALTER PROCEDURE ODPL_CBT (
    IDT INTEGER,
    DTS TIMESTAMP,
    ATR CHAR(9) )
RETURNS (
    IDO INTEGER,
    ARZ CHAR(9) )

AS
declare variable ko integer;
declare variable ko1 integer;
declare variable IDO1 INTEGER;
declare variable ARZ1 CHAR(9) CHARACTER SET WIN1250;
begin
  ko=1000;
  for select ID_ODPLATN,ATRYBUTY,KOLEJNOSC from cbt_listy l
    LEFT JOIN LISTY_ODPL o  on o.ID_LISTY = l.ID_LISTY and  :dts between o.obowiazuje_od and o.obowiazuje_do and  cast(:atr as char(9)) like o.ATRYBUTY
    where l.id_cbt =:idt and :dts between l.obowiazuje_od and l.obowiazuje_do
    into :ido1,:arz1,:ko1 do
  if (ko1<ko  or (ko1=ko and ido1>ido)) then
  begin
    ido=ido1;
    arz=arz1;
    ko=ko1;
  end
  if (SUBSTRING (atr from 8 for 2) = 'S ' ) THEN
  BEGIN
    if ( (SELECT COUNT(*) from CBT_LISTY l WHERE  l.ID_CBT =:idt and :dts between l.obowiazuje_od and l.obowiazuje_do and l.ID_LISTY=27)>0) THEN
      arz = SUBSTRING(arz from 1 for 7) || 'S_';
  END
  if (SUBSTRING (atr from 8 for 2) = 'C ' ) THEN
  BEGIN
    if ( (SELECT COUNT(*) from CBT_LISTY l WHERE  l.ID_CBT =:idt and :dts between l.obowiazuje_od and l.obowiazuje_do and l.ID_LISTY=28)>0) THEN
      arz = SUBSTRING(arz from 1 for 7) || 'C_';
  END
  if (SUBSTRING (atr from 8 for 2) = 'D ' ) THEN
  BEGIN
    if ( (SELECT COUNT(*) from CBT_LISTY l WHERE  l.ID_CBT =:idt and :dts between l.obowiazuje_od and l.obowiazuje_do and l.ID_LISTY=29)>0) THEN
      arz = SUBSTRING(arz from 1 for 7) || 'D_';
  END
  suspend;
end
^
/*alter ODPL_CB*/
ALTER PROCEDURE CBT_ODP_REF (
    DATA timestamp,
    CBTID integer )
RETURNS (
    IDODPZB integer,
    LMODPZB double precision,
    CNODPZB double precision,
    IDODPLZB integer,
    LIMW double precision,
    CENW double precision,
    NMODP varchar(100),
    MINODPL double precision )

AS
declare variable nmPost VARCHAR(100);
declare variable OdpZb integer;
begin
  if (cbtid<0) THEN
    cbtid=-cbtid;
  ELSE
  BEGIN  
    select count(*) from cbt_listy where id_cbt=:cbtid and id_listy in (3,4,5,7,8,9,12,13,14,15,16,17,18,19,25) and :data between obowiazuje_od and obowiazuje_do into OdpZb;
    if (OdpZb=0) then  exit;
  END  
  select first 1 POSTAC,ID_SYNZB,cena_br,limit from cbt c left join cbt_ceny y on y.id_cbt=c.id_cbt  and id_ceny=3
    where c.id_cbt=:cbtid and obowiazuje_od<=:data
    order by y.obowiazuje_od descending
    into nmPost,OdpZb,CenW,limW;

  if (COALESCE(OdpZb,0)=0) then  exit;

  
  for select t.id_cbt,lmt,cna,substring(NAZWA from 1 for 100)
  from cbt t left join cbt_akt_c (t.id_cbt,:data) on 0=0
  LEFT JOIN ODPZB_OK(- t.ID_CBT,- :cbtid, 0,  t.POSTAC, :nmPOST, 0) on 0=0
  where t.id_synzb=:OdpZb and jestok = 'T'
  order by cna,lmt
  into Idodpzb,LmOdpZb,CnOdpZb,nmOdp do
  begin
    select ido from odpl_cbt(:IdOdpZb,:data,'GZ U 00P ') into :idOdplZb;
    if (idOdplZb<>6) then
    begin
      select first 1 oplata from cbt_odpl where id_cbt=:IdOdpZb and id_ceny=3 and id_odplatn=:idOdplZb and obowiazuje_od<=:data order by obowiazuje_od descending into minOdpl;
      suspend;
    end
  end
end
^

ALTER PROCEDURE REFUNDOWANY_JAKO_ZAMIENNIK (
    IDCBT integer,
    CENA double precision,
    DATA timestamp,
    ATR varchar(16) )
RETURNS (
    UZYTY_ODPOWIEDNIK integer,
    LIMIT_RE double precision,
    ID_ODPL integer,
    JEDNODP double precision )

AS
declare OdpZb int;
declare nmPost varchar(100);
declare IdOdpZb int;
declare id_odpl_od int;
declare lmOdpZb double precision;
DECLARE idJedn int;
DECLARE nmJedn VARCHAR(30);
DECLARE Jedn DOUBLE PRECISION;
begin
    
    /*  sprawdzenie czy nie jest OTC */
    if (COALESCE(idcbt,0)>0) then
    if ((select count(*) from cbt_listy where id_cbt = :idcbt and id_listy=1 and :data between obowiazuje_od and obowiazuje_do)=0) then
      select t.id_synzb,t.POSTAC from cbt t  where id_cbt=:idcbt into odpzb,nmPost;
    if (coalesce(odpzb,0)<>0) then
    begin
        for select t.id_cbt,(select ido from odpl_cbt(t.id_cbt,:data,:atr)) ,mn1/dz1,mn2/dz2
        from cbt t
        LEFT JOIN ODPZB_OK(- t.ID_CBT,- :idcbt, 0,  t.POSTAC, :nmPOST, 0) on 0=0
        where t.id_synzb=:OdpZb and t.ID_CBT<>:idcbt and jestok='T'
        into IdOdpZb,id_odpl_od,jednOdp,Jedn do
        if (id_odpl_od<>6) then
        begin
          select first 1 LIMIT from cbt_ceny
           where id_cbt=:IdOdpZb and id_ceny=3 and obowiazuje_od<=:data
           order by obowiazuje_od desc into lmOdpZb;
          if (LmOdpZb/jednOdp +0.0001>=Cena/jedn  and   jednOdp-jedn<0.001 and jedn-JednOdp<0.001) then
          begin
            id_odpl=id_odpl_od;
            UZYTY_ODPOWIEDNIK=-IdOdpZb;
            LIMIT_RE=LMOdpZb*jedn/jednOdp;
            SUSPEND;
            exit;
          end
      end
    end
    uzyty_odpowiednik=0;
    suspend;
end
^

ALTER PROCEDURE CBT_PS (
    EAN varchar(13),
    DAT timestamp,
    ITW integer,
    UPR varchar(3),
    TYPR integer,
    ODPL integer )
RETURNS (
    CU double precision,
    LM double precision,
    MR double precision,
    UP char(1),
    TR char(1),
    IO integer )

AS
declare variable m1 integer;
declare variable d1 integer;
declare variable m2 integer;
declare variable d2 integer;
declare variable iz integer;
declare variable ar varchar(9);
begin
  if (itw<=0 or itw is null) then
    select max(id_cbt) from cbt_klas where id_klasyfikacje=6 and WARTOSC=:ean into :itw;
  up='T';
  tr='T';
  if (itw is not null and itw>0) then
  begin

  select mnoznik,dzielnik from cbt_jedn where id_cbt=:itw and jednostka=-1 into m1,:d1;
  if (m1 is not null) then
  begin
    select mnoznik,dzielnik from cbt_jedn where id_cbt=:itw and jednostka=2 into m2,:d2;
    if (m1<>0 and d2<>0) then
      mr=m2*d1/(m1*d2);
    else
      mr=1;
  end
  else
    mr=1;
  cu=null;
  if (typr=9) then
     if (upr='P-' or upr = 'CNP' or upr='DNP') then
       ar='GN-----P-';
     else
       ar='GN-'||upr||'----';
  else
     if (upr='P-' or upr = 'CNP' or upr='DNP') then
       ar='G------P-';
     else
       ar='G--'||upr||'----';
  select ido from odpl_cbt(:itw,:dat,:ar) into :io;
  for select CENA_BR,LIMIT  from CBT_CENY
      where ID_CBT=:itw and ID_CENY=3 and OBOWIAZUJE_OD<=:dat
      order by OBOWIAZUJE_OD desc
      into :cu,:lm do
   begin
     select count(*) from cbt_listy c left join listy_odpl l on c.id_listy=l.id_listy
      where c.id_cbt=:itw and l.id_odplatn=:odpl and :dat between l.obowiazuje_od and l.obowiazuje_do and :ar like l.atrybuty into :d1;
     if (d1=0) then
       up='N';
     suspend;
     exit;
   end
   if (cu is null) then
     begin
       select id_synzb,mnoznik,dzielnik from cbt c left join cbt_jedn j on c.id_cbt=j.id_cbt and j.jednostka=2 where c.id_cbt=:itw into :iz,:m1,d1;
       if (iz is not null and iz>0) then
       for select c.id_cbt,mnoznik,dzielnik from cbt c left join cbt_jedn j on c.id_cbt=j.id_cbt and j.jednostka=2 where c.id_synzb=:iz into :itw,:m2,d2 do
       begin
         select count(*) from CBT_CENY
           where ID_CBT=:itw and ID_CENY=3 and OBOWIAZUJE_OD<=:dat into :cu;
         if (cu>0) then
         begin
           execute procedure cbt_ps('',:dat,:itw,:upr,:typr,:odpl) returning_values :cu,:lm,:mr,:up,:tr,:io;
           cu=cu*(m1*d2)/(m2*d1);
           lm=-lm*(m1*d2)/(m2*d1);
           mr=mr*(m1*d2)/(m2*d1);
           suspend;
           exit;
         end
       end
     end
  end
end
^

ALTER PROCEDURE OD100_NA_ZN (
    DATA timestamp,
    ODPZB integer,
    NMPOST varchar(100),
    CBTID integer )
RETURNS (
    IDODPZB integer,
    LMODPZB double precision,
    IDODPLZB integer )

AS
declare variable idJedn integer;

begin
  if (odpzb is null or cbtid is null) then
  begin
    suspend;
    exit;
  end
  select count(*) from cbt_listy where id_cbt=:cbtid and id_listy=1 and :data between obowiazuje_od and obowiazuje_do into idJedn;
  if (idJedn>0) then
  begin
    suspend;
    exit;
  end

  for select t.id_cbt,
  (select c.LIMIT from cbt_ceny c where c.id_cbt=t.id_cbt and c.id_ceny=3 and c.obowiazuje_od=
     (select max(obowiazuje_od) from cbt_ceny x where x.id_cbt=t.id_cbt and x.id_ceny=3 and x.obowiazuje_od<=:data) )
  from cbt t
  LEFT JOIN ODPZB_OK(- t.ID_CBT,- :cbtid, 0,  t.POSTAC, :nmPOST, 0) on 0=0
  where t.id_synzb=:OdpZb and jestok='T' into Idodpzb,LmOdpZb do
  begin
    select ido from odpl_cbt(:IdOdpZb,:data,'GZ U 00P ') into :idOdplZb;
    if (idOdplZb<>6) then
    begin
      suspend;
      exit;
    end
  end
end
^

ALTER PROCEDURE CBT_CENA (
    EAN varchar(20),
    DT timestamp,
    IB integer )
RETURNS (
    CEN double precision,
    LIM double precision )

AS
declare variable ic integer;
declare variable il integer;
declare variable ic1 integer;
declare variable rf integer;
declare variable ODPZB INTEGER;
declare variable NMPOST VARCHAR(40);

begin


  for select id_cbt from cbt_klas where id_klasyfikacje=6 and wartosc=:ean order by ifupddate into ic1 do
  begin
    rf=0;
    for select id_listy from cbt_listy where id_cbt=:ic1 and :dt between obowiazuje_od and obowiazuje_do into odpzb do
      if (odpzb>2 and odpzb< 6 or odpzb>6 and odpzb< 10 or odpzb>11 and odpzb<20 or odpzb=25 or odpzb=26) then rf=1;

    odpzb = 1;
    select count(*) from cbt_klas where id_cbt=:ic1 and id_klasyfikacje=7 and wartosc='7' into il;
    if (il>0) then
      select count(*) from cbt_klas where id_cbt=:ic1 and id_klasyfikacje=7 and wartosc='f' into odpzb;


    if (rf=1) then  /* zdarzaja sie refundowane niedopuszczone  ale jezeli tylko jest bierzemy dopuszczony */
    begin
      if (ic is null or ic > 0 or odpzb=0) then ic=-ic1;
    end
    else
    begin
      if (odpzb=0 and ic is null) then ic=ic1;
    end
  end

  if (ic is null) then ic=ic1;

  if (ic<0) then
  begin
   ic=-ic;
   rf=1;
  end

  if (ic is null) then
  begin
    cen=0;
    lim=0;
    suspend;
    exit;
  end


  if (rf=0) then
  begin
    if (ib=0) then
    begin
      select Id_synzb,postac from cbt c
      where id_cbt=:ic  into OdpZb,NmPost;

      if (odpZb is null) then
        ic=null;
      else
        select idOdpZb from od100_na_zn(:dt,:odpzb,:nmpost,:ic) into :ic;
      if (ic is null) then
      begin
        cen=0;
        lim=0;
        suspend;
        exit;
      end

    end
    else
    begin
      cen=0;
      lim=0;
      suspend;
      exit;
    end
  end

  for select cena_br,limit from cbt_ceny where id_cbt=:ic and obowiazuje_od<=:dt and id_ceny=3
    order by obowiazuje_od desc into :cen,:lim do
    begin
      if (rf<=0) then lim=-lim;
      suspend;
      exit;
    end
end
^
/*koniec alter ODPL_CBT */

/*neuca*/
CREATE or alter PROCEDURE TOWAR_Z_KODU (
    IH INTEGER,
    IA INTEGER,
    BLOZ VARCHAR(8),
    EAN VARCHAR(15),
    KOD VARCHAR(15) )
RETURNS (
    IT INTEGER )
AS
DECLARE ik int;
BEGIN
  if (ean is not null) THEN
  BEGIN
    SELECT FIRST 1 k.ID_TOWARY from TW_KLAS k where k.ID_KLASYFIKACJE=6 and k.WARTOSC=:ean and k.ID_APTEKI=:ia into it;
  end
  if (it is null and  bloz is not null) THEN
  BEGIN
    SELECT FIRST 1 k.ID_TOWARY from TW_KLAS k where k.ID_KLASYFIKACJE=3 and k.WARTOSC=:bloz and k.ID_APTEKI=:ia into it;
  end
  if (it is null and kod is not null) THEN
  BEGIN
    SELECT d.ID_KLASYFIKACJE from DOSTAWCY d where d.ID_KONTRAHENCI=:ih and d.ID_APTEKI=:ia into ik;
    if (ik > 10) then
       SELECT FIRST 1 k.ID_TOWARY from TW_KLAS k where k.ID_KLASYFIKACJE=:ik and k.WARTOSC=:kod and k.ID_APTEKI=:ia into it;
  end
  SUSPEND;
end^

CREATE OR ALTER PROCEDURE NEUCA_REKOMENDACJA (
    IT INTEGER,
    DT TIMESTAMP )
RETURNS (
    AKT CHAR(1),
    OPIS VARCHAR(128),
    KOLOR INTEGER )
AS
BEGIN
  akt = 'N';
  SELECT LEFT( list(r.NAZWA),128),max(r.KOLOR) from NEUCA_REK_ZAW z
  left join NEUCA_REK r on z.ID_NEUCA_REK=r.ID_NEUCA_REK
  where r.AKTYWNA=1 and :dt BETWEEN r.DT_OD and r.DT_DO and z.ID_TOWARY = :it
  into opis,kolor;
  if (opis is not NULL) THEN
    akt = 'T';
  SUSPEND;
end
^

CREATE or ALTER PROCEDURE NEUCA_PASUJ (
    IH INTEGER,
    IA INTEGER )

AS
DECLARE ir int;
DECLARE iz int;
DECLARE it int;
BEGIN
  for SELECT z.ID_NEUCA_REK,z.ID_NEUCA_REK_ZAW,t.IT  from NEUCA_REK r 
  join NEUCA_REK_ZAW z on r.ID_NEUCA_REK=z.ID_NEUCA_REK
  LEFT join towar_z_kodu(:ih ,:ia,z.BLOZ,z.EAN,z.ID_NEUCA) t on 0=0
  where r.DT_DO >= 'today' and r.AKTYWNA=1 and z.ID_TOWARY is null and t.IT is not null
  into ir,iz,it do
    UPDATE NEUCA_REK_ZAW z set z.ID_TOWARY = :it where z.ID_NEUCA_REK=:ir and z.ID_NEUCA_REK_ZAW = :iz;

  for SELECT z.ID_NEUCA_REK,z.ID_NEUCA_REK_ZAW,COALESCE(e.ID_CBT,b.ID_CBT)  from NEUCA_REK r
  join NEUCA_REK_ZAW z on r.ID_NEUCA_REK=z.ID_NEUCA_REK
  LEFT join cbt_klas e on e.ID_KLASYFIKACJE=6 and e.WARTOSC = z.EAN
  LEFT join cbt_klas b on b.ID_KLASYFIKACJE=3 and b.WARTOSC = cast(z.BLOZ as VARCHAR(7))
  where r.DT_DO >= 'today' and r.AKTYWNA=1 and z.ID_CBT is null and (e.ID_CBT is not null or b.ID_CBT is not null)
  into ir,iz,it do
    UPDATE NEUCA_REK_ZAW z set z.ID_CBT = :it where z.ID_NEUCA_REK=:ir and z.ID_NEUCA_REK_ZAW = :iz;

  for SELECT z.ID_NEUCA_CENY,z.ID_NEUCA_CENY_ZAW,t.IT  from NEUCA_CENY r
  join NEUCA_CENY_ZAW z on r.ID_NEUCA_CENY=z.ID_NEUCA_CENY
  LEFT join towar_z_kodu(:ih ,:ia,z.BLOZ,z.EAN,z.ID_NEUCA) t on 0=0
  where r.DT_DO >= 'today' and r.AKTYWNA=1 and z.ID_TOWARY is null and t.IT is not null
  into ir,iz,it do
    UPDATE NEUCA_CENY_ZAW z set z.ID_TOWARY = :it where z.ID_NEUCA_CENY=:ir and z.ID_NEUCA_CENY_ZAW = :iz;
    
  for SELECT z.ID_NEUCA_CENY,z.ID_NEUCA_CENY_ZAW,COALESCE(e.ID_CBT,b.ID_CBT)  from NEUCA_CENY r 
  join NEUCA_CENY_ZAW z on r.ID_NEUCA_CENY=z.ID_NEUCA_CENY
  LEFT join cbt_klas e on e.ID_KLASYFIKACJE=6 and e.WARTOSC = z.EAN
  LEFT join cbt_klas b on b.ID_KLASYFIKACJE=3 and b.WARTOSC = cast(z.BLOZ as VARCHAR(7))
  where r.DT_DO >= 'today' and r.AKTYWNA=1 and z.ID_CBT is null and (e.ID_CBT is not null or b.ID_CBT is not null)
  into ir,iz,it do
    UPDATE NEUCA_CENY_ZAW z set z.ID_CBT = :it where z.ID_NEUCA_CENY=:ir and z.ID_NEUCA_CENY_ZAW = :iz;    
end^

create or ALTER PROCEDURE ustaw_data_zamkn (ia integer)
as
DECLARE iz DOUBLE PRECISION;
DECLARE dt date;
DECLARE ds date;
DECLARE st DOUBLE PRECISION;
DECLARE dk date;
DECLARE dz date;
begin
RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
  SELECT o.LASTSYNC from OGOLNE o where o.ID_APTEKI=:ia into ds;
  for SELECT z.ID_ZDST,z.SZTUK,z.DATA FROM ZDST z WHERE z.CZYNNY  = 'N'  and z.ID_APTEKI = :ia  into iz,st,dz do
  BEGIN
    if (not EXISTS (select r.ID_ZDST FROM RZDST r LEFT JOIN SPRZEDAZ s on r.ID_SPRZEDAZ=s.ID_SPRZEDAZ and r.ID_APTEKI=s.ID_APTEKI
        where r.ID_APTEKI=:ia and r.ID_ZDST = :iz and (r.DATA < '01.01.1990'  or s.DATA < '01.01.1990' ))  ) THEN
    BEGIN
      SELECT max(r.DATA) from RZDST r where r.ID_APTEKI=:ia and r.ID_ZDST = :iz INTO :dt;
      if (dt is null and ds is not NULL AND dz < ds) THEN
        dt = ds;
      
      SELECT max(r.DATA) from ZDST r where r.ID_APTEKI=:ia and r.KOREKTA_DO = :iz INTO :dk;  
      if (dk is not null) THEN
      BEGIN
        if (dt is NOT NULL) then
          dt = MAXVALUE(dt,dk);
        ELSE
          dt = dk;  
      END    
      if (dt is null and st < 0) THEN
        dt = dz;
      if (dt is not null) then
        UPDATE ZDST z set z.DATA_ZAMKN = :dt where z.ID_APTEKI=:ia and z.ID_ZDST = :iz;
    END
  END  
RDB$SET_CONTEXT('USER_SESSION','IFROZP',0);
end^

ALTER PROCEDURE ROZR_ALL (
    IAP INTEGER,
    DZIEN TIMESTAMP )
RETURNS (
    IDAPT INTEGER,
    IDDOK INTEGER,
    IDDEK INTEGER,
    DT_WY TIMESTAMP,
    DT_PL TIMESTAMP,
    NRFA VARCHAR(100),
    SMWE VARCHAR(100),
    KWWN DOUBLE PRECISION,
    KWMA DOUBLE PRECISION,
    NZWN DOUBLE PRECISION,
    NZMA DOUBLE PRECISION,
    WPWN DOUBLE PRECISION,
    WPMA DOUBLE PRECISION,
    NPWN DOUBLE PRECISION,
    NPMA DOUBLE PRECISION,
    IDWA CHAR(3),
    ODS DOUBLE PRECISION,
    SZL DOUBLE PRECISION,
    SWA DOUBLE PRECISION,
    IDKTR INTEGER,
    SPLIT DOUBLE PRECISION )
AS
declare variable knt varchar(100);
declare variable kon varchar(100);
declare variable jfk char(3);
declare variable str char(1);
declare variable kwt double precision;
declare variable mnw double precision;
declare variable kwz double precision;
DECLARE powz INT;
DECLARE atrv int;

begin
 for select ID_JEDN_FK from jedn_fk into :jfk do
 for select d.id_apteki,d.id_dokumenty,coalesce(d.data_wy,d.data),d.data_pl,d.SYMB_WEWN,d.SYMB_ZEWN,k.konto,k.id_dekrety,k.strona,round(k.kwota,3),d.POWIAZANY_Z
  from dekrety k
  left join dokumenty d on k.id_apteki=d.id_apteki and k.id_dokumenty=d.id_dokumenty
  where (k.id_apteki=:iap or :iap=0) and k.konto starting with 'R'||:jfk||'-'  and d.data<=:dzien and (select count(*) from pow_fk where id_apteki=k.id_apteki and id_dekrety=k.id_dekrety)=0
  order by d.data
  into :idapt,:iddok,:dt_wy,:dt_pl,:smwe,:nrfa,:knt,:iddek,:str,:kwt,powz do
  begin
    IDKTR=substring(knt from 3+CHAR_LENGTH(jfk) for CHAR_LENGTH(knt)-(3+CHAR_LENGTH(jfk)));
    split = null;
    if (powz is not null) THEN
    BEGIN
      select d.ATRVAT from DOKUMENTY d where d.ID_DOKUMENTY=:powz and d.ID_APTEKI=:idapt into atrv;
      if (bin_and( CAST(power(2,25) as INTEGER),atrv) > 0) THEN
      BEGIN
        SELECT sum(y.KWOTA) FROM DEKRETY y where 
         y.ID_DOKUMENTY=:powz and y.ID_APTEKI=:idapt and y.KONTO like 'VAT-__-__-_-V-%' into split;
      END
    END  
    execute procedure akt_jedn_fk(:idwa,:dzien) returning_values :mnw;
    select round( sum (p.kwota),3) from pow_fk p left join dekrety d on p.id_apteki=d.id_apteki and p.id_dekrety = d.id_dekrety
      left join dokumenty o on d.id_apteki =o.id_apteki and d.id_dokumenty=o.id_dokumenty
      where p.id_a2=:idapt and p.id_d2=:iddek and o.data<=:dzien
    into kwz;
    if (kwz is null) then kwz=0;
    idwa=jfk;
    if (str='W') then
    begin
      kwwn=kwt;
      wpwn=kwt*mnw;
      nzwn=kwt-kwz;
      npwn=nzwn*mnw;
      kwma=null;
      wpma=null;
      nzma=null;
      npma=null;
      swa=nzwn;
      szl=npwn;
    end
    else
    begin
      kwma=kwt;
      wpma=kwt*mnw;
      nzma=kwt-kwz;
      npma=nzma*mnw;
      kwwn=null;
      wpwn=null;
      nzwn=null;
      npwn=null;
      swa=-nzma;
      szl=-npma;
    end
    execute procedure suma_ods(:idapt,:iddek,:idwa,:dt_pl) returning_values :ods;
    suspend;
  end
end^

ALTER PROCEDURE ATR_RZECZ (
    IA INTEGER,
    IR INTEGER,
    TYP INTEGER,
    IT INTEGER,
    DT TIMESTAMP,
    SP100 VARCHAR(1),
    IO INTEGER )
RETURNS (
    AR VARCHAR(10),
    KSR VARCHAR(20) )
AS
declare iio int;
declare aa varchar(11);
declare ud char(1);
DECLARE senior int;
begin
  select atrybuty,kod_srodka from recepta where id_apteki=:ia and id_recepta=:ir into :ar,ksr;
  ud = substring(ar from 8 for 1);
  if ( ud in  ('S','C','D') )  then
     senior=1;
  ELSE
    senior = 0;

  if (sp100='U') then
    ar=substring(ar from 1 for 3) || 'U' || substring(ar from 5 for 3 )  || 'X' ;

    select first 1 l.id_odplatn,l.atrybuty
          from tow_listy t
          left join listy_odpl l on t.id_listy=l.id_listy and :dt between l.obowiazuje_od and l.obowiazuje_do and cast(:ar as char(9)) like l.ATRYBUTY
          where t.id_apteki=:ia and t.id_towary=:it and  :dt between t.obowiazuje_od and t.obowiazuje_do and l.id_odplatn=:io
          order by kolejnosc,id_odplatn
          into :iio,:aa;

   if (aa is null or iio<>io) then aa=ar;

   if (substring(aa from 4 for 2)='__' and substring(ar from 4 for 2)<>'CN' and substring(ar from 4 for 2)<>'DN' and substring(ar from 4 for 2)<>'IN'  and substring(ar from 4 for 2)<>'BW') then
          ar=substring(ar from 1 for 3)||'U '||substring(ar from 6 for 4);

   if (io>2 and substring(ar from 4 for 2)<>'CN' and substring(ar from 4 for 2)<>'DN' and  substring(ar from 4 for 2)<>'BW' and substring(ar from 4 for 2)<>'IN' ) then
          ar=substring(ar from 1 for 3) ||'U '||substring(ar from 6 for 4);

   if (substring(aa from 8 for 2)='__') then
          ar=substring(ar from 1 for 7)||'X ';

   if (senior=1) then
     ar=substring(ar from 1 for 7)|| ud || ' ';


   if (typ>10) then
           if (substring(ar from 6 for 2)>'99') then
             ar=substring(ar from 1 for 5)||'99'||substring(ar from 8 for 2);
           else
             ar=substring(ar from 1 for 5)||'98'||substring(ar from 8 for 2);
  SUSPEND;
end
^

ALTER PROCEDURE SP_SZTUK (
    IAP INTEGER,
    ISP INTEGER )
RETURNS (
    SZT DOUBLE PRECISION,
    JEDN VARCHAR(30),
    RESZTA DOUBLE PRECISION,
    J_RESZTA VARCHAR(30),
    TABLETEK DOUBLE PRECISION )

AS
declare variable it integer;
     declare variable jd integer;
     declare variable mn integer;
     declare variable dz integer;
     declare variable mn1 integer;
     declare variable dz1 integer;
     declare variable midt integer;
     declare variable sz double precision;
begin
  szt=0;
  select ID_TOWARY,JEDNOSTKA from sprzedaz
  where id_apteki=:iap and id_sprzedaz =:isp into :it,:jd;
  if (jd=1) then jd=2;
  midt=it;

  execute procedure ILOSC_JP(:iap,:it,:jd) returning_values :mn,:dz;
  
  tabletek = 0;
  for select sum(SZTUK_JP),ID_TOWARY from rzdst where id_apteki=:iap and id_sprzedaz=:isp
  group by id_towary
  into :sz,:it do
  begin
    execute procedure ILOSC_JP(:iap,:it,:jd) returning_values :mn1,:dz1;
    if (mn1<>0 and dz<>0 and mn<>0 and dz1<>0) then
      szt=szt+sz*(mn1*dz)/(mn*dz1);
    else
      szt=szt+sz;
    tabletek = tabletek + sz * mn1 / dz1;  
  end

  select NAZWA from jednostki where id_apteki=:iap and ID_TOWARY=:midt and PODSTAWOWA='T' into :JEDN;
  if (cast(szt as integer)<>szt) then
  begin
    select NAZWA from jednostki where id_apteki=:iap and ID_TOWARY=:midt and JEDNOSTKA=:jd into :J_RESZTA;
    execute procedure ILOSC_JP(:iap,:midt,:jd) returning_values :mn,:dz;
    if (:szt>0) then
      reszta=(szt-floor(szt))/dz*mn;
    else
      reszta=(-szt - floor(-szt))/dz*mn;
  end
  suspend;
end
^

/* zalezne bez mian */
ALTER PROCEDURE POZYCJE_FAKTURY(IAP INTEGER,
IDTRANZ INTEGER,
DT DATE,
KLASYFIKACJA INTEGER)
 RETURNS(NAZWA VARCHAR(100),
ILOSC NUMERIC(15,5),
CENA NUMERIC(9,2),
DT_WAZN DATE,
IDTOW INTEGER,
NMJEDN VARCHAR(30),
KOD_KL VARCHAR(40),
NR_SERII VARCHAR(40),
UPUST NUMERIC(9,2),
CENA_BU NUMERIC(15,2),
VAT NUMERIC(9,2),
ODPL NUMERIC(15,2),
DOPL NUMERIC(15,2),
REF2 NUMERIC(15,2),
IDREC INTEGER,
KOD_VAT CHAR,
ILOSCJP NUMERIC(15,5),
NMJEDN_JP VARCHAR(30),
IDSPRZED INTEGER,
IDODPL INTEGER,
WARTOSC NUMERIC(15,2),
RABAT_GOT NUMERIC(15,2),
OPIS VARCHAR(256))
 AS
declare variable cenas numeric(9,2);
     declare variable il numeric(15,5);
     declare variable jedn Integer;
     declare variable podst char(1);
     declare variable mn Integer;
     declare variable dz Integer;
     declare variable wr Integer;
     declare variable odb Integer;
     declare variable taksa numeric(9,2);
     declare variable typup char(1);
     declare variable trybs char(1);
     declare variable kwotaup numeric(9,2);
     declare variable irz double precision;
     declare variable typr char(2);
     declare variable ileLekow Integer;
     DECLARE wartt DOUBLE PRECISION;
     DECLARE doplt DOUBLE PRECISION;
     DECLARE odplt DOUBLE PRECISION;
     DECLARE warts DOUBLE PRECISION;
     DECLARE dopls DOUBLE PRECISION;
     DECLARE odpls DOUBLE PRECISION;
begin


for select s.ID_TOWARY, t.NAZWA, s.CENA cenas,
         (select szt from sp_sztuk(s.id_apteki,s.id_sprzedaz)) sztuk_jp, s.JEDNOSTKA,
           s.UPUST,s.ID_ODPLATNOSC,
         stawka_vat vat, s.ODPLATNOSC, s.DOPLATA, s.ID_RECEPTA,
         (select KOD_STAWKI from stawka_vat(s.id_apteki,s.id_towary,s.DATA)) kodvat, s.ID_SPRZEDAZ, s.WARTOSC, s.TAKSA,
         s.TYP_UPUSTU, s.KWOTA_UPUSTU, s.RABAT_W_GOTOWCE,s.tryb,coalesce(s.opis,t.nazwa),left(r.ATRYBUTY ,2 ),
         (select count(*) from (select id_towary from RZDST z where z.ID_APTEKI=s.ID_APTEKI and z.ID_SPRZEDAZ=s.ID_SPRZEDAZ GROUP by id_towary,round(cena,2))),s.REFUNDATOR2
    from sprzedaz s
    left join towary t on t.id_apteki=s.id_apteki and t.ID_TOWARY=s.ID_TOWARY
    left join recepta r on s.ID_RECEPTA=r.ID_RECEPTA and s.ID_APTEKI=r.ID_APTEKI
    where s.Id_apteki=:iap and s.ID_TRANZAKCJE=:idTranz and s.DATA=:dt and s.wartosc<>0
    order by s.pozycja
into :idTow, :nazwa, :cenas, :il, :jedn, :upust, :idodpl, :vat, :odpl, :dopl, :idrec, :KOD_VAT, :IDSPRZED, :wartosc,
   :taksa, :typup, :kwotaup, :rabat_got, :trybs, opis,typr,ileLekow,ref2 do
begin

   

  il=round(il,5);
  if (il is not null and il<>0) then
    cena=(:wartosc+:taksa)/:il;

  if (:upust<>0) then
  begin
    if (:typup='C') then
      cena_bu=:cena/(1-:upust*0.01);
    if (:typup='O') then
      cena_bu=:cena;
    if (:typup='D') then
    begin
      cena_bu=(:wartosc+:kwotaup +:taksa)/:il;
      upust=kwotaup/(wartosc+kwotaup)*100;
    end
  end
  else
    cena_bu=:cena;



  if (idOdpl is null or idOdpl=0 or idOdpl=6) then
  begin
    dopl=dopl+odpl;
    odpl=0;
  end

  select min(id_zdst) from rzdst where id_apteki=:iap and id_sprzedaz=:idsprzed into irz;

  select max(WARTOSC) from zdst_klas where ID_APTEKI=:iap and ID_zdst=:irz and ID_KLASYFIKACJE=5 into :nr_serii;
  select DATA_WAZN from zdst where  ID_APTEKI=:iap and ID_zdst=:irz into dt_wazn;
  select max(WARTOSC) from tw_klas where ID_APTEKI=:iap and  ID_TOWARY=:idTow and ID_KLASYFIKACJE=:KLASYFIKACJA into :kod_kl;
  select PODSTAWOWA, NAZWA from jednostki where ID_APTEKI=:iap and  ID_TOWARY=:idTow and  JEDNOSTKA=:jedn into :podst, nmJedn;
  iloscjp=:il;
  if (:podst='T') then
  begin
    ilosc=:il;
    nmjedn_jp=:nmJedn;
  end
  else
  begin
    /*execute procedure ilosc_jp(:idTow,:jedn) returning_values (:mn, :dz);
      ilosc=:il*:mn/:dz;*/
    ilosc=:il;
    select NAZWA from jednostki where ID_APTEKI=:iap and  ID_TOWARY=:idTow and  PODSTAWOWA='T' into nmJedn_JP;
  end

  /*jesli lek recepturowy to idzie na paragon tylko gdy odbior*/
  if (:idtow=0) then
  begin
    select ID_ODB from receptura where ID_APTEKI=:iap and  ID_SPRZEDAZ=:IDSPRZED into :odb;
    if (:odb>0 or trybs<>'S') then
    begin
      CENA=:WARTOSC+:taksa;
      CENA_BU=:WARTOSC+:kwotaup+:taksa;

      if (trybs='Z') then
      begin
        ILOSC=-1;
        ILOSCJP=-1;
        CENA=-(:WARTOSC+:taksa);
        CENA_BU=-(:WARTOSC+:kwotaup+:taksa);
      end
      else
      begin
        ILOSC=1;
        ILOSCJP=1;
      end
      WARTOSC=WARTOSC+TAKSA;
      NMJEDN_JP='Szt.';
      suspend;
    end
  end
  else
  begin
    if (typr='GW' and ileLekow>1 and wartosc<>0) THEN
    BEGIN
      
      select count(*) from (
      select s.ID_TOWARY
       from rzdst s
       left join towary t on t.id_apteki=s.id_apteki and t.ID_TOWARY=s.ID_TOWARY
       where s.Id_apteki=:iap and s.ID_SPRZEDAZ=:idsprzed
       GROUP by s.ID_TOWARY,t.NAZWA , round(s.CENA,2)
       ) into ileLekow;
      wartt = wartosc;
      doplt = dopl;
      odplt = odpl;
      warts = 0;
      dopls = 0;
      odpls = 0;
      odb = 0;
      for select s.ID_TOWARY, t.NAZWA, round(s.CENA,2) , round(sum(s.sztuk_jp),5),min(s.ID_ZDST)
       from rzdst s
       left join towary t on t.id_apteki=s.id_apteki and t.ID_TOWARY=s.ID_TOWARY
       where s.Id_apteki=:iap and s.ID_SPRZEDAZ=:idsprzed
       GROUP by s.ID_TOWARY,t.NAZWA , round(s.CENA,2)
       into idtow,nazwa,cena,ILOSCJP,irz do
       begin
         odb = odb + 1;
         if (odb<ileLekow) THEN
         begin
           wartosc = round(cena * iloscjp,2);
           dopl = round(doplt * wartosc / wartt,2) ;
           odpl = round(odplt * wartosc / wartt,2) ;
           odpls = odpls + odpl;
           dopls = dopls + dopl;
           warts = warts + wartosc;
         end
         ELSE
         BEGIN
           wartosc = wartt - warts;
           odpl = odplt - odpls;
           dopl = doplt - dopls;
           if (iloscjp<>0) then
             cena = wartosc / iloscjp;
         END
         
         select max(WARTOSC) from zdst_klas where ID_APTEKI=:iap and ID_zdst=:irz and ID_KLASYFIKACJE=5 into :nr_serii;
         select DATA_WAZN from zdst where  ID_APTEKI=:iap and ID_zdst=:irz into dt_wazn;
         select max(WARTOSC) from tw_klas where ID_APTEKI=:iap and  ID_TOWARY=:idTow and ID_KLASYFIKACJE=:KLASYFIKACJA into :kod_kl;
         select NAZWA from jednostki where ID_APTEKI=:iap and  ID_TOWARY=:idTow and  JEDNOSTKA=1 into  nmJedn;
         ilosc=iloscjp;
         cena_bu=:cena/(1-upust*0.01);
         opis = nazwa;
         SUSPEND;
       end  
    END
    else
      suspend;
  END
end
end
^


/* Alter (TRUSP) */
ALTER PROCEDURE TRUSP(IAP INTEGER,
DOD DATE,
DDO DATE,
KOD DATE,
KDO DATE,
TYP INTEGER,
NZ DOUBLE PRECISION)
 RETURNS(WA NUMERIC(15,2),
OD NUMERIC(15,2),
DP NUMERIC(15,2),
TA NUMERIC(15,2),
R2 NUMERIC(15,2),
IR INTEGER,
IO INTEGER,
SZ INTEGER,
SR INTEGER,
DT DATE,
ID INTEGER,
AR CHAR(9),
IA INTEGER,
TT CHAR)
 AS
declare variable tr char(1);
declare variable it integer;
declare variable iodp integer;
declare variable id1 integer;
declare variable iio integer;
declare variable aa char(9);
declare variable ss integer;
declare variable dta date;
declare variable SP100 char(1);
declare ksr varchar(20);
BEGIN
  select cast((cast('NOW' as timestamp)-cast('TODAY' as timestamp))*100000 as integer) from jeden_wiersz into :ss;
  if (ss is null) then ss=0;
  ss=ss+1;
  if (typ=1 or typ=11) then
  begin
    sz=1;
    for select round(s.WARTOSC,2),round(s.ODPLATNOSC,2),round(s.DOPLATA,2),round(s.TAKSA,2),round(s.REFUNDATOR2,2),s.ID_RECEPTA,s.ID_ODPLATNOSC,s.TRYB,s.ID_SPRZEDAZ,s.DATA,s.ID_TOWARY,s.ID_APTEKI,coalesce(s.NA100,'N') 
     from SPRZEDAZ s LEFT JOIN TRANZAKCJE t on s.DATA=t.DATA and s.ID_TRANZAKCJE = t.ID_TRANZAKCJE and s.ID_APTEKI = t.ID_APTEKI 
     where s.id_apteki=:iap and s.DATA BETWEEN :DOD and :DDO and (ABS(s.WARTOSC+s.TAKSA-s.ODPLATNOSC-s.DOPLATA)>=:nz or s.TRYB<>'S') and t.PARAGON<>'B'
      into :wa,:od,:dp,:ta,:r2,:ir,:io,:tr,:id,:dt,:it,:ia,sp100 do
    begin
      ar=null;
      if (not ir is null) then
      begin
        select ar,ksr from  atr_rzecz(:ia,:ir,:typ,:it,:dt,:sp100,:io) into ar,ksr;
      end
      if (tr='S') then
      begin
        if (not ir is null) then
          execute procedure recept(:ss,:ir,'N') returning_values sr;
        suspend;
      end
      if (tr='K') then
      begin
        execute procedure akt_st_sp(:ia,:id,:kdo) returning_values :id,:tr;
        if ((tr is null) and (:WA+:TA-:OD-:DP>:nz or :WA+:TA-:OD-:DP<-:nz) ) then
        begin
         if (not ir is null) then
           execute procedure recept(:ss,:ir,'N') returning_values sr;
         suspend;
        end
        if (tr='P' or tr='N' or tr='R') then
        begin
          select round(WARTOSC,2),round(ODPLATNOSC,2),round(DOPLATA,2),round(TAKSA,2),round(REFUNDATOR2,2),ID_RECEPTA,ID_ODPLATNOSC,DATA,coalesce(NA100,'N') from SPRZEDAZ where
           id_apteki=:ia and id_sprzedaz=:id
           into :wa,:od,:dp,:ta,:r2,:ir,:io,:dta,sp100;
          begin
            if ((:WA+:TA-:OD-:DP>:nz or :WA+:TA-:OD-:DP<-:nz) and dta>'01/01/1910') then
            begin
              if (not ir is null) then
              begin
                select ar,ksr from  atr_rzecz(:ia,:ir,:typ,:it,:dt,:sp100,:io) into ar,ksr;
                execute procedure recept(:ss,:ir,'N') returning_values sr;
              end
              suspend;
            end
          end
        end
      end
    end
  end
  else
  begin
    for select round(WARTOSC,2),round(ODPLATNOSC,2),round(DOPLATA,2),round(TAKSA,2),round(REFUNDATOR2,2),
     (select ID_RECEPTA from sprzedaz x where x.id_apteki=s.id_apteki and x.id_sprzedaz=(select poprzedni from zmiany z where z.id_apteki=s.id_apteki and z.id_sprzedaz=s.id_sprzedaz )),
      ID_ODPLATNOSC,TRYB,ID_SPRZEDAZ,s.DATA,id_towary,s.id_apteki,coalesce(NA100,'N')
      from SPRZEDAZ s  left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje  where
      s.ID_APTEKI=:iap and s.DATA+t.godzina/24>=:DOD and s.DATA+t.godzina/24<=:DDO and tryb = 'Z'
      and (select dt from firstop(s.id_apteki,s.id_sprzedaz)) >= :kod and (select dt from firstop(s.id_apteki,s.id_sprzedaz))<=:kdo
      and (select ok from braz(s.id_apteki,s.id_sprzedaz,:ddo))=1 AND t.PARAGON <> 'B'
      into :wa,:od,:dp,:ta,:r2,:ir,:io,:tr,:id,:dt,:it,:ia,sp100 do
    begin
      ar=null;
      if (not ir is null) then
      begin
        select ar,ksr from  atr_rzecz(:ia,:ir,:typ,:it,:dt,:sp100,:io) into ar,ksr;
      end
      if (typ=2 or typ=12 or ir is null) then
        execute procedure akt_st_zw(:ia,:id,:ddo) returning_values :id1;
      else
        execute procedure akt_st_zw1(:ia,:id,:ddo,:ir) returning_values :id1;
      sz=-1;
      if (id1>0 or id1 is null) then
      begin
        if (not ir is null) then
          execute procedure recept(:ss,:ir,'T') returning_values sr;
        sr=sz*sr;
        if ((typ=2 or typ=12) and wa+ta-od-dp<-nz+0.00001) then
            suspend;
      end
      if ((typ=3 or typ=13) and id1=-1 and wa+ta-od-dp<-nz+0.00001) then
      begin
        if (not ir is null) then
        begin
          execute procedure recept(:ss,:ir,'T') returning_values sr;
          if (substring(ar from 1 for 1)='R') then
            select nastepny from zmiany where id_apteki=:iap and id_sprzedaz=:id into :id;
        end
        sr=sz*sr;
        tt='U';
        suspend;
      end
      if (id1>0) then
      begin
         sz=1;
         if (wa+ta-od-dp<-nz+0.00001) then tt='P' ; else tt='D';
         select round(WARTOSC,2),round(ODPLATNOSC,2),round(DOPLATA,2),round(TAKSA,2),round(REFUNDATOR2,2),ID_RECEPTA,ID_ODPLATNOSC,ID_SPRZEDAZ,coalesce(NA100,'N') from SPRZEDAZ where
           id_apteki=:ia and id_sprzedaz=:id1
           into :wa,:od,:dp,:ta,:r2,:ir,:io,:id,sp100;
         begin
          if (not ir is null) then
          if (not ir is null) then
          begin
            select ar,ksr from  atr_rzecz(:ia,:ir,:typ,:it,:dt,:sp100,:io) into ar,ksr;
            execute procedure recept(:ss,:ir,'N') returning_values sr;
          end
          if (wa+ta-od-dp>nz-0.00001) then    suspend;
         end
        end
    end
  end
  delete from tmp_rec where id_apteki=:ss;
END
^

ALTER PROCEDURE TRUSP1 (
    IAP INTEGER,
    DOD TIMESTAMP,
    DDO TIMESTAMP,
    KOD TIMESTAMP,
    KDO TIMESTAMP,
    TYP INTEGER,
    NZ DOUBLE PRECISION,
    RC INTEGER )
RETURNS (
    WA NUMERIC(15,2),
    OD NUMERIC(15,2),
    DP NUMERIC(15,2),
    TA NUMERIC(15,2),
    R2 NUMERIC(15,2),
    IO INTEGER,
    SZ INTEGER,
    SR INTEGER,
    IR INTEGER,
    DT TIMESTAMP,
    ID INTEGER,
    AR CHAR(9),
    IA INTEGER,
    IT INTEGER,
    JD INTEGER,
    ST DOUBLE PRECISION,
    RR INTEGER,
    IK INTEGER,
    SV INTEGER,
    PH INTEGER )
AS
declare variable tr char(1);
declare variable iio integer;
declare variable aa char(9);
declare variable ss integer;
declare variable wnst char(1);
declare variable sp100 char(1);
declare variable ilw integer;
declare wns DOUBLE PRECISION;
declare wnw DOUBLE PRECISION;
declare ksr varchar(20);
declare mis int;
declare nn int;
BEGIN
  select COALESCE(WNIO_SZT,'N') from ogolne where id_apteki=:iap into wnst;
  select cast((cast('NOW' as timestamp)-cast('TODAY' as timestamp))*100000 as integer) from jeden_wiersz into :ss;
  if (ss is null) then ss=0;
  ss=ss+1;
  mis = 0;
  if (typ=1) then
  begin
    sz=1;

    for select round(p.WARTOSC,2),round(p.ODPL,2),round(p.DOPL,2),round(TAKSA,2),round(p.REF2,2),s.ID_RECEPTA,s.ID_ODPLATNOSC,s.TRYB,s.ID_SPRZEDAZ,
      s.DATA,p.IDTOW,s.ID_APTEKI,s.JEDNOSTKA,p.ILOSC,coalesce(s.NA100,'N'),round(s.STAWKA_VAT),s.ID_ZAMIENNIK
      from SPRZEDAZ s
      left join POZYCJE_FAKTURY(s.id_apteki,s.id_tranzakcje,s.data,11) p on p.IDSPRZED=s.ID_SPRZEDAZ
      where s.id_apteki=:iap and s.id_recepta=:rc and s.DATA BETWEEN :DOD and :DDO and ( abs(s.WARTOSC+TAKSA-ODPLATNOSC-DOPLATA)>=:nz or TRYB<>'S')
      order by s.ID_SPRZEDAZ,p.IDTOW
      into :wa,:od,:dp,:ta,:r2,:ir,:io,:tr,:id,:dt,:it,:ia,:jd,:st,sp100,sv,ph do
    begin
      ar=null;
      if (mis<>id) THEN
      BEGIN
        mis = id;
        rr = 0;
      END
      rr = rr + 1;
      if (not ir is null) then
      begin
        select ar,ksr from  atr_rzecz(:ia,:ir,:typ,:it,:dt,:sp100,:io) into ar,ksr;
      end
      if (tr='S') then
      begin
        if (not ir is null) then
          execute procedure recept(:ss,:ir,'N') returning_values sr;
        if (substring(ar from 1 for 2)='GW' and wnst='T' ) then
           select :st*mnoz/dziel from ilosc_jp(:ia,:it,2) into :st;
        suspend;
      end
      if (tr='K') then
      begin
        execute procedure akt_st_sp(:ia,:id,:kdo) returning_values :id,:tr;
        if (tr is null) then
        begin
         if (not ir is null) then
           execute procedure recept(:ss,:ir,'N') returning_values sr;
         if (substring(ar from 1 for 2)='GW' and wnst='T' ) then
           select :st*mnoz/dziel from ilosc_jp(:ia,:it,2) into :st;
         suspend;
        end

        if (tr in ('P','N','R') and   rr=1) then
        begin
          rr = 0;
          for select round(p.WARTOSC,2),round(p.ODPL,2),round(p.DOPL,2),round(TAKSA,2),round(p.REF2,2),ID_RECEPTA,ID_ODPLATNOSC,p.IDTOW,JEDNOSTKA,p.ILOSC,coalesce(NA100,'N'),round(s.STAWKA_VAT)
           from SPRZEDAZ s
           left join POZYCJE_FAKTURY(s.id_apteki,s.id_tranzakcje,s.data,11) p on p.IDSPRZED=s.ID_SPRZEDAZ
           where s.id_apteki=:ia and s.id_sprzedaz=:id
           order by s.ID_SPRZEDAZ,p.IDTOW
           into :wa,:od,:dp,:ta,:r2,:ir,:io,:it,:jd,:st,sp100,sv do
          begin
            if (abs(:WA+:TA-:OD-:DP)>:nz) then
            begin
              rr = rr + 1;
              if (not ir is null) then
              begin
                select ar,ksr from  atr_rzecz(:ia,:ir,:typ,:it,:dt,:sp100,:io) into ar,ksr;
                execute procedure recept(:ss,:ir,'N') returning_values sr;
                if (substring(ar from 1 for 2)='GW' and wnst='T' ) then
                  select :st*mnoz/dziel from ilosc_jp(:ia,:it,2) into :st;
              end
              suspend;
            end
          end
          rr=1;
        end

      end
    end
  end
  else
  begin
     for select round(p.WARTOSC,2),round(p.ODPL,2),round(p.DOPL,2),round(s.TAKSA,2),round(p.REF2,2),s.ID_RECEPTA,s.ID_ODPLATNOSC,s.TRYB,s.ID_SPRZEDAZ,
      f.DD,p.IDTOW,s.ID_APTEKI,s.JEDNOSTKA,p.ILOSC,coalesce(s.NA100,'N') ,z.POPRZEDNI,z.NASTEPNY,round(s.STAWKA_VAT),s.ID_ZAMIENNIK
      from SPRZEDAZ s
      left join POZYCJE_FAKTURY(s.id_apteki,s.id_tranzakcje,s.data,11) p on p.IDSPRZED=s.ID_SPRZEDAZ
      left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
      left join firstop(s.id_apteki,s.id_sprzedaz) f on 0=0
      left join zmiany z on s.ID_APTEKI=z.ID_APTEKI and z.ID_SPRZEDAZ=s.ID_SPRZEDAZ
      LEFT JOIN SPRZEDAZ sp on z.ID_APTEKI=sp.ID_APTEKI and z.POPRZEDNI=sp.ID_SPRZEDAZ
      left join tranzakcje tp on sp.id_apteki=tp.id_apteki and sp.data=tp.data and sp.id_tranzakcje=tp.id_tranzakcje
      where  s.ID_APTEKI=:iap and s.id_recepta=:rc and s.DATA+t.godzina/24 BETWEEN :kod and :kdo and s.tryb = 'Z' and p.ILOSC<0
      and f.DT between :dod and :ddo and sp.DATA+tp.godzina/24 < :kod
      order by s.ID_SPRZEDAZ,p.IDTOW
      into :wa,:od,:dp,:ta,:r2,:ir,:io,:tr,:id,:dt,:it,:ia,:jd,:st,sp100,ik,nn,sv,ph do
    begin
      ar=null;
      if (mis<>id) THEN
      BEGIN
        mis = id;
        rr = 0;
      END
      rr = rr + 1;
      if (not ir is null) then
      begin
        select ar,ksr from  atr_rzecz(:ia,:ir,:typ,:it,:dt,:sp100,:io) into ar,ksr;
      end
      sz=-1;
      if (not ir is null) then
        execute procedure recept(:ss,:ir,'T') returning_values sr;
      if (substring(ar from 1 for 2)='GW' and wnst='T' ) then
                  select :st*mnoz/dziel from ilosc_jp(:ia,:it,2) into :st;
      sr=sz*sr;
      suspend;
      if (nn is not null and rr=1) then
      BEGIN
        select si from AKT_ST_ZW2(:ia,:id,:kdo) into nn;
        sz=1;
        rr = 0;
        ik = null;
        for select round(p.WARTOSC,2),round(p.ODPL,2),round(p.DOPL,2),round(TAKSA,2),round(p.REF2,2),ID_RECEPTA,ID_ODPLATNOSC,p.IDTOW,JEDNOSTKA,p.ILOSC,coalesce(NA100,'N') ,s.ID_SPRZEDAZ,round(s.STAWKA_VAT),s.ID_ZAMIENNIK
           from SPRZEDAZ s
           left join POZYCJE_FAKTURY(s.id_apteki,s.id_tranzakcje,s.data,11) p on p.IDSPRZED=s.ID_SPRZEDAZ
           where s.id_apteki=:ia and s.id_sprzedaz=:nn and p.ILOSC>0
           order by s.ID_SPRZEDAZ,p.IDTOW
           into :wa,:od,:dp,:ta,:r2,:ir,:io,:it,:jd,:st,sp100,id,sv,ph do
         begin
          rr = rr + 1;
          if (not ir is null) then
            execute procedure recept(:ss,:ir,'N') returning_values sr;
          if (substring(ar from 1 for 2)='GW' and wnst='T' ) then
                  select :st*mnoz/dziel from ilosc_jp(:ia,:it,2) into :st;
          suspend;
         end
         rr = 1;
      END
    end
  end
  delete from tmp_rec where id_apteki=:ss;
END^

ALTER PROCEDURE NOWA_WERSJA_P14 (
    IL Integer default 0,tak smallint DEFAULT 0 )
AS
declare gw char(75);
declare t char(5);
declare i integer;
declare text varchar(200);
declare cr char(2);
declare z varchar(2);
begin 
/* il max dlugosc tekstu / 1.4, 0 automatycznie , 1 testowanie dlugosci 
   tak=0 'wciœnij tak' else 'wciœnij nie',  wersja z Nie moze byc z lamanym wierszem jesli il miedzy 33 i 61*/

 gw='××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××'; 
 t=''; z=' ';
 cr = ASCII_CHAR(13)||ASCII_CHAR(10);
 
 i=(select trunc(max(char_length(trim(cyfry)))/1.38) from tylko_wiersze((select rdb$get_context('USER_SESSION','k') from rdb$database),ascii_char(10)));
 
 if (:il=1) then begin il=:i; t=:i; end else
 begin
 if (:il=0) then 
  begin il=maxvalue(32,:i); 
  if (:tak<>0) then il=maxvalue(62,:i);
  end 
 end
 if (:il between 33 and 61 and :tak<>0) then begin il=maxvalue(33,:i); z=cr ; end
 if (:il is null) then begin il=2; rdb$set_context('USER_SESSION','k','''USER_SESSION'',''k'' zwraca null'); end 
 
 if (tak=0) then
 text=cr||cr||' Wersja zaktualizowana poprawnie WCIŒNIJ "Tak"'||cr||cr;
 else
 text=cr||cr||' WCIŒNIJ  "Nie"  !'||cr||cr||'Ponowne wczytanie jakiegokolwiek skryptu'||z||'mo¿liwe po zamkniêciu i uruchomieniu programu'||cr;
    
 if(rdb$get_context('USER_SESSION','v')>'0') 
 then exception blad left(:gw,:il)||cr||cr||rdb$get_context('USER_SESSION','k')||text||left(:gw,:il)||:t;
end^


create or ALTER PROCEDURE PESELP (
    PESEL CHAR(11) )
RETURNS (
    PESELD TIMESTAMP,
    PLEC CHAR(1) )

AS
  DECLARE waga varchar(11)='13791379131';
  DECLARE suma int=0;
  DECLARE i int=1;
  DECLARE c char(1);
begin 
    if (char_length(trim(:pesel))<>11 or :pesel not similar to '[[:DIGIT:]]*') then exit;
    WHILE (:i<=11) do
    BEGIN
      c=SUBSTRING(:pesel from :i for 1);
      suma=:suma+CAST(SUBSTRING(:waga from :i for 1) as int)*:c;
      i=:i+1;
    END
    if (right(:suma,1)<>0) then exit;
    plec = SUBSTRING(pesel from 10 for 1);
    if (MOD(plec,2) = 1) THEN
      plec = 'M';
    ELSE
      plec = 'K';  
    
    BEGIN
    peseld = CASE WHEN CAST(substring(PESEL FROM 3 FOR 2) AS NUMERIC) < 21 THEN		
     CAST('19' || SUBSTRING(PESEL FROM 1 FOR 2) || '-' || SUBSTRING(PESEL FROM 3 FOR 2) || '-' || SUBSTRING(PESEL FROM 5 FOR 2) AS DATE) else          
     cast('20' || SUBSTRING(PESEL FROM 1 FOR 2) || '-' || cast(cast(substring(PESEL FROM 3 FOR 2) as int)-20 as int) || '-' ||  substring(PESEL FROM 5 FOR 2) as date) end ;
    WHEN ANY DO EXIT;
    end
  suspend;
  
end
^

create or ALTER TRIGGER KONTRAHENCI_PESEL_NIP for kontrahenci ACTIVE
BEFORE UPDATE POSITION 1
AS
declare ap apteka;
begin
  if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

  if (((select peseld from peselp(old.pesel))-cast('30.12.1899' as date))*10000+cast(iif(old.pesel not similar to '[0-9]+',null,substring(old.PESEL from 7 for 4)) as int)
      = old.id_kontrahenci and new.pesel is distinct from old.pesel) THEN
     EXCEPTION BLAD ' PESEL jest zwi¹zany z id pacjenta - nie mo¿na go zmieniæ';

  /* byc moze trzeba rozbudowac na blokade kasowania peselow jesli byly transakcje */
    
  if ((char_length(trim(coalesce(old.nip,'')))<10 and char_length(trim(coalesce(new.nip,'')))>9 OR
       char_length(trim(coalesce(old.nip,'')))>9 and char_length(trim(coalesce(new.nip,'')))<10) and 
      exists (select*from tranzakcje where data>cast('today' as date)-60 and id_kontrahenci=old.id_kontrahenci) and ap<>10425 ) THEN
     EXCEPTION BLAD ' Nie mo¿na dodaæ lub usun¹æ NIP 
 dla tego kontrahenta wystawiona jest faktura';
    
end^

ALTER PROCEDURE HIST_KOREKTY (
    IAP INTEGER,
    ID INTEGER )
RETURNS (
    IDSP INTEGER,
    WERSJA INTEGER )
AS
declare variable it integer;
begin
  wersja = 0;
  SELECT f.IDSP FROM FIRSTOP(:iap,:id) f into it;
  if (it is not NULL) THEN  idsp = it; 
  ELSE idsp = id;
  while (idsp is not null) do
  begin
    WERSJA = wersja + 1;
    SUSPEND; 
    select (select NASTEPNY from ZMIANY where id_apteki=:iap and id_sprzedaz=:idsp) FROM RDB$DATABASE into idsp;
  end
end^

/* 10 zaleznych procedur ale zmiana tylko pod aptus.xml zatem nie wszystkie nizej ujete, w 51 moze pod osoz - chcek */
ALTER PROCEDURE STAN_WART (
    IA INTEGER,
    IT INTEGER,
    WS INTEGER )
RETURNS (
    STAN NUMERIC(15,5),
    WARTOSC NUMERIC(15,5),
    CENA NUMERIC(15,5),
    MARZA NUMERIC(15,5),
    BLOK NUMERIC(15,5),
    ST_PAK DOUBLE PRECISION )
AS
declare variable st numeric(15,5);
declare variable bl numeric(15,5);
declare variable cn numeric(15,5);
declare variable dt TIMESTAMP;
declare variable dp TIMESTAMP;
DECLARE jest_pak INTEGER;
begin
    stan=0;
    wartosc=0;
    blok=0;
    st_pak=0;
    dp='01/01/1900';
    for select z.STAN,case when coalesce(blokada,'N')='N' then 0 else coalesce(ile_blokada,z.stan) end,c.cena_nt_jp,z.DATA ,
     CASE WHEN COALESCE(b.cena_nt,0)>0 and  100*(b.cena_nt-c.cena_nt)/b.cena_nt >= y.RABAT_GRANICZNY THEN 1 ELSE 0 END
     from ZDST z
     left join ceny_dostawy c on z.id_apteki=c.id_apteki and z.id_zdst=c.id_zdst and c.id_ceny=1
     left join ceny_dostawy b on z.id_apteki=b.id_apteki and z.id_zdst=b.id_zdst and b.id_ceny=2
     LEFT JOIN DOSTAWY  d on z.ID_APTEKI=d.ID_APTEKI and d.ID_DOSTAWY=z.ID_DOSTAWY
     LEFT JOIN DOSTAWCY y on d.ID_KONTRAHENCI = y.ID_KONTRAHENCI and d.ID_APTEKI = y.ID_APTEKI
     where Z.ID_APTEKI=:ia and Z.ID_TOWARY=:it and Z.CZYNNY='T'
    into st,bl,cn,dt,jest_pak do
    begin
     if (ws<>0) then
       st=st-bl;
     if (ws<>2 or jest_pak=1) then     
     BEGIN
       stan=stan+st;  
       wartosc=wartosc+st*cn;
     END  
     if (jest_pak=1) then
       st_pak = st_pak + st;
     blok   = blok + bl;
     if (dt>dp) then
     begin
       if (ws <> 3) THEN
         cena=cn;
       dp=dt;
     end
     if (ws = 3 and bl = 0 AND (cena is null or (st > 0 and cn < cena ))) THEN
       cena = cn;
    end
    blok=stan-blok;
    if (cena is null) then
      select cena from ost_cena(:ia,:it,'TODAY',1) into :cena;
    suspend;
end^

ALTER PROCEDURE CENA_Z_OFERTY (
    IAP INTEGER,
    ITW INTEGER,
    IDS INTEGER,
    ZDOST CHAR(1) )
RETURNS (
    CENA DOUBLE PRECISION,
    DT_PROM TIMESTAMP,
    DT_CEN TIMESTAMP,
    Z_CZEGO VARCHAR(1),
    CN_OF DOUBLE PRECISION,
    UP_OF DOUBLE PRECISION,
    DT_OF TIMESTAMP,
    CN_DS DOUBLE PRECISION,
    UP_DS DOUBLE PRECISION,
    DT_DS TIMESTAMP,
    KOD VARCHAR(80),
    ID_P_PROM VARCHAR(10) )
AS
declare variable dt TIMESTAMP;
  declare variable wh char(1);
  declare variable up Double precision;
  declare variable upr Double precision;
  declare variable cena_d Double precision;
  declare variable cena_b Double precision;
  declare variable mcena Double precision;
  declare variable cn integer;
  declare variable idcbt integer;
  declare variable idir integer;
  declare variable wazn integer;
  DECLARE kdr VARCHAR(80);
  DECLARE cnr Double precision;
begin

select KOD from kod_z_oferty(:iap,:itw,:ids) into :kod;
select COALESCE(warunki_handl,'T'),COALESCE(wazn_dost,1) from ogolne where id_apteki=:iap into wh,wazn;


if (ZDOST in ('T','R')  and wazn>=0) then
begin
  select first 1 c.cena_nt_jp,d.data,b.cena_nt_jp from zdst z
    left join ceny_dostawy c on c.id_apteki=z.id_apteki and c.id_zdst=z.id_zdst and c.id_ceny=1
    left join ceny_dostawy b on b.id_apteki=z.id_apteki and b.id_zdst=z.id_zdst and b.id_ceny=2
    left join dostawy d on d.id_apteki=z.id_apteki and d.id_dostawy=z.id_dostawy
    where z.id_apteki=:iap and z.id_towary=:itw and d.id_kontrahenci=:ids
    order by d.data desc  into cena_d,dt_ds,cena_b;
  if (cena_d is not null) then
  begin
    if (:wh='T') then
      cn_ds=cena_d;
    else
      cn_ds=cena_b;
    if (cena_b is not null and cena_b<>0) then
     up_ds=100*(cena_b-cena_d)/cena_b;
  end
end

if (:wh='T') then
BEGIN
  select COALESCE(upust,0),coalesce(upust_ref,0) from dostawcy where id_kontrahenci=:ids and id_apteki=:iap into :up,:upr;
  if ((SELECT j.REFUNDOWANY from JEST_REFUNDOWANY(:iap,:itw,'today',0) j )='T') then up=upr;
  if (zdost<>'C' and up<0) then up=0;
  if (zdost='C' and up>0) then up=0;
END
ELSE
  up = 0;  
  
if (kod is null or kod='') then
begin
  if (zdost<>'R') THEN
  BEGIN
    cena=cena_d;
    z_czego='D';
    dt_cen=dt_ds;
    suspend;
    exit;
  END  
end
ELSE
BEGIN
  z_czego='X';
  cena = 0;
  select first 1 cena, COALESCE(upust,0),c.id_poz_prom,c.DATA from oferty_ceny c 
  where c.kod=:kod and c.id_dostawcy=:ids order by iif(ID_POZ_PROM = '-1', cena * (100 - :up) * 0.01,cena) into cena,up_of,ID_P_PROM,dt;
  if (cena<>0) then
  begin
      z_czego='O';
      /*if (ID_P_PROM = '-1') THEN*/
      cena=cena-(cena*(up)/100);
      cn_of=cena;
      dt_cen=dt;
      dt_of=dt;
  end
END
if (kod > ' ') then
BEGIN
  if (ZDOST='T' and (dt_of is null or (dt_of<dt_ds and wazn>=0 and dt_ds+wazn>='TODAY'))) then
  begin
   cena=cena_d;
   z_czego='D';
   dt_cen=dt_ds;
  end
  suspend;
END
if (cena is null) THEN
  mcena = 99999999;
ELSE
  mcena = cena;
if (zdost = 'R') then
BEGIN
  select max(DATA) from oferty_ceny where id_dostawcy=:ids into :dt;
  SELECT id_cbt FROM TOWARY t where t.id_apteki=:iap and t.ID_TOWARY=:itw into idcbt;
  if (idcbt is NOT NULL ) THEN
    SELECT c.ID_ODPZL FROM CBT c where c.ID_CBT=:idcbt INTO idir;
  z_czego='R';
  dt_cen=dt;
  dt_of =dt;
  kdr = 'ccc';
  if (idir is NOT NULL ) THEN  
    FOR SELECT f.CENA,f.KOD
    FROM CBT c 
    LEFT JOIN CBT_KLAS k on k.ID_CBT=c.ID_CBT and k.ID_KLASYFIKACJE in (1,3)
    LEFT JOIN OFERTY_KLAS l on l.ID_KLASYFIKACJE=k.ID_KLASYFIKACJE and l.WARTOSC = k.WARTOSC and l.ID_DOSTAWCY=:ids
    LEFT JOIN OFERTY_CENY f on l.KOD=f.KOD and f.DATA = :dt  and f.ID_DOSTAWCY=:ids
    WHERE c.ID_ODPZL = :idir and c.ID_CBT<> :idcbt and f.CENA is not NULL
    order by k.id_cbt , k.id_klasyfikacje
    INTO cnr, kdr do
  BEGIN
    if (kdr <> kod) THEN
    BEGIN
      kod = kdr;
      cena=cnr-(cnr*up/100);
      cn_of = cena;
      if (cena < mcena) THEN
        SUSPEND;
    END
  END  
END
end
^

ALTER PROCEDURE AKT_CENA_SP (
    IAP INTEGER,
    ITW INTEGER,
    ICN INTEGER,
    DTA TIMESTAMP,
    IDZDST DOUBLE PRECISION,
    KWN VARCHAR(20) )
RETURNS (
    CENA_NT NUMERIC(15,2),
    CENA_BR NUMERIC(15,2),
    LIMIT NUMERIC(15,2),
    OPLATA DOUBLE PRECISION,
    JAKA CHAR(1),
    ID_ODPL INTEGER,
    DATA_DOSTAWY TIMESTAMP )

AS
declare variable id_typy_c Integer;
     declare variable id_odp Integer;
     declare variable liczenie char(1);
     declare variable nadpisz char(1);
     declare variable upTot char(1);
     declare variable NieZero char(1);
     declare variable marz Double precision;
     declare variable degr Integer;
     declare variable odc Integer;
     declare variable marza Double precision;
     declare variable cb numeric(15,2);
     declare variable cn numeric(15,2);
     declare variable cub numeric(15,2);
     declare variable cdb numeric(15,2);
     declare variable decyz char(1);
     declare variable lim Double precision;
     declare variable stan numeric(15,5);
     declare variable kw numeric(15,2);
     declare variable vat numeric(9,2);
     declare variable cnd numeric(15,2);
     declare variable cbd numeric(15,2);
     declare variable zarez Double precision;
     declare variable izdst Double precision;
     declare variable Upu Double precision;
     declare variable Opl Double precision;
     declare variable Opd Double precision;
     declare variable Odb timestamp;
     declare variable Obb timestamp;
     declare variable wwi Integer;
     declare variable wwn Double precision;
     declare variable r12 char(1);
     declare variable wnb char(1);
     declare variable idc Integer;
     declare variable ccc Double precision;
     declare idZaokr int;
     declare variable podwyzka Double precision;
     declare cenaPersonel int; 
     declare rabPacj Double precision; 
     declare rabGran Double precision; 
     declare cbu Double precision; 
     declare czu Double precision; 
     declare MarzaCentr Double precision; 
     DECLARE dtw date;
     DECLARE mn int;
     DECLARE dz int;
     DECLARE wnGrupa int;
begin
  select rok2012,coalesce(wnioski_bez_umowy,'N'),WWW_DO_DNI,WWW_DO_NARZUT,COALESCE(JAKA_CENA,0) from ogolne where id_apteki=:iap into r12,wnb,wwi,wwn,cenaPersonel;
  if (kwn is null or char_length(kwn)<3 or wnb='T') then
  kwn='N';
  select FIRST 1 ID_TYPY_CEN,NADPISUJ from TW_TYPY_CEN
    where ID_APTEKI=:iap and ID_TOWARY=:ITW and OBOWIAZUJE_OD <= :DTA order by OBOWIAZUJE_OD DESC into :id_typy_c,:nadpisz;
  marza=0;
  if (nadpisz is null) then nadpisz='N';
  select stawka from stawka_vat(:iap,:ITW, :DTA) into :vat;
  select SP_LICZENIA, MARZA, DEGRESJA, LICZONA_OD, UWZGL_UP,coalesce(id_zaokraglenia,0),COALESCE(z.RABAT,0) from Z_TYPY_CEN z
    where ID_CENY=:ICN and ID_TYPY_CEN=:id_typy_c into liczenie, marza, degr, odc,upTot,idZaokr,rabPacj;
  if (liczenie='N') then nadpisz='N';
  if (liczenie='U' and r12='T') then
  begin
    /* 54 = wnioski bezp³atnie Belzerowska  */
    select count(*) from tow_listy where id_apteki=:iap and id_towary=:itw and :dta between obowiazuje_od and obowiazuje_do and id_listy in
     (21,54) into wwi;
    /* dla wnioskow nie stosujemy sztywnej ceny */
    if (wwi>0 and wnb <> 'U') then r12='N';
    /* stala cena dla urzedowych od 2012 */
    if (icn>3) then icn=3;
  end
  
  if (idzdst = 0) THEN
  BEGIN
    select first 1 z.ID_ZDST from ZDST z
      where z.id_apteki=:iap and z.ID_TOWARY=:ITW and z.czynny='T'
      and z.STAN > COALESCE((select sum(ilosc) from rezerwacja r where r.id_apteki=z.ID_APTEKI and r.id_ZDST=z.ID_ZDST),0)
      + CASE WHEN coalesce(z.blokada,'N')='N' THEN 0 ELSE coalesce(z.ile_blokada,z.stan) END
      order by z.DATA, z.ID_ZDST
      into idzdst;
    idzdst = COALESCE(idzdst,0);
  END
  
  if (liczenie<>'U') then
  begin
  
    SELECT first 1 c.CENA from NEUCA_CENY_ZAW c 
    left join NEUCA_CENY e on c.ID_NEUCA_CENY=e.ID_NEUCA_CENY
    WHERE c.ID_TOWARY = :itw and e.AKTYWNA=1 and :dta BETWEEN e.DT_OD and e.DT_DO
    ORDER by c.CENA,e.PRIORYTET into ccc;
    if (ccc is not null) then
    begin
      cena_br=ccc;
      cena_nt=100*ccc/(100+vat);
      jaka='A';
      suspend;
      exit;
    end
  
    if (idzdst<>0)  THEN
    BEGIN
      SELECT FIRST 1 z.DATA_WAZN,c.CENA_BR_JP FROM ZDST z LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and z.ID_ZDST=c.ID_ZDST and c.ID_CENY=1
      WHERE z.ID_APTEKI=:iap AND z.ID_ZDST=:idzdst
      INTO dtw,czu;
      if (dtw is NULL or dtw < cast('01.01.1990' as date)) THEN
        dtw = cast('01.01.3000' as date);
    END
    ELSE
    BEGIN
      dtw = cast('01.01.3000' as date);
      czu = 0;
    END
    select id_cbt from towary where ID_APTEKI=:iap and ID_TOWARY=:ITW into idc;
    if (idc is not null) then
      select first 1 CENA_BR from cbt_c_centr c where id_cbt=:idc and id_ceny=:icn and :dta  between obowiazuje_od and obowiazuje_do
       and coalesce(typ,'A')='A' and c.CENA_BR>0 AND (c.MIN_MARZA is NULL or 100*(c.CENA_BR-:czu)/c.CENA_BR >= c.MIN_MARZA)
       AND (c.MAX_DW is NULL or :dtw-:dta <= c.MAX_DW)
       order by obowiazuje_od desc,c.CENA_BR
       into ccc;
    if (ccc is not null) then
    begin
      cena_br=ccc;
      cena_nt=100*ccc/(100+vat);
      jaka='E';
      suspend;
      exit;
    end
    select first 1 c.MARZA from cbt_c_centr c where id_cbt=:idc and id_ceny=:icn and :dta  between obowiazuje_od and obowiazuje_do
       and coalesce(typ,'A')='A' and c.MARZA > 0
       AND (c.MAX_DW is NULL or :dtw-:dta <= c.MAX_DW)
       order by obowiazuje_od desc
       into MarzaCentr;
  end
  
  if (liczenie = 'U' AND kwn = 'N') THEN
  BEGIN
    select first 1 PROD_HANDL.KOD_SR
      from TOWARY_WNIOSKI  
      left JOIN PROD_HANDL on TOWARY_WNIOSKI.ID_UMOWY = PROD_HANDL.ID_UMOWY and TOWARY_WNIOSKI.ID_PROD=PROD_HANDL.ID_PROD
      LEFT JOIN WNIOSKI_UMOWY u on TOWARY_WNIOSKI.ID_UMOWY=u.KOD
      where TOWARY_WNIOSKI.ID_APTEKI=:iap and TOWARY_WNIOSKI.ID_TOWARY=:itw
     ORDER by u.OD_DNIA DESC into kwn;
  end
  
  if (kwn = 'N') THEN
  begin
  for select CENA_NT,CENA_BR,MARZA,LIMIT,DECYZYJNA,OPLATA,OBOWIAZUJE_DO,OPL_ID_ODPL  from CENY_TOWARY
      where ID_APTEKI=:iap and ID_TOWARY=:itw and ID_CENY=:icn and OBOWIAZUJE_OD<=:dta  and (obowiazuje_do is null or obowiazuje_do>=:dta)
       
      order by OBOWIAZUJE_OD
      into :cn, :cb, :marz, :LIM,:decyz,opl,obb,id_odpl do
  begin
    if (cb is not null and cb>0) then
    begin
      oplata=null;   /*  dla urzedowych bierzemy tylko ostatnia odplatnosc  */
      if (decyz is not null and decyz='D') then
        cdb=cb;
      else
        cub=cb;
      odb=obb;
    end
    if (lim is not null and lim>0) then
      limit=:lim;

    if (opl is not null) then
    begin
      if (decyz is not null and decyz='D') then
         opd=opl;
      else
         opd=null;  /*  Jezeli wpisane dla urzedowej z wyzsza data to zerujemy decyzyjna*/
      oplata=opl;
    end
  end
  END
  ELSE
  BEGIN
    mn=1;
    dz=1;
    if ((select upper(nazwa) from jednostki where id_apteki=:iap and id_towary=:itw and jednostka=1) not like 'SZT%') then
      select mnoznik,dzielnik from jednostki where id_apteki=:iap and id_towary=:itw and jednostka=2 into mn,dz;
    
    SELECT count(*)  from PROD_ZPOSP_GRUPY g where g.KOD_SRODKA = :kwn and :dta BETWEEN g.DATA_OD and g.DATA_DO into wnGrupa;

    begin
    SELECT round(z.LIM_CENA * iif(z.LIM_JEDN='T',:mn/(:dz * 100),1),2),round(a.CENA * iif(z.LIM_JEDN='T',:mn/:dz,1),2) from TOWARY_WNIOSKI t
     join PROD_HANDL h on h.ID_PROD = t.ID_PROD and h.ID_UMOWY = t.ID_UMOWY
     join WNIOSKI_UMOWY u on t.ID_UMOWY = u.KOD
     join PROD_ZPOSP z on h.KOD_SR = z.KOD_SRODKA and :dta BETWEEN z.DATA_OD and z.DATA_DO
     join PAKIET_ZAOP a on a.ID_PROD = h.ID_PROD and a.ID_UMOWY = h.ID_UMOWY
     join PLANY_MIES m on a.ID_PAKIET=m.ID_PAKIET and a.ID_UMOWY = m.ID_UMOWY and m.ID_KOM = u.id_kom  and m.MIESIAC = EXTRACT(MONTH from  :dta)
    where t.ID_TOWARY = :itw and t.ID_APTEKI = :iap and (h.KOD_SR STARTING :kwn || '.' and :wnGrupa>0 or h.KOD_SR = :kwn  and :wnGrupa = 0)  and :dta BETWEEN u.OD_DNIA and u.DO_DNIA and m.MIESIAC is not NULL
    into limit,cub;
    when any do EXCEPTION BLAD  (SELECT t.NAZWA||' Ident: '||t.id_towary from TOWARY t where t.ID_TOWARY = :itw and t.ID_APTEKI = :iap) || '
Jest przyporz¹dkowany do kilku produktów w umowie.
Popraw przyporz¹dkowanie w ''Towary'' - ''Id produktu'' i ponów sprzeda¿. '  ;
    END 
	if (cub is not null) then
    BEGIN
      liczenie = 'U';
      r12 = 'N';
    END
  END
  if (MarzaCentr>0) THEN
  BEGIN
    marz = MarzaCentr;
    nadpisz = 'T';
  END
  if (icn=3 and liczenie<>'U') THEN
  BEGIN
    select u.UPUST from ktory_upust(:iap,0,:itw,:dta, -2, 3,'') u into podwyzka;
    if (podwyzka<0) THEN
      podwyzka =  -podwyzka;
    ELSE
      podwyzka = 0; 
  END
  ELSE
    podwyzka = 0;
  /* jezeli dla ostatnie urzedowej nie wpisano oodplatnosci sprawdzamy czy byla decyzyjna    */
  if (oplata is null) then
     oplata=:opd;
  /* podstaw cene decyzyjna rowna urzedowej jezeli nie znaleziono decyzyjnej*/
  if (cdb is null) then cdb=cub;
  if (r12='T') then
  begin
    oplata=null;
    id_odpl=null;
  end
  select stawka from stawka_vat(:iap,:ITW, :DTA) into :vat;
  /*Chwilowe obejscie dla cen WWW dla przypadku wpisania ceny w karcie */
  if (icn=4 and cdb is not null and cdb>0) then
  begin
    cena_br=cdb;
    cena_nt=100*cdb/(100+vat);
    jaka='X';
    suspend;
    exit;
  end
  /*Obejscie (blokada) dla ceny (6) i grosza */    
  if (icn>3 and icn=cenaPersonel and (idzdst=0 or
     (select cena_nt_jp from ceny_dostawy where ID_APTEKI=:iap and ID_ZDST=:IDZDST and id_ceny=1)<=0.01)
     ) THEN
  begin
    idzdst = 0;
    select first 1 z.id_zdst from ZDST z LEFT JOIN ceny_dostawy c on c.ID_APTEKI=z.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
      where z.ID_APTEKI=:iap and z.ID_TOWARY=:itw and c.cena_nt_jp>0.01 and z.DATA<=:dta
      order by c.obowiazuje_od desc into idzdst;
  end
  /* jezeli wpisano koniec obowiazywania ceny = promocja to zwracamy te cene */
  if (odb is not null and odb>=dta) then
  begin
    jaka='P';
    if (liczenie='U' and (cdb>cub or r12='T')) then
    begin
      cdb=cub;
    end
    cena_br=cdb;
    cena_nt=100*cdb/(100+vat);
    suspend;
    exit;
  end
  izdst=null;
  
  if (icn=0) THEN
  BEGIN
     select first 1 c.cena,c.DT_OF from dostawcy left join
       cena_z_oferty(:iap,:itw,id_kontrahenci,'C') c on 0=0 where id_apteki=:iap and www_dostawca='T' and c.cena>0
       ORDER by c.CENA DESC
     into cena_nt,data_dostawy;
     if (coalesce(cena_nt,0)>0) then
     begin
       CENA_BR=CENA_NT*( (100+vat)/100 );
       jaka='F';
       suspend;
       exit;
     end
     else
     begin
       icn = 2;
     end
  END
  
  if (liczenie<>'U' or r12<>'T') then
  begin
    if (IDZDST<>0) then
    begin
      /* szuka w ceny dostawy jezeli w typie cen jest nie nadpisuj lub w ceny dostawy jest nadpisuj*/
      select data from zdst where id_apteki=:iap and id_zdst=:idzdst into   odb;
      if (dta<odb) then dta=odb;

      select first 1 c.CENA_NT_JP, c.CENA_BR_JP,d.upust,c.id_zdst,c.nadpisuj,z.data from ceny_dostawy c
              left join zdst z on c.id_apteki=z.id_apteki and c.id_zdst=z.id_zdst
              left join dostawy d on z.id_apteki=d.id_apteki and z.id_dostawy=d.id_dostawy
              where c.ID_APTEKI=:iap and c.ID_ZDST=:IDZDST and c.ID_CENY=:ICN
              and (:nadpisz<>'T' or (c.nadpisuj is not null and c.nadpisuj='T'))
              and c.OBOWIAZUJE_OD<=:DTA
      order by c.obowiazuje_od desc
      into CENA_NT, CENA_BR,Upu,izdst,jaka,data_dostawy ;
      upu=upu;
      if (icn>2) THEN
        cena_nt=100*CENA_BR/(100+vat);
      NieZero='T';
    end
    else
    begin
      NieZero='N';
      for select c.CENA_NT_JP, c.CENA_BR_JP, z.STAN, z.ID_ZDST,d.UPUST,c.nadpisuj,z.data from ZDST z
       left join  ceny_dostawy c on c.id_apteki=z.id_apteki and z.ID_ZDST=c.ID_ZDST  and c.ID_CENY=:ICN
       left join dostawy d on z.id_apteki=d.id_apteki and z.id_dostawy=d.id_dostawy
        where z.id_apteki=:iap and z.ID_TOWARY=:ITW and z.czynny='T'
        and (coalesce(z.blokada,'N')='N' or coalesce(z.ile_blokada,z.stan)<z.stan)
        and c.id_ceny is not null and c.cena_br_jp is not null
        and (:nadpisz<>'T' or (c.nadpisuj is not null and c.nadpisuj='T'))
        and c.OBOWIAZUJE_OD<=:DTA
        order by z.DATA, z.ID_ZDST, c.obowiazuje_od
        into cn, cb, stan,izdst,upu,jaka,data_dostawy do
      begin
        select sum(ilosc) from rezerwacja where id_apteki=:iap and id_ZDST=:izdst into :zarez;
        if (:zarez is null) then
          zarez=0;
        if ((:stan-:zarez)>0) then
        begin
          if (icn>2) then
            CENA_NT=100*cb/(100+vat);
          ELSE
            CENA_NT=cn;
          CENA_BR=cb;
          NieZero='T';
        end
      end
       /*
       2010.02.12  poprawiony przypadek
       kiedy jest niezerowa dostawa ale nie ma ceny w dostawie
       if ((cena_nt is null or cena_br is null) and izdst is not null and nadpisz<>'T' ) then
       */

      if (niezero='N') then
      begin
        select sum(stan) from zdst where id_apteki=:iap and ID_TOWARY=:ITW into stan;
        if (stan>0) then niezero='T';
      end
      if ((cena_nt is null or cena_br is null) and nadpisz<>'T' and nieZero='N' ) then
      begin

       select first 1 c.CENA_NT_JP, c.CENA_BR_JP, z.STAN, z.ID_ZDST,d.UPUST,c.nadpisuj,z.data from ZDST z
       left join  ceny_dostawy c on c.id_apteki=z.id_apteki and z.ID_ZDST=c.ID_ZDST  and c.ID_CENY=:ICN
       left join dostawy d on z.id_apteki=d.id_apteki and z.id_dostawy=d.id_dostawy
        where z.id_apteki=:iap and z.ID_TOWARY=:ITW and c.id_ceny is not null and c.cena_br_jp is not null
        and (:nadpisz<>'T' or (c.nadpisuj is not null and c.nadpisuj='T'))
        and c.OBOWIAZUJE_OD<=:DTA
        order by z.DATA desc, z.ID_ZDST, c.obowiazuje_od
        into :cn, :cb, :stan,:izdst,:upu,jaka,data_dostawy;
        CENA_NT=cn;
        CENA_BR=cb;
      end
    end
  end
 /*
  2009.09.08  bylo
   if (liczenie='N' or (izdst is not null and cena_nt is not null and (NieZero='T') )) then

   jezeli nie bylo zadnej niezerowej dostawy liczyc z marzy

 */
  if (liczenie='N' or (izdst is not null and cena_nt is not null )) then
  begin
    if (UpTot='T' and (not Upu is null) and Upu>0 and :icn<3) then
    begin
      CENA_NT=CENA_NT*(1-0.01*Upu);
      CENA_BR=CENA_BR*(1-0.01*Upu);
    end
    /* podstaw cene urzedowa jezeli jest nizsza */
    if (liczenie='U' and (cena_br>cub or r12='T')) then
    begin
      cena_br=cub;
      cena_nt=100*cub/(100+vat);
      jaka='U';
    end
    else
    BEGIN
      if (jaka is null or jaka<>'T') then
        jaka='S';
      else
        jaka='T';
      cena_nt = cena_nt * (1+0.01*podwyzka);
      cena_br = cena_br * (1+0.01*podwyzka);
    END
    suspend;
    exit;
  end


  jaka=liczenie;
  if (liczenie in ('C','U')) then
  begin
    if (liczenie='U' and (cdb>cub or r12='T') ) then
    begin
      cdb=cub;
    end
    cn=100*cdb/(100+vat);
    CENA_NT=cn;
    CENA_BR=cdb;
    MARZA=0;
    cena_nt = cena_nt * (1+0.01*podwyzka);
    cena_br = cena_br * (1+0.01*podwyzka);

    if ((cn=0 or cn is null) and icn>3) then
      select cena_nt,cena_br,limit,oplata,jaka from akt_cena_sp(:iap,:ITW, 3, :DTA, :IDZDST,'')
        into cena_nt,cena_br,limit,oplata,jaka;

    suspend;
    exit;
  end

  if (liczenie in ('O','M','D')) then
  begin
     select CENA_NT, CENA_BR,data_dostawy from AKT_CENA_SP(:iap,:ITW, :odc, :DTA, :IDZDST,'')
          into cn, cb, data_dostawy;
     if (not (marz is null)) then
          marza=marz;
     if (liczenie='O') then
     begin
       CENA_BR=cb*(1+marza/100);
     end
     if (liczenie='M') then
     begin
       CENA_BR=cb/((100-marza)/100);
     end
     if (liczenie='D') then
     BEGIN
       select DETAL from marza_degr(:cb,:degr,:DTA) into CENA_BR;
     END 
     if (rabPacj <> 0) THEN
     BEGIN
       if (idzdst=0) THEN
         SELECT FIRST 1 z.ID_ZDST FROM ZDST z where z.ID_APTEKI=:iap and z.ID_TOWARY=:itw and z.CZYNNY='T' 
         INTO idzdst;
       
       
       SELECT CENA_BR FROM AKT_CENA_SP(:iap,:ITW, 2, :DTA, :IDZDST,'') INTO cbu;
       SELECT CENA_BR FROM AKT_CENA_SP(:iap,:ITW, 1, :DTA, :IDZDST,'') INTO czu;
       if (cbu>0) THEN
       BEGIN
         czu = 100 * (cbu - czu)/cbu ;
         SELECT max(d.OBOWIAZUJE_OD) FROM DEGRESJA d where d.DEGRESJA = :rabPacj into dtw;
         SELECT FIRST 1 d.MARZA FROM DEGRESJA d where d.DEGRESJA=:rabPacj and d.OBOWIAZUJE_OD = :dtw and d.GRANICA<=:czu
         order by d.GRANICA DESC
          into rabGran;
         
         if (rabGran is not null) THEN
            CENA_BR = CENA_BR - cbu * 0.01 * rabGran;
       END

     END
     if (IdZaokr<>0) then
     begin
       select z.ZAOKRAGLONA  from  ZAOKRAGLIJ_CENE(:cena_br,:IdZaokr,:dta) z into cena_br;
     end
     CENA_NT=CENA_BR/ ((100+vat)/100);
     if (icn=4 and wwn>0 and (data_dostawy<cast('TODAY' as date)-wwi or cena_nt is null)) then
     begin
       cn=cena_nt;
       cena_nt=null;
     end
     else
     begin
       cena_nt = cena_nt * (1+0.01*podwyzka);
       cena_br = cena_br * (1+0.01*podwyzka);
       suspend;
       exit;
     end
  end



  if (coalesce(cena_nt,0)=0 and icn=4) then
  begin
     select min(c.cena) from dostawcy left join
       cena_z_oferty(:iap,:itw,id_kontrahenci,'N') c on 0=0 where id_apteki=:iap and www_dostawca='T' and c.cena>0
       into cena_nt;
     if (coalesce(cena_nt,0)>0) then
     begin
       cena_nt=cena_nt*(1+0.01*wwn);
       CENA_BR=CENA_NT*( (100+vat)/100 );
       if (IdZaokr<>0) then
       begin
          select z.ZAOKRAGLONA  from  ZAOKRAGLIJ_CENE(:cena_br,:IdZaokr,:dta) z into cena_br;
          CENA_NT=CENA_BR/ ((100+vat)/100);
       end
       jaka='F';
       suspend;
     end
     else
     if (cena_br>0 and (select stan from stan_wart(:iap,:itw,0))>0) then
     begin
       cena_nt=cn;
       suspend;
     end
  end
end
^

ALTER PROCEDURE AKT_LIMIT (
    IAP INTEGER,
    IDT INTEGER,
    ODPL INTEGER,
    DT TIMESTAMP,
    KW VARCHAR(20) )
RETURNS (
    LIMIT DOUBLE PRECISION )

AS
declare variable cb Double precision;
declare variable lm Double precision;
declare variable wnb char(1);
declare variable ref char(1);
DECLARE mn int;
DECLARE dz int;
DECLARE wnGrupa int;
begin

if (kw is null or char_length(kw)<3) then
  kw='N';
else
begin
  if (left(kw,1) = '-') then   /*  ustawienie dla trybutu GW__WL - nie u¿ywane */
  begin
    kw = substring(kw from 2);
    select first 1 LIMIT  from CENY_TOWARY
    where ID_APTEKI=:iap and ID_TOWARY=:idt and ID_CENY=3 and OBOWIAZUJE_OD<=:dt  and (obowiazuje_do is null or obowiazuje_do>=:dt)
    order by OBOWIAZUJE_OD desc
    into limit;
    SUSPEND;
    exit;
  end
  else
    select coalesce(wnioski_bez_umowy,'N') from ogolne where id_apteki=:iap into wnb; 
end

if (kw<>'N' and wnb='T') then
begin
  mn=1;
  dz=1;
  if ((select upper(nazwa) from jednostki where id_apteki=:iap and id_towary=:idt and jednostka=1) not like 'SZT%') then
      select mnoznik,dzielnik from jednostki where id_apteki=:iap and id_towary=:idt and jednostka=2 into mn,dz;
  select first 1 lim_cena,lim_jedn from PROD_ZPOSP where kod_srodka=:kw and :dt between data_od and data_do into lm,wnb;
  lm=lm*0.01;
  if (wnb<>'N' and dz<>0) then
    lm=lm*0.01*mn/dz;
  limit=lm;
  SUSPEND;
  exit;
end

select refundowany  from jest_refundowany(:iap,:idt,:dt,1) into ref;

if (lm is null and ref='T') then
BEGIN
  if (kw = 'N' or wnb = 'T') then
    for  select CENA_BR,LIMIT  from CENY_TOWARY
       where ID_APTEKI=:iap and ID_TOWARY=:idt and ID_CENY=3 and OBOWIAZUJE_OD<=:dt  and (obowiazuje_do is null or obowiazuje_do>=:dt)
        and  ( :kw = 'N' or wn_kod= :kw) and  (DECYZYJNA='U' or :wnb='T')
        order by OBOWIAZUJE_OD
        into :cb, :LM do
  begin
    if (lm is not null) then
      limit=lm;
  end
  ELSE
  BEGIN
    mn=1;
    dz=1;
    if ((select upper(nazwa) from jednostki where id_apteki=:iap and id_towary=:idt and jednostka=1) not like 'SZT%') then
      select mnoznik,dzielnik from jednostki where id_apteki=:iap and id_towary=:idt and jednostka=2 into mn,dz;
     SELECT count(*)  from PROD_ZPOSP_GRUPY g where g.KOD_SRODKA = :kw and :dt BETWEEN g.DATA_OD and g.DATA_DO into wnGrupa;
     begin
     SELECT round(z.LIM_CENA * iif(z.LIM_JEDN='T',:mn/:dz,1) * 0.01,2) from TOWARY_WNIOSKI t
       left join PROD_HANDL h on h.ID_PROD = t.ID_PROD and h.ID_UMOWY = t.ID_UMOWY
       left join WNIOSKI_UMOWY u on t.ID_UMOWY = u.KOD
       left join PROD_ZPOSP z on h.KOD_SR = z.KOD_SRODKA and :dt BETWEEN z.DATA_OD and z.DATA_DO
       left join PAKIET_ZAOP a on a.ID_PROD = h.ID_PROD and a.ID_UMOWY = h.ID_UMOWY
       left join PLANY_MIES m on a.ID_PAKIET=m.ID_PAKIET and a.ID_UMOWY = m.ID_UMOWY and m.ID_KOM = u.id_kom  and m.MIESIAC = EXTRACT(MONTH from  :dt)
     where t.ID_TOWARY = :idt and t.ID_APTEKI = :iap and (h.KOD_SR STARTING :kw  || '.' and :wnGrupa>0 or h.KOD_SR = :kw  and :wnGrupa = 0) and :dt BETWEEN u.OD_DNIA and u.DO_DNIA and m.MIESIAC is not NULL
     into limit;
         when any do EXCEPTION BLAD  (SELECT t.NAZWA||' Ident: '||t.id_towary from TOWARY t where t.ID_TOWARY = :idt and t.ID_APTEKI = :iap) || '
Jest przyporz¹dkowany do kilku produktów w umowie.
Popraw przyporz¹dkowanie w ''Towary'' - ''Id produktu'''  ;
     end   
  end
  if (ODPL=8) then  LIMIT=:cb;
end
ELSE
  limit = null;  
suspend;
end^

ALTER PROCEDURE AKT_ODPL_PODST (
    IAP INTEGER,
    ID_TOW INTEGER,
    DATA TIMESTAMP,
    ID_LISTY INTEGER,
    ATR CHAR(9),
    CEND DOUBLE PRECISION,
    LIMI DOUBLE PRECISION )
RETURNS (
    CENA NUMERIC(15,2),
    UZYTY_ODPOWIEDNIK INTEGER,
    RABAT NUMERIC(15,2) )
AS
declare variable cn numeric(15,2);
     declare variable opRycz Integer;
     declare variable dzRycz Integer;
     declare variable tabletek Integer;
     declare variable Dztabl Integer;
     declare variable id_odpl Integer;
     declare variable limit numeric(15,2);
     declare variable ryczalt numeric(15,2);
     declare variable ryczalt1 numeric(15,2);
     declare variable sztuk Double precision;
     declare variable reszta Double precision;
     declare variable doplata numeric(15,2);
     declare variable odplatnosc numeric(15,2);
     declare variable maxkol Integer;
     declare variable LmOdpZb double precision;
     declare variable Opl double precision;
     declare variable rycz Numeric(15,2);
     declare variable doli char(1);
     declare variable id_odpl_obn integer;
     declare variable limCu integer;
     declare variable r12 char(1);
begin
  ODPLATNOSC=0;
  DOPLATA=0;
  LIMIT=0;
  tabletek=1;
  UZYTY_ODPOWIEDNIK=0;
  select PODNOS_DO_LIMITU,rok2012 from ogolne where id_apteki=:iap into doli,r12;
  
  select CENA_BR,OPLATA,ID_ODPL from akt_cena_sp(:iap,:ID_TOW,3,:DATA,0,'') into :cn,:opl,id_odpl_obn;
  
  if (limi>0) then 
    limit=limi;
  else  
    select LIMIT from akt_limit(:iap,:ID_TOW,3,:DATA,'') into limit;

  if (cend>0) then cn=cend;

  if (r12='T') then
  begin
    select ILOSC_DDD from towary where id_apteki=:iap and id_towary=:Id_Tow into sztuk;
    dzRycz=0;
    if (sztuk<30) then
      sztuk=30;
  end
  else
    select MNOZNIK,DZIELNIK from jednostki where id_apteki=:iap and id_towary=:Id_Tow and jednostka=-1 into :opRycz,dzRycz;



  if (atr containing '_') then
  begin
    select max(kolejnosc) from listy_odpl where id_listy=:ID_LISTY into :maxkol;
    select max(ID_ODPLATN) from listy_odpl where id_listy=:ID_LISTY and kolejnosc=:maxkol into :id_odpl;
  end
  else
  begin
   select min(kolejnosc) from listy_odpl where id_listy=:ID_LISTY and :atr like atrybuty into :maxkol;
   select max(ID_ODPLATN) from listy_odpl where id_listy=:ID_LISTY and kolejnosc=:maxkol  and :atr like atrybuty into :id_odpl;
  end

  select MNOZNIK,DZIELNIK from jednostki where id_apteki=:iap and id_towary=:Id_Tow and jednostka=2 into :Tabletek,dzTabl;


  if (limi>0) then limit=limi;

  if (limit is null or limit=0) then
    limit=cn;
  ODPLATNOSC=cn;
  if (id_odpl=6 and r12='N') then
  begin

    select uzyty_odpowiednik,limit_re,id_odpl,JednOdp from
      refundowany_jako_zamiennik((select t.id_cbt from towary t where t.id_apteki=:iap and t.id_towary=:Id_Tow ),
      :cn,:data,:atr) into uzyty_odpowiednik,limit,id_odpl,OpRycz;

  end

  rabat=0;

  if (doli='T' and limit>0 and id_odpl<>6 and id_odpl<>0 and cn<limit) then
  begin
     if (Uzyty_Odpowiednik<0) then
         select first 1 CENA_BR*100  from CBT_CENY
         where ID_CBT=-:Uzyty_odpowiednik and ID_CENY=3 and OBOWIAZUJE_OD<=:data
         order by OBOWIAZUJE_OD desc into limCu;
      else
      begin
         if (uzyty_odpowiednik>0) then
           limCu = uzyty_odpowiednik;
         else
           limCu = id_tow;
         select first 1 CENA_BR*100  from CENY_TOWARY
         where ID_APTEKI=:iap and id_towary=:limcu and ID_CENY=3 and OBOWIAZUJE_OD<=:data and  DECYZYJNA='U'  and (obowiazuje_do is null or obowiazuje_do>=:data)
         order by OBOWIAZUJE_OD desc into limCu;
      end
      if (limCu is not null and limCu>0 and limCu*0.01<limit) then
        cn=limCU*0.01;
      else
        cn=limit;
  end

  if (limit>cn) then limit=cn;



  if (r12='T') then
    select OPLATA from akt_oplata(:iap,:ID_TOW,3,:DATA,:id_odpl) into LmOdpZb ;
  else
    LmOdpZb=-1;


  if (LmOdpZb>=0) then
  begin
    DOPLATA=:cn-LIMIT;
    ODPLATNOSC=LmOdpZb-DOPLATA;
  end
  else
  begin

    /*Bezplatne*/
    if (id_odpl=1) then
    begin
      ODPLATNOSC=0;
    end

    /*Bezplatne do limitu*/
    if (id_odpl=2) then
    begin
      ODPLATNOSC=:cn-LIMIT;
    end

    /*Ryczalt%*/
    if (id_odpl=3) then
    begin
      if (r12='T') then
        ryczalt=999;
      else
        select rycz from ktory_upust(:iap,0,:id_tow,:data, -1, 3,'') into :rycz;
      if (:rycz is null) then
        ryczalt=999;
      else
        ryczalt=:rycz;
      select r1 from ryczalt(:data) into :ryczalt1;
      if (ryczalt=999 or ryczalt<0) then
         ryczalt=ryczalt1;
      if (tabletek is not null and tabletek>0 and OpRycz is not null and OpRycz>0 and dzTabl>0 and dzRycz>0) then
        Sztuk=(Tabletek*dzRycz)/(OpRycz*dzTabl);
      else
        if (r12='T' and Sztuk>0) then
          Sztuk= Sztuk/30;
        else
          Sztuk=1;

      if (r12='T') then
        reszta=0;
      else
        reszta=sztuk-floor(sztuk);

      if (LIMIT<=sztuk*ryczalt) then
         ODPLATNOSC=LIMIT;
      else
      if (reszta>0) then
      begin
        if (reszta*limit/sztuk<ryczalt) then
          ODPLATNOSC=floor(sztuk)*ryczalt+reszta*limit/sztuk;
        else
          ODPLATNOSC=(floor(sztuk)+1)*ryczalt;
      end
      else
      begin
        ODPLATNOSC=SZTUK*ryczalt;
        rabat=(ryczalt1-ryczalt)*sztuk;
      end
      DOPLATA=:cn-LIMIT;
    end

    /*30%*/
    if (id_odpl=4) then
    begin
      ODPLATNOSC=cast(30*LIMIT as integer) * 0.01;
      DOPLATA=:cn-LIMIT;
    end

    /*50%*/
    if (id_odpl=5) then
    begin
      ODPLATNOSC=cast(50 *LIMIT as integer) * 0.01;
      DOPLATA=:cn-LIMIT;
    end

    /*100*/
    if (id_odpl=6) then
    begin
      ODPLATNOSC=:cn;
    end

    if (id_odpl=7) then
    begin
      DOPLATA=:cn-LIMIT;
    end

    if (id_odpl=8) then
    begin
      select r3 from ryczalt(:data) into :ryczalt;
      ODPLATNOSC=ryczalt;
    end

    if (id_listy in (27,28,29)) then
    begin
      odplatnosc=0;
      doplata=0;
    end

    if (id_odpl<>0 and id_odpl<>6 and opl is not null and (odplatnosc+doplata)>opl and (id_odpl_obn is null or id_odpl_obn=0 or id_odpl_obn=id_odpl) and r12='N') then
    begin
       if (odplatnosc>opl) then
       begin
         doplata=0;
         rabat=odplatnosc-opl;
         odplatnosc=opl;
       end
       else
       begin
         doplata=opl-odplatnosc;
       end
    end
  end
  CENA=:odplatnosc+:doplata;
  suspend;
end
^

ALTER PROCEDURE DANE_DRR (
    DT TIMESTAMP,
    TR INTEGER,
    SP INTEGER,
    AP INTEGER )
RETURNS (
    IDSP INTEGER,
    CZSP TIMESTAMP,
    RCAT VARCHAR(50),
    RCNR VARCHAR(50),
    RCND INTEGER,
    RCIW INTEGER,
    KOSI INTEGER,
    KOWE INTEGER,
    KODO INTEGER,
    RCPA VARCHAR(50),
    TRSP CHAR(1),
    SPIT INTEGER,
    TPOS VARCHAR(100),
    TDAW VARCHAR(100),
    TOPA VARCHAR(100),
    TEAR VARCHAR(20),
    TTPD VARCHAR(10),
    TRPL VARCHAR(40),
    TILO INTEGER,
    TJNM VARCHAR(30),
    EREA CHAR(1),
    RCTR INTEGER,
    RCTN INTEGER,
    RCDT CHAR(1),
    RCDK CHAR(3),
    RCDN VARCHAR(40),
    RCUP TIMESTAMP,
    DKOI VARCHAR(100),
    DKOP VARCHAR(100),
    PCNM VARCHAR(200),
    PCLE VARCHAR(100),
    PCTL VARCHAR(100),
    PKRA VARCHAR(100),
    PKOD VARCHAR(10),
    PMIA VARCHAR(100),
    PULI VARCHAR(100),
    PNRD VARCHAR(10),
    PNRL VARCHAR(10),
    PPOC VARCHAR(100),
    AKRA VARCHAR(100),
    AKOD VARCHAR(10),
    AMIA VARCHAR(100),
    AULI VARCHAR(100),
    ANRD VARCHAR(10),
    ANRL VARCHAR(10),
    APOC VARCHAR(100),
    ATEL VARCHAR(20),
    APNM VARCHAR(200),
    RCOP BLOB SUB_TYPE 0,
    SPZA INTEGER,
    SPIO INTEGER,
    SPWA DOUBLE PRECISION,
    SPOD DOUBLE PRECISION,
    SPDP DOUBLE PRECISION,
    SPCN DOUBLE PRECISION,
    SPIL DOUBLE PRECISION,
    SPLM DOUBLE PRECISION,
    RCLK VARCHAR(20),
    RCPR VARCHAR(20),
    RCIR INTEGER,
    SPDW TIMESTAMP,
    SPSN VARCHAR(40),
    SPPR INTEGER,
    RCDW TIMESTAMP,
    TNAZ VARCHAR(100),
    ZLTL DOUBLE PRECISION,
    ZLLT CHAR(1),
    ZLNP VARCHAR(100),
    ZLIP INTEGER,
    ZLKP VARCHAR(20),
    ZLNM VARCHAR(200),
    ZLPR INTEGER,
    ZLPN VARCHAR(100),
    ZLPI VARCHAR(100),
    ZLPO VARCHAR(100),
    ZLRN VARCHAR(100),
    ZLRI VARCHAR(100),
    ZLRO VARCHAR(100),
    ZLWG DOUBLE PRECISION,
    ZLWN VARCHAR(100),
    ZLDP TIMESTAMP,
    ZLDR TIMESTAMP,
    ZLDW TIMESTAMP,
    ZLAS CHAR(1),
    EREC BLOB SUB_TYPE 0,
    SPDS TIMESTAMP,
    TMIW INTEGER,
    RLEK CHAR(1),
    PIDK INTEGER )


AS
DECLARE TRGO INTEGER;
DECLARE TRID TIMESTAMP;
DECLARE MRNR VARCHAR(50);
DECLARE MRPA VARCHAR(50);
DECLARE MIDS INTEGER;
DECLARE MREA CHAR(1);
DECLARE MSTA CHAR(1);
DECLARE MTDT DATE;
DECLARE MTRGO INTEGER;
DECLARE MTRID TIMESTAMP;
DECLARE MMTDT DATE;
BEGIN
  FOR SELECT s.ID_SPRZEDAZ,s.TRYB,r.ATRYBUTY,t.IFUPDDATE,r.NUMER,r.NR_W_DNIU,r.ID_WYDAL,t.GODZINA,t.IFINSDATE,r.PACJENT,s.ID_TOWARY,
      o.POSTAC,o.DAWKA,o.OPAKOWANIE,o.EAN_REF,d.TYP,k.WARTOSC,j.MNOZNIK,j.NAZWA,s.CZESCIOWA ,r.TRYB,r.TYP_NR_PAC,r.DOK_KRAJ,r.DOK_NUMER,r.DOK_TYP,r.DT_UR_PACJ,
      rd.OID,rd.OPIS,n.NM_KONTRAHENCI,n.LEG_NR,'Polska',n.kod,n.MIASTO,n.ULICA,n.NR_DOMU,n.NR_LOKALU,n.POCZTA,'Polska',a.kod,a.MIASTO,a.ULICA,a.NR_DOMU,a.NR_LOKALU,a.POCZTA,a.TELEFON,
      a.NM_KONTRAHENCI,r.RECF_OPIS,s.ID_ZAMIENNIK,s.ID_ODPLATNOSC,s.WARTOSC+s.TAKSA,s.ODPLATNOSC,s.DOPLATA,al.LIMIT,r.LEKARZ,r.PRZYCHODNIA,s.ID_RECEPTA,s.POZ_REC,r.DATA_WYST,
      o.NAZWA,left(ud.NMD,100),d.RDZ,n.ID_KONTRAHENCI
  FROM SPRZEDAZ s
  LEFT JOIN ETAKSACJE e on e.ID_SPRZEDAZ=s.ID_SPRZEDAZ and e.ID_APTEKI=s.ID_APTEKI
  LEFT JOIN RECEPTA r on s.ID_RECEPTA=r.ID_RECEPTA and r.ID_APTEKI=s.ID_APTEKI
  LEFT JOIN TRANZAKCJE t on s.DATA=t.DATA and t.ID_TRANZAKCJE=s.ID_TRANZAKCJE and s.ID_APTEKI=t.ID_APTEKI
  LEFT JOIN TOWARY o on s.ID_TOWARY=o.ID_TOWARY and s.ID_APTEKI=o.ID_APTEKI left JOIN typ_dostepnosci  ( s.ID_APTEKI,s.ID_TOWARY,s.DATA) d on 0=0
  LEFT JOIN CBT_KLAS k on k.ID_CBT=o.ID_CBT and k.ID_KLASYFIKACJE=-10 
  LEFT JOIN JEDNOSTKI j on j.ID_APTEKI=o.ID_APTEKI and j.ID_TOWARY=o.ID_TOWARY and j.JEDNOSTKA=2
  LEFT JOIN HL7 rd on rd.ID=2 and rd.TYP=r.DOK_TYP || r.DOK_KRAJ
  LEFT JOIN KONTRAHENCI i on i.PESEL = IIF(r.TYP_NR_PAC=2, r.DOK_NUMER, r.PACJENT)
  LEFT JOIN KONTRAHENT(COALESCE(i.id_kontrahenci,r.ID_KONTRAHENCI)) n on 0=0
  LEFT JOIN KONTRAHENT(0) a on 0=0
  LEFT JOIN AKT_LIMIT(s.ID_APTEKI,s.ID_TOWARY,s.ID_ODPLATNOSC,s.DATA,r.KOD_SRODKA) al on 0=0
  LEFT JOIN UPR_DOD_DOK ud on ud.IDD = i.LEGITYMACJA
  WHERE s.DATA = :dt and s.ID_TRANZAKCJE = :tr and s.ID_APTEKI = :ap  AND (:sp = 0 or s.ID_SPRZEDAZ = :sp) AND s.ID_RECEPTA is not NULL
    AND e.STATUS is DISTINCT from 'W' AND r.ATRYBUTY NOT similar to 'GW%|GP%|GV%'
    ORDER by s.ID_RECEPTA,s.POZ_REC,s.ID_SPRZEDAZ
  INTO IDSP,TRSP,RCAT,CZSP,RCNR,RCND,RCIW,TRGO,TRID,RCPA,SPIT,TPOS,TDAW,TOPA,TEAR,TTPD,TRPL,TILO,TJNM,EREA,RCTR,RCTN,RCDK,RCDN,RCDT,RCUP,DKOI,DKOP,PCNM,PCLE
   ,PKRA,PKOD,PMIA,PULI,PNRD,PNRL,PPOC,AKRA,AKOD,AMIA,AULI,ANRD,ANRL,APOC,ATEL,APNM,RCOP,SPZA,SPIO,SPWA,SPOD,SPDP,SPLM,RCLK,RCPR,RCIR,SPPR,RCDW,TNAZ,PCTL,RLEK,PIDK do
  BEGIN
    SELECT round(sum(r.SZTUK_JP),5),min(z.DATA_WAZN),max(k.WARTOSC) from RZDST r 
    LEFT JOIN ZDST z on r.ID_ZDST=z.ID_ZDST and r.ID_APTEKI=z.ID_APTEKI
    LEFT JOIN ZDST_KLAS k on k.ID_ZDST=z.ID_ZDST and k.ID_APTEKI=z.ID_APTEKI and k.ID_KLASYFIKACJE = 5
    WHERE r.ID_SPRZEDAZ = :IDSP and r.ID_APTEKI = :ap into spil,SPDW,SPSN;
    
    if (CHARACTER_LENGTH(rcnr) = 44) THEN
      SELECT e.ZRODLO FROM ERECEPTY e WHERE e.KLUCZ = :rcnr INTO erec;
    
    if (spdw<'01.01.2000') THEN
      spdw = null;
    if (SPIL<>0) THEN
      SPCN = SPWA / SPIL;
    ELSE
      SPCN = 0;  
    KOSI = IDSP;
    KOWE = 1;
    MTDT = DT;
    KODO = NULL;
    
    if (EXTRACT(DAY FROM CZSP) <> EXTRACT(DAY FROM MTDT)) THEN
      if (EXTRACT(DAY FROM TRID) <> EXTRACT(DAY FROM MTDT)) THEN
        czsp = trid;
      ELSE
        czsp = mtdt + trgo/24;

    SPDS = czsp;
    if (CHARACTER_LENGTH(TEAR) = 13 ) THEN
      TEAR = '0' || TEAR;

    if (TRSP <> 'S') THEN
    BEGIN
      
      if (TRSP = 'Z') THEN
      BEGIN
        SELECT r.NUMER,r.PACJENT
        FROM ZMIANY z 
        LEFT JOIN SPRZEDAZ s on z.NASTEPNY=s.ID_SPRZEDAZ and s.ID_APTEKI = z.ID_APTEKI
        LEFT JOIN RECEPTA r on s.ID_RECEPTA=r.ID_RECEPTA and r.ID_APTEKI=s.ID_APTEKI
        WHERE z.ID_SPRZEDAZ = :idsp and z.ID_APTEKI = :ap and (s.ID_TOWARY<>0 or s.DATA>'01.01.1900'  or z.NASTEPNY is NULL)
        INTO MRNR,MRPA;
        if (NOT (RCNR is DISTINCT FROM MRNR or RCPA is DISTINCT FROM MRPA)) THEN
          TRSP = 'P';
      END
      if (TRSP in ('R','N')) THEN
      BEGIN
        SELECT r.NUMER,r.PACJENT
        FROM ZMIANY z
        LEFT JOIN SPRZEDAZ s on z.POPRZEDNI=s.ID_SPRZEDAZ and s.ID_APTEKI = z.ID_APTEKI
        LEFT JOIN RECEPTA r on s.ID_RECEPTA=r.ID_RECEPTA and r.ID_APTEKI=s.ID_APTEKI
        WHERE z.ID_SPRZEDAZ = :idsp and z.ID_APTEKI = :ap
        INTO MRNR,MRPA;
        if (RCNR is DISTINCT FROM MRNR or RCPA is DISTINCT FROM MRPA) THEN TRSP = 'S';
      END

      if (TRSP NOT IN ('S','P')) THEN
      BEGIN
        FOR SELECT h.IDSP,e.REALIZACJA,e.STATUS
        FROM HIST_KOREKTY(:ap,:idsp) h
        LEFT JOIN ETAKSACJE e on e.ID_SPRZEDAZ = h.IDSP and e.ID_APTEKI = :ap
        WHERE h.IDSP<:idsp and e.STATUS in ('W','N','B','Z')
        ORDER by h.WERSJA DESC
        INTO MIDS,MREA,MSTA do
        BEGIN
          if (MREA in ('W') and MSTA not in ('B','Z')) THEN LEAVE; /* wycofuj¹ca */
          if (MSTA in ('B','Z')) THEN 
          BEGIN
             if (MSTA = 'B') THEN
             BEGIN
               UPDATE ETAKSACJE e set e.STATUS = 'Z' WHERE e.ID_SPRZEDAZ = :mids and e.ID_APTEKI = :ap;
             END
          END
          ELSE
          BEGIN
            KOSI = MIDS;
            KOWE = KOWE + 1;
            if (KODO is null) THEN
              KODO = KOSI;
          END  
        END
        IF (TRSP = 'Z' AND KOWE = 1) THEN
        BEGIN
          TRSP = 'P';
        END  
        ELSE
        BEGIN
          SELECT t.IFUPDDATE,t.GODZINA,t.IFINSDATE,t.DATA FROM SPRZEDAZ s  LEFT JOIN TRANZAKCJE t on s.DATA=t.DATA and t.ID_TRANZAKCJE=s.ID_TRANZAKCJE and s.ID_APTEKI=t.ID_APTEKI
          WHERE s.ID_SPRZEDAZ = :kosi AND s.ID_APTEKI = :ap INTO spds,MTRGO,MTRID,MMTDT;
          if (EXTRACT(DAY FROM SPDS) <> EXTRACT(DAY FROM MMTDT)) THEN
            if (EXTRACT(DAY FROM MTRID) <> EXTRACT(DAY FROM MMTDT)) THEN
              spds = mtrid;
            ELSE
              spds = mmtdt + mtrgo/24;
          
        END  
      END  
    END
    if (TRSP <> 'P') THEN
    BEGIN
      if (SPIT=0) THEN
      BEGIN

        SELECT FIRST 1 a.TL,z.TYP_LIMITU,z.NM_POST_ZL,r.PROSZKOW, u1.NAZWISKO  przyj,u1.NFZID przi,h1.OID przr,u2.NAZWISKO  rozl,u2.NFZID rozi,h2.OID rozr,
             (select sum(sztuk_rp) from rzdst d where d.ID_APTEKI=r.ID_APTEKI and d.id_sprzedaz=r.ID_SPRZEDAZ and
               (select count(*) from tw_klas k where k.id_towary=d.id_towary and k.id_klasyfikacje=7 and k.wartosc='Opakowanie do receptury')=0) waga,
             u3.NAZWISKO wydal,r.dt_przyj,r.dt_rozl,r.dt_odb,z.ASEPTYCZNE,coalesce(r.ID_ODB,:RCIW),r.ID_ODB,z.KOD_XML,l.TYP,l.OPIS,r.DT_WAZN
           FROM HIST_KOREKTY(:ap,:IDSP) h
           LEFT JOIN RECEPTURA r on h.IDSP = r.ID_SPRZEDAZ and r.ID_APTEKI = :ap
           LEFT JOIN POST_ZL z on r.ID_POST_ZL = z.ID_POST_ZL
           LEFT JOIN users u1 on u1.ID_APTEKI=r.ID_APTEKI and u1.ID_USERS=r.ID_PRZYJ LEFT JOIN hl7 h1 on h1.ID=1 AND u1.TYP_ID=h1.TYP
           left JOIN users u2 on u2.ID_APTEKI=r.ID_APTEKI and u2.ID_USERS=r.ID_ROZL  LEFT JOIN hl7 h2 on h2.ID=1 AND u2.TYP_ID=h2.TYP
           LEFT JOIN users u3 on u3.ID_APTEKI=r.ID_APTEKI and u3.ID_USERS=r.ID_ODB
           LEFT JOIN akt_tl(r.id_post_zl,r.dt_rozl, 'T') a on 0=0
           LEFT JOIN HL7 l on z.POST_POD = l.TYP AND l.ID = 3
           WHERE r.ID_SPRZEDAZ is not NULL
           INTO
             ZLTL,ZLLT,ZLNP,ZLPR,ZLPN,ZLPI,ZLPO,ZLRN,ZLRI,ZLRO,ZLWG,ZLWN,ZLDP,ZLDR,ZLDW,ZLAS,RCIW,TMIW,ZLIP,ZLKP,ZLNM,SPDW;

      END
      if (SPIT <> 0 or TMIW is not null or trsp='Z') THEN
           SUSPEND;
    END
  END
END
^

ALTER PROCEDURE MOJA_REZERWACJA (
    IAP INTEGER,
    ID_TOW INTEGER,
    ID_ZDST DOUBLE PRECISION,
    ILOSC NUMERIC(15,5),
    NRKASY INTEGER,
    TRYB CHAR(1),
    DATA_SP TIMESTAMP,
    JAKA_CENA INTEGER )
RETURNS (
    IDZDST DOUBLE PRECISION,
    ILE NUMERIC(15,5),
    DATAWAZN TIMESTAMP,
    CENA NUMERIC(15,2),
    MINST DOUBLE PRECISION,
    SERIA VARCHAR(50) )
AS
declare variable astan numeric(15,5);
     declare variable blok numeric(15,5);
     declare variable moje numeric(15,5);
     declare variable usluga char(1);
     declare variable spis double precision;
     DECLARE pelne int;
     
begin


if (round( ilosc - round(ilosc,0),5) = 0) THEN
BEGIN
  pelne = 1;
  select sum(floor( STAN-IIF( coalesce(blokada,'N')='N', 0 , coalesce(ile_blokada,stan))))
     from ZDST z  where ( id_apteki=:iap and ID_TOWARY=:ID_TOW) and (cast(STAN*10000 as integer)>=0)
             and (coalesce(blokada,'N')='N' or coalesce(ile_blokada,stan)<stan)
             and (data_wazn>=:data_sp or data_wazn is null or data_wazn<'01/01/1901' or :ILOSC<0 or :JAKA_CENA=-1)  
   into astan;  
   if (astan < ilosc) THEN
     pelne = 0;        
END
ELSE
  pelne = 0;  
  


data_sp = cast(extract(day from data_sp)||
'.'|| extract(month from data_sp)||
'.'|| extract(year from data_sp) as date);

select USLUGA from towary where id_apteki=:iap and ID_TOWARY=:ID_TOW into :usluga;
if (:USLUGA='T') then
begin
  IDZDST=-1;
  ILE=ILOSC;
  DATAWAZN='10-10-2200';
  if (jaka_cena<0) then jaka_cena=-1*jaka_cena;
  select CENA_BR from AKT_CENA_SP(:iap,:ID_TOW,:JAKA_CENA,:DATA_SP,:IDZDST,'') into :CENA;
  suspend;
end
else
begin
  /*stan=0 musi byc uwzgledniany ze wzgledu na obsl. zwrotow  : stan=0 a ilosc siedzi w tablicy rezerwacja*/

  if (:ILOSC=0) then
    exit;

  


  select dzielnik/mnoznik from jednostki where id_apteki=:iap and id_towary=:id_tow and jednostka=2 and (coalesce(dostawy,'N')='N' or coalesce(sprzedaz,'N')='T')  into minst;
  if (minst is null or minst>=1) then
     minst = 0.000021;
  ELSE
     minst = 0.1 * minst;

  if (jaka_cena<0) THEN
    minst =  minvalue(0.0000001,minst);


  if (tryb='D') then
    for select z.ID_ZDST, z.STAN, z.DATA_WAZN , (SELECT FIRST 1 k.WARTOSC from ZDST_KLAS k WHERE k.ID_ZDST=z.ID_ZDST and k.ID_APTEKI=z.ID_APTEKI and k.ID_KLASYFIKACJE=5) from ZDST z
      where z.id_apteki=:iap and z.ID_ZDST=:ID_ZDST
      order by DATA, ID_ZDST into :IDZDST, :astan,  :DATAWAZN,seria do
    begin
      select sum (roznica) from spisyzaw where id_apteki=:iap and id_zdst=:idzdst and (zaksiegowany<>'T' or zaksiegowany is null)  into :spis;
      if ((:spis is null) or (:spis<0)) then spis=0;
      astan=astan-spis;
      if (astan<0) then astan=0;
      select sum(ILOSC) from REZERWACJA where  id_apteki=:iap and ID_ZDST=:IDZDST into :blok;
      if (not :blok is null) then
        astan=:astan-:blok;
      if (astan<=ILOSC) then
        ILE = :astan;
      else
        ILE = :ILOSC;

      if (abs(astan-ile - round(astan-ile,0))<minst) then
        ile = ile + astan-ile - round(astan-ile,0);

      select count(ILOSC) from rezerwacja where  id_apteki=:iap and NRKASY=:NRKASY and ID_ZDST=:IDZDST into :moje;
      ILOSC=:ILOSC-:ILE;
      if (abs(ilosc)<minst) then ilosc=0;
      if (:ILE<>0) then
      begin
        if (:JAKA_CENA<0) then
          select CENA_NT from AKT_CENA_SP(:iap,:ID_TOW,-:JAKA_CENA,:DATA_SP,:IDZDST,'') into :CENA;
        else
          select CENA_BR from AKT_CENA_SP(:iap,:ID_TOW,:JAKA_CENA,:DATA_SP,:IDZDST,'') into :CENA;
        if (:moje>0) then
          update rezerwacja set ILOSC=ILOSC+:ILE where  id_apteki=:iap and ID_ZDST=:IDZDST and NRKASY=:NRKASY;
        else
          insert into REZERWACJA (ID_APTEKI,ID_ZDST, NRKASY, ILOSC) values (:iap,:IDZDST, :NRKASY, :ILE);
        suspend;
      end
    end
  else
    for  select id_zdst,sta,data_wazn,klas from 
      (select ID_ZDST, STAN-IIF( coalesce(blokada,'N')='N', 0 , coalesce(ile_blokada,stan)) sta, DATA_WAZN,
     (SELECT FIRST 1 k.WARTOSC from ZDST_KLAS k WHERE k.ID_ZDST=z.ID_ZDST and k.ID_APTEKI=z.ID_APTEKI and k.ID_KLASYFIKACJE=5) klas ,data
     from ZDST z
      where ( id_apteki=:iap and ID_TOWARY=:ID_TOW) and (cast(STAN*10000 as integer)>=0)
             and (coalesce(blokada,'N')='N' or coalesce(ile_blokada,stan)<stan)
             and (data_wazn>=:data_sp or data_wazn is null or data_wazn<'01/01/1901' or :ILOSC<0 or :JAKA_CENA=-1))
         /*    and data<=:data_sp */
      order by  iif(:pelne = 1 and sta>=1,0,1 ),
        DATA, ID_ZDST into IDZDST, astan,  DATAWAZN,seria do
    begin
       if (pelne = 1) then
         astan = floor(astan);
       
      if (JAKA_CENA<0) then
          select CENA_NT from AKT_CENA_SP(:iap,:ID_TOW,-:JAKA_CENA,:DATA_SP,:IDZDST,'') into CENA;
      else
          select CENA_BR from AKT_CENA_SP(:iap,:ID_TOW,:JAKA_CENA,:DATA_SP,:IDZDST,'') into CENA;
      if (cena is not null) then
      begin
        select sum(ILOSC) from REZERWACJA where  id_apteki=:iap and ID_ZDST=:IDZDST into :blok;
        if (not :blok is null) then  astan=:astan-:blok;
        if (astan>0) then
        begin
          select sum (roznica) from spisyzaw where id_apteki=:iap and id_zdst=:idzdst and (zaksiegowany<>'T' or zaksiegowany is null)  into :spis;
          if ((:spis is null) or (:spis<0)) then spis=0;
          astan=astan-spis;
          if (astan<0) then astan=0;
        end
        if (astan<=ILOSC+minst) then
          ILE = :astan;
        else
          ILE = :ILOSC;
         if (abs(astan-ile - round(astan-ile,0))<minst) then
          ile = ile + astan-ile - round(astan-ile,0);

        select count(ILOSC) from rezerwacja where  id_apteki=:iap and NRKASY=:NRKASY and ID_ZDST=:IDZDST into :moje;
        ILOSC=:ILOSC-:ILE;
        if (abs(ilosc)<minst) then ilosc=0;
        if (ILE<>0) then
        begin
          if (moje>0) then
            update rezerwacja set ILOSC=ILOSC+:ILE where  id_apteki=:iap and ID_ZDST=:IDZDST and NRKASY=:NRKASY;
          else
            insert into REZERWACJA (ID_APTEKI,ID_ZDST, NRKASY, ILOSC) values (:iap,:IDZDST, :NRKASY, :ILE);
          suspend;
        end
      end
    end
end
end
^

ALTER PROCEDURE WARTFAKT (
    IAP INTEGER,
    IDTRANZ INTEGER,
    DT TIMESTAMP )
RETURNS (
    KOD CHAR(1),
    STV NUMERIC(15,2),
    NT NUMERIC(15,2),
    VT NUMERIC(15,2),
    BR NUMERIC(15,2),
    ODPL NUMERIC(15,2) )

AS
declare variable brr integer;
     declare variable brs integer;
     declare variable snt NUMERIC(15,2);
     declare variable svt NUMERIC(15,2);
     declare variable sbr NUMERIC(15,2);
     declare variable odp Integer;
     declare variable iktr integer;
begin
snt=0;
 svt=0;
 sbr=0;
 select id_kontrahenci from tranzakcje where id_apteki=:iap and id_tranzakcje=:idtranz and data=:dt into iktr;

 if ((iktr is not null) and (iktr<=0)) then
 begin
   for select sum(wart_zak),s.stawka_vat,v.kod,sum(wart_zak*(1+0.01*s.stawka_vat)) from sprzedaz s left outer join akt_stawki_vat(:dt) v on s.stawka_vat=v.vat
   where s.id_apteki=:iap and s.data=:dt and s.id_tranzakcje=:idtranz and v.KOD <> 'Z'
   group by s.stawka_vat,v.kod into nt,stv,kod,br do
   begin
     br=cast(br*100 as integer)*0.01;
     nt=cast(nt*100 as integer)*0.01;
     vt=:br-:nt;

      snt=:snt+:nt;
      svt=:svt+:vt;
      sbr=:sbr+:br;

      suspend;
   end
   odpl=snt;
 end
 else
 begin

   odp=3;
   if (iktr is not null) then
     select coalesce(typ_ceny,3) from kontrahenci where id_kontrahenci=:iktr into odp;

   if (odp<3) then
   for select sum(wartosc+taksa),s.stawka_vat,v.kod from sprzedaz s left outer join akt_stawki_vat(:dt) v on s.stawka_vat=v.vat
   where s.id_apteki=:iap and s.data=:dt and s.id_tranzakcje=:idtranz and v.KOD <> 'Z'
   group by s.stawka_vat,v.kod into br,stv,kod do
   begin
      br=cast(br*100 as integer)*0.01;
      nt=cast(:br/(1+(0.01*:stv))*100 as integer)*0.01;
      vt=:br-:nt;

      snt=:snt+:nt;
      svt=:svt+:vt;
      sbr=:sbr+:br;

      suspend;
   end
   else

     for select f.kod_vat, f.VAT, sum(f.WARTOSC) from pozycje_faktury(:iap,:idtranz,:dt,11) f

     group by f.KOD_VAT, f.VAT order by f.kod_vat
     into :kod,:stv,:br do
     begin
        if (:br is null) then br=0;
        nt=cast(:br/(1+(0.01*:stv))*100 as integer)*0.01;
        vt=:br-:nt;

        snt=:snt+:nt;
        svt=:svt+:vt;
        sbr=:sbr+:br;

        suspend;
     end
   select sum(ODPLATNOSC+DOPLATA) from sprzedaz where id_apteki=:iap and DATA=:DT and ID_TRANZAKCJE=:IDTRANZ into :ODPL;
 end
 kod='S';
 nt=snt;
 vt=svt;
 br=sbr;
 stv=null;

 suspend;
end
^

ALTER PROCEDURE WARTFAKT1 (
    IAP INTEGER,
    IDTRANZ INTEGER,
    DT TIMESTAMP )
RETURNS (
    KOD CHAR(1),
    STV NUMERIC(15,2),
    NT NUMERIC(15,2),
    VT NUMERIC(15,2),
    BR NUMERIC(15,2),
    ODPL NUMERIC(15,2) )

AS
declare variable brr integer;
     declare variable brs integer;
     declare variable snt NUMERIC(15,2);
     declare variable svt NUMERIC(15,2);
     declare variable sbr NUMERIC(15,2);
     declare variable odp Integer;
     declare variable iktr integer;
begin
snt=0;
 svt=0;
 sbr=0;
 select id_kontrahenci from tranzakcje where id_apteki=:iap and id_tranzakcje=:idtranz and data=:dt into iktr;

 if ((iktr is not null) and (iktr<=0)) then
 begin
   for select sum(wart_zak),s.stawka_vat,v.kod,sum(wart_zak*(1+0.01*s.stawka_vat)) from sprzedaz s left outer join akt_stawki_vat(:dt) v on s.stawka_vat=v.vat
   where s.id_apteki=:iap and s.data=:dt and s.id_tranzakcje=:idtranz  and s.sztuk>0 and v.KOD <> 'Z'
   group by s.stawka_vat,v.kod into nt,stv,kod,br do
   begin
     br=cast(br*100 as integer)*0.01;
     nt=cast(nt*100 as integer)*0.01;
     vt=:br-:nt;

      snt=:snt+:nt;
      svt=:svt+:vt;
      sbr=:sbr+:br;

      suspend;
   end
   odpl=snt;
 end
 else
 begin
   for select f.kod_vat, f.VAT, sum(f.CENA*f.ILOSC) from pozycje_faktury(:iap,:idtranz,:dt,11) f
   where f.ilosc>0
   group by f.KOD_VAT, f.VAT order by f.kod_vat
   into :kod,:stv,:br do
   begin
      if (:br is null) then br=0;
      nt=cast(:br/(1+(0.01*:stv))*100 as integer)*0.01;
      vt=:br-:nt;

      snt=:snt+:nt;
      svt=:svt+:vt;
      sbr=:sbr+:br;

      suspend;
   end
   select sum(ODPLATNOSC+DOPLATA) from sprzedaz where id_apteki=:iap and DATA=:DT and ID_TRANZAKCJE=:IDTRANZ into :ODPL;
 end
 kod='S';
 nt=snt;
 vt=svt;
 br=sbr;
 stv=null;

 suspend;
end
^

/* Alter (VAT_FA) */
ALTER PROCEDURE VAT_FA(IA INTEGER,
IT INTEGER,
DT DATE)
 RETURNS(NA DOUBLE PRECISION,
VA DOUBLE PRECISION,
NB DOUBLE PRECISION,
VB DOUBLE PRECISION,
NC DOUBLE PRECISION,
VC DOUBLE PRECISION,
ND DOUBLE PRECISION,
VD DOUBLE PRECISION,
NE DOUBLE PRECISION,
VE DOUBLE PRECISION,
N0 DOUBLE PRECISION,
NZ DOUBLE PRECISION,
BR DOUBLE PRECISION)
 AS
DECLARE kd varchar(2);
DECLARE nt  DOUBLE PRECISION;
DECLARE vt  DOUBLE PRECISION;
BEGIN
  br = 0 ;
  FOR SELECT w.KOD,round(w.NT,2),round(w.VT,2)
  FROM WARTFAKT(:ia,:it,:dt) w into kd,nt,vt do
  BEGIN
    if (kd='A') THEN
    BEGIN
      na=nt;
      va=vt;
    END
    if (kd='B') THEN
    BEGIN
      nb=nt;
      vb=vt;
    END
    if (kd='D') THEN
    BEGIN
      nc=nt;
      vc=vt;
    END
    if (kd='C') THEN
    BEGIN
      n0=nt;
    END
    if (kd='Z') THEN
    BEGIN
      nz=nt;
    END
    if (kd='S') THEN
    BEGIN
      br=nt+vt;
    END
  END
  SUSPEND;
END
^

/* Alter (VAT_ZB) */
ALTER PROCEDURE VAT_ZB(IA INTEGER,
IZ INTEGER)
 RETURNS(NA DOUBLE PRECISION,
VA DOUBLE PRECISION,
NB DOUBLE PRECISION,
VB DOUBLE PRECISION,
NC DOUBLE PRECISION,
VC DOUBLE PRECISION,
ND DOUBLE PRECISION,
VD DOUBLE PRECISION,
NE DOUBLE PRECISION,
VE DOUBLE PRECISION,
N0 DOUBLE PRECISION,
NZ DOUBLE PRECISION,
BR DOUBLE PRECISION)
 AS
DECLARE kd varchar(2);
DECLARE nt  DOUBLE PRECISION;
DECLARE vt  DOUBLE PRECISION;
BEGIN
  br = 0 ;
  for select f.KOD, round(sum(nt),2) nt,round(sum(vt),2) vt  from  fakt_zb_zaw left join  wartfakt1(p_id_apteki,p_id_tranzakcje,p_data) f on 0=0
  where id_apteki=:ia and id_fakt_zb=:iz
  group by f.KOD
  into kd,nt,vt do
  BEGIN
    if (kd='A') THEN
    BEGIN
      na=nt;
      va=vt;
    END
    if (kd='B') THEN
    BEGIN
      nb=nt;
      vb=vt;
    END
    if (kd='D') THEN
    BEGIN
      nc=nt;
      vc=vt;
    END
    if (kd='C') THEN
    BEGIN
      n0=nt;
    END
    if (kd='Z') THEN
    BEGIN
      nz=nt;
    END
    if (kd='S') THEN
    BEGIN
      br=nt+vt;
    END
  END
  SUSPEND;
END
^

ALTER PROCEDURE KS_FA (
    IAP INTEGER,
    ID INTEGER,
    DTA TIMESTAMP )
AS
declare variable kd char(1);
declare variable kk char(1);
declare variable ko integer;
declare variable nt double precision;
declare variable vt double precision;
declare variable br double precision;
declare variable tt double precision;
declare variable od double precision;
declare variable po double precision;
declare variable ii integer;
declare variable ik integer;
declare variable lp integer;
declare variable nk char(1);
declare variable idro integer;
declare variable idsd integer;
declare variable ds integer;
declare variable dtp timestamp;
declare variable nrf varchar(100);
DECLARE manip INTEGER;
DECLARE katR char(1);
DECLARE pan char(1);
DECLARE pow char(1);
DECLARE swz char(1);
DECLARE atrVT int;
DECLARE defi int;
DECLARE dtw date;
begin
  RDB$SET_CONTEXT('USER_SESSION','KS_FA',1); -- nie kasowac - odblokowuje trigera blokujacego zmiane statusu transacji wstecz
  select TERMIN_PLAT,NUMER,id_kontrahenci,PARAGON, iif(NR_KASY BETWEEN 1 and 9,'T','N'),kor_tr,COALESCE(kategoria,'S'),t.DATA_WYST from tranzakcje t
  where id_apteki=:iap and id_tranzakcje=:id and data=:dta
    into dtp,nrf,ds,kd,nk,idro,katR,dtw;

  /* sprawdz czy zaksiegowana  */
  if (kd='X' or kd='Z'  or kd='V') then exit;

  if (COALESCE(ds,100) <> 0 or katR not in ('U','A') ) THEN
     katR = 'S';

  SELECT IIF(CHARACTER_LENGTH( trim(coalesce(k.NIP,'')))>9,1,0),COALESCE(k.POWIAZANY,'N'),COALESCE(k.ZAGRANICZNY,'N')  FROM KONTRAHENCI k where k.ID_KONTRAHENCI=:ds into manip,pow,swz;

  select COALESCE(o.PARAGON_NIP,'N') from ogolne o where id_apteki=:iap into pan;

  /*

    pan = T paragon do faktur kasowych z NIP
  */
  
  if ((nk='T') and manip=1 and pan='N') THEN
  BEGIN
    nk = 'N';
    kd = 'N';
  END 
  
  if (dtp is null) then
  begin
    if (nk='T') then 
      kk = 'E';
    ELSE
      kk = 'G';
  end
  else
  begin
    if (nk='T') then
    begin
      select sum(t.KWOTA)  from TRANZ_WPLATY t where t.ID_APTEKI=:iap and t.ID_TRANZAKCJE=:id and t.ID_TRANZ_OPISY=5 and t.DATA=:dta  into po;
      kk = 'K';
    END
    ELSE
      kk = 'A';
  end

  select count(*) from sprzedaz where id_apteki=:iap and id_tranzakcje=:id and data=:dta and tryb='Z'  into ko;
  select count(*) from sprzedaz  s left join TOWARY t on s.ID_TOWARY = t.ID_TOWARY and s.ID_APTEKI = t.ID_APTEKI 
  left join cbt c on t.ID_CBT = c.ID_CBT
  where s.id_apteki=:iap and s.id_tranzakcje=:id and s.data=:dta and COALESCE(c.DEFICYTOWY,'N')='T'  into defi;

  /* sprawdzamy czy zwrot */
  if (idro>0 or ko>0) THEN kk = 'O';

  select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING :kk into idsd;
  
  if (kk = 'E' and manip=0) THEN
  begin
    idsd = null;
  end  

  if (coalesce(idsd,0)<1 and kk='O' and ko>0) then
    select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING 'Z' into idsd;
  
  if (ds>0 and (kd<>'K' or manip=1)) then
  begin
      if (kd in ('T','K') and kk <> 'O') THEN
      BEGIN
        atrVT = bin_shl(1,29);
        if (dtw is null) THEN
            dtw = 'today';
      END  
      ELSE
      BEGIN
        atrVT = 0;
        dtw = dta;
      END  
      if (swz = 'T') THEN    
        atrVT = atrVT + bin_shl(1,13);
      if (pow = 'T') THEN    
        atrVT = atrVT + bin_shl(1,15);  
      if (defi > 0) THEN    
        atrVT = atrVT + bin_shl(1,8);
      select GEN_ID(SQ_DOKUMENTY,1) from JEDEN_WIERSZ into :ii;
      insert into dokumenty (ID_APTEKI,id_dokumenty,data,data_pl,data_wy,symb_wewn,symb_zewn,id_okres_fk,id_szabl_dek,atrvat) values
        (:iap,:ii,:dta,:dtp,:dtw,'VAT' || :ii,:nrf,0,:idsd,:atrVT);
    
    lp=0;
    tt=0;
    for select kod,nt,vt,br,odpl from wartfakt(:iap,:id,:dta) into :kk,:nt,:vt,:br,od do
    if (kk<>'S') then
    begin
      lp=lp+1;
      
        select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
        insert into dekrety (ID_APTEKI,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,'VAT-SP-SP-'||:kk||'-N-'||:ds||'-','W',:nt,'',:lp);
        select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
        insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,'VAT-SP-SP-'||:kk||'-V-'||:ds||'-','W',:vt,'',:lp);
      
    end
    else
      tt=od;
   /*  platnosc odroczona moze byc czescia odplatnosci*/
    if (po is not null) then
      tt=po;

    if (idsd is not null) then
    begin
      select idro from dekretacja(:iap,:ii) into idro;
      if (idro is not null) then
        update dekrety set kwota = :tt where id_apteki=:iap and id_dekrety=:idro;
    end
  end
  if (kd='T') then
    kd='X';
  else
    if (kd='K') then
      kd='V';
    else
      kd='Z';
  if (ds >= 0 and nk='N' ) THEN
    for SELECT s.ID_SPRZEDAZ from sprzedaz s LEFT JOIN towary t on s.ID_APTEKI=t.ID_APTEKI and s.ID_TOWARY = t.ID_TOWARY
    where s.id_apteki=:iap and s.id_tranzakcje=:id and s.data=:dta and t.SER_PODL = 'T' INTO idsd do
      UPDATE OPAKOWANIA o SET o.STATUS=:katR,o.ST_WYSL=-1 where o.ID_SPRZEDAZ = :idSd and o.ID_APTEKI = o.ID_APTEKI and COALESCE(ST_WYSL,-1) < 0;
  update tranzakcje set paragon=:kd,data_wyst=:dtw where id_apteki=:iap and data=:dta and id_tranzakcje=:id;
  RDB$SET_CONTEXT('USER_SESSION','KS_FA',0);
end^


/* bez zmian Alter (KS_ZB_FA) */
ALTER PROCEDURE KS_ZB_FA(IA INTEGER,
DT DATE,
RW INTEGER,
FA INTEGER,
MR INTEGER)
 AS
declare da date;
declare it integer;
declare nr varchar(80);
begin
  for select data,id_tranzakcje,numer from tranzakcje
    where id_apteki=:ia and data between '01/01/2000' and :dt and (PARAGON='N' or PARAGON is null)
    and id_kontrahenci is not null
    and (
     id_kontrahenci=0 and coalesce(kategoria,'X')<>'U' and data<=cast('today' as date)-90 and :rw=1
     or
     id_kontrahenci=0 and coalesce(kategoria,'U')<>'U' and :rw=1
     or
     id_kontrahenci>0 and :fa=1
     or
     id_kontrahenci<0 and :mr=1
     )
      into da,it,nr do
      execute procedure ks_fa(:ia,:it,:da);
 when any do
  begin
    exception blad '
ksiêgowania dokumentu ' || nr || ' z dnia ' || da || ' transakcja ' || it;
  end

end
^

ALTER PROCEDURE KS_DST1 (
    IAP INTEGER,
    ID INTEGER )

AS
declare variable kd char(1);
     declare variable nt double precision;
     declare variable vt double precision;
     declare variable br double precision;
     declare variable tt double precision;
     declare variable ii integer;
     declare variable ib integer;
     declare variable ik integer;
     declare variable lp integer;
     declare variable ds integer;
     declare variable idsd integer;
     declare variable dta timestamp;
     declare variable dtw timestamp;
     declare variable dtp timestamp;
     declare variable nrf varchar(100);
     declare variable przyszlo Double precision;
     declare variable idz integer;
     declare variable rjv varchar(100);
     declare variable dd integer;
     declare variable kod_szablonu varchar(1);
     declare iz integer;
     declare lz integer;
begin
  select DATA,DT_WYST,DT_PLATN,NR_FAKTURY,id_kontrahenci,STATUS,ID_BRAKI,rej_vat 
  from dostawy d where id_apteki=:iap and id_dostawy=:id
    into :dta,:dtw,:dtp,:nrf,:ds,:kd,:ib,:rjv;
  if (rjv is null or CHAR_LENGTH(rjv)<10) then
    rjv='VAT-ZK-ZT-';
  if (ds>0) then
  begin
    if (dtp is null) then
      kod_szablonu = 'B';
    else
    begin
      if (rjv<>'VAT-ZK-ZT-') then
        kod_szablonu = 'W';
      ELSE
        kod_szablonu = 'C';
    end
    select GEN_ID(SQ_DOKUMENTY,1) from JEDEN_WIERSZ into :ii;
    select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING :kod_szablonu into idsd;
    insert into dokumenty (id_apteki,id_dokumenty,data,data_pl,data_wy,symb_wewn,symb_zewn,id_okres_fk,id_szabl_dek) values
      (:iap,:ii,:dta,:dtp,:dtw,'VAT' || :ii,:nrf,0,:idsd);
    tt=0;
    lp=0;
    for select kod,nt,vt,br from dost_suma where id_apteki=:iap and id_dostawy=:id  into :kd,:nt,:vt,:br do
    if (kd<>'S') then
    begin
      select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
      tt=tt+br;
      lp=lp+1;
      insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,:rjv ||:kd||'-N-'||:ds||'-','W',:nt,'',:lp);
      select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
      insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,:rjv ||:kd||'-V-'||:ds||'-','W',:vt,'',:lp);
    end
    select * from dekretacja(:iap,:ii) into dd;
  end

  update dostawy set status='Z' where id_apteki=:iap and  id_dostawy=:id;
  
end
^

create or ALTER PROCEDURE NAPRRPE(DZIEN DATE)
 AS
declare variable ia apteka;
declare variable ss integer;
declare variable dt date;
begin

 if (:dzien < '1.1.2020') then exit;
 
 dt = maxvalue((select max(data)-1 from WERSJA),:dzien) ;  
  
/*chwilowe rozwiazanie na 'A' - dla P nie sa generowane drr wiec przestawiamy P na N */
for select id_sprzedaz from etaksacje where id_apteki=:ia and status='A' and (left(ifinsdate,11)=:dzien or left(ifinsdate,11)>=:dt) into ss do 
 begin
 ss=(select min(idsp) from  hist_korekty(:ia,:ss) where idsp>:ss);
 update sprzedaz set tryb='N' where id_apteki=:ia and id_sprzedaz=:ss and tryb='P'; --and data>'1.1.19' niech poprawi tez ewentualne odbiory
 end 

/*for przyspiesza w stosunku do wczesniejszgo or t.data>=:dt ale moze trzeba calkiem zrezygnowac i zostawic tylko dzien utargu*/
for select distinct data from tranzakcje where id_apteki=:ia and data BETWEEN :dt and cast('today' as date) into dzien do
begin
/*etaksacje*/ 
 insert into ETAKSACJE  (ID_SPRZEDAZ,ID_APTEKI,KLUCZ,status,kasa,opis,tryb)   
 select s.ID_SPRZEDAZ,s.ID_APTEKI,r.numer,iif(r.numer='9','Z','K'),t.NR_KASY,'Odtworzona, Ref: '||trim(TRAILING 0 from round(s.WARTOSC + s.TAKSA - s.ODPLATNOSC - s.DOPLATa,2)),s.tryb 
  from TRANZAKCJE t join sprzedaz s on t.DATA = s.DATA and t.ID_TRANZAKCJE =  s.ID_TRANZAKCJE and t.ID_APTEKI = s.ID_APTEKI
  join recepta r on s.id_apteki=r.id_apteki and s.id_recepta=r.id_recepta and r.numer is not null and r.ATRYBUTY NOT similar to 'GW%|GP%|GV%'
  left join ETAKSACJE e on s.id_apteki=e.id_apteki and s.id_sprzedaz=e.id_sprzedaz 
 where t.id_apteki=:ia and t.data=:dzien and s.tryb in ('S','R','N') and t.PARAGON <> 'B' and e.id_sprzedaz is null ; --bez pomyslu co z tym 9.1.1900

 /*korekty - zwroty */
 insert into ETAKSACJE  (ID_SPRZEDAZ,ID_APTEKI,KLUCZ,status,kasa,opis,tryb)  
 select ID_SPRZEDAZ,ID_APTEKI,K,s,NR_KASY,op,tryb from (
 select (select max(wersja) from  hist_korekty(s.ID_APTEKI,s.ID_SPRZEDAZ)) mawer,
  s.ID_SPRZEDAZ,s.ID_APTEKI,r.numer k,'K' s,t.NR_KASY,'OdtworzonaZ, Ref: '||trim(TRAILING 0 from round(s.WARTOSC + s.TAKSA - s.ODPLATNOSC - s.DOPLATa,2)) op,s.tryb 
  from TRANZAKCJE t join sprzedaz s on t.DATA = s.DATA and t.ID_TRANZAKCJE =  s.ID_TRANZAKCJE and t.ID_APTEKI = s.ID_APTEKI 
  join recepta r on s.id_apteki=r.id_apteki and s.id_recepta=r.id_recepta and r.numer<>'9' and r.ATRYBUTY NOT similar to 'GW%|GP%|GV%'
  left join ETAKSACJE e on s.id_apteki=e.id_apteki and s.id_sprzedaz=e.id_sprzedaz 
 where t.id_apteki=:ia and t.data=:dzien and s.tryb in ('Z') and t.PARAGON <> 'B' and e.id_sprzedaz is null  
 ) z where exists (select*from  hist_korekty(z.ID_APTEKI,z.ID_SPRZEDAZ) where IDSP=z.id_sprzedaz and wersja=z.mawer ) 
 and exists (select*from hist_korekty(z.ID_APTEKI,z.ID_SPRZEDAZ) mi left join ETAKSACJE e on mi.idsp=e.id_sprzedaz where e.id_sprzedaz is not null);
end

/*nadal nie znana przyczyna generowania drr dla bufora - raczej przy utargu*/
update etaksacje e set e.status='Z' where e.id_apteki=:ia and e.status='K' and e.opis like 'Odtworzona%' and
 ( not exists(select*from sprzedaz s where s.id_apteki=e.id_apteki and e.id_sprzedaz=s.id_sprzedaz)
  or exists(select*from sprzedaz s where s.id_apteki=e.id_apteki and e.id_sprzedaz=s.id_sprzedaz and s.data='9.1.1900'));

/*trzymanie niewyslanych farmaceutycznych nie ma sensu, oraz powyzej 180 dni*/
 ss=null;
for select id_sprzedaz from etaksacje where id_apteki=:ia and status in ('B','N','K','S') into ss do --ifins oddzielnie ze wzgledu na predkosc wyszukania
 begin
 update etaksacje set status='Z' where id_apteki=:ia and id_sprzedaz=:ss and papier='F' and ifinsdate<cast('today' as date)-1;
 update etaksacje set status='Z' where id_apteki=:ia and id_sprzedaz=:ss and ifinsdate<cast('today' as date)-180;
 end

update eprzyjecia set status='Z' where status in ('B') and ifinsdate<cast('today' as date)-1;
 
end
^

ALTER PROCEDURE NAPRRP(DNI INTEGER)
 AS
declare variable ia apteka;
declare variable ss integer;
declare variable ir integer;
declare variable dt timestamp;
begin
 /* to jest pierwsza najstarsza naprawa trzeba ustalic czy nadal problem wystepuje i co wowczas sie dzieje - wylaczam w 130.62 
  wydaje sie ze druga naprawa powinna wystarczyc?
  na piekos proboje przestawic 2 rp juz odebrane  - czyli cos zmienilo im date odbioru --
  
for select r.id_sprzedaz ,s.id_recepta from receptura r
  left join sprzedaz s on  s.id_apteki=r.id_apteki and s.id_sprzedaz=r.id_sprzedaz
  where r.id_apteki=:ia and dt_odb is not null and dt_odb>=cast('TODAY' as date)-:dni and s.data<dt_odb-1 and s.data<>'31.12.1899' into ss,ir do
  begin
    update receptura set id_odb=null,dt_odb=null where  id_apteki=:ia and id_sprzedaz=:ss;
    update recepta set nr_w_dniu =-1 where id_apteki=:ia and id_recepta=:ir;
  end
 */

/*nowy warunek - ma znaczenie id_odb is not null */
  update receptura r set id_odb=null,dt_odb=null
    where r.id_apteki=:ia and dt_odb is not null and id_odb is not null and dt_odb>=cast('TODAY' as date)-:dni
    and exists (select*from sprzedaz s where s.id_apteki=r.id_apteki and s.id_sprzedaz=r.id_sprzedaz and s.data='31.12.1899') ;

/*nowy przypadek jest sprzedane, jest drr, a rp jest do odbioru (brak id_odb) - dodane 130.62
  (proba odebrania pokazuje blad o zmianie fiskalizacji i zapisuje aktualny czas jako odbiór do receptura) do xml!
  brana 'data realizacji' tekstowa z drr */ 
 begin
  for select r.id_sprzedaz,t.ID_USER,cast(substring(taksacja from position('data realizacji',taksacja)+17 for 19)as timestamp)   
   from receptura r
   join sprzedaz s on s.id_apteki=r.id_apteki and s.id_sprzedaz=r.id_sprzedaz and s.sztuk>0 and s.tryb<>'K'--nie powinno brac zwrotow ale nie zawadzi
   join tranzakcje t on t.ID_APTEKI=s.ID_APTEKI and t.DATA=s.DATA and t.ID_TRANZAKCJE=s.ID_TRANZAKCJE and t.paragon='T' and t.data<>'31.12.1899'
   join etaksacje e on e.ID_APTEKI=s.ID_APTEKI and e.id_sprzedaz=s.id_sprzedaz and e.status='W'
   where r.id_apteki=:ia and dt_odb is null and id_odb is null and dt_rozl>=cast('TODAY' as date)-:dni into ss,ir,dt do 
   begin
    update receptura set id_odb=:ir,dt_odb=:dt where id_apteki=:ia and id_sprzedaz=:ss;    
   end
  end 

 EXECUTE PROCEDURE NAPRRPE('1.1.2020');

end
^

ALTER PROCEDURE NAPRAW_WPLATE (
    IA INTEGER,
    DZIEN TIMESTAMP,
    IT INTEGER )
AS
declare variable sumsp double precision;
declare variable sumwp double precision;
declare variable sumwr double precision;
declare variable sumro double precision;
declare variable sumra double precision;
declare variable sumin double precision;
declare variable epr double precision;
declare variable epj double precision;
declare variable nka integer;
declare variable tpl timestamp;
declare variable ept char(1);
DECLARE lpr INT;
DECLARE lpe int;
DECLARE lpp int;
DECLARE tpp int;
begin
    select TERMIN_PLAT,NR_KASY,EPRUF_TYP from tranzakcje where id_apteki=:ia and data=:dzien and id_tranzakcje=:it into tpl,nka,ept;
    if (ept is null) then ept='D';
    select WART,RABAT_KW,EPRUF from tranz_odplatnosc(:ia,:it,:dzien) into :sumsp,:sumra,:epr;
    select COALESCE(sum(kwota),0),COALESCE(min(LP),1),COALESCE(max(id_tranz_opisy),1) from tranz_wplaty  where id_apteki=:ia and data=:dzien and id_tranzakcje=:it and id_tranz_opisy < 4  into sumwp,lpp,tpp;
    select COALESCE(sum(kwota),0) from tranz_wplaty  where id_apteki=:ia and data=:dzien and id_tranzakcje=:it and id_tranz_opisy not in (4,6) and id_tranz_opisy > 3  into sumin;
    select COALESCE(sum(kwota),0),COALESCE(max(LP),4) from tranz_wplaty  where id_apteki=:ia and data=:dzien and id_tranzakcje=:it and id_tranz_opisy=4 into sumwr,lpr;
    select COALESCE(sum(kwota),0),COALESCE(max(LP),6) from tranz_wplaty  where id_apteki=:ia and data=:dzien and id_tranzakcje=:it and id_tranz_opisy=6 into epj,lpe;

    if (ept>='Q') then epr=0;
       
    
    if (sumra <> 0) then
    begin
      if (abs(sumra - sumwr) > 0.01) THEN
        update or insert into tranz_wplaty (id_apteki,data,id_tranzakcje,kwota,id_tranz_opisy,lp)
           values (:ia,:dzien,:it,:sumra,4,:lpr);
    end
    ELSE
       DELETE FROM TRANZ_WPLATY where id_apteki=:ia and data=:dzien and id_tranzakcje=:it and id_tranz_opisy=4;
     
    if (epr <> 0) then
    begin
      if (abs(epr - epj) > 0.01) THEN
        update or insert into tranz_wplaty (id_apteki,data,id_tranzakcje,kwota,id_tranz_opisy,lp)
           values (:ia,:dzien,:it,:epr,6,:lpe);
    end
    ELSE
       DELETE FROM TRANZ_WPLATY where id_apteki=:ia and data=:dzien and id_tranzakcje=:it and id_tranz_opisy=6;   
    
    
    if (abs(sumsp - sumwp - sumin )>0.01) then
    begin
      if ((nka=0 or nka>10) and tpl is not null) then
        tpp=3;
      
      sumro = sumsp - sumin;
      DELETE FROM TRANZ_WPLATY where id_apteki=:ia and data=:dzien and id_tranzakcje=:it and id_tranz_opisy < 4;   
      insert into tranz_wplaty (id_apteki,data,id_tranzakcje,kwota,id_tranz_opisy,lp)
        values (:ia,:dzien,:it,:sumro,:tpp,:lpp);
      
   end
 end
^

ALTER PROCEDURE NAPRAW_WPLATY(IA INTEGER,
DZIEN DATE,
KASA SMALLINT)
 AS
declare variable it integer;
declare variable iu integer;
declare variable ik integer;
declare variable tr integer;
declare variable tp integer;
declare variable dp date;
declare variable dz date;
begin
  /* 2011.06.27  dodana naprawa przyjêc receptury count(*)=0 */
  /* 2013.11.21 dodana naprawa o_operator w bufor */
  for select b.id_recepta,t.id_user,t.NR_KASY,s.id_tranzakcje from bufor_recept b left join sprzedaz s on b.id_recepta=s.id_recepta and b.id_apteki=s.id_apteki
  left join tranzakcje t on t.id_apteki=s.id_apteki and t.data=s.data and t.id_tranzakcje=s.id_tranzakcje
  where  b.id_apteki=:ia and b.id_recepta>0 and b.status='O' and  s.data=:dzien and s.tryb<>'Z' and (o_operator<>t.id_user or o_operator is null)
    into it,iu,ik,tr do
    begin
      select first 1 data,id_tranzakcje from sprzedaz where id_apteki=:ia and id_recepta=:it order by data,id_tranzakcje into dp,tp;
      if (tp=tr and dzien=dp) then
        update bufor_recept set o_operator=:iu,o_data=:dzien,o_kasa=:ik where id_apteki=:ia and id_recepta=:it;
    end
  for select b.id_recepta,t.id_user,t.NR_KASY,s.id_tranzakcje,s.data from bufor_recept b left join sprzedaz s on b.id_recepta=s.id_recepta and b.id_apteki=s.id_apteki
  left join tranzakcje t on t.id_apteki=s.id_apteki and t.data=s.data and t.id_tranzakcje=s.id_tranzakcje
  where  b.id_apteki=:ia and b.id_recepta>0 and b.status<>'O' and  s.data>='01/01/2000' and s.tryb<>'Z'
  group by b.id_recepta,t.id_user,t.NR_KASY,s.id_tranzakcje,s.data
    into it,iu,ik,tr,dp do
      update bufor_recept set o_operator=:iu,o_data=:dp,o_kasa=:ik,status='O' where id_apteki=:ia and id_recepta=:it;
  for select id_tranzakcje from tranzakcje where id_apteki=:ia and data=:dzien and (id_kontrahenci is null or id_kontrahenci>0)
  and ((paragon <>'N') or (select count(*) from sprzedaz where id_apteki=tranzakcje.id_apteki and id_tranzakcje=tranzakcje.id_tranzakcje and data=tranzakcje.data)=0
   or (select count(*) from sprzedaz where id_apteki=tranzakcje.id_apteki and id_tranzakcje=tranzakcje.id_tranzakcje and data=tranzakcje.data and tryb='R')>0)
   into :it do
    execute procedure napraw_wplate(:ia,:dzien,:it);
    
 if (kasa=0) then -- wylaczone w ekspedycji
 BEGIN 
  update sprzedaz s set s.sztuk=(select sum(r.sztuk_jp) from rzdst r where s.id_apteki=r.id_apteki and s.id_sprzedaz=r.id_sprzedaz), s.jednostka=1
   where s.sztuk>100000000000 and s.id_apteki=:ia and s.data>= :dzien - 5;

  /* naprawa wartosci w cenach zakupu dla wersji > 125.01 (od nastepniego dnia po wgraniu) */ 
  if (exists (select*from wersja where wersja>125.01 and data<:dzien and id_apteki=:ia)) then 
   update sprzedaz s set s.wart_zak=
   (select sum (c.CENA_NT_JP*r.SZTUK_JP) from RZDST r left join ceny_dostawy c on r.id_apteki=c.id_apteki and r.id_zdst=c.id_zdst and c.id_ceny=1
    where r.id_apteki=s.id_apteki and r.ID_SPRZEDAZ=s.id_sprzedaz)
   where coalesce(round(s.wart_zak,2),0)-
   coalesce(round((select sum (c.CENA_NT_JP*r.SZTUK_JP) from RZDST r left join ceny_dostawy c on r.id_apteki=c.id_apteki and r.id_zdst=c.id_zdst and c.id_ceny=1
          where r.id_apteki=s.id_apteki and r.ID_SPRZEDAZ=s.id_sprzedaz),2),0) <> 0
   and s.id_apteki=:ia and (s.data= :dzien or s.data='09.01.1900' or s.data='31.12.1899');
  
  /* od wersji 128.04 lub 128.03 (dogrywane) */
  /* pojedyncze zglosznia ze wiesza sie utarg na ekspedycji wylaczam w 128.06 (nie wiadomo czy ma zwiazek) 
   update sprzedaz s set s.cena_zak=(select xml_cn_zak from dane_xml (s.id_apteki,s.id_sprzedaz,1))
    where round(s.cena_zak,2)-(select xml_cn_zak from dane_xml (s.id_apteki,s.id_sprzedaz,1)) <> 0 
    and s.id_apteki=:ia and s.data= :dzien ;     
  
   update sprzedaz s set s.cena_zak_br=(select xml_cena_zak from dane_xml (s.id_apteki,s.id_sprzedaz,1))
    where round(s.cena_zak_br,2)-(select xml_cena_zak from dane_xml (s.id_apteki,s.id_sprzedaz,1)) <> 0 
    and s.id_apteki=:ia and s.data= :dzien ;        
   */ 
   
    /* naprawa data_zamkn i nowego dziwnego przypadku braku zmiany na czynny T po zaksiegowaniu dostawy przypadki od 130.391 */   
    select napr_dtzamk from ogolne where id_apteki=:ia into dz;
    update zdst z set data_zamkn=(select max(data)from rzdst where ID_APTEKI=z.ID_APTEKI and id_zdst=z.id_zdst)
     where stan=0 and coalesce(data_zamkn,'1.1.1900')<(select max(data)from rzdst where id_zdst=z.id_zdst) and id_zdst<>-1 
     and not EXISTS (select r.ID_ZDST FROM RZDST r LEFT JOIN SPRZEDAZ s on r.ID_SPRZEDAZ=s.ID_SPRZEDAZ and r.ID_APTEKI=s.ID_APTEKI
        where r.ID_APTEKI=z.ID_APTEKI and r.ID_ZDST = z.ID_ZDST and (r.DATA < '01.01.1990'  or s.DATA < '01.01.1990' )) 
    and id_apteki=:ia and ifupddate>:dz;    
    update zdst z set czynny='T' where czynny='N' and stan>0 and id_apteki=:ia and ifupddate>:dz;
    update ogolne set napr_dtzamk=cast('TODAY' as timestamp) where id_apteki=:ia;
   
    FOR SELECT t.ID_TRANZAKCJE
    FROM TRANZAKCJE t WHERE t.id_apteki=:ia and t.DATA= :dzien and t.PARAGON in ('K','T') and t.ID_KONTRAHENCI>0
    INTO it do 
    EXECUTE PROCEDURE ks_fa(:ia,it,:dzien);

    for SELECT b.ID_RECEPTA from GPL_ZAM g LEFT JOIN BUFOR_RECEPT b on g.IDW = b.ID_GPL WHERE g.DTW < 'now' AND b.STATUS = 'N' and b.ID_RECEPTA > 0 into tr
      do SELECT a.STA FROM gpl_anuluj(:tr) a into tp;

    for select d.id_dostawy from dostawy d
    left join dokumenty dk on dk.id_apteki=d.id_apteki and dk.data=d.data and dk.symb_zewn=d.NR_FAKTURY and dk.symb_wewn like 'VAT%'
    where d.id_kontrahenci>0 and d.status='Z' and dk.id_dokumenty is null
     and d.id_apteki=:ia and d.data=:dzien into it DO
    EXECUTE PROCEDURE KS_DST1 (:ia,it);     
     
    EXECUTE PROCEDURE NAPRRPE(:dzien);
    
 END

end
^

CREATE OR ALTER PROCEDURE DEKODUJ_GTU (
    GTU INTEGER,
    KNT VARCHAR(200),
    DTA DATE )
RETURNS (
    ID INTEGER,
    KOD VARCHAR(50),
    OPIS VARCHAR(500) )

AS
DECLARE i int;
DECLARE r int;
BEGIN
  i = 0;
  if (knt STARTING 'VAT-SP' ) THEN
    r = 31;
  ELSE
    r = 32;
  while (i < r) do
  BEGIN
    if (bin_and(gtu,bin_shl(1,i)) > 0) THEN
    BEGIN
      SELECT v.ID,v.KOD,v.OPIS from VAT7ATR v where v.ID = :i + 1 and :dta BETWEEN v.DT_OD and v.DT_DO
       into id,kod,opis;
      SUSPEND;
    END
    i = i + 1;
  END
END
^


ALTER PROCEDURE TYLKO_DATA (
    IPARAM Timestamp,
    FORMAT Smallint DEFAULT 0 )
RETURNS (
    CYFRY Varchar(10) )
AS
begin
  /* przy alter uwaga na default 'format smallint = 0' */
  if (format=0) then  
  cyfry=lpad(EXTRACT(day from IPARAM),2,0)||'-'||lpad(EXTRACT(month from IPARAM),2,0)||'-'||EXTRACT(year from IPARAM);  
  else
  cyfry=EXTRACT(year from IPARAM)||'-'||lpad(EXTRACT(month from IPARAM),2,0)||'-'||lpad(EXTRACT(day from IPARAM),2,0);  
  
  suspend;
end^

ALTER PROCEDURE CBT_PRZED (
    IA Integer )
AS
declare variable il integer;
declare variable st varchar(10);
declare variable dt date;
declare variable ok varchar(40);
begin
 ok='';
 for
  select 'e',sum(a) from (select 1 a from RECEPTA r left join erecepty e on e.klucz=r.numer join sprzedaz s on s.id_recepta=r.id_recepta
   where r.id_apteki=:ia and r.ifupddate>'1.1.21' and char_length(r.numer)>40 and e.klucz is null group by r.numer having sum(s.sztuk)>0)
  union
  select status,count(status) from ETAKSACJE where id_apteki=:ia and status in ('B','N','K','A','S') group by status into :st,:il do
      begin
        if (:il>0) then
        ok=trim(ok)||' '||trim(:st)||:il;    
      end
    select max(ifupddate) from ETAKSACJE where id_apteki=:ia and status  in ('W') into :dt;        
    update ogolne set EREC_ILE=trim(left((select cyfry from TYLKO_DATA(:dt,1))||' '||trim(:ok),40)) where id_apteki=:ia;
  
 ok=''; st='';
 for
  select (st_wysl),count(st_wysl) from opakowania where id_apteki=:ia and st_wysl in(-1,-3) and status<>'K' and id_sprzedaz is not null group by st_wysl into :st,:il do
      begin
        ok=trim(ok)||' '||trim(:st)||':'||:il;    
      end
    st=(select cast(datediff(day,max(ifupddate),cast('today' as date)) as int) from op_transakcje where status=-2);      
    if (st>1) then ok=trim(ok)||' '||'D:'||:st;
    st=(select count(*) from opakowania where IFupdDATE>=cast('today' as date)-182 and (opis containing 'Alert' or opis containing 'nieaktywne' or char_length(alerty)>10));      
    if (st>1) then ok=trim(ok)||' '||'A:'||:st;
    /*do tego osoz moze tymczasowo*/
    st=(select count(*) from tranzakcje where id_apteki=:ia and id_osoz in ('B','N') and data>'31.12.19');
    if (st>1) then ok=trim(ok)||' '||'Os:'||:st;
    /*do tego sa czytniki w trybie klawiaturowym moze tymczasowo - bez cyfry zeby odczytac latwo u nas*/
    st=(select count(*) from par_uzytk a join par_uzytk b on a.id_apteki=b.id_apteki and a.dla=b.dla where a.id_apteki=:ia and a.parvalue='S50' and b.parname||b.parvalue='HID_U0');
    if (st>0) then ok=trim(ok)||' '||'Kl';    
    /*do tego jesli uruchamianie lokalne moze tymczasowo - bez cyfry zeby odczytac latwo u nas, jak raz sie zapisze to juz bedzie zawsze nawet jesli zostanie zlikwidowane */
    st=(select 2 FROM MON$ATTACHMENTS WHERE mon$remote_process containing 'C:\infofarm\Ekspedycja.exe' union select 2 FROM ogolne where id_apteki=:ia and kowal_ile containing 'Lo');
    if (st>1) then ok=trim(ok)||' '||'Lo'; 
    select max(IFINSDATE) from opakowania where id_apteki=:ia and st_wysl>0 and opis starting 'Pomy' into :dt;        
    update ogolne set KOWAL_ILE=trim(left((select cyfry from TYLKO_DATA(:dt,1))||' '||trim(:ok),40)) where id_apteki=:ia;   
  
  ok='-'; st='-';
  if ((select EPRUF_USL_LAST from ogolne where id_apteki=:ia) is not null)
  then  
   BEGIN
   select max(data) from tranzakcje where epruf_id is not null and epruf_aut='T' and data between cast('today' as date)-60 and cast('today' as date)-1 and id_apteki=:ia into dt;
   select zatw,coalesce(IFINSUSER,'START') from epruf_raporty where data=:dt and id_apteki=:ia into st,ok;
   update ogolne set EPRUF_RAP_LAST=(
   select trim(left((select cyfry from TYLKO_DATA(IFINSDATE,1))||' '||lpad(extract(hour from IFINSDATE),2,0)||':'||lpad(extract(minute from IFINSDATE),2,0)||' '||:st||' '||:ok,40)) 
   from epruf_raporty where id_apteki=:ia order by ifinsdate desc rows 1
   ) where id_apteki=:ia;   
   END
   
end^

/* bez zmian Alter */
ALTER TRIGGER INS_UPD_CBT_KLAS ACTIVE
BEFORE INSERT OR UPDATE POSITION 0
as
 declare variable ap apteka;
 declare variable tp char(1);
 declare variable NC VARCHAR(40) CHARACTER SET WIN1250;
 declare variable nk VARCHAR(250) CHARACTER SET WIN1250;
 declare variable ic integer;
 DECLARE VARIABLE zal date;
 DECLARE VARIABLE len integer;
 DECLARE VARIABLE waga integer;
 DECLARE VARIABLE Suma integer;
begin
IF (rdb$get_context('USER_SESSION','BAZYL')=1) THEN EXIT; 

   if (:ap=99 and new.id_klasyfikacje=18 AND COALESCE(OLD.WARTOSC,'')<>NEW.WARTOSC) THEN
    BEGIN
   UPDATE OR INSERT INTO SYNCCBTKLAS (ID_CBT, ID_KLASYFIKACJE, WARTOSC, AKTYWNY) VALUES (NEW.ID_CBT,18, NEW.WARTOSC, 'P');
   UPDATE SYNCCBTKLAS SET AKTYWNY='N' WHERE ID_CBT=OLD.ID_CBT AND ID_KLASYFIKACJE=18 AND WARTOSC=OLD.WARTOSC;
    END
 
IF (rdb$get_context('USER_SESSION','PROCEDURE')=1) THEN EXIT;
 
 /* blokada dopisania 2x takiego samego ean,bloz do karty w³asnej*/
 select COALESCE(kontrola_ean,'N') from ogolne where id_apteki=:ap into :tp;
 if (tp='T' and new.id_klasyfikacje in (3,6) and new.id_cbt>500000) then
 begin
 select max(id_cbt) from cbt_klas where id_cbt<>new.id_cbt and id_klasyfikacje=new.id_klasyfikacje
  and /* id_cbt>500000 and */ wartosc=new.wartosc into :ic; 
  if (ic>0) then
    begin
    SELECT NM_SHORT from cbt where id_cbt=:ic into :nc;
    select nm_klasyfikacje from klasyfikacje where id_klasyfikacje=new.id_klasyfikacje into :nk;
    select min(minvalue(c.ifupddate,coalesce(o.ifupddate,cast('1.1.3000' as timestamp)))) from  cbt c left join cbt_klas o on o.id_cbt=c.id_cbt where c.id_cbt=new.id_cbt into :zal;
     if (ic<500000 and cast('today' as date)-2<:zal) then   -- blokada na dopisywanie eanu jesli istnieje do 3-ch dni od zalozenia karty wg ifupd
     exception klasyfik '  Podany '||nk||' przyporz¹dkowany jest do CBT : '||ic||' 
  ' || nc || '
  Podany '||nk||' mo¿na wprowadziæ nie wczeœniej ni¿ '||(select * from tylko_data(dateadd(day,3,:zal)))||' 
  
  Jeœli zostanie wprowadzony EAN karta zostanie sklejona z ww';
     if (ic>500000) then
     exception klasyfik '  Podany '||nk||' przyporz¹dkowany jest ju¿ do karty w³asnej
  CBT : '||ic||' 
  ' || nc || '
  Popraw lub anuluj zmianê ';     
    end
 end
  /* kontrola nr EAN */ 
 if (tp='T' and new.id_klasyfikacje = 6) THEN
 if (new.id_cbt<1000000 and 1<>:ap) then EXCEPTION blad ' Nie mo¿na wpisywaæ kodów EAN do kart oryginalnych';
 ELSE           
 begin
  len = CHAR_LENGTH(new.wartosc)-1;
  waga = 3;
  Suma = 0;
    if (:len in (7,12,13)) then 
     begin
     WHILE (:len > 0) do
      BEGIN
      Suma = Suma + waga * CAST(SUBSTRING(new.wartosc from len for 1) AS integer);
      waga = 4 - waga;
      len = len - 1;
      END
     ic=10-cast(right(:SUMa,1) as integer);
     ic=right(:ic,1);
     len = CHAR_LENGTH(new.wartosc);
     if (:ic<>CAST(SUBSTRING(new.wartosc from len for 1) AS integer)) then EXCEPTION blad ' B³êdna cyfra kontrolna EAN - '||:ic ;
     end
    ELSE
    EXCEPTION blad ' B³êdna d³ugoœæ EAN';
 end
 
  /* blokada dopisywania czegokolwiek do oryginalnych */
 if (tp='T' and new.id_klasyfikacje not in (-1,18,27,28) and new.id_cbt<1000000 and 1<>:ap) 
  then EXCEPTION blad ' Nie mo¿na wpisywaæ klasyfikacji '||(select nm_klasyfikacje from klasyfikacje where id_klasyfikacje=new.id_klasyfikacje)||' do kart oryginalnych';
 
 
end^

/* bez zmian Alter */
ALTER PROCEDURE DEL_DEK_DOST (
    IA Integer,
    DW Timestamp,
    DD Timestamp,
    DP Timestamp,
    NF Varchar(100),
    IZ Integer )
AS
declare variable id integer;
declare variable ib integer;
declare variable ds integer;
DECLARE idz DOUBLE PRECISION;
DECLARE tt DOUBLE PRECISION;
DECLARE PRZYSZLO DOUBLE PRECISION;
begin
  for select id_dokumenty from dokumenty where id_apteki=:ia and data=:dd and data_wy =:dw and symb_zewn=:nf and symb_wewn like 'VAT%' into :id do
  begin    
    delete from dokumenty where id_apteki=:ia and powiazany_z=:id;            
    delete from dokumenty where id_apteki=:ia and id_dokumenty=:id;
    when any do EXCEPTION blad 'Dokument zap³acony - najpierw usuñ zap³atê z modu³u kasowego 
Kasa: '||(select o.opis||', '||(select*from TYLKO_DATA(o.DATA)) from dokumenty o1 
          left join dekrety d1 on o1.id_apteki=d1.id_apteki and o1.ID_DOKUMENTY=d1.ID_DOKUMENTY
          left join pow_fk p on p.id_apteki=d1.id_apteki and p.id_d2=d1.id_dekrety
          left join dekrety d on p.id_apteki=d.id_apteki and  p.id_dekrety=d.id_dekrety
          left join dokumenty o on o.id_apteki=d.id_apteki and d.id_dokumenty=o.id_dokumenty
          where o1.id_apteki=:ia and o1.powiazany_z=:id and o1.symb_wewn like 'R%' rows 1);     
  end
  SELECT d.ID_BRAKI,d.ID_KONTRAHENCI FROM DOSTAWY d  where id_apteki=:ia and id_dostawy=:iz INTO ib,ds;
  if (id is not null) THEN
  BEGIN
    for select zp.id_zam,id_towary,przyszlo from zam_poz zp left join zaminfo zi on zi.id_apteki=zp.id_apteki and zi.id_zam=zp.id_zam
    where zp.id_apteki=:ia and zp.id_braki=:ib and COALESCE(zi.ID_HURTOWNI,zi.id_kontrahenci)=:ds into :idz, :id, :przyszlo do
    begin
      select sum(sztuk_jp) from zdst where id_apteki=:ia and  id_dostawy=:iz and id_towary=:id into :tt;
      
      if (przyszlo is not null and tt is not null) then
        update zam_poz set przyszlo=przyszlo- :tt where id_apteki=:ia and id_zam=:idz and id_towary=:id;
    end
    update zaminfo set stan=5 where id_apteki=:ia and id_braki=:ib and COALESCE(ID_HURTOWNI,id_kontrahenci)=:ds and stan=6;
  END
  update dostawy set status='P' where id_apteki=:ia and id_dostawy=:iz;
  
end^

ALTER PROCEDURE WARTDST (
    IAP INTEGER,
    IDDST INTEGER,
    IDCN INTEGER,
    BN INTEGER,
    APHU INTEGER )
RETURNS (
    KOD CHAR(1),
    STV NUMERIC(15,2),
    NT NUMERIC(15,2),
    VT NUMERIC(15,2),
    BR NUMERIC(15,2),
    PO INTEGER,
    OP INTEGER,
    RF NUMERIC(15,2) )

AS
declare variable nth integer;
declare variable brh integer;
declare variable nta integer;
declare variable bra integer;
declare variable nt1 integer;
declare variable br1 integer;
declare variable vt1 integer;
declare variable snt integer;
declare variable svt integer;
declare variable sbr integer;
declare variable sop integer;
declare variable spo integer;
begin
  snt=0;
  svt=0;
  sbr=0;
  op=0;
  po=0;
  rf=0;
  for select s.KOD_STAWKI,s.STAWKA,sum(z.SZTUK*c.CENA_NT)*100,sum(z.SZTUK*c.CENA_BR)*100,sum(z.SZTUK_JP*c.CENA_NT_JP)*100,sum(z.SZTUK_JP*c.CENA_BR_JP)*100,sum(sztuk),count(*) from zdst z
      left join ceny_dostawy c on z.id_apteki=c.id_apteki and z.ID_ZDST=c.ID_ZDST and c.ID_CENY=:idcn and c.OBOWIAZUJE_OD = (SELECT max(y.OBOWIAZUJE_OD) FROM ceny_dostawy y WHERE z.id_apteki=y.id_apteki and z.ID_ZDST=y.ID_ZDST and y.ID_CENY=:idcn)
      left join dostawy d on z.id_apteki=d.id_apteki and z.id_dostawy=d.id_dostawy
      left join dostawy k on d.id_apteki=k.id_apteki and d.korekta_do=k.id_dostawy
      left join stawka_VAT(z.id_apteki,z.ID_TOWARY,coalesce(k.data,z.DATA)) s on 0=0
  where z.id_apteki=:iap and z.ID_DOSTAWY=:iddst
  group by s.KOD_STAWKI,s.STAWKA
  into :kod,:stv,:nth,:brh,:nta,:bra,:sop,:spo do
  begin
    if (bn=1) then
    begin
      if (aphu=1) then
        nt1=nth;
      else
        nt1=nta;
      br1=nt1*(1+0.01*stv);
    end
    else
    begin
      if (aphu=1) then
        br1=brh;
      else
        br1=bra;
      nt1=br1/(1+0.01*stv);
    end
    vt1=br1-nt1;
    snt=snt+nt1;
    svt=svt+vt1;
    sbr=sbr+br1;
    op=op+sop;
    po=po+spo;
    nt=nt1*0.01;
    vt=vt1*0.01;
    br=br1*0.01;
    suspend;
  end

  select sum(z.sztuk*c.cena_nt)
  from zdst z
  left join ceny_dostawy c on z.id_apteki=c.id_apteki and z.id_zdst=c.id_zdst and c.id_ceny=1
  left join TYP_LEKU(:IAP,z.id_towary,z.data) t on 0=0
  where z.id_apteki=:IAP and z.id_dostawy=:iddst and t.TYP='REF' into :rf;
  kod='S';
  nt=snt*0.01;
  vt=svt*0.01;
  br=sbr*0.01;
  suspend;
end
^

/*to tylko alter*/
ALTER PROCEDURE UP_DOST_SUMA (
    IAP Integer,
    IDD Integer,
    A Integer,
    B Integer )
AS
declare variable k char(1);
declare variable n double precision;
declare variable r double precision;
declare variable v double precision;
begin
  delete from dost_suma where id_apteki=:iap and id_dostawy=:idd;
  for select KOD,NT,VT,BR from wartdst(:iap,:idd,1,:a,:b) into :K,:n,:v,:r do
   insert into dost_suma (id_apteki,id_dostawy,kod,nt,vt,br) values (:iap,:idd,:K,:n,:v,:r);
end^

ALTER PROCEDURE KS_DST (
    IAP INTEGER,
    ID INTEGER )

AS
declare variable kd char(1);
     declare variable nt double precision;
     declare variable vt double precision;
     declare variable br double precision;
     declare variable tt double precision;
     declare variable ii integer;
     declare variable ib integer;
     declare variable ik integer;
     declare variable lp integer;
     declare variable ds integer;
     declare variable idsd integer;
     declare variable dta timestamp;
     declare variable dtw timestamp;
     declare variable dtp timestamp;
     declare variable nrf varchar(100);
     declare variable przyszlo Double precision;
     declare variable idz integer;
     declare variable rjv varchar(100);
     declare variable dd integer;     
     declare variable kod_szablonu varchar(1);
     declare variable k_uboczne Double precision;
     DECLARE blo char(1);
     DECLARE sta DOUBLE PRECISION;
     DECLARE ilb DOUBLE PRECISION;
     DECLARE blok_pak INTEGER;
     DECLARE rabat_pakiet DOUBLE PRECISION;
     DECLARE czy char(1);
     declare iz integer;
     declare lz integer;
     
begin
 RDB$SET_CONTEXT('USER_TRANSACTION','ZDSTZW',1); -- dopuszczamy w spisie i wszelkich naprawach potem jest problem przy kiegowaniu pakietow  
 RDB$SET_CONTEXT('USER_TRANSACTION','ZDSTZW1',1); --blokada zmiany stanu niezaksiegowanej dostawy
  select pozycja from zdst where id_apteki=:iap and id_dostawy=:id and id_towary<=0 order by pozycja rows 1 into :ib;
    if (ib is not null) then
      exception NIE_SPASOWANE '  Towar na pozycji nr '||ib||' niespasowany ';


  select id_zdst from zdst where id_apteki=:iap and id_dostawy=:id and sztuk=0 order by pozycja rows 1 into :ii;
   if (ii >0) then 
    BEGIN
    select pozycja,id_towary from zdst where id_apteki=:iap and id_dostawy=:id and id_zdst=:ii into :ib,:ik;
    SELECT NAZWA from towary where id_apteki=:iap and id_towary=:ik into :nrf;
    exception ZEROWA_DOSTAWA '  Dostawa nie mo¿e zawieraæ zerowych iloœci
  Skoryguj '||nrf||'
  na pozycji nr '||ib||' ';
    end
    
  select z.id_zdst from zdst z where z.id_apteki=:iap and z.id_dostawy=:id and 
   exists(select * from CENY_DOSTAWY c where c.id_apteki=z.id_apteki and c.id_zdst=z.id_zdst and c.id_ceny=1 and coalesce(c.cena_nt,0)=0) order by pozycja rows 1 into :ii;
   if (ii >0) then 
    BEGIN
    select pozycja,id_towary from zdst where id_apteki=:iap and id_dostawy=:id and id_zdst=:ii into :ib,:ik;
    SELECT NAZWA from towary where id_apteki=:iap and id_towary=:ik into :nrf;
    exception ZEROWA_DOSTAWA '  Cena zakupu nie mo¿e byæ równa 0 z³
  Skoryguj '||nrf||'
  na pozycji nr '||ib||'  ';
    end   
 
  select z.id_zdst from zdst z where z.id_apteki=:iap and z.id_dostawy=:id and 
   exists(select * from TOWARY c where c.smopl_rap='T' and  c.id_apteki=z.id_apteki and c.id_towary=z.id_towary)
   and not exists (select*from ZDST_KLAS k where k.id_apteki=z.id_apteki and k.id_zdst=z.id_zdst and k.id_klasyfikacje=5 and k.wartosc>'' )
   order by pozycja rows 1 into :ii;
   if (ii >0) then 
    BEGIN
    select pozycja,id_towary from zdst where id_apteki=:iap and id_dostawy=:id and id_zdst=:ii into :ib,:ik;
    SELECT NAZWA from towary where id_apteki=:iap and id_towary=:ik into :nrf;
    exception BLAD '  Pozycja podlegaj¹ca raportowaniu ZSMOPL brak serii
  Uzupe³nij '||nrf||'
  na pozycji nr '||ib||'  ';
    end      
    
  select z.id_zdst from zdst z where z.id_apteki=:iap and z.id_dostawy=:id and coalesce(z.DATA_WAZN,'1.1.2000')<=cast('today' as date) - 1095 and
   exists(select * from TOWARY c where c.smopl_rap='T' and  c.id_apteki=z.id_apteki and c.id_towary=z.id_towary)  
   order by pozycja rows 1 into :ii;
   if (ii >0) then 
    BEGIN
    select pozycja,id_towary from zdst where id_apteki=:iap and id_dostawy=:id and id_zdst=:ii into :ib,:ik;
    SELECT NAZWA from towary where id_apteki=:iap and id_towary=:ik into :nrf;
    exception BLAD '  Pozycja podlegaj¹ca raportowaniu ZSMOPL 
  brak lub starsza ni¿ 3 lata data wa¿noœci
  Uzupe³nij '||nrf||'
  na pozycji nr '||ib||'  ';
    end  
    
  select z.id_zdst from zdst z where z.id_apteki=:iap and z.id_dostawy=:id and z.sztuk>0
   and not exists (select*from ZDST_KLAS k where k.id_apteki=z.id_apteki and k.id_zdst=z.id_zdst and k.id_klasyfikacje=6 and char_length(k.wartosc) between 13 and 14) 
   and exists (select*from JEDNOSTKI j left join typ_skladnika(z.id_apteki,z.id_towary) s on 0=0
     where j.id_apteki=z.id_apteki and j.id_towary=z.ID_TOWARY and j.RECEPTURA='T' and j.jednostka=1 and trim(trailing '.' from j.nazwa) ='G' and s.typs=1)
   order by pozycja rows 1 into :ii;
   if (ii >0) then 
    BEGIN
    select pozycja,id_towary from zdst where id_apteki=:iap and id_dostawy=:id and id_zdst=:ii into :ib,:ik;
    SELECT NAZWA from towary where id_apteki=:iap and id_towary=:ik into :nrf;
    exception BLAD ' Surowiec recepturowy prowadzony w karcie 1 gramowej 
 wymagane wpisanie EAN
  Uzupe³nij '||nrf||'
  na pozycji nr '||ib||'  ';
    end    
    

  select pozycja from zdst where id_apteki=:iap and id_dostawy=:id and korekta_do=0 and sztuk<0 order by pozycja rows 1 into :ib;
    if (ib is not null) then
      exception dostawa_korygowana ' Towar na pozycji nr '||ib||' nie ma wybranego leku w polu ''Korekta do''
 Jeœli nie da siê wybraæ leku w polu, nale¿y wprowadziæ korektê rêcznie
 aby unikn¹æ problemu nale¿y sprawdziæ kody dostawców w karcie   ';
       
  select z.id_zdst from zdst z left join zdst k on z.id_apteki=k.id_apteki and z.korekta_do=k.id_zdst
    where  z.id_apteki=:iap and z.id_dostawy=:id and z.korekta_do is not null and z.sztuk_jp<0 and z.sztuk_jp+k.stan+COALESCE((select a.SZTUK_JP FROM zdst a where a.id_apteki = z.id_apteki and a.skorygowana_przez = z.ID_ZDST ),0)   <-0.00001 order by z.pozycja rows 1 into :ii;
    if (ii >0) then
       BEGIN
       select pozycja,id_towary from zdst where id_apteki=:iap and id_dostawy=:id and id_zdst=:ii into :ib,:ik;
       SELECT NAZWA from towary where id_apteki=:iap and id_towary=:ik into :nrf;
       exception dostawa_korygowana '  '||nrf||' 
  na pozycji nr '||ib||'
  Zosta³ ju¿ rozchodowany  ';
       end  
  
   select  min(z.korekta_do) from zdst z
    left join zdst k on k.id_apteki=:iap and k.id_dostawy=:id
    where  z.id_apteki=:iap and z.id_dostawy=:id and z.korekta_do is not null and z.id_zdst<>k.id_zdst and z.korekta_do=k.korekta_do
    and z.sztuk * k.sztuk > 0 and not exists(select*from zdst where id_apteki=:iap and id_dostawy=:id and pozycja>100 and sztuk<0) into :ii;
    if (ii >0) then
       BEGIN
       select min(pozycja),max(pozycja),min(id_towary) from zdst where id_apteki=:iap and id_dostawy=:id and korekta_do=:ii into :lp,:ib,:ik;
       SELECT NAZWA from towary where id_apteki=:iap and id_towary=:ik into :nrf;
       exception stan '  '||nrf||'
  Wybrany ponownie z tej samej podkartoteki na pozycjach
  nr '||lp||' oraz nr '||ib||' ';
       end   
       
  select z.id_zdst from zdst z where z.id_apteki=:iap and z.id_dostawy=:id and z.korekta_do is not null and z.sztuk_jp<0 and z.stan>0 order by pozycja rows 1 into :ii;
    if (ii >0) then
       BEGIN
       select pozycja,id_towary from zdst where id_apteki=:iap and id_dostawy=:id and id_zdst=:ii into :ib,:ik;
       SELECT NAZWA from towary where id_apteki=:iap and id_towary=:ik into :nrf;
       exception dostawa_korygowana '  '||nrf||' 
  na pozycji nr '||ib||'
  Pozycja ujemna nie mo¿e wprowadzaæ stanu na magazyn
Korekty cenowe mo¿na wprowadzaæ tylko dla ca³kowicie rozchodowanych towarów  ';
       end         
       
  select min(pozycja) from zdst z
      left join ceny_dostawy c on z.id_apteki=c.id_apteki and z.ID_ZDST=c.ID_ZDST and c.ID_CENY=1
      where z.id_apteki=:iap and z.id_dostawy=:id and abs((z.SZTUK*c.CENA_NT)-(z.SZTUK_JP*c.CENA_NT_JP))>0.1 into :ii;
   if (ii >0) then
      exception BLAD  ' Ró¿nica pomiêdzy wyliczon¹ wartoœci¹ dostawy w opakowaniach
aptecznych a wartoœci¹ w opakowaniach hurtowych 
na pozycji nr '||:ii||' wynosi '||cast((select min((z.SZTUK*c.CENA_NT)-(z.SZTUK_JP*c.CENA_NT_JP)) 
  from zdst z left join ceny_dostawy c on z.id_apteki=c.id_apteki and z.ID_ZDST=c.ID_ZDST and c.ID_CENY=1
  where z.id_apteki=:iap and z.id_dostawy=:id and z.pozycja=:ii) as numeric (8,2))||' z³ 
Popraw przeliczenia opakowañ fabrycznych (jednostki dostawowe) ';

 
  select BR,NT from dost_suma where id_apteki=:iap and id_dostawy=:id and kod='S' into :br,:nt;
  if (br is null) then
    execute procedure up_dost_suma(:iap,:id,1,1);
  else
     if (abs((select BR from wartdst(:iap,:id,1,1,1) where kod='S') - br) > 1 or
         abs((select NT from wartdst(:iap,:id,1,1,1) where kod='S') - nt) > 1) then
       exception BLAD  '  Ró¿nica pomiêdzy wyliczon¹ wartoœci¹ 
  dostawy a wartoœci¹ wg faktury 
  
   Brutto: '||cast((select BR from wartdst(:iap,:id,1,1,1) where kod='S') - br as numeric (8,2))||' z³  Netto: '||cast((select NT from wartdst(:iap,:id,1,1,1) where kod='S') - nt as numeric (8,2))||' z³ 
   
  Popraw zawartoœæ faktury lub kwoty w prawej tabelce ';
  
  
  SELECT COALESCE(o.PAKIET_BLOKUJ,0) FROM OGOLNE o where o.ID_APTEKI=:iap into blok_pak;

  select d.DATA,d.DT_WYST,d.DT_PLATN,d.NR_FAKTURY,d.id_kontrahenci,d.STATUS,d.ID_BRAKI,d.rej_vat,y.RABAT_GRANICZNY,d.CZYTNIKIEM ,
    (SELECT FIRST 1 z.id_zam FROM ZAMINFO z WHERE z.id_braki=d.id_braki and z.id_apteki=d.id_apteki and (z.id_kontrahenci=d.id_kontrahenci or z.id_hurtowni=d.id_kontrahenci)),
    (SELECT COUNT(*) FROM ZDST z WHERE z.id_dostawy=d.id_dostawy and z.id_apteki=d.id_apteki and z.id_zam is not NULL)
   from dostawy d
   LEFT JOIN DOSTAWCY y on d.ID_APTEKI=y.ID_APTEKI and d.ID_KONTRAHENCI = y.ID_KONTRAHENCI
   
   where d.id_apteki=:iap and d.id_dostawy=:id
    into :dta,:dtw,:dtp,:nrf,:ds,:kd,:ib,rjv,rabat_pakiet,czy,iz,lz;

  if (ds >0 and (nrf is null or nrf<' ' or nrf='' or  :dtw is null or :dtw<'01-01-1910' ) ) then
    exception dostawa_niepelna;
  if (ds <>0) then
  begin
    select count(*) from dostawy where id_apteki=:iap and nr_faktury=:nrf and id_dostawy<>:id and status ='Z' and id_kontrahenci=:ds into :ii;
    if (ii>0) then
      exception dostawa_jest;
  end
  if (kd='Z') then exit;
  if (rjv is null or CHAR_LENGTH(rjv)<10) then
    rjv='VAT-ZK-ZT-';
  if (ds>0) then
  begin
    SELECT sum(z.SZTUK * c.CENA_NT)
     FROM zdst z 
     LEFT JOIN CENY_DOSTAWY c on z.ID_ZDST=c.ID_ZDST and z.ID_APTEKI=c.ID_APTEKI and c.ID_CENY=1
     LEFT JOIN TOWARY t on z.ID_TOWARY=t.ID_TOWARY and z.ID_APTEKI=t.ID_APTEKI
     where  z.id_apteki=:iap and z.id_dostawy=:id and sztuk_jp>0 and COALESCE(t.USLUGA,'N')='T'
    into k_uboczne; 
    if (dtp is null) then
      kod_szablonu = 'B';
    else
    begin
      if (rjv<>'VAT-ZK-ZT-') then
        kod_szablonu = 'W';
      ELSE
        kod_szablonu = 'C';  
    end
    select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING :kod_szablonu into idsd;
    select GEN_ID(SQ_DOKUMENTY,1) from JEDEN_WIERSZ into :ii;
    insert into dokumenty (id_apteki,id_dokumenty,data,data_pl,data_wy,symb_wewn,symb_zewn,id_okres_fk,id_szabl_dek) values
      (:iap,:ii,:dta,:dtp,:dtw,'VAT' || :ii,:nrf,0,:idsd);
    tt=0;
    lp=0;
    for select kod,nt,vt,br from dost_suma where id_apteki=:iap and id_dostawy=:id  into :kd,:nt,:vt,:br do
    if (kd<>'S') then
    begin
      select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
      tt=tt+br;
      lp=lp+1;
      insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,:rjv ||:kd||'-N-'||:ds||'-','W',:nt,'',:lp);
      select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
      insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,:rjv ||:kd||'-V-'||:ds||'-','W',:vt,'',:lp);
    end
    if (COALESCE(k_uboczne,0) > 0) then
    begin
      select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
      lp=lp+1;
      insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,:rjv ||'Y-N-'||:ds||'-','W',:k_uboczne,'',:lp);
      select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
      insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,:rjv ||'Y-V-'||:ds||'-','W',0,'',:lp);
    end
    select * from  dekretacja(:iap,:ii) into dd;
  end
  lp=0;
  if (ds>0) then
    select max(NR_REJ) from dostawy where id_apteki=:iap and extract(year from data)=extract(year from :dta) and id_kontrahenci>0 into :lp;
  else
    select max(NR_REJ) from dostawy where id_apteki=:iap and  extract(year from data)=extract(year from :dta) and id_kontrahenci<=0 into :lp;
  if (lp is null) then lp=0;
  lp=lp+1;
  
  
  update zdst z set stan=sztuk_jp where  id_apteki=:iap and id_dostawy=:id and sztuk_jp>0
   and (SELECT COUNT(*) FROM TOWARY t WHERE t.id_apteki=z.id_apteki and t.id_towary=z.id_towary and COALESCE(t.USLUGA,'N')='T')=0;
  for select sztuk_jp,korekta_do from zdst where id_apteki=:iap and id_dostawy=:id and korekta_do is not null and sztuk_jp<0 ORDER by pozycja
    into nt,tt do
    begin 
     select stan,blokada,ile_blokada from zdst where id_apteki=:iap and id_zdst=:tt into sta,blo,ilb;
       if (sta + nt > 0.01) THEN
       BEGIN
         if (ilb is not null) THEN
         BEGIN
           ilb = ilb + nt;
           if (ilb < 0.01) THEN
           BEGIN
             ilb = null;
             blo = null;
           END
         END
       END
       ELSE
       BEGIN
         blo = null;
         ilb = null;
       END
       update zdst set stan=stan+:nt, blokada=:blo,ile_blokada=:ilb where id_apteki=:iap and id_zdst=:tt;
       if (blo is null) then
         delete from zdst_klas where id_apteki=:iap and id_zdst=:tt and id_klasyfikacje=7;
    end
  update dostawy set status='Z',nr_rej=:lp where id_apteki=:iap and  id_dostawy=:id;
  if (blok_pak>0 and rabat_pakiet>0) THEN
  BEGIN
    FOR SELECT d.ID_TOWARY,cu.CENA_NT  FROM ZDST d
      LEFT JOIN CENY_DOSTAWY cu on cu.ID_APTEKI=d.ID_APTEKI and cu.ID_ZDST=d.ID_ZDST and cu.ID_CENY=1
      LEFT JOIN CENY_DOSTAWY cb on cb.ID_APTEKI=d.ID_APTEKI and cb.ID_ZDST=d.ID_ZDST and cb.ID_CENY=2
      where  d.id_apteki=:iap and d.id_dostawy=:id and sztuk_jp>0 and d.korekta_do is null and cb.CENA_NT>0
        and  100*(cb.cena_nt-cu.cena_nt)/cb.cena_nt > :rabat_pakiet
        into ik,nt  do
      BEGIN  
        FOR SELECT z.ID_ZDST FROM ZDST z 
         LEFT JOIN CENY_DOSTAWY cu on cu.ID_APTEKI=z.ID_APTEKI and cu.ID_ZDST=z.ID_ZDST and cu.ID_CENY=1
         LEFT JOIN CENY_DOSTAWY cb on cb.ID_APTEKI=z.ID_APTEKI and cb.ID_ZDST=z.ID_ZDST and cb.ID_CENY=2
         LEFT JOIN DOSTAWY o on z.ID_DOSTAWY=o.ID_DOSTAWY and z.ID_APTEKI=o.ID_APTEKI
         LEFT JOIN DOSTAWCY y on o.ID_APTEKI=y.ID_APTEKI and o.ID_KONTRAHENCI=y.ID_KONTRAHENCI
        WHERE z.id_apteki=:iap and z.ID_TOWARY=:ik and z.ID_DOSTAWY<>:id  and z.DATA>=:dta-:blok_pak and coalesce(z.BLOKADA,'N')='N'
        and cu.cena_nt-1>:nt and cb.cena_nt>0 and  100*(cb.cena_nt-cu.cena_nt)/cb.cena_nt < y.RABAT_GRANICZNY
        into tt do
        BEGIN
          UPDATE ZDST z SET z.blokada ='Z' where z.id_apteki=:iap and z.id_zdst=:tt;
          delete from zdst_klas where id_apteki=:iap and id_zdst=:tt and id_klasyfikacje=7;
          update or INSERT INTO zdst_klas(id_apteki,id_zdst,id_klasyfikacje,wartosc) VALUES
            (:iap,:tt,7,left('Pakietowe ' || (select cyfry from tylko_data(:dta)) || ' ' || :nrf,40));
        end
     end      
  END
/*  if (czy='T') THEN  --czytnikiem blokowanie niewczytanych 
  BEGIN
    FOR SELECT z.id_zdst,z.sztuk - COALESCE(z.ile_czytnik,0)
    FROM zdst z 
    where z.id_apteki=:iap and z.id_dostawy=:id and  z.sztuk - COALESCE(z.ile_czytnik,0) > 0
    INTO tt,przyszlo do
    BEGIN
       UPDATE ZDST z SET z.blokada ='Z',z.ILE_BLOKADA=:PRZYSZLO where z.id_apteki=:iap and z.id_zdst=:tt;
       delete from zdst_klas where id_apteki=:iap and id_zdst=:tt and id_klasyfikacje=7;
       update or INSERT INTO zdst_klas(id_apteki,id_zdst,id_klasyfikacje,wartosc) VALUES
            (:iap,:tt,7,left('Niedobór ' || (select cyfry from tylko_data(:dta)) || ' ' || :nrf,40));
    END
  END*/
  
  if (ib is not null or lz > 0) then
  begin
    update zdst t set t.ID_ZAM = :iz WHERE t.id_dostawy = :id and t.id_apteki = :iap and t.ID_ZAM is NULL;
    FOR SELECT DISTINCT z.ID_ZAM,z.ID_TOWARY
    FROM zdst z 
    where z.id_apteki=:iap and z.id_dostawy=:id and  z.ID_ZAM is not null
    INTO tt,lz do
    BEGIN
      SELECT sum(z.SZTUK_JP) from ZDST z  where z.ID_APTEKI = :iap and z.ID_ZAM = :tt and z.ID_TOWARY = :lz
      into przyszlo;  
      update zam_poz set przyszlo=:przyszlo where id_apteki=:iap and id_zam=:tt and id_towary=:lz;
    END  
    
    FOR SELECT DISTINCT z.ID_ZAM
    FROM zdst z 
    where z.id_apteki=:iap and z.id_dostawy=:id and  z.ID_ZAM is not null 
    into tt do
      update zaminfo set stan=6 where id_apteki=:iap and id_zam=:tt and stan>3;
  end
 RDB$SET_CONTEXT('USER_TRANSACTION','ZDSTZW',0);    
 RDB$SET_CONTEXT('USER_TRANSACTION','ZDSTZW1',0);
end

^

create OR ALTER PROCEDURE STAN_KARTOTEKI (
    IA INTEGER,
    IZ double precision,
    SA double precision,
    DT TIMESTAMP )
RETURNS (
    ST NUMERIC(15,5)
    )
AS
declare variable ss numeric(15,5);
begin
    st = sa;
    select sum(r.sztuk_jp) from rzdst r left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
      where r.id_apteki=:ia and r.id_zdst=:iz and (s.data>:dt or s.data<'01/01/1901') into :ss;
    if (not ss is null) then
       st=st+ss;
    ss=null;
    select sum(r.sztuk_jp) from zdst r left join dostawy d on r.id_apteki=d.id_apteki and r.id_dostawy=d.id_dostawy
        where r.id_apteki=:ia and r.korekta_do=:iz and r.data>:dt and d.status in ('Z','P') into :ss;
    if (not ss is null) then
       st=st-ss;
    suspend;
end^


ALTER PROCEDURE ABD_Z (
    IA INTEGER,
    D1 TIMESTAMP,
    D2 TIMESTAMP,
    TR INTEGER )
RETURNS (
    KOR INTEGER,
    VZDZN TIMESTAMP,
    VZ2SK VARCHAR(8),
    VZEAN VARCHAR(15),
    VZCND DOUBLE PRECISION,
    VZCNZ DOUBLE PRECISION,
    VZILA DOUBLE PRECISION,
    VZILZ DOUBLE PRECISION,
    VZMNH DOUBLE PRECISION,
    VZNRD INTEGER,
    VZNRT INTEGER,
    VZIDZ INTEGER,
    VZPLT INTEGER,
    VZSKO VARCHAR(8),
    VZUST DOUBLE PRECISION,
    VZVAT DOUBLE PRECISION,
    VILMG DOUBLE PRECISION,
    VWCZK DOUBLE PRECISION,
    VWCDT DOUBLE PRECISION,
    VZNZW VARCHAR(42),
    VMNMG DOUBLE PRECISION,
    VWCZP DOUBLE PRECISION,
    VSERN VARCHAR(42),
    VSDTW TIMESTAMP,
    VZINT INTEGER,
    ID INTEGER )
AS
BEGIN
  FOR SELECT t.DATA,t.ID_DOSTAWY,COALESCE(t.DT_PLATN,t.DATA)-t.DATA,t.ID_KONTRAHENCI,t.UPUST,IIF(t.KOREKTA_DO is null,0,1) FROM DOSTAWY t
  where t.DATA BETWEEN :d1 and :d2 and t.ID_DOSTAWY > :tr and COALESCE(t.ID_KONTRAHENCI,1)>0   and t.STATUS in ('P','Z')
  ORDER by t.DATA,t.ID_DOSTAWY
  into vzdzn,id,vzplt,vznrd,vzust,kor do
  for SELECT  z.ID_TOWARY,mod(z.ID_ZDST,1000000),round(l.CENA_BR,2),round(c.CENA_NT_JP,2),z.STAN,z.SZTUK_JP,v.STAWKA,z.STAN,round(z.STAN*c.CENA_NT_JP,2),round(z.STAN*l.CENA_BR,2)
   ,LEFT(t.NAZWA,42),round(z.STAN*c.CENA_NT_JP,2),(SELECT FIRST 1 k.WARTOSC FROM ZDST_KLAS k where k.ID_APTEKI = z.ID_APTEKI and k.ID_ZDST=z.ID_ZDST and k.ID_KLASYFIKACJE=5 ORDER by k.IFUPDDATE DESC),
   z.DATA_WAZN
  FROM ZDST z 
    LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI = c.ID_APTEKI and z.ID_ZDST = c.ID_ZDST and c.ID_CENY = 1
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,z.DATA,z.ID_ZDST,'') l on 0=0
    LEFT JOIN TOWARY t on z.ID_APTEKI=t.ID_APTEKI and z.ID_TOWARY = t.ID_TOWARY
    LEFT JOIN STAWKA_VAT(z.id_apteki,z.id_towary,z.DATA) v on 0=0
  WHERE z.ID_APTEKI=:ia and z.ID_DOSTAWY=:id
  into vznrt,vzidz,vzcnd,vzcnz,vzila,vzilz,vzvat,vilmg,vwczk,vwcdt,vznzw,vwczp,vsern,vsdtw do
  BEGIN
    vzsko = null;
    vzean = null;
    SELECT FIRST 1 wartosc from tw_KLAS k where k.ID_APTEKI=:ia and  k.ID_TOWARY = :vznrt and k.ID_KLASYFIKACJE=3 and char_length(wartosc)=7 into vzsko;
    SELECT FIRST 1 wartosc from tw_KLAS k where k.ID_APTEKI=:ia and  k.ID_TOWARY = :vznrt and k.ID_KLASYFIKACJE=6 and char_length(wartosc) in (13,14) into vzean;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_CYFRY(:vzsko) s into vzsko;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_CYFRY(:vzean) s into vzean;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_znaki(:vznzw) s into vznzw;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_znaki(:vsern) s into vsern;
    vz2sk = vzsko;
    vzmnh = 1;
    vmnmg = 1;
    vzint = 1;
    SUSPEND;
  END
END^


ALTER PROCEDURE ABD_T (
    IA INTEGER, DT DATE )
RETURNS (
    VTSKO VARCHAR(8),
    VTEAN VARCHAR(15),
    VTDET DOUBLE PRECISION,
    VTILA DOUBLE PRECISION,
    VTMNH DOUBLE PRECISION,
    VTNRT INTEGER,
    VTNZW VARCHAR(42),
    VTVAT DOUBLE PRECISION,
    VTZAK DOUBLE PRECISION,
    VSERN VARCHAR(42),
    VSDTW TIMESTAMP )
AS
BEGIN

  for SELECT  z.ID_TOWARY,round(l.CENA_BR* s.ST,2),s.ST,v.STAWKA,round(s.ST*c.CENA_NT_JP,2)
   ,LEFT(t.NAZWA,42),(SELECT FIRST 1 k.WARTOSC FROM ZDST_KLAS k where k.ID_APTEKI = z.ID_APTEKI and k.ID_ZDST=z.ID_ZDST and k.ID_KLASYFIKACJE=5 ORDER by k.IFUPDDATE DESC),
   z.DATA_WAZN
  FROM ZDST z 
    LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI = c.ID_APTEKI and z.ID_ZDST = c.ID_ZDST and c.ID_CENY = 1
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,:dt,z.ID_ZDST,'') l on 0=0
    LEFT JOIN TOWARY t on z.ID_APTEKI=t.ID_APTEKI and z.ID_TOWARY = t.ID_TOWARY
    LEFT JOIN STAWKA_VAT(z.id_apteki,z.id_towary,:dt) v on 0=0
    left join stan_kartoteki ( z.ID_APTEKI,z.ID_ZDST,z.STAN,:dt) s on 0=0
  WHERE  (z.DATA_ZAMKN is NULL or z.DATA_ZAMKN >= :dt) AND z.ID_APTEKI=:ia  and c.CENA_NT_JP is not NULL and z.DATA <= :dt and s.ST>0
  into vtnrt,vtdet,vtila,vtvat,vtzak,vtnzw,vsern,vsdtw do
  BEGIN    
    vtsko = null;
    vtean = null;
    SELECT FIRST 1 wartosc from tw_KLAS k where k.ID_APTEKI=:ia and  k.ID_TOWARY = :vtnrt and k.ID_KLASYFIKACJE=3 and char_length(wartosc)=7 into vtsko;
    SELECT FIRST 1 wartosc from tw_KLAS k where k.ID_APTEKI=:ia and  k.ID_TOWARY = :vtnrt and k.ID_KLASYFIKACJE=6 and char_length(wartosc) in (13,14) into vtean;    
    SELECT nullif(s.CYFRY,'') FROM TYLKO_CYFRY(:vtsko) s into vtsko;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_CYFRY(:vtean) s into vtean;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_znaki(:vtnzw) s into vtnzw;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_znaki(:vsern) s into vsern;
    vtmnh = 1;
    SUSPEND;
  END
END^

ALTER PROCEDURE ABD_S (
    IA INTEGER,
    D1 TIMESTAMP,
    D2 TIMESTAMP,
    TR INTEGER )
RETURNS (
    KOR INTEGER,
    VSDZN TIMESTAMP,
    VSGDZN TIMESTAMP,
    VSIDS INTEGER,
    VSDTR TIMESTAMP,
    PDTREC VARCHAR(1),
    VSKJC VARCHAR(5),
    ORPRW VARCHAR(8),
    ORPRE VARCHAR(15),
    VSSKO VARCHAR(8),
    VS2SK VARCHAR(8),
    VSEAN VARCHAR(15),
    VSODP INTEGER,
    VSUPS INTEGER,
    VSBRW INTEGER,
    VSCND DOUBLE PRECISION,
    VSCNZ DOUBLE PRECISION,
    VSIDZ VARCHAR(6),
    VSILO DOUBLE PRECISION,
    VSILR DOUBLE PRECISION,
    VSMNH DOUBLE PRECISION,
    VSNAS INTEGER,
    VSNRK INTEGER,
    VSNRT INTEGER,
    VSNUM INTEGER,
    VSTAX DOUBLE PRECISION,
    VSTYP INTEGER,
    VSVAT DOUBLE PRECISION,
    VSLMC DOUBLE PRECISION,
    VSWMR DOUBLE PRECISION,
    VSZPL DOUBLE PRECISION,
    VSDR1 DOUBLE PRECISION,
    VSDR2 DOUBLE PRECISION,
    VSUST DOUBLE PRECISION,
    VSODU INTEGER,
    VSKEU VARCHAR(2),
    VSKWJ INTEGER,
    VILMG DOUBLE PRECISION,
    VWCZK DOUBLE PRECISION,
    VWCDT DOUBLE PRECISION,
    VSNZW VARCHAR(42),
    VSERN VARCHAR(42),
    VSDTW TIMESTAMP,
    VZINT INTEGER,
    VWSKU INTEGER,
    VSPLE VARCHAR(1),
    VSWIE INTEGER,
    VMNMG DOUBLE PRECISION,
    VWCZP DOUBLE PRECISION,
    VSUPD INTEGER )
AS
DECLARE ts VARCHAR(1);
DECLARE ra VARCHAR(12);
DECLARE kk int;
DECLARE iz int;
DECLARE io int;
DECLARE it int;
DECLARE pr int;
DECLARE si int;
DECLARE dk DATE;
DECLARE ti int;
DECLARE sl int;
DECLARE tn VARCHAR(50);
DECLARE tt int;
DECLARE ss DOUBLE PRECISION;
DECLARE s2 DOUBLE PRECISION;
DECLARE sp int;
DECLARE u1 VARCHAR(2);
DECLARE u2 VARCHAR(2);
DECLARE pa VARCHAR(20);
DECLARE dp TIMESTAMP;
DECLARE ki INTEGER;
BEGIN
  sl = 0;
  SELECT COALESCE(o.PROGN_KASA,-1) FROM OGOLNE o WHERE o.ID_APTEKI = :ia into ki;
  FOR SELECT t.data,t.IFINSDATE,t.id_tranzakcje FROM TRANZAKCJE t
  where t.DATA BETWEEN :d1 and :d2 and t.ID_TRANZAKCJE > :tr and COALESCE(t.ID_KONTRAHENCI,1)>0
  ORDER by t.DATA,t.ID_TRANZAKCJE
  into vsdzn,vsgdzn,vsnrk do
  for SELECT  s.pozycja, r.ID_TOWARY,r.SZTUK_JP,(s.DATA-cast('01.01.2015' as date)) * 10000 + s.ID_TRANZAKCJE * 10,s.TRYB,a.DATA_WYST,a.ATRYBUTY,s.ID_ZAMIENNIK
    ,s.ID_ODPLATNOSC,r.CENA,round(c.CENA_NT_JP,2),mod(r.ID_ZDST,1000000),round(r.SZTUK_JP,5),iif(s.POZ_REC>1,1,1),s.TAKSA,s.ID_TOWARY,r.POZYCJA,s.STAWKA_VAT
    ,l.LIMIT,round(0.2*(s.WARTOSC+s.TAKSA),2),s.ODPLATNOSC+s.DOPLATA,s.WARTOSC+s.TAKSA - s.ODPLATNOSC-s.DOPLATA,s.REFUNDATOR2,s.RABAT_W_GOTOWCE ,
    b.STAN,round(b.STAN * c.CENA_NT_JP,2),round(b.STAN*r.CENA,2),left(t.NAZWA,42),(SELECT FIRST 1 k.WARTOSC FROM ZDST_KLAS k where k.ID_APTEKI = b.ID_APTEKI and k.ID_ZDST=b.ID_ZDST and k.ID_KLASYFIKACJE=5 ORDER by k.IFUPDDATE DESC),
    b.DATA_WAZN,s.ID_SPRZEDAZ,r.SZTUK_JP * j.MNOZ / j.DZIEL,a.PACJENT,IIF(n.NR_KASY = :ki,1,0)
    FROM SPRZEDAZ s 
    LEFT join RZDST r on s.ID_SPRZEDAZ = r.ID_SPRZEDAZ and r.ID_APTEKI=s.ID_APTEKI 
    LEFT JOIN RECEPTA a on s.ID_APTEKI=a.ID_APTEKI and s.ID_RECEPTA=a.ID_RECEPTA
    LEFT JOIN CENY_DOSTAWY c on r.ID_APTEKI = c.ID_APTEKI and r.ID_ZDST = c.ID_ZDST and c.ID_CENY = 1
    LEFT JOIN AKT_LIMIT(s.id_apteki,s.id_towary,s.id_odplatnosc,s.DATA,a.KOD_SRODKA) l on 0=0
    LEFT JOIN RECEPTURA e on e.ID_APTEKI = s.ID_APTEKI and e.ID_SPRZEDAZ = s.ID_SPRZEDAZ
    LEFT JOIN ZDST b on r.ID_APTEKI = b.ID_APTEKI and r.ID_ZDST = b.ID_ZDST
    LEFT JOIN TOWARY t on r.ID_APTEKI=t.ID_APTEKI and r.ID_TOWARY = t.ID_TOWARY
    left join  ILOSC_JP( r.ID_APTEKI,r.ID_TOWARY,2) j on 0=0
    LEFT JOIN TRANZAKCJE n on n.ID_TRANZAKCJE=s.ID_TRANZAKCJE and n.DATA=s.DATA and n.ID_APTEKI=s.ID_APTEKI
    WHERE s.ID_APTEKI=:ia and s.DATA=:vsdzn and s.ID_TRANZAKCJE=:vsnrk and s.TRYB <> 'K'
    UNION
    SELECT  0,0,1,(s.DATA-cast('01.01.2015' as date)) * 10000 + s.ID_TRANZAKCJE * 10,s.TRYB,a.DATA_WYST,a.ATRYBUTY,s.ID_ZAMIENNIK
    ,s.ID_ODPLATNOSC,0,0,0,1,1,s.TAKSA,s.ID_TOWARY,0,s.STAWKA_VAT
    ,0,round(0.2*(s.WARTOSC+s.TAKSA),2),s.ODPLATNOSC+s.DOPLATA,s.WARTOSC+s.TAKSA - s.ODPLATNOSC-s.DOPLATA,s.REFUNDATOR2,s.RABAT_W_GOTOWCE ,
    0,0,0,left(t.NAZWA,42),null,
    null,s.ID_SPRZEDAZ,1,a.PACJENT,0
    FROM SPRZEDAZ s 
    LEFT JOIN RECEPTA a on s.ID_APTEKI=a.ID_APTEKI and s.ID_RECEPTA=a.ID_RECEPTA
    LEFT JOIN RECEPTURA e on e.ID_APTEKI = s.ID_APTEKI and e.ID_SPRZEDAZ = s.ID_SPRZEDAZ
    LEFT JOIN TOWARY t on s.ID_APTEKI=t.ID_APTEKI and s.ID_TOWARY = t.ID_TOWARY
    WHERE s.ID_APTEKI=:ia and s.DATA=:vsdzn and s.ID_TRANZAKCJE=:vsnrk and s.TRYB <> 'K' and s.ID_TOWARY = 0
    ORDER by 5 desc, 1,16
    INTO sp,vsnrt,vsilo,vsids,ts,vsdtr,ra,iz,io,vscnd,vscnz,vsidz,vsilo,vsnas,vstax,it,pr,vsvat,
    vslmc,vswmr,vszpl,vsdr1,vsdr2,vsust,vilmg,vwczk,vwcdt,vsnzw,vsern,vsdtw,si,s2,pa,vzint do
  BEGIN   
    if (sl <> si and it<>0) THEN
    BEGIN
      sl = si;
      ss = 0;
      select sum(r.SZTUK_JP * j.MNOZ / j.DZIEL) from RZDST r left join  ILOSC_JP( r.ID_APTEKI,r.ID_TOWARY,2) j on 0=0
       where r.ID_SPRZEDAZ = :si and r.ID_APTEKI = :ia into ss;
    END 
    if (it <>0 AND ss <> 0 and ss >= vsilo) THEN
    BEGIN
      vszpl = round(vszpl * s2 / ss,2);
      vsdr1 = round(vsdr1 * s2 / ss,2);
      vsdr2 = round(vsdr2 * s2 / ss,2);
      vsust = round(vsust * s2 / ss,2);
    END
    u1 = 'X';
    u2 = 'X';
    kk = 1;
    vsilr = vsilo;
    vsmnh = 1;
    kor = 0;
    if (ts in ('Z','N','P','R')) THEN
    BEGIN
      SELECT dd,ti from FIRSTOP(:ia,:si) into dk,ti;
      if (dk<d1 or (dk=d1 and tr <=vsnrk)) then
      BEGIN
        kor = 1;
        if (ts = 'Z') THEN
          kk = 0;
      END    
      ELSE
        if (ts = 'Z') THEN kor = -1;
    END
    
    vsids = vsids + kk;  
    vsups = 0;
    vsupd = 0;
    
    vsodu = null;
    vskeu = NULL;
    vsodp = 7;
    if (not ra is NULL) THEN
    BEGIN
      vsbrw = 1;
      u1 = SUBSTRING(ra from 4 for 2);
      u2 = SUBSTRING(ra from 8 for 1);
      ts = SUBSTRING(ra from 2 for 1);
      if (ts='Z') THEN ts = 'A';
      if (ts='P') THEN ts = 'Z';
      if (ts in ('O','Z','F')) THEN
        pdtrec = ts;
      ELSE
        pdtrec = null;
      if (u2 = 'S') THEN  vsups =  iif(vszpl=0,2,1);
      if (u2 = 'D') THEN  vsupd =  iif(vszpl=0,2,1);
      if (SUBSTRING(ra from 2 for 1) = 'W') THEN  vsbrw = 2;
      if (SUBSTRING(ra from 2 for 1) = 'N') THEN  vsbrw = 3;
      
      ra = SUBSTRING(ra from 6 for 2);
      if (SUBSTRING(ra from 1 for 1) in ('0','1')) THEN
      BEGIN
        if (SUBSTRING(ra from 2 for 1) SIMILAR TO '[0-9]+') THEN
          vsodu = ra;
        ELSE
          vsodu = 0;  
      END    
      ELSE
        vskeu = ra;    
      if (io = 1 ) THEN 
      BEGIN
        vsodp = 2;
        if (u1 = 'AZ') then vsodp = 10;
      end
      if (io = 2 ) THEN
      BEGIN
       vsodp = 3;
       if (u1 = 'AZ') then vsodp = 10;
       if (u1 = 'ZK') then vsodp = 1;
       if (u1 = 'IW') then vsodp = 8;
       if (u1 = 'PO') then vsodp = 9;
      END 
      if (io = 3 ) THEN vsodp = 4;
      if (io = 4 ) THEN vsodp = 5;
      if (io = 5 ) THEN vsodp = 6;  
      if (u2 = 'S') THEN vsodp = vsodp + 20;
      if (u2 = 'C') THEN vsodp = vsodp + 60;
      if (vszpl = 0 and u2 in ('C','S')) THEN vsodp = vsodp + 20;
    end
    ELSE
    BEGIN
      vsbrw = 5;
    END
    if (CHARACTER_LENGTH(pa) = 11) THEN
    BEGIN
      SELECT PESELD,PLEC FROM PESELP(:pa)  INTO dp,VSPLE;
      if (dp is not null) THEN
        vswie = floor(DATEDIFF(day from dp to :vsdzn)/365.25);
      ELSE
        VSWIE = NULL;
    END
    ELSE
    BEGIN
      VSPLE = NULL;
      VSWIE = NULL;
    END
    if (not iz is null) THEN
    BEGIN
      SELECT FIRST 1 wartosc from CBT_KLAS k where k.ID_CBT = :iz and k.ID_KLASYFIKACJE=3 and char_length(wartosc)=7 into orprw;
      SELECT FIRST 1 wartosc from CBT_KLAS k where k.ID_CBT = :iz and k.ID_KLASYFIKACJE=6 and char_length(wartosc) in (13,14) into orpre;
      SELECT nullif(s.CYFRY,'') FROM TYLKO_CYFRY(:orprw) s into orprw;
      SELECT nullif(s.CYFRY,'') FROM TYLKO_CYFRY(:orpre) s into orpre;
    END
    ELSE
    BEGIN
      orpre = null;
      orprw = null;
    END
    vssko = null;
    vsean = NULL;
    
    vwsku = 0;
    vmnmg = 1;
    vwczp = vwczk;
    vssko = null;
    vsean = null;
    SELECT FIRST 1 wartosc from tw_KLAS k where k.ID_APTEKI=:ia and  k.ID_TOWARY = :vsnrt and k.ID_KLASYFIKACJE=3 and char_length(wartosc)=7 into vssko;
    SELECT FIRST 1 wartosc from tw_KLAS k where k.ID_APTEKI=:ia and  k.ID_TOWARY = :vsnrt and k.ID_KLASYFIKACJE=6 and char_length(wartosc) in (13,14) into vsean;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_CYFRY(:vssko) s into vssko;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_CYFRY(:vsean) s into vsean;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_znaki(:vsnzw) s into vsnzw;
    SELECT nullif(s.CYFRY,'') FROM TYLKO_znaki(:vsern) s into vsern;    
    
    
    vsnum = 0;
    if (it=0) THEN
    BEGIN
      if (sp = 0) THEN
      BEGIN
        vstyp = 128;
      END
      ELSE
      BEGIN
        vstax = 0;
        vswmr = 0;
        vszpl = 0;
        vsdr1 = 0;
        vsdr2 = 0;
        vsust = 0;
        vstyp = 160;
      END
    END
    ELSE
    BEGIN
      vstyp = 0;
      vswmr = 0;
    END 
    if (kor <> -1) then 
      SUSPEND;
  END
END
^

ALTER PROCEDURE KSIEGUJ_OKRES (
    IDAPT INTEGER,
    DTOD TIMESTAMP,
    DTDO TIMESTAMP )
AS
DECLARE kasa int;
DECLARE akt_kasa int;
DECLARE id_szabl int;
DECLARE szabl_fakt int;
DECLARE szabl_bezn int;
DECLARE idd int;
DECLARE lp int;
DECLARE idod int;
DECLARE iddo int;
DECLARE netto DOUBLE PRECISION;
DECLARE vat DOUBLE PRECISION;
DECLARE kod VARCHAR(1);
DECLARE nmd VARCHAR(100);
DECLARE atrv INTEGER;
DECLARE dt TIMESTAMP;
BEGIN

  /*naprawy wplat*/
  BEGIN    
    for select distinct data from TRANZAKCJE where id_apteki=:IDAPT and data between :DTOD and :DTDO
    INTO dt do 
    EXECUTE PROCEDURE NAPRAW_WPLATY(IDAPT,dt,1);
  END

  select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING 'D' into id_szabl;
  akt_kasa = -1;
  
  /* Drukarki  */
  if (id_szabl>0) then
  begin
   for select nr_kasy,sum(netto) netto ,sum(vat) vat ,kod from  (
   select t.NR_KASY,round(sum(s.WARTOSC+s.TAKSA)/(1+0.01*s.stawka_vat),2) NETTO,round(sum(s.WARTOSC+s.TAKSA)*(0.01*s.stawka_vat)/(1+0.01*s.stawka_vat),2) VAT,v.kod
   from sprzedaz s
   left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
   left join akt_stawki_vat(s.data) v on  (v.vat=s.stawka_vat and v.kod<>'Z')
   where s.id_apteki=:idapt and s.data BETWEEN :dtod and :dtdo and
   (
   ((s.tryb='S') and (t.id_kontrahenci is null or t.id_kontrahenci>0)  )
    or
   (s.tryb='K' and (t.id_kontrahenci is null or (t.id_kontrahenci>0 and (select poprzedni from zmiany where id_apteki=s.id_apteki and id_sprzedaz=s.id_sprzedaz) is null))  )
   or
   ((s.tryb='P' or s.tryb='N'  or s.tryb='K') and (t.id_kontrahenci is null  or t.paragon='V' or (s.ID_TOWARY=0 and t.KOR_DT is null )) )
   )
   and (t.paragon='X' or t.paragon='T' or t.paragon='V' )
   group by t.NR_KASY,v.kod,s.DATA,s.STAWKA_VAT )
  GROUP by nr_kasy,kod into kasa,netto,vat,kod do
  begin
    if (akt_kasa<>kasa) THEN
    BEGIN
      lp = 0;
      idd = GEN_ID(SQ_DOKUMENTY,1);
      if (idod is null) then idod=idd;
      iddo = idd;
      akt_kasa = kasa;
      nmd = 'Drukarka : ' || kasa;
      atrv = bin_shl(1,27);

      delete from DOKUMENTY where id_apteki=:idapt and data = :dtdo and symb_zewn=:nmd and id_szabl_dek = :id_szabl;
      insert into dokumenty (ID_APTEKI,id_dokumenty,data,data_wy,symb_wewn,symb_zewn,id_okres_fk,id_szabl_dek,atrvat)
        values  (:idapt,:idd,:dtdo,:dtdo,'VAT' || :idd,:nmd,0,:id_szabl,:atrv);

    END
    lp = lp + 1;
    insert into dekrety (ID_APTEKI,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-N-'||0||'-','W',:netto,'',:lp);
    insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-V-'||0||'-','W',:vat  ,'',:lp);
  end
  END
  
  
  szabl_fakt = -1;
  select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING 'S' into szabl_fakt;
  
  if (szabl_fakt>0) THEN
  begin
    akt_kasa = 0;
    for  select -sum(s.WARTOSC+s.TAKSA)/(1+0.01*s.stawka_vat) ,-sum(s.WARTOSC+s.TAKSA)*(0.01*s.stawka_vat)/(1+0.01*s.stawka_vat) ,v.kod
      from sprzedaz s
      left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje left join akt_stawki_vat(s.data) v on  v.vat=s.stawka_vat
      LEFT JOIN KONTRAHENCI k on t.ID_KONTRAHENCI = k.ID_KONTRAHENCI
      where s.id_apteki=:IDAPT and s.data BETWEEN :dtod and :dtdo and t.id_kontrahenci > 0 and 
      ((s.tryb='S')  
      or (s.tryb='K' and (select poprzedni from zmiany where id_apteki=s.id_apteki and id_sprzedaz=s.id_sprzedaz) is null)
      or ((s.tryb='P' or s.tryb='N'  or s.tryb='K') and (t.paragon='V' or (s.ID_TOWARY=0 and t.KOR_DT is null )) )
      ) and  t.paragon in ('X','V') and t.id_kontrahenci > 0 and CHARACTER_LENGTH( trim(coalesce(k.NIP,'')))>9
      group by s.stawka_vat,v.kod
    into netto , vat , kod do
    BEGIN
    if (akt_kasa=0) THEN
    BEGIN
      lp = 0;
      idd = GEN_ID(SQ_DOKUMENTY,1);
      if (idod is null) then idod=idd;
      iddo = idd;
      akt_kasa = 1;
      nmd = 'Faktury z NIP do paragonów';
      id_szabl = szabl_fakt;
      atrv = -2147483648;

      delete from DOKUMENTY where id_apteki=:idapt and data = :dtdo and symb_zewn=:nmd and id_szabl_dek = :id_szabl;
      insert into dokumenty (ID_APTEKI,id_dokumenty,data,data_wy,symb_wewn,symb_zewn,id_okres_fk,id_szabl_dek,atrvat)
        values  (:idapt,:idd,:dtdo,:dtdo,'VAT' || :idd,:nmd,0,:id_szabl,:atrv);

    END
    lp = lp + 1;
    insert into dekrety (ID_APTEKI,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-N-'||0||'-','W',:netto,'',:lp);
    insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-V-'||0||'-','W',:vat  ,'',:lp);

    END
  end
  
  
  szabl_bezn = -1;
  select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING 'Z' into szabl_bezn;

  if (szabl_bezn>0) THEN
  begin
    akt_kasa = 0;
    for  select -sum(s.WARTOSC+s.TAKSA)/(1+0.01*s.stawka_vat) ,-sum(s.WARTOSC+s.TAKSA)*(0.01*s.stawka_vat)/(1+0.01*s.stawka_vat) ,v.kod
      from sprzedaz s
      left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje left join akt_stawki_vat(s.data) v on  v.vat=s.stawka_vat
      LEFT JOIN KONTRAHENCI k on t.ID_KONTRAHENCI = k.ID_KONTRAHENCI
      where s.id_apteki=:IDAPT and s.data BETWEEN :dtod and :dtdo and t.id_kontrahenci > 0 and 
      ((s.tryb='S')  
      or (s.tryb='K' and (select poprzedni from zmiany where id_apteki=s.id_apteki and id_sprzedaz=s.id_sprzedaz) is null)
      or ((s.tryb='P' or s.tryb='N'  or s.tryb='K') and (t.paragon='V' or (s.ID_TOWARY=0 and t.KOR_DT is null )) )
      ) and  t.paragon in ('X','V') and t.id_kontrahenci > 0 and CHARACTER_LENGTH( trim(coalesce(k.NIP,'')))<=9
      group by s.stawka_vat,v.kod
    into netto , vat , kod do
    BEGIN
    if (akt_kasa=0) THEN
    BEGIN
      lp = 0;
      idd = GEN_ID(SQ_DOKUMENTY,1);
      if (idod is null) then idod=idd;
      iddo = idd;
      akt_kasa = 1;
      nmd = 'Faktury bez NIP do paragonów';
      id_szabl = szabl_bezn;
      atrv = -2147483648;
      delete from DOKUMENTY where id_apteki=:idapt and data = :dtdo and symb_zewn=:nmd and id_szabl_dek = :id_szabl;
      insert into dokumenty (ID_APTEKI,id_dokumenty,data,data_wy,symb_wewn,symb_zewn,id_okres_fk,id_szabl_dek,atrvat)
        values  (:idapt,:idd,:dtdo,:dtdo,'VAT' || :idd,:nmd,0,:id_szabl,:atrv);

    END
    lp = lp + 1;
    insert into dekrety (ID_APTEKI,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-N-'||0||'-','W',:netto,'',:lp);
    insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-V-'||0||'-','W',:vat  ,'',:lp);

    END
  end

  if (szabl_bezn>0) THEN
  begin
    akt_kasa = 0;
    for  select sum(s.WARTOSC+s.TAKSA)/(1+0.01*s.stawka_vat) ,sum(s.WARTOSC+s.TAKSA)*(0.01*s.stawka_vat)/(1+0.01*s.stawka_vat) ,v.kod
      from sprzedaz s
      left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje left join akt_stawki_vat(s.data) v on  v.vat=s.stawka_vat
      LEFT JOIN KONTRAHENCI k on t.ID_KONTRAHENCI = k.ID_KONTRAHENCI
      where s.id_apteki=:IDAPT and s.data BETWEEN :dtod and :dtdo and t.id_kontrahenci > 0 and 
      ((s.tryb='S')  
      or (s.tryb='K' and (select poprzedni from zmiany where id_apteki=s.id_apteki and id_sprzedaz=s.id_sprzedaz) is null)
      or ((s.tryb='P' or s.tryb='N'  or s.tryb='K') and (t.paragon='V' or (s.ID_TOWARY=0 and t.KOR_DT is null )) )
      ) and  t.paragon in ('X','V') and t.id_kontrahenci > 0 and CHARACTER_LENGTH( trim(coalesce(k.NIP,'')))<=9 and  (t.TERMIN_PLAT is null)
      group by s.stawka_vat,v.kod
    into netto , vat , kod do
    BEGIN
    if (akt_kasa=0) THEN
    BEGIN
      lp = 0;
      idd = GEN_ID(SQ_DOKUMENTY,1);
      if (idod is null) then idod=idd;
      iddo = idd;
      akt_kasa = 1;
      atrv = -2147483648;
      nmd = 'Kasowe faktury gotówkowe bez NIP';
      delete from DOKUMENTY where id_apteki=:idapt and data = :dtdo and symb_zewn=:nmd and id_szabl_dek = :szabl_bezn;
      insert into dokumenty (ID_APTEKI,id_dokumenty,data,data_wy,symb_wewn,symb_zewn,id_okres_fk,id_szabl_dek,atrvat)
        values  (:idapt,:idd,:dtdo,:dtdo,'VAT' || :idd,:nmd,0,:szabl_bezn,:atrv);

    END
    lp = lp + 1;
    insert into dekrety (ID_APTEKI,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-N-'||0||'-','W',:netto,'',:lp);
    insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-V-'||0||'-','W',:vat  ,'',:lp);

    END
  end

  id_szabl = -1;
  select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING 'T' into id_szabl;
  if (id_szabl>0) THEN
  begin
    akt_kasa = 0;
    for select sum(s.WARTOSC+s.TAKSA)/(1+0.01*s.stawka_vat) ,sum(s.WARTOSC+s.TAKSA)*(0.01*s.stawka_vat)/(1+0.01*s.stawka_vat) ,v.kod from sprzedaz s
      left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje left join akt_stawki_vat(s.data) v on  v.vat=s.stawka_vat
      LEFT JOIN KONTRAHENCI k on t.ID_KONTRAHENCI = k.ID_KONTRAHENCI
      where s.id_apteki=:IDAPT and s.data BETWEEN :dtod and :dtdo  and ((s.tryb='Z' ) and (t.paragon='X' or t.paragon='T'  or t.paragon='V') 
       and (t.id_kontrahenci is null  or (t.paragon='V' and CHARACTER_LENGTH( trim(coalesce(k.NIP,'')))<=9)) )
      group by s.stawka_vat,v.kod into netto , vat , kod do
    BEGIN
    if (akt_kasa=0) THEN
    BEGIN
      lp = 0;
      idd = GEN_ID(SQ_DOKUMENTY,1);
      if (idod is null) then idod=idd;
      iddo = idd;
      akt_kasa = 1;
      nmd = 'Zwroty paragonów';

      delete from DOKUMENTY where id_apteki=:idapt and data = :dtdo and symb_zewn=:nmd and id_szabl_dek = :id_szabl;
      insert into dokumenty (ID_APTEKI,id_dokumenty,data,data_wy,symb_wewn,symb_zewn,id_okres_fk,id_szabl_dek)
        values  (:idapt,:idd,:dtdo,:dtdo,'VAT' || :idd,:nmd,0,:id_szabl);

    END
    lp = lp + 1;
    insert into dekrety (ID_APTEKI,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-N-'||0||'-','W',:netto,'',:lp);
    insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:idapt,gen_id(SQ_DEKRETY,1),:idd,'VAT-SP-SP-'||:kod ||'-V-'||0||'-','W',:vat  ,'',:lp);

    END
  end


  for select id_dokumenty from DOKUMENTY where id_apteki = :idapt and id_dokumenty BETWEEN :idod and :iddo into idd do
    EXECUTE PROCEDURE DEKRETACJA (:idapt,:idd) RETURNING_VALUES :lp;
END^


ALTER TRIGGER UPD_SPRZEDAZ ACTIVE
BEFORE UPDATE POSITION 0
AS
     declare variable w Numeric(15,2);
     declare variable idsp Integer;
     declare variable sv numeric(9,2);
     declare variable dv date;
     declare variable poz Integer;
     declare variable par char(1);
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

if (rdb$get_context('USER_SESSION','PHARMONIA')=1) THEN EXIT;  -- m.in. zerowanie ilosc sprzedazy dla bufora i recptury w pharmonii


if (new.tryb='R' and abs(new.wartosc-old.wartosc)>0.005) then EXCEPTION BLAD ' Wartoœæ recepty ulegnie zmianie,
 nie mo¿na wykonaæ operacji w trybie niefiskalnym.
 Wycofaj zmiany Ctrl-Del i u¿yj korekty fiskalnej';

if (old.DATA<>new.DATA or old.ID_TRANZAKCJE<>new.ID_TRANZAKCJE or old.ID_APTEKI<>new.ID_APTEKI) THEN
BEGIN
  if (old.data>'01.01.2000') then
    select coalesce(PARAGON,'N') from tranzakcje where id_apteki=old.id_apteki and data=old.data and id_tranzakcje=old.id_tranzakcje into par ;
  else
    par = 'N';
  if (par<>'T' and new.DATA>'01.01.2000') THEN
      select coalesce(PARAGON,'N') from tranzakcje where id_apteki=new.id_apteki and data=new.data and id_tranzakcje=new.id_tranzakcje into par ;

  if (par='T') THEN  EXCEPTION  BLAD '  Wyst¹pi³ b³¹d - powiadom serwis
  Przenoszenie sprzeda¿y zafiskalizowanej
  jest zablokowane';
END


  select count(ID_SPRZEDAZ) from zmiany where id_apteki=old.id_apteki and POPRZEDNI=old.ID_SPRZEDAZ into :idsp;
  if ((:idsp>0) and ((abs(new.wartosc-old.wartosc)>0.005) or (old.SZTUK<>new.SZTUK))) then
  begin
    exception sprzedaz_korygowana;
  end

  if ((old.TRYB='P') and ((abs(new.wartosc-old.wartosc)>0.005) or (old.SZTUK<>new.SZTUK) or (old.ODPLATNOSC<>new.ODPLATNOSC) or (old.czesciowa<>new.czesciowa))) then
  begin
    new.TRYB='N';
  end

/* wariant ze zwrotem w starym VAT */
  if (new.tryb='Z') then
  begin
    select poprzedni from zmiany where id_apteki=old.id_apteki and id_sprzedaz=old.id_sprzedaz into idsp;
    select data from sprzedaz where id_apteki=old.id_apteki and id_sprzedaz=:idsp into dv;
    if (dv is null) then dv=new.data;
  end
  else
    dv=new.data;

  /*dv=new.data;*/
  if (new.id_towary<>old.id_towary) then
  begin
    select coalesce(PARAGON,'N') from tranzakcje where id_apteki=new.id_apteki and data=new.data and id_tranzakcje=new.id_tranzakcje into par ;
    if (par='N') then
    begin
      select STAWKA from stawka_VAT(new.id_apteki,new.ID_TOWARY,:dv) into sv;
      new.STAWKA_VAT=:sv;
    end
  end

  if (new.sztuk<>0 and  (new.CENA_ZAK is null or (new.CENA_ZAK<=0.01 and new.CENA_ZAK>=-0.01)) ) then
  begin
    new.CENA_ZAK=new.WART_ZAK/new.SZTUK;
    new.CENA_ZAK_BR=new.WART_ZAK*(1+0.01*new.STAWKA_VAT)/new.SZTUK;
    when any do EXCEPTION blad 'dzielenia - ID_TOWARY: '||new.id_towary||' CENA_ZAK: '||new.WART_ZAK||'÷'||new.SZTUK||'
    ';
  end
  if (old.data<>new.data and new.data>cast('12/31/1999' as date)) then
    update rzdst set data=new.data where id_apteki=new.id_apteki and id_sprzedaz=new.id_sprzedaz;

  if (new.id_recepta is not null and (old.id_recepta is null or old.id_recepta<>new.id_recepta)) then
  begin
    select max(poz_rec) from sprzedaz where id_apteki=new.id_apteki and id_recepta=new.id_recepta into poz;
    if (poz is null) then poz=0;
    poz=poz+1;
    new.poz_rec=poz;
  end

  if (new.poz_rec is not null and (new.poz_rec<>old.poz_rec or old.poz_rec is null)) then
  begin
    poz=null;
    select max(id_odplatnosc) from sprzedaz where id_apteki=new.id_apteki and id_recepta=new.id_recepta and poz_rec=new.poz_rec into poz;
    if (poz is not null and poz<>new.id_odplatnosc) then
      exception POZYCJA_RECEPTY;
    UPDATE ETAKSACJE e set e.STATUS = 'K' WHERE e.ID_SPRZEDAZ=new.ID_SPRZEDAZ and e.ID_APTEKI = new.ID_APTEKI and e.STATUS='N';
  end
  
end^

ALTER PROCEDURE CBT_KAS_EAN AS
declare variable dt timestamp;
declare variable ic integer;

declare variable iap apteka;
declare variable idt integer;
declare variable idc integer;
declare variable jd integer;

declare variable od date;
declare variable dd date;

declare variable op varchar(50);
declare variable ot varchar(50);

DECLARE rgd INTEGER;
DECLARE rgi INTEGER;

DECLARE rad INTEGER;
DECLARE rai INTEGER;

begin
 RDB$SET_CONTEXT('USER_SESSION','PROCEDURE',1);
 RDB$SET_CONTEXT('USER_SESSION','BAZYL',1);
  
  for select a.id_cbt,b.id_cbt from cbt_klas a join cbt_klas b on b.id_klasyfikacje=6 and b.wartosc=a.wartosc and b.id_cbt<1000000
    where a.id_cbt>500000 and a.id_klasyfikacje=6 and a.id_cbt>b.id_cbt order by a.id_cbt desc, iif(b.id_cbt<500000,b.id_cbt,1) desc into ic,idt do
   begin
      if (not exists (select * from cbt where id_cbt=:ic and nazwa like '%zmiany na % w aptekach')) then 
      begin
       insert into CBT_KOR (ID_APTEKI,ID_STARY,ID_NOWY,NAZWA,CENTRALNA,BLOZ)
        select :iap,:ic,:idt,NAZWA,CENTRALNA,(select min(wartosc) from CBT_KLAS where id_cbt=:ic and id_klasyfikacje=3) from cbt where id_cbt=:ic;
             
       update cbt set ZAMAWIAJ=(select ZAMAWIAJ from cbt where id_cbt=:ic) where coalesce(ZAMAWIAJ,'N')='N' and id_cbt=:idt and :iap=99;
       update cbt set ID_SYNWL=(select ID_SYNWL from cbt where id_cbt=:ic) where ID_SYNWL is null and id_cbt=:idt;
       update cbt set PROMOWANY=(select PROMOWANY from cbt where id_cbt=:ic) where PROMOWANY is null and id_cbt=:idt;
       update cbt set PROM_WG=(select PROM_WG from cbt where id_cbt=:ic) where PROM_WG is null and id_cbt=:idt;
       update cbt set CENTRALNA=(select CENTRALNA from cbt where id_cbt=:ic) where coalesce(CENTRALNA,'N')='N' and id_cbt=:idt and :iap=99;      
      end
      
      INSERT INTO CBT_KLAS (ID_CBT, ID_KLASYFIKACJE, WARTOSC, IFUPDDATE)
       select :idt,3,wartosc,cast('today' as date)+30 from cbt_klas k where id_cbt=:ic and id_klasyfikacje=3 
       and not exists(select * from CBT_KLAS s where id_cbt=:idt and id_klasyfikacje=3);
      INSERT INTO CBT_KLAS (ID_CBT, ID_KLASYFIKACJE, WARTOSC, IFUPDDATE, IFINSUSER, IFINSDATE)
       select :idt,18,wartosc,cast('today' as date)+30,IFINSUSER,IFINSDATE from cbt_klas k where id_cbt=:ic and id_klasyfikacje=18 
       and not exists(select * from CBT_KLAS s where id_cbt=:idt and id_klasyfikacje=18 and k.wartosc=s.wartosc);
      INSERT INTO CBT_KLAS (ID_CBT, ID_KLASYFIKACJE, WARTOSC, IFUPDDATE, IFINSUSER, IFINSDATE)
       select :idt,-1,wartosc,cast('today' as date)+30,IFINSUSER,IFINSDATE from cbt_klas k where id_cbt=:ic and id_klasyfikacje=-1
       and not exists(select * from CBT_KLAS s where id_cbt=:idt and id_klasyfikacje=-1 and k.wartosc=s.wartosc);

      BEGIN 
      update CBT_C_CENTR c set ID_CBT=:idt where id_cbt=:ic;
      /*
       and not exists(select * from CBT_C_CENTR where ('today' between OBOWIAZUJE_OD and OBOWIAZUJE_DO or OBOWIAZUJE_OD > 'today' or OBOWIAZUJE_OD=c.OBOWIAZUJE_OD) and id_cbt=:idt and ID_CENY=c.ID_CENY and ID_KL_AP=c.ID_KL_AP);  
       */
      WHEN ANY DO 
       insert into CBT_KOR (ID_APTEKI,ID_STARY,ID_NOWY,NAZWA,IFUPDDATE) VALUES (:iap,:ic,:idt,'Nieprzeniesiona centralna cena - wyst¹pi³ b³¹d (cena mog³a ju¿ istnieæ)',cast('now' as date)+0.0000001);
      END
     
      BEGIN
      update ZAMPZA set id_cbt=:idt where id_cbt=:ic ; 
      WHEN ANY DO 
       insert into CBT_KOR (ID_APTEKI,ID_STARY,ID_NOWY,NAZWA,IFUPDDATE) VALUES (:iap,:ic,:idt,'Zosta³o stare id w ZAMPZA',cast('now' as date)+0.0000002);
      END
      
      update zampza z set z.id_cbt=:idt where z.id_cbt=:ic
       and not exists (select * from zampza where id_zampak=z.id_zampak and id_cbt=:idt);
      update koszyki set id_towary=:idt where id_towary=:ic;
      update koszyk_towary set id_towary=:idt where id_towary=:ic;
      update towary set id_cbt=:idt where id_cbt=:ic and id_apteki=:iap;     
      if (:iap=99 and exists(select * from towary t left join ogolne o on t.id_apteki=o.id_apteki where t.id_cbt=:ic and o.AUTO_ZAM='T')) then -- nie kasujemy w ph do czasu zmiany spasowan w aptekach
       update cbt set nazwa='ZZ '||left(trim(nazwa),167)||' zmiany na '||:idt||' w aptekach',nm_short='ZZ '||left(trim(nm_short),37) , ifupddate=ifupddate+0.0000001
         where id_cbt=:ic and nazwa not like '%zmiany na % w aptekach' ;
       else       
       delete from cbt where id_cbt=:ic;          
   end
   
  for select ifupddate,id_cbt,id_klasyfikacje from cbt_klas a where a.id_klasyfikacje in (2,3,6,12,13,14,11,23,-12,-10,-11)
     and id_apteki in(0,1,99,:iap) and a.ifupddate>(select max(IFUPDDATE) from SYNCLOGIN WHERE ID_SYNC=10)-1 into dt,ic,jd do
    delete from cbt_klas where id_cbt=:ic and id_klasyfikacje=:jd and ifupddate<:dt;  

  for select id_towary,id_cbt,REGL_DNI,REGL_ILE from towary where id_cbt is not null and id_apteki=:iap into :idt,:idc,:rad,:rai do
  begin
    for select c.id_listy,c.obowiazuje_od,c.obowiazuje_do from cbt_listy c
     LEFT JOIN TOW_LISTY t on t.ID_APTEKI=:iap and t.ID_TOWARY=:idt and t.ID_LISTY=c.ID_LISTY and t.OBOWIAZUJE_OD=c.OBOWIAZUJE_OD
     where c.id_cbt=:idc and c.id_listy in (1,2,6,23,24) and t.OBOWIAZUJE_DO is DISTINCT FROM c.OBOWIAZUJE_DO
    into :jd,:od,:dd do
      update or insert into tow_LISTY (ID_APTEKI,id_towary,id_listy,obowiazuje_od,obowiazuje_do) values (:iap,:idt,:jd,:od,:dd);

    select s.OPIS from cbt_klas c left outer join klas_sl s on c.id_klasyfikacje=s.id_klasyfikacje and c.wartosc = s.wartosc
      where c.id_cbt=:idc  and c.id_klasyfikacje=14 into op;
    select min(wartosc) from tw_klas where id_apteki=:iap and id_towary=:idt and id_klasyfikacje=14 into ot;
    if (ot<>op) then
    begin
      delete from tw_klas where id_apteki=:iap and id_towary=:idt and id_klasyfikacje=14;
      update or insert into tw_klas (id_apteki,id_towary,id_klasyfikacje,wartosc) values (:iap,:idt,14,substring(:op from 1 for 40));      
    end
    
    select REGL_DNI,REGL_ILE from cbt where id_cbt=:idc into :rgd,:rgi;
    if (rgd is DISTINCT FROM rad or rgi is DISTINCT FROM rai) THEN
    update towary set REGL_DNI=:rgd,REGL_ILE=:rgi where id_apteki=:iap and id_towary=:idt;      
  end
  
  delete from cbt_listy where obowiazuje_do<obowiazuje_od;
  delete from tow_listy where obowiazuje_do<obowiazuje_od;

 RDB$SET_CONTEXT('USER_SESSION','PROCEDURE',0);
 RDB$SET_CONTEXT('USER_SESSION','BAZYL',0);
end
^

ALTER TRIGGER OPAKOWANIA_BU ACTIVE
BEFORE UPDATE POSITION 0
AS
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

  if (new.ID_SPRZEDAZ is null and old.ID_SPRZEDAZ is not null ) THEN
  BEGIN
    if (new.ID_ZDST is null) THEN
      new.STATUS = null;
    ELSE
      new.STATUS = 'D';
  END
  ELSE
  BEGIN
   if (new.STATUS = 'D' and old.STATUS is not NULL) THEN
     new.STATUS = old.STATUS;
  END   
    if (new.STATUS is DISTINCT from old.STATUS AND new.ST_WYSL <> -1 AND  FLOOR(old.ST_WYSL/1000) <> 601 ) THEN
    new.ST_WYSL = -2;
  if (new.STATUS = 'Z' and old.STATUS = 'S') THEN
    if (old.ST_WYSL < 0) THEN
      new.STATUS = 'K'; 
    ELSE
      new.ST_WYSL = -2;  
  if (old.ID_ZDST is not null and new.ID_ZDST is not NULL) THEN
    new.ID_ZDST = old.ID_ZDST;
  if (CHARACTER_LENGTH(new.ALERTY)<5) THEN
    new.ALERTY = null;       
  if (old.ALERTY is not null) THEN
    if (new.ALERTY is not null and old.ALERTY not CONTAINING new.ALERTY) THEN
      new.ALERTY =  left(new.ALERTY || ',' || old.ALERTY,512);
    ELSE
      new.ALERTY = old.ALERTY;  
END
^


ALTER PROCEDURE NA_FB3 (
    I Integer )
RETURNS (
    USR Varchar(32) )
AS
declare ap apteka;
/*zalada uzytkownikow i dodaje funkcje po przejsciu z fb2 na fb3
zaklada rowniez wszystkich uzytkownikow dla fb2 (np jesli nie ma security)
aby zalozyc tylko funcje select*from na_fb3(0) 
na f3 do dodania tw_full_info_galen jesli nie bylo wgrane w wersji 2.5*/
begin
if (not exists(select*from rdb$functions where rdb$function_name='SUBSTR'))
 then execute statement 'DECLARE EXTERNAL FUNCTION SUBSTR
   CSTRING(255) NULL, SMALLINT, SMALLINT
   RETURNS CSTRING(255) FREE_IT
   ENTRY_POINT ''IB_UDF_substr'' MODULE_NAME ''ib_udf''';
   
if (i<>0) then 
 update users set aktywny='N' where grupa=0 and aktywny='T' and id_apteki=:ap and lower(nazwa) in /*dla dialect3 moga byc zakladani z " np "AS" (musi byc duzymi)*/ 
 ('add','admin','all','alter','and','any','as','at','avg','begin','blob','both','by','case','cast','char','check','close','count','cross','date','day'
 ,'dec','drop','else','end','fetch','float','for','from','full','grant','group','hour','in','index','inner','int','into','is','join','left','like'
 ,'long','lower','max','merge','min','month','nchar','no','not','null','of','on','only','open','or','order','outer','plan','real','right','rows','set'
 ,'some','start','sum','table','then','time','to','trim','union','upper','user','using','value','view','when','where','while','with','year');

if ((SELECT rdb$get_context('SYSTEM', 'ENGINE_VERSION') from rdb$database)>'3') 
 then 
 begin
  /*
  if ((select count(*)from rdb$functions where rdb$function_name in ('DZIEN','CYFRY'))<>2) 
  then --aktualizowac liczbe funkcji
  podmiana dzien */
  begin
 execute statement 'create or alter FUNCTION dzien (dt timestamp default current_timestamp) RETURNS DATE
 as
 BEGIN
  RETURN cast(left(dt,11) as date);
 END';
 execute statement 'create or alter FUNCTION CYFRY (ch VARCHAR(100)) RETURNS integer
 as
 BEGIN
  RETURN ch; 
  WHEN ANY DO RETURN null;
 END';
 execute statement 'create or ALTER FUNCTION TDzien (DT TIMESTAMP DEFAULT current_timestamp) RETURNS CHAR(10)
 AS
 BEGIN /*tekstowo w analizach i w komunikatach za tylko_dzien*/
  RETURN lpad(EXTRACT(day from dt),2,0)||''-''||lpad(EXTRACT(month from dt),2,0)||''-''||EXTRACT(year from dt);
 END';
 execute statement 'create or alter FUNCTION substr (DANE varchar(255),a smallint,b smallint = 255) RETURNS varchar(255)
 AS
 BEGIN
  if (a>b) then 
  return '''';
  else
  return substring(dane from a for b-a+1);
 END';
  end
 if (i<>0) then 
 for 
  execute statement /*przez statement bo na fb2 nie ma sec$users, nazwa nie moze zaczynac sie od cyfry*/
  ('select nazwa from users where grupa=0 and aktywny=''T'' and id_apteki='||ap||' and nazwa similar to ''[[:ALPHA:]][[:ALNUM:]]*''
  and not exists (SELECT * FROM SEC$USERS where SEC$USER_NAME=upper(nazwa))') into :usr do 
  begin 
  if (usr='oferty') then
  execute statement 'create user '||usr||' password ''1''';
  else
  execute statement 'create user '||usr||' password '''||usr||'''';
  suspend;
  end
 end 
 else
 if (i<>0) then
 for 
  select nazwa from users where grupa=0 and aktywny='T' and id_apteki=:ap and nazwa similar to '[[:ALPHA:]][[:ALNUM:]]*' into :usr do 
  begin 
  if (usr='oferty') then
  execute statement 'create user '||usr||' password ''1''';
  else
  execute statement 'create user '||usr||' password '''||usr||'''';
  suspend;
  end
   
end
^

ALTER PROCEDURE GPL_REZERWACJA (
    IDG VARCHAR(40),
    PAC VARCHAR(50),
    TEL VARCHAR(20),
    DTW TIMESTAMP,
    POZ VARCHAR(2048) )
RETURNS (
    IDR INTEGER,
    STA INTEGER,
    BLP VARCHAR(1024) )
AS
DECLARE zam VARCHAR(512);
DECLARE pz VARCHAR(100);
DECLARE p INTEGER;
DECLARE idz DOUBLE PRECISION;
DECLARE ile DOUBLE PRECISION;
DECLARE cen DOUBLE PRECISION;
DECLARE stn DOUBLE PRECISION;
DECLARE cna DOUBLE PRECISION;
DECLARE ia APTEKA;
DECLARE st INTEGER;
DECLARE ir INTEGER;
DECLARE it INTEGER;
DECLARE si INTEGER;
DECLARE ww char(2);
BEGIN
 UPDATE OR INSERT INTO GPL_ZAM (IDG, PAC, TEL, DTW, POZ, IDW, STW) VALUES (:idg,:pac,:tel,:dtw,:poz,GEN_ID(SQ_GPL,1),-1) RETURNING IDW INTO idr;
 sta = 0;
 blp = '';
 FOR SELECT id from ST_EXPLODE_s(:poz,'|') INTO zam do
 BEGIN
   p = 0;
   st = 0;
   FOR SELECT id from ST_EXPLODE_s(:zam,';') INTO pz do
   BEGIN
     if (p=0) THEN idz = pz;
     if (p=1) THEN ile = pz;
     if (p=2) THEN cen = pz;
     p = p + 1;
   END
   SELECT z.STAN-IIF(coalesce(blokada,'N')='N',0, coalesce(z.ile_blokada,z.stan))-COALESCE((SELECT sum(r.ILOSC) FROM REZERWACJA r WHERE r.ID_ZDST = z.ID_ZDST and r.ID_APTEKI = z.ID_APTEKI ),0),c.CENA_BR,z.ID_TOWARY,COALESCE(t.WWW_WIDOCZNOSC,'ZZ')
   FROM ZDST z LEFT JOIN AKT_CENA_SP(:ia,z.id_towary,3,'today',z.id_zdst,'') c on 0=0 LEFT JOIN TOWARY t on z.ID_TOWARY=t.ID_TOWARY and z.ID_APTEKI = t.ID_APTEKI
   WHERE z.ID_ZDST=:idz and z.ID_APTEKI = :ia INTO stn,cna,it,ww;

   if (stn < ile) THEN
     st = 99;
   if (ww = 'N') THEN
     st = 98;  
   if (cna > cen) THEN
     st = 105;  
   if (st = 0) THEN
   BEGIN
     blp = blp || idz || ';' || '0' || '|';
     insert INTO recepta (ID_APTEKI,ID_RECEPTA,ATRYBUTY,DATA_WYST,TRYB,NR_W_DNIU,NUMER,DATA_PRZYJ) values
           (:ia,gen_id(SQ_RECEPTA,1),(SELECT FIRST 1 s.ATRYBUTY FROM SZABL_REC s WHERE s.ID_APTEKI = :ia and s.DOMYSLNY = 'T'),'today',1,-1,'9','09.01.1900')
           RETURNING ID_RECEPTA into ir;
     insert into bufor_recept (ID_APTEKI,ID_RECEPTA,KLIENT,UWAGI,DATA,STATUS,P_OPERATOR,P_KASA,ID_GPL) VALUES  (:ia,:ir,:pac,:tel,'today','N',1,0,:idr);      

     insert into SPRZEDAZ (ID_APTEKI,ID_SPRZEDAZ,DATA,ID_TRANZAKCJE,POZYCJA,SZTUK,JEDNOSTKA,ID_RECEPTA,WARTOSC,ODPLATNOSC,TAKSA,DOPLATA,CENA,ID_ODPLATNOSC,TRYB,ID_TOWARY,STAWKA_VAT,KWOTA_UPUSTU,WART_ZAK,CENA_ZAK,CENA_ZAK_BR,POZ_REC) values
      (:ia,gen_id(SQ_SPRZEDAZ,1),'09.01.1900',1,COALESCE((SELECT max(POZYCJA) from SPRZEDAZ s WHERE s.ID_APTEKI = :ia and s.DATA = '09.01.1900' and s.ID_TRANZAKCJE =1 ),0)+1,:ile,1,:ir,:ile * :cen,:ile * :cen,0,0,null,0,'S',:it,
      (select stawka from stawka_vat(:ia,:it,'today')),0,null,null,null,1) RETURNING id_sprzedaz into si;
     insert into rzdst(ID_APTEKI,ID_SPRZEDAZ,ID_ZDST,POZYCJA,SZTUK_JP,ID_TOWARY,DATA,CENA) VALUES (:ia,:si,:idz,1,:ile,:it,'today',:cen);
     UPDATE ZDST z set z.STAN = z.STAN - :ile WHERE z.id_zdst = :idz and z.ID_APTEKI = :ia;
 
   END
   ELSE
   BEGIN
     sta = st;
     blp = blp || idz || ';' || st || '|';
   END
 END  
 SUSPEND;
END^

create or ALTER PROCEDURE TRIM_POLE (IPARAM Varchar(1000))
RETURNS (CYFRY Varchar(1000))
AS
declare i int;
DECLARE mi int;
declare mx int;
begin
/* trimuje spacje, entery i inne dzidostwo, tabulatory w srodku zamienia na ' ' */
  i = 1;  
  while (i <= char_length(:iparam)) do
  begin
   cyfry = null;  
   if (ascii_val(substring(:iparam from i for 1)) between 33 and 255) then
    cyfry = (substring(:iparam from i for 1));     
   if(cyfry is not null and mi is null) then mi=i;  
   if(cyfry is not null ) then mx=i;  
   i = :i + 1;
  end
 cyfry=substring(IPARAM from mi for mx-mi+1); 
 cyfry=replace(cyfry,ascii_char(9),' ');
 suspend;  
end^

create or ALTER TRIGGER INS_UPD_SL_LEKARZ for SL_LEKARZ ACTIVE
BEFORE INSERT OR UPDATE POSITION 1
AS
declare variable it integer;
begin
   if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
     
   if (new.opis is distinct from old.opis) then new.opis=(select cyfry from trim_pole(new.opis));  
   
end^

CREATE OR ALTER TRIGGER RZDST_VAT FOR RZDST
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
DECLARE ks CHAR(1);
DECLARE k1 CHAR(1);
BEGIN
 if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  if ((select s.ID_TOWARY from SPRZEDAZ s where s.ID_APTEKI=new.ID_APTEKI and s.ID_SPRZEDAZ=new.ID_SPRZEDAZ)=0) then exit;
  SELECT v.KOD_STAWKI FROM STAWKA_VAT(new.id_apteki,new.id_towary,new.data) v   into ks;
  for SELECT v.KOD_STAWKI FROM RZDST r LEFT JOIN STAWKA_VAT(r.id_apteki,r.id_towary,r.data) v on 0=0
  WHERE r.ID_APTEKI=new.ID_APTEKI and r.ID_SPRZEDAZ = new.ID_SPRZEDAZ   into k1 do
    if (ks<>k1) THEN
      EXCEPTION BLAD 'Ró¿ne stawki VAT';
END^

ALTER PROCEDURE ODPL_TW (
    IAP INTEGER,
    IDT INTEGER,
    DTS TIMESTAMP,
    ATR CHAR(9) )
RETURNS (
    IDO INTEGER,
    ARZ CHAR(9) )

AS
DECLARE il INTEGER;
DECLARE k1 INTEGER;
DECLARE k2 INTEGER;
begin
  ido=0;
  il = 0;
  if (RIGHT(atr,2) = 'S ' and (SELECT COUNT(*) from TOW_LISTY l WHERE l.id_apteki=:iap and l.id_towary =:idt and :dts between l.obowiazuje_od and l.obowiazuje_do and l.ID_LISTY=27)>0) THEN
  BEGIN
    atr = LEFT(atr,7) || 'P '; 
    il = 1;
  END
  if (RIGHT(atr,2) = 'C ' and (SELECT COUNT(*) from TOW_LISTY l WHERE l.id_apteki=:iap and l.id_towary =:idt and :dts between l.obowiazuje_od and l.obowiazuje_do and l.ID_LISTY=28)>0) THEN
  BEGIN
    atr = LEFT(atr,7) || 'P '; 
    il = 2;
  END
  if (RIGHT(atr,2) = 'D ' and (SELECT COUNT(*) from TOW_LISTY l WHERE l.id_apteki=:iap and l.id_towary =:idt and :dts between l.obowiazuje_od and l.obowiazuje_do and l.ID_LISTY=29)>0) THEN
  BEGIN
    atr = LEFT(atr,7) || 'P '; 
    il = 3;
  END
  select FIRST 1 ID_ODPLATN,ATRYBUTY,KOLEJNOSC,IIF(o.ID_ODPLATN BETWEEN 1 and 5,10 - o.ID_ODPLATN,10) 
    from tow_listy l
    left join  LISTY_ODPL o  on o.ID_LISTY = l.ID_LISTY and  :dts between o.obowiazuje_od and o.obowiazuje_do and cast(:atr as char(9)) like o.ATRYBUTY
    where l.id_apteki=:iap and l.id_towary =:idt and :dts between l.obowiazuje_od and l.obowiazuje_do  and o.ID_LISTY is not null
    order by 3,4
    into ido,arz,k1,k2;
  
  if (il = 1) THEN
  BEGIN
    arz = SUBSTRING(arz from 1 for 7) || 'S_';
  END
  if (il = 2) THEN
  BEGIN
    arz = SUBSTRING(arz from 1 for 7) || 'C_';
  END
  if (il = 3) THEN
  BEGIN
    arz = SUBSTRING(arz from 1 for 7) || 'D_';
  END
  suspend;
end^

ALTER PROCEDURE RECRYCZ (
    IAP Integer,
    ID_SPRZ Integer,
    ATR Varchar(10) )
RETURNS (
    OPRYCZ Integer,
    DATA Timestamp,
    TAKSA Double precision,
    ZL Double precision,
    IOD Integer,
    MAXR Integer )
AS
declare pr double precision;
declare lm double precision;
declare wg double precision;
declare sp double precision;
declare tl varchar(2);
begin
  select r.PROSZKOW,l.limit,l.typ_limitu,100*TL,coalesce(r.zaliczka,0),r.dt_przyj,maxr
    from receptura r left join post_zl l on r.id_post_zl=l.id_post_zl
    left join akt_tl(r.id_post_zl,r.dt_przyj, r.ceny_brutto) on 0=0
      where r.id_apteki=:iap and r.id_sprzedaz=:id_sprz
    into :pr,:lm,:tl,:taksa,:zl,:data, maxr;
    select ido from odpl_tw(:iap,0,:data,:atr) into iod;
    OpRycz  =1 ;
    if (tl='W') then
    begin
      select sum(sztuk_rp) ,sum(case when s.WARTOSC is null then 0 else r.SZTUK_JP * cast(s.WARTOSC as numeric(3,2))/95 end)
        from rzdst r
        LEFT JOIN TW_KLAS s on s.ID_APTEKI=r.ID_APTEKI and s.ID_TOWARY=r.ID_TOWARY and s.ID_KLASYFIKACJE=-5 and s.wartosc similar to '[[:DIGIT:]]*.?[[:DIGIT:]]*'
        where r.id_apteki=:iap and r.id_sprzedaz=:id_sprz
        and (select count(*) from tw_klas k where k.id_apteki=:iap and k.id_towary=r.id_towary and k.id_klasyfikacje=7 and k.wartosc='Opakowanie do receptury')=0
      into wg,sp;
      if (wg>0 and lm>0) then
        OpRycz = ceiling(wg/lm);
      if (sp>0) then
        OpRycz = maxvalue(ceiling(wg/lm),ceiling(sp/100));
    end
    else
      if (pr>0 and lm>0) then
        OpRycz = ceiling(pr/lm);

  suspend;
end^

ALTER PROCEDURE TANSZY_ODPOWIEDNIK(IAP INTEGER,
ID_TOW INTEGER,
DT DATE,
IDSYNZB INTEGER,
ATR CHAR(9))
 RETURNS(ID_ODP INTEGER,
OPTW DOUBLE PRECISION,
CNTW DOUBLE PRECISION,
OPOD DOUBLE PRECISION,
CNOD DOUBLE PRECISION,
ILOD DOUBLE PRECISION)
 AS
declare variable id_odpl Integer;
 declare variable nmPost varchar(100);
 declare variable idZb Integer;
 declare variable idWl Integer;
 declare variable mPr varchar(1);
 declare variable iPr Integer;
 declare variable mPt varchar(1);
 declare variable iNm Integer;
 declare variable iSs Integer;
 declare variable idCbt Integer;
begin
select ido from odpl_tw(:iap,:Id_Tow,:dt,:atr) into id_odpl;
select cena from akt_odpl_podst(:iap,:Id_Tow,:dt,:id_odpl,:atr,0,0) into optw;
select cena_br from akt_cena_sp(:iap,:Id_tow,3,:dt,0,'') into cntw;

select c.POSTAC,coalesce(c.ID_SYNZB,-15),coalesce(c.ID_SYNWL,-15),coalesce(c.PROMOWANY,'N'),coalesce(c.PROM_WG,'X'),
  coalesce(c.ID_SYNSZCZ,-15),coalesce(c.ID_INTERNM,-15),c.id_cbt
 from towary t left join cbt c on t.id_cbt=c.id_cbt
  where t.id_apteki=:iap and t.id_towary=:id_tow into nmPost,idsynzb,idWl,mPr,mpt,iss,inm,idCbt;

if (idsynzb=0) then
  idsynzb=-15;


if (idWl>0 and (select count(*) from cbt where id_synwl=:idwl and promowany='1' and prom_wg='W')>0) then
begin
  for select ID_CBT from cbt where id_synwl=:idWl  and promowany<:mpr and promowany is not null
  order by promowany into iPr do
  if (ipr > 0) then
  begin
    idzb=null;
    ilod=0;
    select min(id_towary) from towary where id_apteki=:iap and id_cbt=:ipr into idzb;
    if (idzb is not null) then
      select stan from stan_wart(:iap,:idzb,1) into ilod;
    if (ilod >0.01) then
    begin
      id_odp=idzb;
      opod=-100;
      optw=100;
      suspend;
      exit;
    end
  end
end

if (inm<>0  and (select count(*) from cbt where id_internm=:inm and promowany='1' and prom_wg='N')>0) then
begin
  for select ID_CBT from cbt where id_INTERNM=:inm  and promowany<:mpr and promowany is not null
  order by promowany into iPr do
  if (ipr > 0) then
  begin
    idzb=null;
    ilod=0;
    select min(id_towary) from towary where id_apteki=:iap and id_cbt=:ipr into idzb;
    if (idzb is not null) then
      select stan from stan_wart(:iap,:idzb,1) into ilod;
    if (ilod >0.01) then
    begin
      id_odp=idzb;
      opod=-100;
      optw=100;
      suspend;
      exit;
    end
  end
end



if (iss<>0  and (select count(*) from cbt where id_SYNSZCZ=:iss and promowany='1' and prom_wg='S')>0) then
begin
  for select ID_CBT from cbt where id_SYNSZCZ=:iss  and promowany<:mpr and promowany is not null
  order by promowany into iPr do
  if (ipr > 0) then
  begin
    idzb=null;
    ilod=0;
    select min(id_towary) from towary where id_apteki=:iap and id_cbt=:ipr into idzb;
    if (idzb is not null) then
      select stan from stan_wart(:iap,:idzb,1) into ilod;
    if (ilod >0.01) then
    begin
      id_odp=idzb;
      opod=-100;
      optw=100;
      suspend;
      exit;
    end
  end
end

if (idsynzb>0  and (select count(*) from cbt where id_SYNZB=:idsynzb and promowany='1' and prom_wg in ('Z','O'))>0) then
begin
  for select ID_CBT from cbt 
  LEFT JOIN ODPZB_OK(- ID_CBT,- :idCbt, 0 , POSTAC, :nmPost , 0) on 0=0
  where id_SYNZB=:idsynzb  and promowany<:mpr and promowany is not null 
  and  (prom_wg = 'Z' or prom_wg='O' and jestok='T')
  order by promowany into iPr do
  if (ipr > 0) then
  begin
    idzb=null;
    ilod=0;
    select min(id_towary) from towary where id_apteki=:iap and id_cbt=:ipr into idzb;
    if (idzb is not null) then
      select stan from stan_wart(:iap,:idzb,1) into ilod;
    if (ilod >0.01) then
    begin
      id_odp=idzb;
      opod=-100;
      optw=100;
      suspend;
      exit;
    end
  end
end

if (mpr<>'N') then
  exit;

if (dt>='12.06.2016') THEN
  iss = 1;
ELSE
  iss = 0;

for select ID_TOWARY from towary t
LEFT JOIN ODPZB_OK(t.ID_TOWARY ,:id_tow, :iap,  t.POSTAC, :nmPOST, :iss) on 0=0
LEFT JOIN TYP_LEKU(t.ID_APTEKI,t.ID_TOWARY,:dt) y on 0=0
where id_apteki=:iap and ID_SYNZB=:IDSYNZB and jestok='T' and (:atr NOT STARTING 'O' or y.TYP='OTC')
into :idzb do
begin
    select ido from odpl_tw(:iap,:Idzb,:dt,:atr) into id_odpl;
    select cena from akt_odpl_podst(:iap,:IdZb,:dt,:id_odpl,:atr,0,0) into opod;
    select cena_br from akt_cena_sp(:iap,:IdZb,3,:dt,0,'') into cnod;
    select stan from stan_wart(:iap,:idZb,1) into ilOd;
    id_odp=idZb;
   suspend;
end
end
^

ALTER PROCEDURE OBL_SZT_JP (
    IAP INTEGER,
    ID_SP INTEGER,
    ID_TO INTEGER,
    SZ_RP DOUBLE PRECISION )
RETURNS (
    SZ_JP DOUBLE PRECISION,
    PRZEL DOUBLE PRECISION )
AS
declare variable pr integer;
declare variable bz integer;
declare variable mn integer;
declare variable dz integer;
declare variable pj integer;
declare variable nm varchar(30);
begin
  select proszkow from receptura where id_apteki=:iap and id_sprzedaz=:id_sp into pr;
  sz_rp=sz_rp*pr;
  select first 1 mnoznik,dzielnik,pochodzi_od from jednostki where id_apteki=:iap and  id_towary=:id_to and receptura='T' into mn,dz,pj;
  bz=0;
  przel = 1;
  while (pj is not null and pj>0) do
  begin
    pr=pj;
    pj=null;
    sz_rp=sz_rp*dz/mn;
    przel = przel * dz / mn;
    select mnoznik,dzielnik,pochodzi_od,upper(nazwa) from jednostki where id_apteki=:iap and id_towary=:id_to and jednostka=:pr into :mn,:dz,:pj,:nm;
    if (bz=0 and nm<>'G'  and nm<>'KG' and nm<>'ML' and nm<>'L' and nm<>'OP.' and nm<>'OP' and nm<>'SZT') then
    begin
      bz=1;
      sz_rp=ceiling(sz_rp-0.00000001);
    end
  end
  sz_jp=sz_rp;
  SUSPEND;
  exit;
end
^

ALTER PROCEDURE WYCENA_SPRZEDAZY (
    IAP INTEGER,
    ID_SPRZ INTEGER,
    UPUST DOUBLE PRECISION )
RETURNS (
    ID_ODPL INTEGER,
    ODPLATNOSC NUMERIC(15,2),
    DOPLATA NUMERIC(15,2),
    REF2 NUMERIC(15,2),
    WARTOSC NUMERIC(15,2),
    TAKSA NUMERIC(15,2),
    UZYTY_ODPOWIEDNIK INTEGER,
    WART_ZAK DOUBLE PRECISION,
    TYP_UP CHAR(1),
    KWOTA_UP DOUBLE PRECISION,
    PROC_UP DOUBLE PRECISION,
    LIMIT_RE DOUBLE PRECISION,
    RABAT_GOTOWKA DOUBLE PRECISION,
    IDTOW INTEGER,
    SZTUK DOUBLE PRECISION )
AS
declare variable wart integer;
     declare variable atr varchar(50);
     declare variable nmJedn varchar(30);
     declare variable idRec Integer;
     declare variable Tabletek Double precision;
     declare variable data TIMESTAMP;
     declare variable cena double precision;
     declare variable limit integer;
     declare variable reszta double precision;
     declare variable ryczalt double precision;
     declare variable sztr double precision;
     declare variable sv double precision;
     declare variable Up double precision;
     declare variable typup char(1);
     declare variable maxup Double precision;
     declare variable mdopl numeric(15,2);
     declare variable modpl numeric(15,2);
     declare variable mref numeric(15,2);
     declare variable mwart numeric(15,2);
     declare variable mtaksa numeric(15,2);
     declare variable memc numeric(15,2);
     declare variable mar Double precision;
     declare variable minmar Double precision;
     declare variable minmaru Double precision;
     declare variable wart_zakbr Double precision;
     declare variable maxkwup Double precision;
     declare variable idKtr integer;
     declare variable idTr integer;
     declare variable upk Double precision;
     declare variable mtypup char(1);
     declare variable rabat_kw Double precision;
     declare variable cenaIB Double precision;
     declare variable id_odplup integer;
     declare variable idJedn integer;
     declare variable ryczrab Double precision;
     declare variable mrycz Double precision;
     declare variable marod char(1);
     declare variable sp100 char(1);
     declare variable odcenyzak integer;
     declare variable mzapl Double precision;
     declare variable opl double precision;
     declare variable idProm integer;
     declare variable bylParagon char(1);
     declare variable doli char(1);
     declare variable up100 char(1);
     declare variable TaBr char(1);
     declare variable idOplObn integer;
     declare variable limCU integer;
     declare variable idLimitu integer;
     declare variable cbtTow integer;
     declare variable TypCeny integer;
     declare variable pes varchar(11);
     declare variable opl1 double precision;
     declare variable oplWpis integer;
     declare variable idOplObn1 integer;
     declare variable r12 char(1);
     declare variable try char(1);
     declare variable marr double precision;
     declare variable max_marr double precision;
     declare variable kds varchar(100);
     declare variable wnb char(1);
     declare variable ProcWn integer;
     declare variable WNaIle integer;
     declare variable SlProcWn integer;
     declare variable SlLimit integer;
     declare variable SlLimIl integer;
     declare variable SlLimJd char(1);
     declare variable WnStare char(1);
     declare OpRycz  Double precision;
     declare variable NadLimit integer;
     declare variable JestRefundowany char(1);
     declare MaxUpCenyC  Double precision;
     declare wartBU integer;
     declare dtTr date;
     DECLARE senior int;
     declare ileTow integer;
     declare strona char(1);
     declare OdplDef integer;
     declare WnNoLimit integer;
     declare trw integer;
     DECLARE wnidz DOUBLE PRECISION;
     declare ileT1 integer;
     DECLARE wnWartosc DOUBLE PRECISION;
     DECLARE wnIlosc DOUBLE PRECISION;
     DECLARE IdProd int;
     DECLARE mn int;
     DECLARE dz int;
     Declare jest_zk int;
begin
ID_ODPL=0;
DOPLATA=0;
REF2=0;
TAKSA=0;
UZYTY_ODPOWIEDNIK=0;
LIMIT_RE=0;
IleTow = 1;
rabat_kw=0;  /*upust udzielany jako pomniejszenie gotowki*/
jest_zk = 0;
select coalesce(PODNOS_DO_LIMITU,'N'),coalesce(UPUSTY_W_100,'N'),coalesce(TAKSA_BR,'N'),coalesce(ROK2012,'N'),coalesce(MARZA_REC,0),coalesce(wnioski_bez_umowy,'N')
 from ogolne where id_apteki=:iap into doli,up100,TaBr,r12,marr,wnb;

marr = marr*0.01;

select ID_TOWARY, ID_RECEPTA, ID_TRANZAKCJE, DATA, CENA, UPUST, COALESCE(NA100,'N'),ID_PROMOCJE,cast(WARTOSC*100  as integer),coalesce(id_odplatnosc,0),TRYB,ID_ZAMIENNIK from SPRZEDAZ
  where id_apteki=:iap and ID_SPRZEDAZ=:ID_SPRZ  into idTow, idRec, idTr, data, cena, up, sp100, idProm, wart, id_odpl, try, IdProd;

dtTr = data;

if (try is not null and try<>'S') then
  select coalesce(DT,:data) from firstop(:iap,:id_sprz) into data;

select refundowany  from jest_refundowany(:iap,:idtow,:data,1) into JestRefundowany;

select first 1 COALESCE(t.paragon,'N'),COALESCE(k.typ_ceny,3),COALESCE(k.ID_KONTRAHENCI,0)
   from tranzakcje t left join klientkody d on d.kreskowy=t.numer_karty
   left join kontrahenci k on d.id_kontrahenci=k.id_kontrahenci
   where t.id_apteki=:iap and t.data=:dtTr and t.id_tranzakcje=:idTr into bylParagon,TypCeny,idKtr;

if (:cena is null) then
  memc=0;
else
  memc=cena;

pes='';

select COALESCE(id_cbt,0) from towary where id_apteki=:iap and id_towary=:idTow  into cbtTow;

if (not idRec is null) then
begin
  select atrybuty,IIF( typ_nr_pac=1 , substring(pacjent from 1 for 11),'') ,coalesce(KOD_SRODKA,' '),coalesce(na_ile,1),left(COALESCE(RECEPTA.PRZYCZ_GL,'L'),1),tryb
    from RECEPTA  where ID_APTEKi=:iap and ID_RECEPTA = :idRec into atr,pes,kds,WNaIle,strona,trw;
  if (char_length(kds)>=3) then
  BEGIN
    if (wnb = 'T' or IdProd is null) then
      select first 1 lim_ilosc,lim_cena,lim_jedn,refundacja from PROD_ZPOSP where kod_srodka=:kds and :data between data_od and data_do ORDER by data_od DESC
        into SlLimIl,SlLimit,SlLimJd,SlProcWn ;
    ELSE    
      SELECT first 1 z.lim_ilosc,z.lim_cena,z.lim_jedn,z.refundacja from PROD_HANDL h 
      left join WNIOSKI_UMOWY u on u.KOD = h.ID_UMOWY
      left join PROD_ZPOSP z on h.KOD_SR = z.KOD_SRODKA and :data BETWEEN z.DATA_OD and z.DATA_DO
      where h.ID_PROD = :IdProd  AND :data BETWEEN u.OD_DNIA and u.DO_DNIA 
      into SlLimIl,SlLimit,SlLimJd,SlProcWn ;
  END    
  if (SlLimIl=0) THEN
    SlLimIl = 100;              
  if (char_length(kds)<3 or wnb='T') then
    kds='N';
  if (sp100='T') then
    atr=substring(atr from 1 for 3) || 'X' || substring(atr from 5 for 3 )  || 'X' ;
  if (sp100='U') then
    atr=substring(atr from 1 for 3) || 'U' || substring(atr from 5 for 3 )  || 'X' ;
    
  if (SUBSTRING(atr from 4 for 2) = 'ZK') THEN
    SELECT count(*) from TOW_LISTY t where t.ID_TOWARY=:idTow and t.ID_APTEKI=:iap and t.ID_LISTY=11 and :data BETWEEN t.OBOWIAZUJE_OD and t.OBOWIAZUJE_DO
      into jest_zk;


  if (id_odpl between 2 and 5) then
  begin
    if ((select count(*) from tow_listy t
      left join listy_odpl l on t.id_listy=l.id_listy and :data between l.obowiazuje_od and l.obowiazuje_do and cast(:atr as char(9)) like l.ATRYBUTY
      where t.id_apteki=:iap and t.id_towary=:idtow and  :data between t.obowiazuje_od and t.obowiazuje_do and l.id_listy is not null
      and id_odplatn=:id_odpl)=0) 
    then
    BEGIN
      id_odpl=0;

    END  
    else
    BEGIN
      SELECT FIRST 1 l.ID_ODPLATN from tow_listy t
      left join listy_odpl l on t.id_listy=l.id_listy and :data between l.obowiazuje_od and l.obowiazuje_do and cast(:atr as char(9)) like l.ATRYBUTY
      where t.id_apteki=:iap and t.id_towary=:idtow and  :data between t.obowiazuje_od and t.obowiazuje_do and l.id_listy is not null
      and l.KOLEJNOSC=10 ORDER by l.ID_ODPLATN INTO odplDef;
      
      if (odplDef is not null and odplDef < id_odpl) THEN
        id_odpl = odplDef;
    END 
  end
  
  if (id_odpl > 2 and jest_zk > 0 and sp100<>'T') THEN
    id_odpl = 0;
  
  
  if ((r12='N' or :data<'01/01/2012') or id_odpl=0 or sp100='T' or sp100='X') then
    select ido from odpl_tw(:iap,:IdTow,:data,:atr) into :id_odpl;
  if (id_odpl=6  and (sp100 in ('N','P')) and :data<'01/01/2012' and cbtTow>0) then
  begin
    select uzyty_odpowiednik,limit_re,id_odpl,JednOdp from
      refundowany_jako_zamiennik(:cbtTow,
      coalesce(:cena,(select max(CENA) from RZDST where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ )),
      :data,:atr) into uzyty_odpowiednik,limit_re,id_odpl,OpRycz;
    if (UZYTY_ODPOWIEDNIK<>0) then JestRefundowany='T';
  end
end
else
begin
   id_odpl=0;
   select first 1 substring(pacjent from 1 for 11)
   from sprzedaz s
   left join RECEPTA r on s.id_apteki=r.id_apteki and r.id_recepta=s.id_recepta
   where s.ID_APTEKi=:iap and s.data=:dtTr and s.id_tranzakcje=:idTr and pacjent is not null and typ_nr_pac=1 into pes;
end


/*-------------------------------*/

if (atr  like 'GW_____WL') then
  WnStare = '-';
ELSE
  WnStare = '';


if (data<'01/01/2012') THEN
BEGIN
  /* wyszukiwanie jednostki ryczaltowej */
  if (Uzyty_Odpowiednik<0) then
    select nazwa from cbt_jedn where id_cbt=- :Uzyty_Odpowiednik and jednostka=-1 into nmJedn;
  else
    select nazwa from jednostki where id_apteki=:iap and id_towary=:idTow and jednostka=-1 into nmJedn;
  idJedn=null;
  if (nmJedn is not null) then
    select min(jednostka) from jednostki where id_apteki=:iap and id_towary=:idTow and nazwa=:nmJedn and jednostka>1 into idJedn;
  if (idJedn is null) then idJedn=2;
END
ELSE
  idJedn=2;

if (bylParagon in ('N','B')) then
begin
  /* sprawdzanie czy upust wynika z klasyfikacji klient/towar */
  upk=0;
  if ((r12='N' or id_odpl=0 or id_odpl=6) and (idprom is null ) ) then
    select upust, typup, minmar, marod, rycz from ktory_upust(:iap,:idKtr,:idTow,:data,:idTr, :id_odpl,:pes) into :upk,:mtypup,:minmaru, :marod, :ryczrab;
  else
    upk=0;

  if ((r12='N' or id_odpl=0 or id_odpl=6) ) then
  begin
    if (cbtTow > 0 ) then
      select min(max_rabat) from cbt_c_centr where id_cbt=:cbtTow and id_ceny=3 and :data between obowiazuje_od and obowiazuje_do into MaxUpCenyC;
  end

  minmar=null;

  if (marod='B') then
    odcenyzak=2;
  else
    odcenyzak=1;

  if (cena>0) then
    select cast(sum(:cena*SZTUK_JP*100) as integer),sum(SZTUK_JP*100*c.CENA_BR_JP)
    from RZDST
    left outer join ceny_dostawy c on rzdst.id_apteki=c.id_apteki and rzdst.id_zdst=c.id_zdst and c.id_ceny=:odcenyzak
    where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ  into :wart,:wart_zakbr;
  else
    select cast(sum(CENA*SZTUK_JP*100) as integer),sum(SZTUK_JP*100*c.CENA_BR_JP)
    from RZDST left outer join ceny_dostawy c on rzdst.id_apteki=c.id_apteki and rzdst.id_zdst=c.id_zdst and c.id_ceny=:odcenyzak
    where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ
    into :wart,:wart_zakbr;

  if (marod='D') then
  begin
    select sum(r.SZTUK_JP*100*c.CENA_BR) from rzdst r left outer join akt_cena(r.id_apteki,r.id_towary,2,r.DATA) c on 1=1
    where r.id_apteki=:iap and r.id_sprzedaz=:ID_SPRZ into :wart_zakbr;
  end

  /**********************************************/

  id_odplup=:id_odpl;
  if (id_odpl=6) then
  begin
    select ido from odpl_tw(:iap,:IdTow,:data,'O________') into :id_odplup;
    if (:id_odplup is null) then
      id_odplup=id_odpl;
  end

  select TYP_UPUSTU, COALESCE(MAX_UPUST,0), COALESCE(MIN_MARZA,0), ryczalt from odplatn where ID_ODPLATN=:id_odplup into :typup, :maxup, :minmar, :mrycz;

  if (:minmaru is not null) then minmar=minmaru;

  if (idprom is not null and idProm>0) then
  begin
    maxup=100;
    minmar=-10000000;
    minmaru=-10000000;
  end

  if ((:upust>:maxup) and (:mtypup is null)) then
    up=:maxup;
  else
    up=:upust;
  if (up is null) then up=0;

  if (:mtypup is not null ) then
  begin
    typup=:mtypup;
    up=:upk;
  end
  else
    ryczrab=mrycz;

  if (MaxUpCenyC is not null) then
    up=minValue(up,MaxUpCenyC);

  if (id_odpl=6) then
    typup='C';

  if (up100='T') then
    up = 100 * ( 1 - (1 / (1+up*0.01)));

  /* ograniczenie minimalna marza */
  if (typup='C'   and (atr is null or atr not like 'R%')) then
  begin
    if (wart<>0 and minmar<100) then
    begin
      mar=(:wart-:wart_zakbr)/:wart*100;
      minmar=wart_zakbr/(1-0.01*minmar);
      if (wart*(100-up)*0.01<minmar) then up=100*(wart-minmar)/wart;
      if (up<0) then
        up=0;
    end
    else
      mar=0;
  end

  if ((up<>0) or (ryczrab is not null)) then
    TYP_UP=typup;
  else
    TYP_UP='N';  /*nie ma upustu*/

  PROC_UP=up;
  KWOTA_UP=0;

  if (TYP_UP in ('O','D','M')) then
    up=0;

  cena=memc;

  if (memc<0 ) then
    cena=0;
    
    
    
  if (atr is not null and atr like 'GW%') then
  begin

   /* sprawdzenie czy wniosek jest przypisany do danego kodu */
   if (wnb='N') then
   BEGIN
     mn=1;
     dz=1;
     if ( SlLimJd = 'T' and (select upper(nazwa) from jednostki where id_apteki=:iap and id_towary=:idTow and jednostka=1) not like 'SZT%') then
      select mnoznik,dzielnik from jednostki where id_apteki=:iap and id_towary=:idTow and jednostka=2 into mn,dz;
    RYCZALT = null;  
    SELECT round(a.CENA * :mn/:dz,2) 
       from  PROD_HANDL h 
       left join WNIOSKI_UMOWY u on h.ID_UMOWY = u.KOD
       left join PAKIET_ZAOP a on a.ID_PROD = h.ID_PROD and a.ID_UMOWY = h.ID_UMOWY
       left join PLANY_MIES m on a.ID_PAKIET=m.ID_PAKIET and a.ID_UMOWY = m.ID_UMOWY and m.ID_KOM = u.id_kom  and m.MIESIAC = EXTRACT(MONTH from  :data)
     where h.ID_PROD = :IdProd and :data BETWEEN u.OD_DNIA and u.DO_DNIA and m.MIESIAC is not NULL
       into RYCZALT;
     if (RYCZALT is NULL) THEN
       id_odpl=6;  
     ELSE
        UPDATE RZDST r SET cena=:RYCZALT where  r.ID_SPRZEDAZ=:id_sprz and r.ID_APTEKI=:iap and r.CENA > :RYCZALT;
   END
   ELSE
   BEGIN
   /* obnzka ceny do urzedowej  */
    for SELECT CENA_BR,ID_ZDST FROM
    (
      SELECT  
      (
        select first 1 CENA_BR  from CENY_TOWARY
           where ID_APTEKI=r.ID_APTEKI and id_towary=r.ID_TOWARY and ID_CENY=3
           and OBOWIAZUJE_OD<=r.DATA and (obowiazuje_do is null or obowiazuje_do>=r.DATA) and DECYZYJNA='U' and ( :kds = 'N' or wn_kod= :kds)
           order by OBOWIAZUJE_OD desc  
      ) CENA_BR,r.CENA
    ,r.ID_ZDST
    FROM RZDST r
    WHERE r.ID_SPRZEDAZ=:id_sprz and r.ID_APTEKI=:iap )
    where CENA>CENA_BR
    INTO RYCZALT ,wnidz do
    BEGIN
      UPDATE RZDST r SET cena=:RYCZALT where  r.ID_SPRZEDAZ=:id_sprz and r.ID_APTEKI=:iap and r.ID_ZDST=:wnidz;
    END
    END
  end  

  if (atr STARTING 'R') then
  BEGIN
   select 100*sum(SZTUK_JP*c.CENA_NT_JP),100*sum(SZTUK_JP*c.CENA_BR_JP), 
      100*sum(iif(l.LIMIT is null or l.LIMIT*j.PRZEL>=c.CENA_NT_JP,0,c.CENA_NT_JP-l.LIMIT*j.PRZEL) * r.SZTUK_JP),
      100*sum(iif(l.LIMIT is null or l.LIMIT*j.PRZEL*(1+0.01*v.STAWKA)>=c.CENA_BR_JP,0,c.CENA_BR_JP-l.LIMIT*j.PRZEL*(1+0.01*v.STAWKA)) * r.SZTUK_JP)
    from RZDST  r
    left join ceny_dostawy c on r.id_apteki=c.id_apteki and r.id_zdst=c.id_zdst and c.id_ceny=1
    left join AKT_LIMIT(r.ID_APTEKI,r.ID_TOWARY,0,:data,'-REC') l on 0=0
    LEFT join OBL_SZT_JP(r.id_apteki,r.ID_SPRZEDAZ,r.ID_TOWARY,r.SZTUK_RP) j on 0=0
    LEFT join stawka_vat(r.ID_APTEKI,r.ID_TOWARY,:data) v on 0=0
    where r.ID_APTEKI=:iap and r.ID_SPRZEDAZ=:ID_SPRZ
    into :wart_zak,wart_zakbr,limit,nadLimit;
  END
  else
  begin
  if (cena>0 or memc<0 ) then
    select cast(sum(:cena*(1-0.01*:up)*SZTUK_JP*100) as integer),cast(sum(akt_limit.LIMIT*SZTUK_JP*100) as integer),sum(SZTUK_JP*j1.MNOZNIK/j1.dzielnik),sum(SZTUK_JP),
      sum(SZTUK_JP*100*c.CENA_NT_JP),sum(OPLATA*SZTUK_JP*100),max(akt_cena_sp.id_odpl),sum(SZTUK_JP*100*c.CENA_BR_JP),
      cast(sum(maxvalue(:cena-akt_limit.LIMIT,0)*(1-0.01*:up)*SZTUK_JP*100) as integer),cast(sum(:cena*SZTUK_JP*100) as integer),
      count(DISTINCT rzdst.ID_TOWARY)
    from RZDST
    left outer join jednostki j1 on rzdst.id_apteki=j1.id_apteki and rzdst.id_towary=j1.id_towary and j1.jednostka=:idJedn
    left outer join ceny_dostawy c on rzdst.id_apteki=c.id_apteki and rzdst.id_zdst=c.id_zdst and c.id_ceny=1
    left join akt_cena_sp(rzdst.id_apteki,rzdst.ID_TOWARY,3,:data,0,:kds) on 0=0
    left join akt_limit(rzdst.id_apteki,rzdst.ID_TOWARY,3,:data,:WnStare || :kds) on 0=0
    where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ  into :wart,:limit,:tabletek,:sztuk,:wart_zak,:opl,idOplObn,wart_zakbr, nadLimit,wartBu,IleTow;
  else
  BEGIN
    select cast(sum(CENA*(1-0.01*:up)*SZTUK_JP*100) as integer),cast(sum(akt_limit.LIMIT*SZTUK_JP*100) as integer),
    sum(SZTUK_JP*j1.MNOZNIK/j1.dzielnik),sum(SZTUK_JP),max(CENA*(1-0.01*:up)),sum(SZTUK_JP*100*c.CENA_NT_JP),sum(OPLATA*SZTUK_JP*100),max(akt_cena_sp.id_odpl),sum(SZTUK_JP*100*c.CENA_BR_JP)
    ,cast(cast(sum(maxvalue(CENA-akt_limit.LIMIT,0)*(1-0.01*:up)*SZTUK_JP*1000) as integer)*0.1 as integer),cast(sum(CENA*SZTUK_JP*100) as integer),
    count(DISTINCT rzdst.ID_TOWARY || round(cena,2)),count(DISTINCT rzdst.ID_TOWARY)
    from RZDST left outer join jednostki j1 on (rzdst.id_apteki=j1.id_apteki and  rzdst.id_towary=j1.id_towary and j1.jednostka=:idJedn)
    left outer join ceny_dostawy c on rzdst.id_apteki=c.id_apteki and rzdst.id_zdst=c.id_zdst and c.id_ceny=1
    left join akt_cena_sp(rzdst.id_apteki,rzdst.ID_TOWARY,3,:data,rzdst.id_zdst,:kds) on 0=0
    left join akt_limit(rzdst.id_apteki,rzdst.ID_TOWARY,3,:data,:WnStare || :kds) on 0=0
    where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ
    into :wart,:limit,:tabletek,:sztuk,:cena,:wart_zak,:opl,idOplObn,wart_zakbr,nadLimit,wartBu,IleTow,IleT1;
    if (atr is null or atr not like  'GW%') THEN
      IleTow = IleT1;
  END  
  End

  if (wart is null) then
    wart=0;



  select szt from sp_sztuk1(:iap,:id_sprz,:idTow) into :sztr;
  
  sztr= round(sztr,5);


  /* tutaj sprawdzamy czy nie przekroczono ceny urzedowej */
  if (atr is not null and atr not like 'R%' and id_odpl<>0 and atr not STARTING 'GW') then
  begin
     limCu=null;
     if (JestRefundowany='T') then
       if (Uzyty_Odpowiednik<0) then
           select first 1 CENA_BR*100  from CBT_CENY
           where ID_CBT=-:Uzyty_odpowiednik and ID_CENY=3 and OBOWIAZUJE_OD<=:data
           order by OBOWIAZUJE_OD desc into limCu;
        else
        begin
           idLimitu = idtow;
           select first 1 CENA_BR*100,WN_REF,LIMIT  from CENY_TOWARY
           where ID_APTEKI=:iap and id_towary=:idLimitu and ID_CENY=3
           and OBOWIAZUJE_OD<=:data and (obowiazuje_do is null or obowiazuje_do>=:data) and DECYZYJNA='U' 
           order by OBOWIAZUJE_OD desc into limCu,ProcWn,LIMIT_RE;
        end

      if (id_odpl=1 or atr like 'GI%' or jest_zk > 0 and jestRefundowany='N') then
      begin
        if (r12='N' or sztr<=0 or data <= '12/31/2011') then
          limCu=0;
        else
        begin
          /*  marza dla nierefundowanego IB max 20 zl  */
          select detal from marza_degr(0.01*:wart_zakbr/:sztr,-1,:data) into cenaIB;
          if (cenaIb - 0.01*:wart_zakbr/:sztr > 20 and atr not like 'GI%')
            then cenaIb = 20 + 0.01*:wart_zakbr/:sztr;
          limCu=cenaIb*100;
          update rzdst set CENA= :limCu*0.01 where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ and id_towary=:idTow;
        end
      end

      if (atr not like  'GW%' and limCu is not null and limCu>0 and sztr>0 and (wart>limCU*sztr or (wart<limCU*sztr and  r12='T' and data>='01/01/2012'))) then
      begin
        wart=limCu*sztr;
        update rzdst set CENA= :limCu*0.01 where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ and id_towary=:idTow;
      end
  end


  if ( ((atr not like 'R%') or (atr is null)) and (sztr<>0) and (IleTow=1 or atr not like 'GW%')  ) then
  begin
    /*  zaokraglenie wartosc tak zeby dzialalo na drukarce fiskalej  */


    wart=wart/sztr;
    wart=wart*sztr;
    /* tutaj sprawdzamy czy cena nie nizsza niz limit dla wariantu podnos do limitu */
    if (doli='T' and limit>wart and id_odpl<>6 and id_odpl<>0 and  memc=0 ) then
    begin
      if (limCu is not null and limCu>0 and limCu*sztr<limit) then
      begin
        wart=limCU*sztr;
        update rzdst set CENA= :limCu*0.01 where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ and id_towary=:idTow;
      end
      else
      begin
        wart=limit;
        update rzdst set CENA= :limit*0.01/ :sztr where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ and id_towary=:idTow;
      end
    end
  end
end
else
begin
  select cast(sum(akt_limit.LIMIT*SZTUK_JP*100) as integer),
    sum(SZTUK_JP*j1.MNOZNIK/j1.dzielnik),sum(SZTUK_JP),max(CENA*(1-0.01*:up)),sum(SZTUK_JP*100*c.CENA_NT_JP),sum(OPLATA*SZTUK_JP*100),max(akt_cena_sp.id_odpl),sum(SZTUK_JP*100*c.CENA_BR_JP)
    from RZDST left outer join jednostki j1 on (rzdst.id_apteki=j1.id_apteki and  rzdst.id_towary=j1.id_towary and j1.jednostka=:idJedn)
    left outer join ceny_dostawy c on rzdst.id_apteki=c.id_apteki and rzdst.id_zdst=c.id_zdst and c.id_ceny=1
    left join akt_cena_sp(rzdst.id_apteki,rzdst.ID_TOWARY,3,:data,rzdst.id_zdst,:kds) on 0=0
    left join akt_limit(rzdst.id_apteki,rzdst.ID_TOWARY,3,:data,:WnStare || :kds) on 0=0
    where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ
    into :limit,:tabletek,:sztuk,:cena,:wart_zak,:opl,idOplObn,wart_zakbr;

  select szt from sp_sztuk(:iap,:id_sprz) into :sztr;
  sztr=round(sztr,5);
  wartBu = wart;
end


if (SlLimJd is not null ) then  /*  Kod srodka znalezione w slowniku   */
begin
  
  ProcWn=SlProcWn;
  if (atr not like 'GW_____WL') then
  begin
    SELECT COALESCE(SUM(s.WARTOSC),0),COALESCE(SUM((select sum(r.SZTUK_JP * j.MNOZ / j.DZIEL) from RZDST r left join  ILOSC_JP( r.ID_APTEKI,r.ID_TOWARY,2) j on 0=0
       where r.ID_SPRZEDAZ = s.ID_SPRZEDAZ  and r.ID_APTEKI = s.ID_APTEKI )),0)
    FROM SPRZEDAZ s WHERE s.ID_RECEPTA = :idRec and s.ID_APTEKI = :iap AND s.ID_SPRZEDAZ < :id_sprz
    into wnWartosc,wnIlosc;
        
    limit=SlLimit*WNaIle;
    WnNoLimit = 0;
    if (atr like 'GW_DN____'  or atr like 'GW_ZN____'  or atr like 'GW_ZD____') THEN
      WnNoLimit = 1;
    if (SlLimJd<>'N') then /* limit jednostkowy */
    BEGIN
      limit =   SlLimit*minvalue(coalesce(tabletek,sztuk),iif( WnNoLimit = 1 , 999999 , SlLimIl*0.01*WNaIle-wnIlosc ));
    End
    else
    BEGIN
      limit=SlLimit*WNaIle;
       if (strona='O') THEN
        limit = limit * 2;
      limit = limit  - wnWartosc * 100;  
      if (WnNoLimit = 1 ) THEN
      BEGIN
        limit = wart;
      END
    END
    if (limit < 0 ) THEN
      limit = 0;
  end
end


if (TypCeny>3) then
begin
   select first 1 cast(oplata * 100 * :sztuk as integer),opl_id_odpl from ceny_towary
    where id_apteki=:iap and id_towary=:idTow and id_ceny=:TypCeny and obowiazuje_od<=:data
    order by obowiazuje_od desc
    into opl1,idOplObn1;
  if (opl1 is not null) then
  begin
    opl=opl1;
    idOplObn=idOplObn1;
  end
end

if (atr like 'R%') then
begin
 sztr=1;
 opl = null;
end

if (opl is not null and opl>0 and opl<1) then opl=1;


WARTOSC=:wart;
ODPLATNOSC=:wart;
senior = 0;

if (not :atr is null) then
begin
  if (atr STARTING 'R') then
  begin
    select OpRycz,Data,Taksa,iod from RecRycz(:iap,:id_sprz,:atr) into OpRycz,Data,Taksa,id_odpl;
    SELECT COALESCE(r.CENY_BRUTTO,'N') FROM RECEPTURA  r WHERE r.ID_APTEKI=:iap and r.ID_SPRZEDAZ=:id_sprz INTO tabr;
    
    if (data >= '01.11.2023')  THEN
      SELECT a.TL * 100 from akt_tl(17,:data,'T') a into max_marr;
    ELSE
      max_marr = 99999999;  
      
    
    if (tabr='T') then
    begin
       wartosc = wart_zakbr + MINVALUE(wart_zakbr * marr,max_marr);
       max_marr = MAXVALUE(max_marr - wart_zakbr * marr,0);
       taksa=taksa + MINVALUE(taksa * marr,max_marr);
    end
    else
    begin
       select stawka from stawka_vat(:iap,:IdTow,:data) into :sv;
       sv=1+0.01*sv;
       
       wartosc = wart_zak * sv + MINVALUE(wart_zak * sv * marr,max_marr);
       max_marr = MAXVALUE(max_marr - wart_zak * sv * marr,0);
       taksa=taksa * sv + MINVALUE(taksa * sv * marr,max_marr);
       nadLimit = Limit * sv;
    end
    if (typ_up='C' and up>0) then
    begin
      wartosc = wartosc*(1-0.01*up);
      taksa   = taksa*(1-0.01*up);
    end
    if (OpRycz>1) then
    begin
       wartosc = FLOOR((wartosc + taksa) / OpRycz) * OpRycz;
       wartosc = wartosc - taksa;
    end
    limit=wartosc+taksa;
    wart=wartosc;
  end
  else
  if (r12='T' and  :data>='01/01/2012' and id_odpl<>6) then
  begin
    select   sum(IIF( oplata <0 , -1000 ,  IIF(sztuk*oplata <214 , cast( cast(SZTUK*100000 as integer)*maxvalue(cast(OPLATA*100 as integer),-1)*0.00001 as integer)
     , cast( cast(SZTUK*1000 as integer)*maxvalue(cast(OPLATA*100 as integer),-1)*0.001 as integer))))  from
    (
    select sum(sztuk_jp) sztuk,id_apteki,id_towary
      from RZDST  where rzdst.ID_APTEKI=:iap and rzdst.ID_SPRZEDAZ=:ID_SPRZ
      group by id_towary,id_apteki
    )
    left join akt_oplata(id_apteki,ID_TOWARY,3,:data,:id_odpl) on 0=0 into oplWpis;

    /*        PLAN (RZDST INDEX (FK_RZDST_SPRZEDAZ))*/

    if (oplWpis is null ) then oplWpis=-99;
    if (id_odpl=3) then
      select ILOSC_DDD from towary where id_apteki=:iap and id_towary=:IdTow into :opRycz;
    if (opRycz<30 or opRycz is null) then
      opRycz=30;
  end
  else
  begin
    if (uzyty_odpowiednik=0 and id_odpl=3) then
      select MNOZNIK/DZIELNIK from jednostki where id_apteki=:iap and id_towary=:IdTow and jednostka=-1 into :opRycz;
    OplWpis=-999;
  end


  if ((limit is null or limit=0) and SlLimIl is null or limit>wart) then limit=wart;


  if (oplWpis>=0) then
  begin
    DOPLATA=WART-LIMIT;
    ODPLATNOSC=OPLWPIS-DOPLATA;
  end
  else
  begin

    /*Bezplatne*/
    if (id_odpl=1) then
    begin
      ODPLATNOSC=0;
      DOPLATA=0;
    end

    /*Bezplatne do limitu*/
    if (id_odpl=2) then
    begin
      ODPLATNOSC=0;
      if (sztuk>0  and atr not like 'GW%') then
        DOPLATA=coalesce(nadLimit,0);
      else
        DOPLATA=WART-LIMIT;
    end

    /*Ryczalt%*/
    if (id_odpl=3) then
    begin
      if (atr STARTING 'R') then
      begin
        select r2*100 from ryczalt(:data) into :ryczalt;
        ODPLATNOSC=ryczalt*OpRycz;
        DOPLATA=coalesce(nadLimit,0);
      end
      else
      begin
        select r1*100 from ryczalt(:data) into :ryczalt;
        if (r12='T') then
          if (OpRycz>0) then
            Sztuk=Sztr*OpRycz/30;
          else
            Sztuk=Sztr;
        else
          if (tabletek is not null and tabletek>0 and OpRycz is not null and OpRycz>0) then
            Sztuk=Tabletek/OpRycz;

        if (r12='T') then
          reszta=0;
        else
          reszta=sztuk-floor(sztuk);

        if (LIMIT<=sztuk*ryczalt) then
           ODPLATNOSC=LIMIT;
        else
        if (reszta>0) then
        begin
          if (reszta*limit/sztuk<ryczalt) then
            ODPLATNOSC=floor(sztuk)*ryczalt+reszta*limit/sztuk;
          else
            ODPLATNOSC=(floor(sztuk)+1)*ryczalt;
        end
        else
          ODPLATNOSC=SZTUK*ryczalt;
        DOPLATA=WART-LIMIT;
      end
    end

    /*30%*/
    if (id_odpl=4) then
    begin
      if (sztuk>0 and atr not like 'GW%') then
        ODPLATNOSC=cast(0.3*LIMIT/SZTUK as integer)*sztuk;
      else
      begin
        if (procWn is null) then
          procWn=70;
        ODPLATNOSC=(0.01*(100-ProcWn))*LIMIT;
      end
      DOPLATA=WART-LIMIT;
    end

    /*50%*/
    if (id_odpl=5) then
    begin
      if (sztuk>0  and atr not like 'GW%') then
        ODPLATNOSC=cast(0.5*LIMIT/SZTUK as integer)*sztuk;
      else
        ODPLATNOSC=0.5*LIMIT;
      DOPLATA=WART-LIMIT;
    end

    /*100*/
    if (id_odpl=6) then
    begin
      ODPLATNOSC=WART+TAKSA;
    end

    /**/
    if (id_odpl=7) then
    begin
      DOPLATA=WART-LIMIT;
    end

    if (id_odpl=8) then
    begin
      select r3*100 from ryczalt(:data) into :ryczalt;
      ODPLATNOSC=SZTUK*ryczalt;
    end
  end
  
  if (atr  like 'G______S%' and id_odpl between 2 and 5) then
  BEGIN
    select COUNT(*) from TOW_LISTY t
     where t.ID_APTEKI=:iap and t.ID_TOWARY=:idTow and t.ID_LISTY=27 and :data BETWEEN t.OBOWIAZUJE_OD and t.OBOWIAZUJE_DO
    into senior;
    if (senior>0) then
    BEGIN
      ODPLATNOSC=0;
      DOPLATA=0;
    END
  END
  
  if (atr  like 'G______C%' and id_odpl between 2 and 5) then
  BEGIN
    select COUNT(*) from TOW_LISTY t
     where t.ID_APTEKI=:iap and t.ID_TOWARY=:idTow and t.ID_LISTY=28 and :data BETWEEN t.OBOWIAZUJE_OD and t.OBOWIAZUJE_DO
    into senior;
    if (senior>0) then
    BEGIN
      ODPLATNOSC=0;
      DOPLATA=0;
    END
  END
  
  if (atr  like 'G______D%' and id_odpl between 2 and 5) then
  BEGIN
    select COUNT(*) from TOW_LISTY t
     where t.ID_APTEKI=:iap and t.ID_TOWARY=:idTow and t.ID_LISTY=29 and :data BETWEEN t.OBOWIAZUJE_OD and t.OBOWIAZUJE_DO
    into senior;
    if (senior>0) then
    BEGIN
      ODPLATNOSC=0;
      DOPLATA=0;
    END
  END

end

odplatnosc=cast(odplatnosc as integer)*0.01;
taksa=cast(taksa as integer)*0.01;
doplata=cast(doplata as integer)*0.01;
ref2=cast(ref2 as integer)*0.01;
wartosc=cast(wartosc as integer)*0.01;
if (wartosc+taksa<odplatnosc+doplata) then
  doplata=wartosc+taksa-odplatnosc;
if (doplata<0) then
begin
  odplatnosc=odplatnosc+doplata;
  doplata=0;
end

modpl=odplatnosc;
mdopl=doplata;
mref=ref2;
mwart=wartosc;
mtaksa=taksa;


/*------ jesli upust to obliczenia bez upustu----------------------*/

if (:TYP_UP='C') then
begin
  up=0;

  ODPLATNOSC=0;
  DOPLATA=0;
  REF2=0;
  WARTOSC=0;
  TAKSA=0;

  wart = wartBU;

  if ( ((atr not like 'R%') or (atr is null)) and (sztr<>0) ) then
  begin
    wart=wart/sztr;
    wart=wart*sztr;
  end

  WARTOSC=:wart;
  ODPLATNOSC=:wart;

  if (not :atr is null) then
  begin
    if (atr like 'R%') then
    begin
      select OpRycz,Data,Taksa,iod from RecRycz(:iap,:id_sprz,:atr) into OpRycz,Data,Taksa,id_odpl;
      limit=0;
       if (tabr='T') then
       begin
         wartosc=wart_zakbr*marr;
         taksa=taksa*marr;
       end
       else
       begin
         select stawka from stawka_vat(:iap,:IdTow,:data) into :sv;
         sv=1+0.01*sv;
         wartosc=wart_ZAK*marr*sv;
         taksa=round(taksa*sv,2)*marr;
       end
       if (OpRycz>1) then
       begin
         wart = (wartosc + taksa) / OpRycz;
         wart = wart * OpRycz;
         wartosc = wart - taksa;
       end
       limit=wartosc+taksa;
       wart=wartosc;
    end

    if (limit is null or limit=0 or limit>wart) then limit=wart;


    if (oplWpis>=0) then
    begin
      DOPLATA=WART-LIMIT;
      ODPLATNOSC=OPLWPIS-DOPLATA;
    end
    else
    begin
      /*Bezplatne*/
      if (id_odpl=1) then
      begin
        ODPLATNOSC=0;
        DOPLATA=0;
      end

      /*Bezplatne do limitu*/
      if (id_odpl=2) then
      begin
        ODPLATNOSC=0;
        if (sztuk>0  and atr not like 'GW%') then
          DOPLATA=coalesce(nadLimit,0);
        else
          DOPLATA=WART-LIMIT;
      end

      /*Ryczalt%*/
      if (id_odpl=3) then
      begin
        if (atr like 'R%') then
        begin
          select r2*100 from ryczalt(:data) into :ryczalt;
          ODPLATNOSC=ryczalt*OpRycz;
        end
        else
        begin
          select r1*100 from ryczalt(:data) into :ryczalt;
          if (r12='T') then
            if (OpRycz>0) then
              Sztuk=Sztr*OpRycz/30;
            else
              Sztuk=Sztr;
          else
            if (tabletek is not null and tabletek>0 and OpRycz is not null and OpRycz>0) then
              Sztuk=Tabletek/OpRycz;

          if (r12='T') then
            reszta=0;
          else
            reszta=sztuk-floor(sztuk);

          if (LIMIT<=sztuk*ryczalt) then
             ODPLATNOSC=LIMIT;
          else
          if (reszta>0) then
          begin
            if (reszta*limit/sztuk<ryczalt) then
              ODPLATNOSC=floor(sztuk)*ryczalt+reszta*limit/sztuk;
            else
              ODPLATNOSC=(floor(sztuk)+1)*ryczalt;
          end
          else
            ODPLATNOSC=SZTUK*ryczalt;
          DOPLATA=WART-LIMIT;
        end
      end

      /*30%*/
      if (id_odpl=4) then
      begin
        if (sztuk>0 and atr not like 'GW%') then
          ODPLATNOSC=cast(0.3*LIMIT/SZTUK as integer)*sztuk;
        else
        begin
          if (procWn is null) then
            procWn=70;
          ODPLATNOSC=(0.01*(100-ProcWn))*LIMIT;
        end
        DOPLATA=WART-LIMIT;
      end

      /*50%*/
      if (id_odpl=5) then
      begin
        if (sztuk>0  and atr not like 'GW%') then
          ODPLATNOSC=cast(0.5*LIMIT/SZTUK as integer)*sztuk;
        else
          ODPLATNOSC=0.5*LIMIT;
        DOPLATA=WART-LIMIT;
      end

      /*100*/
      if (id_odpl=6) then
      begin
        ODPLATNOSC=WART+TAKSA;
      end

      /**/
      if (id_odpl=7) then
      begin
        DOPLATA=WART-LIMIT;
      end

      if (id_odpl=8) then
      begin
        select r3*100 from ryczalt(:data) into :ryczalt;
        ODPLATNOSC=SZTUK*ryczalt;
      end
    end
    if (senior>0) then
    BEGIN
      ODPLATNOSC=0;
      DOPLATA=0;
    END
  end

  odplatnosc=cast(odplatnosc as integer)*0.01;
  taksa=cast(taksa as integer)*0.01;
  doplata=cast(doplata as integer)*0.01;
  ref2=cast(ref2 as integer)*0.01;
  wartosc=cast(wartosc as integer)*0.01;
  if (wartosc+taksa<odplatnosc+doplata) then
    doplata=wartosc+taksa-odplatnosc;
  if (doplata<0) then
  begin
    odplatnosc=odplatnosc+doplata;
    doplata=0;
  end

  KWOTA_UP=odplatnosc+doplata-modpl-mdopl;

  odplatnosc=modpl;
  doplata=mdopl;
  ref2=mref;
  wartosc=mwart;
  taksa=mtaksa;
  

end /* dodatkowe obliczenia bez upustu */

/*#########################################################################*/

mzapl=odplatnosc+doplata;
wart_zakbr=wart_zakbr*0.01;


if (TYP_UP='O' or TYP_UP='D' or TYP_UP='M') then
begin
  maxkwup=wartosc - (wart_zakbr*(1+:minmar*0.01));
  if (maxkwup<=0) then maxkwup=0;
  KWOTA_UP = (odplatnosc+doplata) - (odplatnosc+doplata)*(1-PROC_UP*0.01);
  if (:KWOTA_UP>:maxkwup) then
  begin
    KWOTA_UP=maxkwup;
    if ((odplatnosc+doplata)<>0) then
      proc_up=KWOTA_UP / (odplatnosc+doplata) * 100;
    else
      proc_up=0;
  end
end


if (sztr=0) then sztr=1;
if (TYP_UP='O') then
begin
  KWOTA_UP=cast(KWOTA_UP*100/sztr as integer)*sztr*0.01;
  rabat_kw=KWOTA_UP;
end

if (TYP_UP='D') then
begin
  KWOTA_UP = (odplatnosc+doplata) - (odplatnosc+doplata)*(1-PROC_UP*0.01);
  KWOTA_UP=cast(KWOTA_UP*100/sztr as integer)*sztr*0.01;
  if (:KWOTA_UP>:doplata) then
  begin
    KWOTA_UP=doplata;
    if (odplatnosc+doplata<>0) then
      proc_up=((odplatnosc+doplata)-(odplatnosc)) / (odplatnosc+doplata) * 100;
    else
      proc_up=0;
  end
  WARTOSC=WARTOSC-KWOTA_UP;
  DOPLATA=DOPLATA-KWOTA_UP;
end

if (TYP_UP='M') then
begin
  KWOTA_UP = (odplatnosc+doplata) - (odplatnosc+doplata)*(1-PROC_UP*0.01);
  KWOTA_UP=cast(KWOTA_UP*100/sztr as integer)*sztr*0.01;
  if (:KWOTA_UP>:doplata) then
  begin
    rabat_kw=KWOTA_UP-doplata;
    WARTOSC=WARTOSC-doplata;
    if (odplatnosc+doplata<>0) then
      proc_up=kwota_up / (odplatnosc+doplata) * 100;
    else
      proc_up=0;
    DOPLATA=0;
  end
  else
  begin
    WARTOSC=WARTOSC-KWOTA_UP;
    DOPLATA=DOPLATA-KWOTA_UP;
  end

end

if (id_odpl=3 and ryczrab is not null and ryczrab>=0 and r12<>'T') then
begin
  kwota_up=mzapl-ryczrab*sztr;
  rabat_kw=odplatnosc-ryczrab*sztr;
  if ((odplatnosc+doplata)<>0) then
    proc_up=KWOTA_UP / (mzapl) * 100;
  else
    proc_up=100;
end

if (id_odpl<>0 and id_odpl<>6 and opl is not null and (odplatnosc+doplata)>0.001+opl*0.01 and (idOplObn is null or idOplObn=0 or idOplObn=id_odpl)  and r12<>'T') then
begin
   opl=cast(opl as integer)*0.01;
   /*  Upust = wszystkie poprzednie upusty + dodatkowo roznica */
   if (id_odpl=3 and ryczrab is not null and ryczrab>=0) then
     kwota_up=kwota_up+odplatnosc+doplata-opl-rabat_kw;
   else
     kwota_up=kwota_up+odplatnosc+doplata-opl;
   if ((odplatnosc+doplata)<>0) then
     proc_up=KWOTA_UP / (mzapl) * 100;
   else
     proc_up=100;
   if (odplatnosc>opl) then
   begin
     wartosc=wartosc-doplata;
     doplata=0;
     rabat_kw=odplatnosc-opl;
   end
   else
   begin
     wartosc=wartosc-(doplata-(opl-odplatnosc));
     doplata=opl-odplatnosc;
   end
   typ_up='O';
end

if (taksa=0 and (IleTow=1 or atr not like 'GW%') ) then
  wartosc = ROUND( wartosc/sztr ,2)*sztr;




if (wartosc+taksa>0 and wartosc+taksa-(odplatnosc+doplata)<0) then
  if (doplata>0) then
    doplata=wartosc+taksa-odplatnosc;
  else
    odplatnosc=wartosc+taksa-doplata;

KWOTA_UP=KWOTA_UP*100;
KWOTA_UP=cast(KWOTA_UP as integer);
KWOTA_UP=KWOTA_UP*0.01;


RABAT_GOTOWKA=rabat_kw*100;
RABAT_GOTOWKA=cast(RABAT_GOTOWKA as integer);
RABAT_GOTOWKA=RABAT_GOTOWKA*0.01;

wart_zak=0.01*wart_zak;

if (memc<0) then
begin
  typ_up='N';
  kwota_up=-memc*sztuk;
  rabat_gotowka=-memc*sztuk;
end

if (up100='T' and proc_up<99) then
  proc_up=100*(1/(1-proc_up*0.01)-1) ;

suspend;
end
^

CREATE or alter TRIGGER DEL_SPRZEDAZ1 FOR SPRZEDAZ ACTIVE
AFTER DELETE or update POSITION 0


AS
  declare idsp Integer;
  declare st   char(1);
  declare variable odpl numeric(15,2);
  declare variable dopl numeric(15,2);
  declare variable ref2 numeric(15,2);
  declare variable wart numeric(15,2);
  declare variable taksa numeric(15,2);
  declare variable idodpl integer;
  declare variable up Double precision;
  declare variable kwup Double precision;
  declare variable procup Double precision;
  declare variable typup char(1);
  declare variable rk Double precision;

begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
IF (rdb$get_context('USER_SESSION','PHARMONIA')=1) THEN EXIT; -- jak del-sprzedaza


if (old.ID_RECEPTA is NOT NULL) THEN
  if (SUBSTRING( (SELECT r.ATRYBUTY FROM RECEPTA r where r.ID_RECEPTA=old.ID_RECEPTA and r.ID_APTEKI = old.ID_APTEKI ) from 1 for 2) = 'GW') THEN
  BEGIN
    for SELECT  s.ID_SPRZEDAZ,s.UPUST FROM SPRZEDAZ s where s.ID_RECEPTA=old.ID_RECEPTA and s.ID_APTEKI = old.ID_APTEKI and s.ID_SPRZEDAZ>old.ID_SPRZEDAZ  and s.TRYB <> 'Z'
    order by s.ID_SPRZEDAZ INTO idsp,up do 
    BEGIN
    select ID_ODPL, ODPLATNOSC, DOPLATA, REF2, WARTOSC, TAKSA, TYP_UP ,KWOTA_UP,PROC_UP,RABAT_GOTOWKA from wycena_sprzedazy (old.ID_APTEKI,:IDSP,:up)
        into :idodpl, :odpl, :dopl, :ref2, :wart, :taksa, :typup, :kwup, :procup, :rk;
     update sprzedaz set ID_ODPLATNOSC=:idodpl, ODPLATNOSC=:odpl, DOPLATA=:dopl, REFUNDATOR2=:ref2, WARTOSC=:wart, TAKSA=:taksa,
                    UPUST=:procup, KWOTA_UPUSTU=:kwup, TYP_UPUSTU=:typup, RABAT_W_GOTOWCE=:rk
     where  ID_APTEKI=old.ID_APTEKI and ID_SPRZEDAZ=:IDSP;
     END
  END

end
^


ALTER TRIGGER UPD_RECEPTAA ACTIVE
AFTER UPDATE POSITION 0


AS
     declare variable id Integer;
     declare variable ido Integer;
     declare variable odpl numeric(15,2);
     declare variable dopl numeric(15,2);
     declare variable ref2 numeric(15,2);
     declare variable wart numeric(15,2);
     declare variable tr char(1);
     declare variable tu char(1);
     declare variable pa char(1);
     declare variable tks numeric(15,2);
     declare variable up numeric(15,2);
     declare variable nrok char(1);
     declare variable ook char(1);
     declare variable kwu numeric(15,2);
     declare variable rgo numeric(15,2);
     declare variable proc numeric(15,2);
     declare variable odd Integer;
     declare variable kol Integer;
     declare variable akol Integer;
     declare variable aopl Integer;
     declare variable itw Integer;
     declare variable dts date;
     declare variable pwart numeric(15,2);

begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
if ( substring(old.ATRYBUTY from 4 for 2)<>substring(new.ATRYBUTY from 4 for 2)  or substring(old.ATRYBUTY from 8 for 2)<>substring(new.ATRYBUTY from 8 for 2) or
   (substring (old.ATRYBUTY from 2 for 2)<>substring(new.ATRYBUTY from 2 for 2) and (substring(old.ATRYBUTY from 2 for 1)='I' or substring(new.ATRYBUTY from 2 for 1)='I')) or old.kod_srodka is DISTINCT from new.kod_srodka
    or old.WNUMOWA is DISTINCT from new.WNUMOWA or old.na_ile<>new.NA_ILE or (LEFT(new.ATRYBUTY,2)='GF' and old.TRYB is DISTINCT from new.TRYB)) 
   then
  begin
    
    for select s.ID_SPRZEDAZ, s.TRYB, s.UPUST, t.PARAGON,s.id_odplatnosc,s.id_towary,s.data from sprzedaz s
     left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
     where s.id_apteki=old.id_apteki and s.ID_RECEPTA=old.ID_RECEPTA into :id, :tr, :up, pa,ido,itw,dts do
     begin
      if ((:tr<>'Z') and (:tr<>'K')) then
      begin
        akol=1000;
        ook='N';
        for select distinct l.id_odplatn,kolejnosc
        from tow_listy t
        left join listy_odpl l on t.id_listy=l.id_listy and :dts between l.obowiazuje_od and l.obowiazuje_do and cast(new.atrybuty as char(9)) like l.ATRYBUTY
        left join  ODPLATN o on o.id_odplatn=l.id_odplatn
        where t.id_apteki=old.id_apteki and t.id_towary=:itw and  :dts between t.obowiazuje_od and t.obowiazuje_do
        order by kolejnosc,id_odplatn into odd,kol do
          if (kol<=akol) then
          begin
            akol=kol;
            if  (odd=ido) then
               ook='T';
          end
        if (ook='N') then
          update sprzedaz set  ID_ODPLATNOSC=0
          where ID_APTEKI=old.id_apteki and ID_SPRZEDAZ=:id;
        select ID_ODPL,ODPLATNOSC,DOPLATA,REF2,WARTOSC,TAKSA,KWOTA_UP,RABAT_GOTOWKA,TYP_UP,PROC_UP from wycena_sprzedazy(old.id_apteki,:id,:up) into
               :ido, :odpl, :dopl, :ref2, :wart, :tks, kwu, rgo, tu, proc;
        if (tr='R')  THEN
        BEGIN
          select wartosc+taksa from SPRZEDAZ s where s.ID_APTEKI=old.ID_APTEKI and s.ID_SPRZEDAZ=(select z.POPRZEDNI from zmiany z where z.ID_APTEKI=old.ID_APTEKI and z.ID_SPRZEDAZ=:id )
          into pwart;
          if (pwart is not null and abs(wart+tks-abs(pwart))>0.005)  THEN
            EXCEPTION BLAD 'Wartoœæ recepty uleg³a zmianie.
Wycofaj zmiany Ctrl-Del i u¿yj korekty fiskalnej';
        end  
        update sprzedaz set
           ID_ODPLATNOSC=:ido,
           ODPLATNOSC=coalesce(:odpl,0),
           DOPLATA=:dopl,
           REFUNDATOR2=:ref2,
           WARTOSC=coalesce(:wart,0),
           TAKSA=:tks,
           UPUST=:proc,
           KWOTA_UPUSTU=:kwu,
           RABAT_W_GOTOWCE=:rgo,
           TYP_UPUSTU=:tu
        where ID_APTEKI=old.id_apteki and ID_SPRZEDAZ=:id;
      end
    end
  end
  
if (old.ATRYBUTY is DISTINCT from new.ATRYBUTY or old.NUMER is DISTINCT from new.NUMER or old.NR_W_DNIU is DISTINCT from new.NR_W_DNIU or old.DATA_WYST is DISTINCT from new.DATA_WYST 
  or old.LEKARZ is DISTINCT from new.LEKARZ or old.PRZYCHODNIA is DISTINCT from new.PRZYCHODNIA or old.PACJENT is DISTINCT from new.PACJENT or old.TYP_NR_PAC is DISTINCT from new.TYP_NR_PAC
  or old.TRYB is DISTINCT from new.TRYB or old.ID_WYDAL is DISTINCT from new.ID_WYDAL
  or old.RECF_OPIS is DISTINCT FROM new.RECF_OPIS)   THEN
BEGIN
  tu = 'N';
  if (new.ATRYBUTY not like 'GW%') THEN
  BEGIN
    insert into ETAKSACJE  (ID_SPRZEDAZ,ID_APTEKI,KLUCZ,status,kasa)
    select s.ID_SPRZEDAZ,s.ID_APTEKI,'','K',t.NR_KASY
     from sprzedaz s LEFT join TRANZAKCJE t on t.DATA = s.DATA and t.ID_TRANZAKCJE =  s.ID_TRANZAKCJE and t.ID_APTEKI = s.ID_APTEKI
     where s.id_apteki=new.ID_APTEKI and s.ID_RECEPTA=new.ID_RECEPTA and s.tryb = 'P' and t.PARAGON <> 'B'
     and s.data >= '01.01.2019' and s.id_towary<>0 and  not exists
     (select*from ETAKSACJE e where s.id_apteki=e.id_apteki and s.id_sprzedaz=e.id_sprzedaz) ;
    UPDATE SPRZEDAZ s SET s.TRYB = 'N' WHERE s.ID_RECEPTA = new.ID_RECEPTA and s.ID_APTEKI = new.ID_APTEKI and s.TRYB = 'P' and s.data >= '01.01.2019' ;
  end

  FOR SELECT e.STATUS from SPRZEDAZ s LEFT JOIN ETAKSACJE e on s.ID_SPRZEDAZ = e.ID_SPRZEDAZ and s.ID_APTEKI = e.ID_APTEKI 
  WHERE s.ID_APTEKI = new.ID_APTEKI and s.ID_RECEPTA=new.ID_RECEPTA INTO tr do
    if (tr='W') THEN
      tu = 'W';
    ELSE
      if (tu = 'N') THEN
        tu = 'B';
 if (tu = 'W') THEN
   EXCEPTION BLAD 'DRR dla tej recepty zosta³ ju¿ wys³any.
Poprawy zablokowane. U¿yj korekty fiskalnej lub korekty recepty';

  if (old.NUMER = '9' and (CHARACTER_LENGTH(new.NUMER)=22 or new.NUMER='0')) THEN
    tu = 'B';

  if (tu = 'B') THEN
    FOR SELECT e.ID_SPRZEDAZ from SPRZEDAZ s LEFT JOIN ETAKSACJE e on s.ID_SPRZEDAZ = e.ID_SPRZEDAZ and s.ID_APTEKI = e.ID_APTEKI
      WHERE s.ID_APTEKI = new.ID_APTEKI and s.ID_RECEPTA=new.ID_RECEPTA INTO id do
        UPDATE ETAKSACJE e set e.STATUS = 'K' where e.ID_APTEKI = new.ID_APTEKI and e.ID_SPRZEDAZ = :id and e.status <> 'W';

END

if (old.nr_w_dniu<>new.nr_w_dniu) then
begin
  select ok from chk_nrrec(new.id_apteki, new.id_recepta) into :nrok;
  if (nrok='N') then
    exception nr_rec;
end

end
^

/*bez zmian */
ALTER PROCEDURE NOWA_CENASP (
    IAP Integer,
    IDSPRZ Integer,
    CN Numeric(15,2) )
AS
declare variable odpl numeric(15,2);
     declare variable dopl numeric(15,2);
     declare variable ref2 numeric(15,2);
     declare variable wart numeric(15,2);
     declare variable taksa numeric(15,2);
     declare variable idodpl integer;
     declare variable up Double precision;
     declare variable kwup Double precision;
     declare variable procup Double precision;
     declare variable typup char(1);
     declare variable rk Double precision;
begin

select UPUST from sprzedaz where ID_APTEKI=:iap and id_SPRZEDAZ=:idsprz into :up;
update sprzedaz set CENA=:cn where ID_APTEKI=:iap and ID_SPRZEDAZ=:idSprz;
update rzdst set cena = :cn where ID_APTEKI=:iap and  ID_SPRZEDAZ=:idSprz;

select ID_ODPL, ODPLATNOSC, DOPLATA, REF2, WARTOSC, TAKSA, TYP_UP ,KWOTA_UP,PROC_UP,RABAT_GOTOWKA from wycena_sprzedazy (:iap,:IDSPRZ,:up)
  into :idodpl, :odpl, :dopl, :ref2, :wart, :taksa, :typup, :kwup, :procup, :rk;

update sprzedaz set ID_ODPLATNOSC=:idodpl, ODPLATNOSC=:odpl, DOPLATA=:dopl, REFUNDATOR2=:ref2, WARTOSC=:wart, TAKSA=:taksa,
                    UPUST=:procup, KWOTA_UPUSTU=:kwup, TYP_UPUSTU=:typup, RABAT_W_GOTOWCE=:rk
where  ID_APTEKI=:iap and ID_SPRZEDAZ=:IDSPRZ;
end^

CREATE or alter TRIGGER FAKT_ZB_ZAKS FOR FAKT_ZB
ACTIVE BEFORE UPDATE OR DELETE POSITION 0
AS
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
   if (UPDATING AND new.ZAKSIEGOWANA = 'N') THEN exit;
   if (COALESCE(old.ZAKSIEGOWANA,'N') = 'T') THEN
     EXCEPTION BLAD 'Faktura zaksiêgowana';
END^

CREATE or alter TRIGGER FAKT_ZB_ZAW_BIUD FOR FAKT_ZB_ZAW
ACTIVE BEFORE INSERT OR UPDATE OR DELETE POSITION 0
AS
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  if ( (SELECT COALESCE(z.ZAKSIEGOWANA,'N') from FAKT_ZB z where z.ID_FAKT_ZB =  iif(INSERTING,new.ID_FAKT_ZB,old.ID_FAKT_ZB)) = 'T') THEN
    EXCEPTION BLAD 'Faktura zaksiêgowana';
END^

CREATE OR ALTER PROCEDURE KS_FA_ZBIORCZA (
    IAP INTEGER,
    IDZ INTEGER )
RETURNS (
    ST CHAR(1) )

AS
declare kd char(1);
declare variable kk char(1);
declare variable ko integer;
declare variable nt double precision;
declare variable vt double precision;
declare variable br double precision;
declare variable tt double precision;
declare variable od double precision;
declare variable po double precision;
declare variable ii integer;
declare variable ik integer;
declare variable lp integer;
declare variable nk char(1);
declare variable idro integer;
declare variable idsd integer;
declare variable ds integer;
declare variable dtw timestamp;
declare variable dtp timestamp;
declare variable nrf varchar(100);
DECLARE manip INTEGER;
DECLARE katR char(1);
DECLARE pan char(1);
DECLARE pow char(1);
DECLARE swz char(1);
DECLARE atrVT int;
DECLARE defi int;
DECLARE dta date;
DECLARE dwy date;
begin
  select COALESCE(z.ZAKSIEGOWANA,'N'),z.ID_KONTRAHENCI,z.DATA_PL,COALESCE(z.DATA_SP,z.DATA),z.NUMER,z.DATA FROM FAKT_ZB z WHERE z.ID_APTEKI = :iap and z.ID_FAKT_ZB = :idz into kd,ds,dtp,dta,nrf,dwy;
  
  SELECT IIF(CHARACTER_LENGTH( trim(coalesce(k.NIP,'')))>9,1,0),COALESCE(k.POWIAZANY,'N'),COALESCE(k.ZAGRANICZNY,'N')  FROM KONTRAHENCI k where k.ID_KONTRAHENCI=:ds into manip,pow,swz;
  
  select COALESCE(o.PARAGON_NIP,'N') from ogolne o where id_apteki=:iap into pan;
  
  if (kd='T') THEN
  BEGIN
    DELETE FROM DOKUMENTY d where d.ID_APTEKI = :iap and d.DATA = :dta and d.SYMB_ZEWN = :nrf;
    st = 'N';
    SUSPEND;
    exit;
  END
  
  nk = 'T';
  if ((nk='T') and manip=1 and pan='N') THEN
  BEGIN
    nk = 'N';
    kd = 'N';
  END 
  
  if (dtp is null) then
  begin
    if (nk='T') then 
      kk = 'E';
    ELSE
      kk = 'G';
  end
  else
  begin
    if (nk='T') then
    begin
      select sum(t.KWOTA)  from FAKT_ZB_ZAW z left JOIN
      TRANZ_WPLATY t on t.ID_APTEKI=z.P_ID_APTEKI and t.ID_TRANZAKCJE=z.P_ID_TRANZAKCJE and t.ID_TRANZ_OPISY=5 and t.DATA=z.P_DATA  
      where z.id_apteki=:iap and z.ID_FAKT_ZB=:idz into po;
      kk = 'K';
    END
    ELSE
      kk = 'A';
  end

  select count(*) from  FAKT_ZB_ZAW z LEFT JOIN sprzedaz s on s.ID_APTEKI=z.P_ID_APTEKI and s.DATA=z.P_DATA and s.ID_TRANZAKCJE=z.P_ID_TRANZAKCJE
   where z.id_apteki=:iap and z.ID_FAKT_ZB=:idz and s.tryb='Z'  into ko;
   
  select count(*) from  FAKT_ZB_ZAW z LEFT JOIN sprzedaz s on s.ID_APTEKI=z.P_ID_APTEKI and s.DATA=z.P_DATA and s.ID_TRANZAKCJE=z.P_ID_TRANZAKCJE
    left join TOWARY t on s.ID_TOWARY = t.ID_TOWARY and s.ID_APTEKI = t.ID_APTEKI 
    left join cbt c on t.ID_CBT = c.ID_CBT
  where z.id_apteki=:iap and z.ID_FAKT_ZB=:idz and COALESCE(c.DEFICYTOWY,'N')='T'  into defi;

  /* sprawdzamy czy zwrot */
  if (idro>0 or ko>0) THEN kk = 'O';

  select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING :kk into idsd;
  
  if (kk = 'E' and manip=0) THEN
  begin
    idsd = null;
  end  

  if (coalesce(idsd,0)<1 and kk='O' and ko>0) then
    select min(s.ID_SZABL_DEK) from SZABL_DEK s where s.STOSUJ_DO CONTAINING 'Z' into idsd;
  
  if (ds>0 and (kd<>'K' or manip=1)) then
  begin
      atrVT = bin_shl(1,29);
      if (swz = 'T') THEN    
        atrVT = atrVT + bin_shl(1,13);
      if (pow = 'T') THEN    
        atrVT = atrVT + bin_shl(1,15);  
      if (defi > 0) THEN    
        atrVT = atrVT + bin_shl(1,8);  
      select GEN_ID(SQ_DOKUMENTY,1) from JEDEN_WIERSZ into :ii;
      insert into dokumenty (ID_APTEKI,id_dokumenty,data,data_pl,data_wy,symb_wewn,symb_zewn,id_okres_fk,id_szabl_dek,atrvat) values
        (:iap,:ii,:dta,:dtp,:dwy,'VAT' || :ii,:nrf,0,:idsd,:atrVT);
    
    lp=0;
    tt=0;
    for select kod,sum(nt),sum(vt),sum(br),sum(odpl) from  FAKT_ZB_ZAW z left JOIN wartfakt( z.P_ID_APTEKI,z.P_ID_TRANZAKCJE,z.P_DATA) on 0=0
     where z.id_apteki=:iap and z.ID_FAKT_ZB=:idz
     GROUP by KOD into :kk,:nt,:vt,:br,od do
    
    if (kk<>'S') then
    begin
      lp=lp+1;
      
        select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
        insert into dekrety (ID_APTEKI,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,'VAT-SP-SP-'||:kk||'-N-'||:ds||'-','W',:nt,'',:lp);
        select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :ik;
        insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
               (:iap,:ik,:ii,'VAT-SP-SP-'||:kk||'-V-'||:ds||'-','W',:vt,'',:lp);
      
    end
    else
      tt=od;
   /*  platnosc odroczona moze byc czescia odplatnosci*/
    if (po is not null) then
      tt=po;

    if (idsd is not null) then 
    begin
      select idro from dekretacja(:iap,:ii) into idro;
      if (idro is not null) then
        update dekrety set kwota = :tt where id_apteki=:iap and id_dekrety=:idro;
    end
  end
  st='T';
  SUSPEND;
end
^

ALTER PROCEDURE ZAW_VAT (
    IAP INTEGER,
    ID INTEGER,
    DT TIMESTAMP,
    KN VARCHAR(100) )
RETURNS (
    KOD CHAR(1),
    STAWKA DOUBLE PRECISION,
    NETTO DOUBLE PRECISION,
    VAT DOUBLE PRECISION )
AS
DECLARE dod INTEGER;
begin

if (iap<0) THEN
BEGIN
  dod = 1;
  iap = - iap;
END
ELSE
  dod = 0;

for select v.kod,v.vat stawka,(select sum(r.KWOTA) from dekrety r where r.id_apteki=:iap and r.id_dokumenty=:id and r.konto like :kn || v.kod || '-N%' ) Netto,
(select sum(b.KWOTA) from dekrety b where b.id_apteki=:iap and b.id_dokumenty=:id and b.konto like :kn || v.kod || '-V%' )  VAT  from
 ( select kod,vat from akt_stawki_vat(:dt)
   union 
   SELECT 'X',0 from JEDEN_WIERSZ WHERE :dod =1
   union 
   SELECT 'Y',0 from JEDEN_WIERSZ WHERE :dod =1
    ) v
  order by v.kod into :kod,:stawka,:netto,:vat do
    suspend;
end^

/* bez zmian dla ZAW_VAT  */
ALTER PROCEDURE DP_VAT(IAP INTEGER,
NK VARCHAR(100),
ID INTEGER,
DT DATE,
KT INTEGER)
 AS
declare variable sv char(1);
declare variable kn varchar(100);
declare variable kv varchar(100);
declare variable cn varchar(100);
declare variable kk integer;
declare variable ll integer;
begin
  select max(lp) from dekrety where id_apteki=:iap and id_dokumenty=:id into :ll;
  if (ll is null) then ll=0;
  for select kod from zaw_vat(-1,0,:dt,'') into :sv do
  begin
    ll=ll+1;
    kn=nk || sv || '-N-' || kt || '-';
    kv=nk || sv || '-V-' || kt || '-';
    cn=null;
    select konto from dekrety where id_apteki=:iap and id_dokumenty=:id and konto like :nk || :sv || '-N%' into :cn;
    if (cn<>kn) then
      update dekrety set konto = :kn where  id_apteki=:iap and  id_dokumenty=:id and konto like :nk || :sv || '-N%';
    else
      if (cn is null) then
      begin
        select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :kk;
          insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
             (:iap,:kk,:id,:kn,'W',0,'',:ll);
      end
    select konto from dekrety where id_apteki=:iap and  id_dokumenty=:id and konto like :nk || :sv || '-V%' into :cn;
    if (cn<>kv) then
      update dekrety set konto = :kv where  id_apteki=:iap and  id_dokumenty=:id and konto like :nk || :sv || '-V%';
    else
      if (cn is null) then
      begin
        select GEN_ID(SQ_DEKRETY,1) from JEDEN_WIERSZ into :kk;
          insert into dekrety (id_apteki,id_dekrety,id_dokumenty,konto,strona,kwota,opis,lp) values
             (:iap,:kk,:id,:kv,'W',0,'',:ll);
      end
  end
  delete from dekrety where id_apteki=:iap and  id_dokumenty=:id and konto > :nk || :sv and konto < :nk || 'Z';
end
^

ALTER TRIGGER UPD_TRANZAKCJE ACTIVE
BEFORE UPDATE POSITION 0
as
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

  if (old.data<>new.data) then
  begin
    if (new.paragon not in ('N','B')) then
       exception BLAD 'Transakcja zaksiêgowana';
  end

  if (old.id_kontrahenci is null and new.id_kontrahenci>0 and old.paragon='T' and new.kor_tr is not null) then
    new.paragon='K';
    
  if (old.TERMIN_PLAT='30.12.1899') then new.TERMIN_PLAT=null;  
  if (new.TERMIN_PLAT='30.12.1899') then new.TERMIN_PLAT=null;  
  
  if (rdb$get_context('USER_SESSION','KS_FA') is distinct from 1 and old.data<cast('today' as date)-50 and new.paragon<>old.paragon) then --blokada na problemy z drukarka fiskalna
       exception BLAD 'Próba zmiany statusu transakcji z '||(select*from tylko_data(old.data))||'
Zmiana dopuszczalna do 50 dni wstecz od daty bie¿¹cej ';
  
end^
ALTER PROCEDURE POSTOK (
    PA varchar(100),
    PO varchar(100) )
RETURNS (
    OK char(1) )
AS
begin
  if (('KREM MAŒÆ' containing po and 'LOTIO P£YN' containing pa) or ('KREM MAŒÆ' containing pa and 'LOTIO P£YN' containing po)
    or (po CONTAINING 'TABL' and po CONTAINING 'ZAWIESINA' and pa not CONTAINING 'ZAWIESINA')
    or (pa CONTAINING 'TABL' and pa CONTAINING 'ZAWIESINA' and po not CONTAINING 'ZAWIESINA')   
    or (po='MAŒÆ' and pa = 'KREM') or (pa='MAŒÆ' and po = 'KREM') ) then    
    ok='F';
  else
    ok='T';
  suspend;
end^

ALTER PROCEDURE TEST_ZAMIENNIKA (
    EANR varchar(15),
    IC integer,
    IO integer )
RETURNS (
    ZG integer )
AS
DECLARE ij INTEGER;
DECLARE oz INTEGER;
DECLARE mn INTEGER;
DECLARE dz INTEGER;
DECLARE PS VARCHAR(100);
DECLARE ZN VARCHAR(100);
DECLARE NM VARCHAR(100);
DECLARE od VARCHAR(5);
DECLARE ln INTEGER;

DECLARE oz1 INTEGER;
DECLARE mn1 INTEGER;
DECLARE dz1 INTEGER;
DECLARE PS1 VARCHAR(100);
DECLARE ZN1 VARCHAR(100);
DECLARE NM1 VARCHAR(100);
DECLARE od1 VARCHAR(5);

DECLARE pok char(1);
declare ap apteka;
BEGIN
   SELECT FIRST 1 c.JEDNOSTKA FROM CBT_JEDN c 
    WHERE  c.id_cbt=:ic  AND c.JEDNOSTKA > 1 and c.NAZWA in ('DAWEK') 
    ORDER by c.JEDNOSTKA INTO ij;
    
    if (ij is NULL) THEN ij = 2;
  
    select first 1 c.POSTAC,c.ID_SYNZB,COALESCE(j.MNOZNIK,1),COALESCE(j.DZIELNIK,1),t.TYP,c.NM_SHORT
    from cbt c 
    LEFT JOIN CBT_JEDN j on j.ID_CBT = c.ID_CBT and j.JEDNOSTKA = :ij
    LEFT JOIN TYP_LEKU_CBT(c.ID_CBT,'today') t on 0=0
    where c.id_cbt=:ic 
    into ps,oz,mn,dz,od,zn;
    
    LN = POSITION(' ' , zn || ' ') - 1;
    nm = SUBSTRING(zn from 1 for ln);
    
    select first 1 c.POSTAC,c.ID_SYNZB,COALESCE(j.MNOZNIK,1),COALESCE(j.DZIELNIK,1),t.TYP,c.NM_SHORT
    from CBT_KLAS k
    LEFT join cbt c  on k.ID_CBT = c.ID_CBT
    LEFT JOIN CBT_JEDN j on j.ID_CBT = c.ID_CBT and j.JEDNOSTKA = :ij
    LEFT JOIN TYP_LEKU_CBT(c.ID_CBT,'today') t on 0=0
    where k.WARTOSC=:eanr and k.ID_KLASYFIKACJE=6
    into ps1,oz1,mn1,dz1,od1,zn1;
    
    LN = POSITION(' ' , zn1 || ' ') - 1;
    nm1 = SUBSTRING(zn1 from 1 for ln);
    
    SELECT OK FROM POSTOK(:ps1,:ps) INTO pok;
    if (od = 'OTC' and od1 = 'OTC') THEN
      zg = 0;
    else if (pok = 'N' or oz <> oz1 or (od1<>'REF' and io <> 6)) THEN
      zg = 3; --czerowny
    else if (nm <> nm1 or ps <> ps1) THEN 
      zg = 2; --zó³ty
    else if (dz*mn1 <> dz1*mn) THEN
      zg = 1; --zielony
    ELSE
      zg = 0;
    
    if (ap in (10472,10474) and zg=0) then zg = 2;
    
    SUSPEND;    
END
^

ALTER PROCEDURE ODPZB_OK (
    ID1 integer,
    ID2 integer,
    IAP integer,
    PO1 varchar(100),
    PO2 varchar(100),
    T90 integer )
RETURNS (
    JESTOK char(1),
    MN1 integer,
    MN2 integer,
    DZ1 integer,
    DZ2 integer )
AS
DECLARE CBT1 INTEGER;
DECLARE cbt2 INTEGER;
DECLARE je1  INTEGER;
DECLARE je2  INTEGER;
DECLARE nj1  VARCHAR(100);
BEGIN
  SELECT ok FROM POSTOK(:po1,:po2) into jestok;
  if (id1<0) THEN
  BEGIN
    cbt1 = 1;
    id1 = - id1;
  END
  ELSE
    cbt1 = 0;

  if (id2<0) THEN
  BEGIN
    cbt2 = 1;
    id2 = - id2;
  END
  ELSE
    cbt2 = 0;

  if (jestok='T') THEN
  BEGIN
    jestok = 'N';
    if (cbt1=1) THEN
       SELECT FIRST 1  j.JEDNOSTKA,j.NAZWA FROM CBT_JEDN j WHERE   j.ID_CBT=:id1 and j.JEDNOSTKA>1 and j.NAZWA  not in ('BUTELKA','POJEMNIK' ,'DOZOWNIK')
       ORDER by j.JEDNOSTKA
       INTO je1,nj1;
    ELSE
       SELECT FIRST 1  j.JEDNOSTKA,j.NAZWA FROM JEDNOSTKI j WHERE  j.ID_TOWARY=:id1 AND j.ID_APTEKI=:iap and j.JEDNOSTKA>1  and j.NAZWA  not in ('BUTELKA','POJEMNIK' ,'DOZOWNIK')
       ORDER by j.JEDNOSTKA
       INTO je1,nj1;
    if (je1 is not null)   THEN
    BEGIN
      if (cbt2=1) THEN
       SELECT FIRST 1 j.JEDNOSTKA FROM CBT_JEDN j WHERE   j.ID_CBT=:id2 and j.NAZWA = :nj1
       ORDER by j.JEDNOSTKA
       INTO je2;
      ELSE
       SELECT FIRST 1  j.JEDNOSTKA FROM JEDNOSTKI j WHERE  j.ID_TOWARY=:id2 AND j.ID_APTEKI=:iap and j.NAZWA= :nj1
       ORDER by j.JEDNOSTKA
       INTO je2;
     if (je2 is null) THEN je2=2;
     if (cbt1=1) THEN
      select mnoz,dziel from ilosc_jp_cbt(:id1,:je1) into mn1,dz1;
     ELSE
       SELECT mnoz,dziel FROM ilosc_jp(:iap,:id1,:je1) INTO :mn1, :dz1;
     if (cbt2=1) THEN
      select mnoz,dziel from ilosc_jp_cbt(:id2,:je2) into mn2,dz2;
     ELSE
       SELECT mnoz,dziel FROM ilosc_jp(:iap,:id2,:je2) INTO :mn2, :dz2;
     if (mn1*dz2 = mn2*dz1 or (t90=1 and mn1/dz1 between 0.9 * mn2/dz2 and 1.1 * mn2/dz2 )) THEN
       jestok='T';
    END
  END
  SUSPEND;
END
^ 

ALTER PROCEDURE ERECEPTA_LEK (
    IA INTEGER,
    BC VARCHAR(20),
    BL VARCHAR(7),
    ST DOUBLE PRECISION,
    NZ CHAR(1),
    IO INTEGER,
    NR VARCHAR(50),
    DD DOUBLE PRECISION DEFAULT 0 )
RETURNS (
    IT INTEGER,
    SZ DOUBLE PRECISION,
    ZA INTEGER,
    SA DOUBLE PRECISION,
    MD DOUBLE PRECISION,
    IC INTEGER,
    ZN VARCHAR(100),
    TN VARCHAR(100),
    OD VARCHAR(5),
    TA DOUBLE PRECISION,
    IW DOUBLE PRECISION,
    EA VARCHAR(20),
    FS TIMESTAMP,
    TP DOUBLE PRECISION,
    ZG INTEGER,
    KO BLOB SUB_TYPE 0,
    IP DOUBLE PRECISION,
    ZO INTEGER,
    RL char(1),
    op DOUBLE PRECISION  )

AS
DECLARE TT INTEGER;
DECLARE PS VARCHAR(100);
DECLARE oz INTEGER;
DECLARE oi INTEGER;
DECLARE mn INTEGER;
DECLARE dz INTEGER;
DECLARE po CHAR(1);
DECLARE ij INTEGER;
DECLARE nj VARCHAR(100);


DECLARE NM VARCHAR(100);
DECLARE LN INTEGER;
BEGIN
  rl = 'G';
  if (CHARACTER_LENGTH(BC) = 14 and left(bc,1) = '0') THEN
    bc = RIGHT(bc,13);
  if (CHARACTER_LENGTH(BC) > 10) THEN
    SELECT FIRST 1 k.ID_CBT FROM CBT_KLAS k left join towary t on t.id_apteki= :ia and t.id_cbt = k.id_cbt 
     left join zdst z on z.id_apteki= :ia and z.id_towary=t.id_towary and z.czynny='T' 
     where k.ID_KLASYFIKACJE = 6 and k.WARTOSC = :bc order by z.czynny desc NULLS LAST, t.id_towary desc INTO IC;
    
  if (IC is NULL AND CHARACTER_LENGTH(BL) = 7) THEN
    SELECT FIRST 1 k.ID_CBT FROM CBT_KLAS k where k.ID_KLASYFIKACJE = 3  and k.WARTOSC = :bl order by k.ID_CBT DESC INTO IC; 
 
  po = 'N';
  sz = st;   
  ip = sz;
  if (IC is not null) THEN
  BEGIN
    SELECT FIRST 1 c.JEDNOSTKA FROM CBT_JEDN c 
    WHERE  c.id_cbt=:ic  AND c.JEDNOSTKA > 1 and c.NAZWA in ('DAWEK')
    ORDER by c.JEDNOSTKA INTO ij;
    
    if (ij is NULL) THEN ij = 2;
  
    select first 1 c.POSTAC,IIF(t.TYP<>'OTC' or :po = 'N', c.ID_SYNZB,c.ID_SYNSZCZ),COALESCE(j.MNOZNIK,1),COALESCE(j.DZIELNIK,1),o.OPLATA,t.TYP,left(c.NAZWA,100),COALESCE(c.ID_ODPZL,-1),j.NAZWA
    from cbt c
    LEFT JOIN CBT_JEDN j on j.ID_CBT = c.ID_CBT and j.JEDNOSTKA = :ij
    LEFT JOIN CBT_ODPL o on o.ID_CBT = c.ID_CBT AND (o.ID_ODPLATN=:io or :io=0) and o.OBOWIAZUJE_OD<='today'
    LEFT JOIN TYP_LEKU_CBT(c.ID_CBT,'today') t on 0=0
    where c.id_cbt=:ic
    order by o.obowiazuje_od descending,o.OPLATA
    into ps,oz,mn,dz,op,od,zn,oi,nj;
    
    if (EXISTS(SELECT k.WARTOSC FROM CBT_KLAS k where k.ID_CBT = :ic and k.ID_KLASYFIKACJE = 7 AND k.WARTOSC = 'L')) THEN rl = 'S';
    if (EXISTS(SELECT k.WARTOSC FROM CBT_KLAS k where k.ID_CBT = :ic and k.ID_KLASYFIKACJE = 7 AND k.WARTOSC = 'l')) THEN rl = 'W';
    
    if (ps STARTING 'INJ' or EXISTS(select wartosc from cbt_klas where id_cbt=:ic AND id_klasyfikacje=7 and wartosc='0')) THEN
      zo = 2;
    ELSE
      zo = 0;  
    
    if (dz>0) THEN tp = mn / dz;
    
    LN = POSITION(' ' , zn || ' ') - 1;
    nm = SUBSTRING(zn from 1 for ln);

    SELECT  sum(z.SZTUK_JP * (:dz * COALESCE(j.MNOZNIK , 1)/(:mn * COALESCE(j.DZIELNIK,1)))),min(s.DATA),LIST(distinct r.RECF_OPIS)
    FROM RECEPTA r
    LEFT JOIN SPRZEDAZ s on r.ID_APTEKI=s.ID_APTEKI and r.ID_RECEPTA=s.ID_RECEPTA
    LEFT JOIN RZDST z on z.ID_APTEKI=s.ID_APTEKI and z.ID_SPRZEDAZ=s.ID_SPRZEDAZ
    LEFT JOIN JEDNOSTKI j on j.ID_APTEKI = s.ID_APTEKI and j.ID_TOWARY = z.ID_TOWARY AND j.JEDNOSTKA = :ij
    WHERE r.NUMER = :nr INTO iw,fs,ko;

    if (iw is not NULL) THEN
    BEGIN
      iw = round(MAXVALUE(iw,0),4);
      st = MAXVALUE( st - iw , 0);
    end

    if ((nj STARTING 'TABL'  or nj STARTING 'KAPS' ) AND DD > 0) THEN
    BEGIN
      st = MINVALUE(CEIL(180 * dd / tp ) ,st);
      ip = st;
    END
    
    SELECT FIRST 1 ID_TOWARY,MINVALUE(SZT,STAN),STAN ,id_cbt,wsp,nazwa,tabl,ean,ten FROM
    (SELECT  IIF(ID_CBT=:ic,0,IIF(COALESCE(ID_ODPZL,-2)=:oi,1, IIF(SUBSTRING(NM_SHORT from 1 for :ln) = :nm ,2,3))) ten,  id_cbt,IIF (round(SZT,:zo)<=STAN+0.0001 or (STAN>=iif(:zo=0,1,0.05) and (ID_CBT=:ic or SUBSTRING(NM_SHORT from 1 for :ln) = :nm) ),0,1) sto,
      ID_TOWARY,round(SZT,:zo) SZT,STAN,EAN,wsp,nazwa,tabl FROM
    (SELECT  t.id_towary,t.id_cbt, (SELECT SUM(IIF( coalesce(z.BLOKADA,'N')='N' , z.STAN , z.STAN -  coalesce(z.ile_blokada,z.stan) )
       - COALESCE((select sum(ILOSC) from rezerwacja r where r.id_apteki=z.ID_APTEKI and r.ID_ZDST=z.ID_ZDST),0) ) 
      FROM ZDST z WHERE z.ID_TOWARY = t.ID_TOWARY AND z.ID_APTEKI = t.ID_APTEKI and z.CZYNNY ='T' AND (z.DATA_WAZN is NULL or z.DATA_WAZN<'01.01.1900' or z.DATA_WAZN > 'today')) stan,
      (:st * :mn * COALESCE(j.DZIELNIK,1)) / (:dz * COALESCE(j.MNOZNIK , 1)) szt, (:mn * COALESCE(j.DZIELNIK,1)) / (:dz * COALESCE(j.MNOZNIK , 1)) wsp,COALESCE(j.MNOZNIK , 1)/ COALESCE(j.DZIELNIK,1) tabl,
      iif(y.TYP = 'REF' ,
      (SELECT FIRST 1 o.OPLATA  FROM CBT_ODPL o WHERE o.ID_CBT = c.ID_CBT AND (o.ID_ODPLATN=:io or :io=0) and o.OBOWIAZUJE_OD<='today' ORDER BY o.OBOWIAZUJE_OD DESC),
      (SELECT a.CENA_BR FROM AKT_CENA_SP (t.ID_APTEKI,t.ID_TOWARY,3,'today',0,'' ) a )) OPLA,
      (SELECT FIRST 1 k.WARTOSC FROM CBT_KLAS k WHERE k.ID_CBT = c.ID_CBT and k.ID_KLASYFIKACJE=6 ORDER by k.IFUPDDATE DESC) EAN,t.NAZWA,left(c.NAZWA,100) NM_SHORT,COALESCE(c.ID_ODPZL,-2) ID_ODPZL
    FROM  CBT c
    LEFT JOIN POSTOK(c.POSTAC,  :ps) p on 0=0
    LEFT JOIN TOWARY t on t.ID_APTEKI = :ia and t.ID_CBT = c.ID_CBT
    LEFT JOIN CBT_JEDN j on j.ID_CBT = c.ID_CBT and j.JEDNOSTKA = :ij
    LEFT JOIN TYP_LEKU_CBT(c.ID_CBT,'today') y on 0=0
    WHERE (c.ID_CBT = :ic or  iif(:od <> 'OTC'  or :po = 'N',c.ID_SYNZB,c.ID_SYNSZCZ) = :oz)  and p.OK = 'T' and t.ID_TOWARY is not NULL
     and (:od <> 'REF' or y.TYP = 'REF') and (:nz <> 'T' or c.ID_CBT = :ic or COALESCE(c.ID_ODPZL,-2) = :oi))
    where IIF(szt>0, abs(szt-round(szt,:zo))/szt,0) <= 0.1
    ORDER by 3,1,opla*round(SZT,0)   )  
    INTO  it,sz,sa,za,md,tn,ta,ea,zg;
    SUSPEND;
  END
  ELSE
  BEGIN
    if (CHARACTER_LENGTH(BC) > 10) THEN  
      SELECT FIRST 1 k.ID_TOWARY FROM TW_KLAS k left join zdst z on z.id_apteki= :ia and z.id_towary=k.id_towary and z.czynny='T' 
       where k.ID_APTEKI=:ia AND k.ID_KLASYFIKACJE = 6 and k.WARTOSC = :bc order by z.czynny desc,k.ID_TOWARY DESC INTO tt;
 
    if (tt is NULL AND CHARACTER_LENGTH(BL) = 7) THEN
      SELECT FIRST 1 k.ID_TOWARY FROM TW_KLAS k where k.ID_APTEKI=:ia AND k.ID_KLASYFIKACJE = 3  and k.WARTOSC = :bl  order by k.ID_TOWARY DESC INTO tt;
    
    if (tt is null) then exit;  

    SELECT FIRST 1 c.JEDNOSTKA FROM JEDNOSTKI c 
    where c.ID_TOWARY=:tt  AND c.ID_APTEKI = :ia AND c.JEDNOSTKA > 1 and c.NAZWA in ('DAWEK')
    ORDER by c.JEDNOSTKA INTO ij;
    
    if (ij is NULL) THEN ij = 2;
    
    select first 1 c.POSTAC,IIF(t.TYP<>'OTC'  or :po = 'N', c.ID_SYNZB,c.ID_SYNSZCZ),COALESCE(j.MNOZNIK,1),COALESCE(j.DZIELNIK,1),o.OPLATA,t.TYP,c.ID_CBT,left(b.NAZWA,100),COALESCE(c.ID_ODPZL,-1)
    from  TOWARY c 
    LEFT JOIN JEDNOSTKI j on j.ID_APTEKI=c.ID_APTEKI and j.ID_TOWARY = c.ID_TOWARY and j.JEDNOSTKA = :ij
    LEFT JOIN ODPL_TOWARY o on o.ID_APTEKI = c.ID_APTEKI and  o.ID_TOWARY = c.ID_TOWARY AND (o.ID_ODPLATN=:io or :io=0) and o.OBOWIAZUJE_OD<='today'
    LEFT JOIN TYP_LEKU(c.ID_APTEKI, c.ID_TOWARY,'today') t on 0=0
    LEFT JOIN cbt b on c.ID_CBT = b.ID_CBT
    where c.ID_TOWARY=:tt  AND c.ID_APTEKI = :ia
    order by o.obowiazuje_od descending,o.OPLATA
    into ps,oz,mn,dz,op,od,ic,zn,oi;
    
    if (dz>0) THEN tp = mn / dz;
    
    LN = POSITION(' ' , zn || ' ') - 1;
    nm = SUBSTRING(zn from 1 for ln);
    
    SELECT sum(z.SZTUK_JP * (:dz * COALESCE(j.MNOZNIK , 1)/(:mn * COALESCE(j.DZIELNIK,1)))),min(s.DATA),LIST(DISTINCT r.RECF_OPIS)
    FROM RECEPTA r 
    LEFT JOIN SPRZEDAZ s on r.ID_APTEKI=s.ID_APTEKI and r.ID_RECEPTA=s.ID_RECEPTA
    LEFT JOIN RZDST z on z.ID_APTEKI=s.ID_APTEKI and z.ID_SPRZEDAZ=s.ID_SPRZEDAZ
    LEFT JOIN JEDNOSTKI j on j.ID_APTEKI = s.ID_APTEKI and j.ID_TOWARY = z.ID_TOWARY AND j.JEDNOSTKA = :ij
    WHERE r.NUMER = :nr INTO iw,fs,ko;
    
    if (iw is not NULL) THEN
    BEGIN
      iw = round(MAXVALUE(iw,0),4);
      st = st - iw;
    end
    
    SELECT FIRST 1  ID_TOWARY,MINVALUE(SZT,STAN),STAN ,id_cbt,wsp,nazwa,tabl,ean FROM
    (SELECT IIF(ID_TOWARY=:tt,0,IIF(COALESCE(ID_ODPZL,-2)=:oi,1, IIF(SUBSTRING(NAZWA from 1 for :ln) = :nm ,2,3))) ten, id_cbt,IIF (round(SZT,0)<=STAN+0.0001 or (STAN>=1 and (ID_TOWARY=:tt or SUBSTRING(NAZWA from 1 for :ln) = :nm)),0,1) sto,ID_TOWARY,round(SZT,0) SZT,STAN,EAN,wsp,nazwa,tabl FROM
    (SELECT  c.ID_CBT, c.id_towary, (SELECT SUM(IIF( coalesce(z.BLOKADA,'N')='N' , z.STAN , z.STAN -  coalesce(z.ile_blokada,z.stan) )
       - COALESCE((select sum(ILOSC) from rezerwacja r where r.id_apteki=z.ID_APTEKI and r.ID_ZDST=z.ID_ZDST),0) ) 
      FROM ZDST z WHERE z.ID_TOWARY = c.ID_TOWARY AND z.ID_APTEKI = c.ID_APTEKI and z.CZYNNY ='T' AND (z.DATA_WAZN is NULL or z.DATA_WAZN<'01.01.1900' or z.DATA_WAZN > 'today')) stan,
      (:st * :mn * COALESCE(j.DZIELNIK,1)) / (:dz * COALESCE(j.MNOZNIK , 1)) szt, (:mn * COALESCE(j.DZIELNIK,1)) / (:dz * COALESCE(j.MNOZNIK , 1)) wsp,COALESCE(j.MNOZNIK , 1)/ COALESCE(j.DZIELNIK,1) tabl,
      iif(y.TYP = 'REF' ,
      (SELECT FIRST 1 o.OPLATA  FROM ODPL_TOWARY o WHERE o.ID_APTEKI=c.ID_APTEKI AND o.ID_TOWARY = c.ID_TOWARY AND (o.ID_ODPLATN=:io or :io=0) and o.OBOWIAZUJE_OD<='today' ORDER BY o.OBOWIAZUJE_OD DESC),
      (SELECT a.CENA_BR FROM AKT_CENA_SP (c.ID_APTEKI,c.ID_TOWARY,3,'today',0,'' ) a )) OPLA,
      (SELECT FIRST 1 k.WARTOSC FROM TW_KLAS k WHERE k.ID_TOWARY = c.ID_TOWARY and k.ID_APTEKI=c.ID_APTEKI and k.ID_KLASYFIKACJE=6 ORDER by k.IFUPDDATE DESC) EAN,c.NAZWA,COALESCE(c.ID_ODPZL,-2) ID_ODPZL
    FROM  TOWARY c
    LEFT JOIN POSTOK(c.POSTAC,  :ps) p on 0=0
    LEFT JOIN JEDNOSTKI j on j.ID_TOWARY = c.ID_TOWARY and j.JEDNOSTKA = :ij and j.ID_APTEKI = c.ID_APTEKI
    LEFT JOIN TYP_LEKU (c.ID_APTEKI, c.ID_TOWARY,'today') y on 0=0
    WHERE c.ID_APTEKI =:ia AND (c.ID_TOWARY = :tt or  iif(:od <> 'OTC'  or :po = 'N',c.ID_SYNZB,c.ID_SYNSZCZ) = :oz)  and p.OK = 'T' 
     and (:od <> 'REF' or y.TYP = 'REF') and (:nz <> 'T' or c.ID_TOWARY = :tt))
    where IIF(szt>0, abs(szt-round(szt,0))/szt,0) <= 0.1
    ORDER by 3,1,opla*round(SZT,0)   )
    INTO  it,sz,sa,za,md,tn,ta,ea;


    SUSPEND;
  END


END
^


CREATE OR ALTER PROCEDURE ERECEPTA_API (
    IA INTEGER,
    EA VARCHAR(20),
    IL DOUBLE PRECISION,
    NZ CHAR(1),
    IO INTEGER,
    KL VARCHAR(50),
    UP VARCHAR(10),
    DD DOUBLE PRECISION )
RETURNS (
    DST INTEGER,
    OPL DOUBLE PRECISION,
    ILD DOUBLE PRECISION,
    DNW INTEGER,
    NMZ VARCHAR(100),
    OPZ DOUBLE PRECISION,
    IDO INTEGER,
    NMA VARCHAR(100),
    ULO VARCHAR(200),
    MNO DOUBLE PRECISION,
    ILW DOUBLE PRECISION,
    TBL DOUBLE PRECISION,
    ILP DOUBLE PRECISION )
AS
declare IT INTEGER;
declare SZ DOUBLE PRECISION;
declare ZA INTEGER;
declare SA DOUBLE PRECISION;
declare MD DOUBLE PRECISION;
declare IC INTEGER;
declare ZN VARCHAR(100);
declare TN VARCHAR(100);
declare OD VARCHAR(5);
declare TA DOUBLE PRECISION;
declare TP DOUBLE PRECISION;
declare IW DOUBLE PRECISION;
declare EE VARCHAR(20);
declare FS TIMESTAMP;
declare OP INTEGER;
declare ZG INTEGER;
DECLARE iu INTEGER;

/* procedura do obslugi aplikacji android */
BEGIN
  
  if (CHARACTER_LENGTH(ea) = 14 and left(ea,1) = '0') THEN
    ea = RIGHT(ea,13);
  SELECT it,sz,za,sa,md,ic,zn,tn,od,ta,iw,ea,fs,c.WWW_ULOTKA,e.ZG,e.TP,e.ip from ERECEPTA_LEK(:ia,:ea,NULL,:il,:nz,:io,:kl,:dd) e
  LEFT join cbt c on e.ic = c.ID_CBT
  INTO it,sz,za,sa,md,ic,zn,tn,od,ta,iw,ee,fs,ulo,zg,tp,ilp;

  if (COALESCE(TA,0) > 1 and COALESCE(TP,0) > 1) THEN
    mno = tp / ta;
  ELSE
    mno = 1;  
  tbl = coalesce(ta,1);
  sz = COALESCE(sz,0); 
  ild = sz;
  ilw = COALESCE(iw,0);
  if (sz < ilp*mno or ee <> ea) THEN
  BEGIN
    if (it is not null and (select count(*) from DOSTAWCY d left join CENA_Z_OFERTY(:ia,:it,d.id_kontrahenci,'N') c on 0=0 where d.ID_APTEKI=:ia and d.WWW_DOSTAWCA='T' and c.CENA>0 )>0) THEN
      dst = 2;
    ELSE
      dst = 0;  
  END
  ELSE
    dst = 1;
  if (io between 2 and 5) then
  begin
    if ((select count(*) from tow_listy t
      left join listy_odpl l on t.id_listy=l.id_listy and 'today' between l.obowiazuje_od and l.obowiazuje_do and cast(:up as char(9)) like l.ATRYBUTY
      where t.id_apteki=:ia and t.id_towary=:it and  'today' between t.obowiazuje_od and t.obowiazuje_do and l.id_listy is not null
      and id_odplatn=:io)=0) 
    then
    BEGIN
      io=0;
    END  
    else   
    BEGIN
      SELECT FIRST 1 l.ID_ODPLATN from tow_listy t
      left join listy_odpl l on t.id_listy=l.id_listy and 'today' between l.obowiazuje_od and l.obowiazuje_do and cast(:up as char(9)) like l.ATRYBUTY
      where t.id_apteki=:ia and t.id_towary=:it and  'today' between t.obowiazuje_od and t.obowiazuje_do and l.id_listy is not null
      and l.KOLEJNOSC=10 ORDER by l.ID_ODPLATN INTO op;
      if (op is not null and op < io) THEN
        io = op;
    END 
  end
  if (io = 0) then
    select ido from odpl_tw(:ia,:it,'today',:up) into io;
  
  iu = 0;
  if (io between 2 and 5) then
  BEGIN
    if (up  like 'G______S%') THEN
      iu = 27;
    if (up  like 'G______C%') THEN
      iu = 28;  
    if (up  like 'G______D%') THEN
      iu = 29;  
  END
  if (iu > 0) then
  BEGIN
    if ((select COUNT(*) from TOW_LISTY t
     where t.ID_APTEKI=:ia and t.ID_TOWARY=:it and t.ID_LISTY=:iu and 'today' BETWEEN t.OBOWIAZUJE_OD and t.OBOWIAZUJE_DO)>0) THEN
       io = 1;
  END
  if (io = 6) THEN
  BEGIN
    SELECT c.CENA_BR FROM AKT_CENA_SP(:ia,:it,3,'today',0,'') c INTO opl;
  END
  ELSE
  if (io = 1) THEN
  BEGIN
    opl = 0;
  END
  ELSE
  if (it is not null) THEN
  BEGIN
    SELECT FIRST 1 o.OPLATA  FROM ODPL_TOWARY o WHERE o.ID_APTEKI = :ia and o.ID_TOWARY = :it and o.ID_CENY = 3 and o.ID_ODPLATN = :io and o.OBOWIAZUJE_OD <= 'today' ORDER by o.OBOWIAZUJE_OD DESC INTO opl;
    if (opl is NULL and io = 2) THEN
      SELECT FIRST 1 o.CENA_BR-o.LIMIT  FROM CENY_TOWARY o WHERE o.ID_APTEKI = :ia and o.ID_TOWARY = :it and o.ID_CENY = 3  and o.OBOWIAZUJE_OD <= 'today' ORDER by o.OBOWIAZUJE_OD DESC INTO opl;
  END
  if (it is NULL and ic is not null and io BETWEEN 2 and 5) THEN
  BEGIN
    SELECT FIRST 1 o.OPLATA  FROM CBT_ODPL o WHERE o.ID_CBT = :ic and o.ID_CENY = 3 and o.ID_ODPLATN = :io and o.OBOWIAZUJE_OD <= 'today' ORDER by o.OBOWIAZUJE_OD DESC INTO opl;
    if (opl is NULL and io = 2) THEN
        SELECT FIRST 1 o.CENA_BR-o.LIMIT  FROM CBT_CENY o WHERE o.ID_CBT = :ic and o.ID_CENY = 3  and o.OBOWIAZUJE_OD <= 'today' ORDER by o.OBOWIAZUJE_OD DESC INTO opl;
  END
  if (zg > 1)  THEN
  BEGIN
    opz = opl;
    opl = null;
    nmz = tn;
    nma = zn;
    if (io <> 6 ) then
    BEGIN
      SELECT FIRST 1 o.OPLATA  FROM CBT_ODPL o WHERE o.ID_CBT = :ic and o.ID_CENY = 3 and o.ID_ODPLATN = :io and o.OBOWIAZUJE_OD <= 'today' ORDER by o.OBOWIAZUJE_OD DESC INTO opl;
      if (opl is NULL and io = 2) THEN
        SELECT FIRST 1 o.CENA_BR-o.LIMIT  FROM CBT_CENY o WHERE o.ID_CBT = :ic and o.ID_CENY = 3  and o.OBOWIAZUJE_OD <= 'today' ORDER by o.OBOWIAZUJE_OD DESC INTO opl;
    END
    ELSE
    if ((SELECT TYP FROM TYP_LEKU_CBT(:ic,'today')) = 'REF') THEN
    BEGIN
      SELECT FIRST 1 o.CENA_BR  FROM CBT_CENY o WHERE o.ID_CBT = :ic and o.ID_CENY = 3  and o.OBOWIAZUJE_OD <= 'today' ORDER by o.OBOWIAZUJE_OD DESC INTO opl;
    END
    if (opl is not NULL AND zg  < 3 AND opl >= opz * mno)  THEN
    BEGIN
      nma = tn;
      nmz = null;
      opl = opz;
      opz = -1;   
      dst = 1;
    END
  END
  ELSE
  BEGIN
    nma = tn;
    op=0;
    select first 1 t.NAZWA,opod from tanszy_odpowiednik(:ia, :it,'today',0, :up) o
    LEFT JOIN TOWARY t on t.ID_APTEKI = :ia and t.ID_TOWARY = o.ID_ODP
    where o.id_odp<>:it and o.ilod>=:ilp*:mno and o.OpOd<o.OpTw
    order by opOd into nmz, opz;

  END  
  ido = COALESCE(io,6);
  opl = round(COALESCE(opl,-1),2);
  opz = round(COALESCE(opz,-1),2);
  
  SELECT o.KLAS_ANTYB FROM OGOLNE o WHERE o.ID_APTEKI = :ia into io;
  if ((select count(*) jest from tw_klas where id_apteki=:ia and id_towary=:it and id_klasyfikacje=:io and wartosc='Antybiotyk')>0) THEN
    dnw = 7;
  ELSE
    dnw = 30;  
  SUSPEND;
END
^

ALTER PROCEDURE PROGN(IAP INTEGER,
IDT INTEGER,
ILE INTEGER,
DTM DATE)
 RETURNS(DTS DATE,
SPR NUMERIC(15,5),
MIN_OP NUMERIC(15,5))
 AS
declare variable cnt integer;
declare variable pie integer;
declare variable pop integer;
declare variable cnn integer;
declare variable mx integer;
declare variable il numeric(15,5);
declare variable dt TIMESTAMP;
declare variable dp TIMESTAMP;
declare variable kai integer;
declare variable spn integer;
begin
  cnt=1;
  select /*coalesce(PROGN_KASA,-100)*/-100,COALESCE(progn_spn,0),COALESCE(progn_poprzednia,0) from OGOLNE where id_apteki=:iap into kai,spn,pop;
  for SELECT szt,COUNT(*),max(dt) from (
      select sum(r.SZTUK_JP) szt,t.DATA dt
      from rzdst r
      left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
      left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
      where r.id_apteki=:iap and r.ID_TOWARY=:idt and r.data>=cast('TODAY' as date)-365 and  (t.id_kontrahenci is null or t.id_kontrahenci>0)
            and (t.NIE_BIERZ<>'T' or t.nie_bierz is null) and (t.id_tranzakcje<>0) and t.nr_kasy <> :kai
      GROUP by t.DATA,t.ID_TRANZAKCJE,s.ID_RECEPTA )
      group by szt
      order by 2 ,1
      into  min_op,mx,dp do
  BEGIN
    if (dt is null or dt<dp) THEN dt=dp;
  END    

  if (dt<dtm) then exit;

  if (pop>0 and mx=1) THEN
  BEGIN
    dp = null;
    select max(r.DATA) dt
      from rzdst r
      left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
      left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
      where r.id_apteki=:iap and r.ID_TOWARY=:idt and r.data<:dt and  (t.id_kontrahenci is null or t.id_kontrahenci>0)
            and (t.NIE_BIERZ<>'T' or t.nie_bierz is null) and (t.id_tranzakcje<>0) and t.nr_kasy <> :kai
      into dp;
    if (dp is not null and dp+pop<dt) then exit;

  END

  for select data,sum(CASE WHEN :spn=0 or szt<=(:min_op+2)*2 THEN szt ELSE :min_op END) from
   (select r.data,sum(r.SZTUK_JP) szt
   from rzdst r
   left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
   left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
   where r.id_apteki=:iap and r.ID_TOWARY=:idt and r.data>=cast('TODAY' as date)-365 and  (t.id_kontrahenci is null or t.id_kontrahenci>0)
        and (t.NIE_BIERZ<>'T' or t.nie_bierz is null) and (t.id_tranzakcje<>0) and t.nr_kasy <> :kai
   group by r.data,t.ID_TRANZAKCJE)
   GROUP by data
   order by data descending
   into  dts,spr do
  begin
    if (spr>0) then
    begin
      select WAGA from okresy where id_apteki=:iap and DATA=:dts into :il;
      if (il>0) then spr=spr/il;
      suspend;
      if (cnt=1) then
        dt=dts;
      cnt=cnt+1;
      if (cnt>ile+11 and dt-dts>30) then
          exit;
     end
  end
end
^

create or ALTER TRIGGER INS_UPD_CBT_KLAS2 for CBT_KLAS ACTIVE
BEFORE INSERT OR UPDATE POSITION 1
AS
begin
       
   if (new.id_klasyfikacje in (3,6) and new.wartosc<>(select cyfry from tylko_cyfry(new.wartosc))) THEN new.wartosc=(select cyfry from tylko_cyfry(new.wartosc));  
      
end^

create or ALTER TRIGGER INS_UPD_TW_KLAS2 for TW_KLAS ACTIVE
BEFORE INSERT OR UPDATE POSITION 1
AS
begin
       
   if (new.id_klasyfikacje in (3,6) and new.wartosc<>(select cyfry from tylko_cyfry(new.wartosc))) THEN new.wartosc=(select cyfry from tylko_cyfry(new.wartosc));  
      
end^

ALTER TRIGGER FAKT_ZB_ZAW_BIUD ACTIVE
BEFORE INSERT OR UPDATE OR DELETE POSITION 0
AS
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

  if ( (SELECT COALESCE(z.ZAKSIEGOWANA,'N') from FAKT_ZB z where z.ID_FAKT_ZB =  iif(INSERTING,new.ID_FAKT_ZB,old.ID_FAKT_ZB)) = 'T') THEN
    EXCEPTION BLAD 'Faktura zaksiêgowana';
    
  if ((SELECT right(z.data_sp,8) from FAKT_ZB z where z.ID_FAKT_ZB = new.ID_FAKT_ZB) <> right(new.p_data,8)) THEN
    EXCEPTION BLAD 'Dla wype³nionej daty sprzeda¿y 
dopuszczone paragony z podanego miesi¹ca sprzeda¿y';  

  if ((SELECT z.data_sp from FAKT_ZB z where z.ID_FAKT_ZB = new.ID_FAKT_ZB) is not null) THEN
  begin
    if((SELECT count(distinct r.pacjent) FROM sprzedaz s join recepta r on s.id_apteki=r.id_apteki and r.id_recepta=s.id_recepta 
        where s.id_apteki=new.p_id_apteki and s.data=new.p_data and s.id_tranzakcje=new.p_id_tranzakcje)>1) THEN
    EXCEPTION BLAD 'Dla wype³nionej daty sprzeda¿y 
paragon nie mo¿e zawieraæ ró¿nych peseli';  
    if((SELECT r.pacjent FROM FAKT_ZB_ZAW join sprzedaz s on s.id_apteki=p_id_apteki and s.data=p_data and s.id_tranzakcje=p_id_tranzakcje 
     join recepta r on s.id_apteki=r.id_apteki and r.id_recepta=s.id_recepta where ID_FAKT_ZB = new.ID_FAKT_ZB order by pacjent nulls last rows 1)<>
    (SELECT list(distinct r.pacjent) FROM sprzedaz s join recepta r on s.id_apteki=r.id_apteki and r.id_recepta=s.id_recepta 
      where s.id_apteki=new.p_id_apteki and s.data=new.p_data and s.id_tranzakcje=new.p_id_tranzakcje)) THEN
    EXCEPTION BLAD 'Dla wype³nionej daty sprzeda¿y 
nie mo¿na dodawaæ transakcji z ró¿nymi peselami';  
   end
           
END^

create or alter procedure szukaj_Konta (nm VARCHAR(30)) 
RETURNS ( idapteka INTEGER, nazwa VARCHAR(256),pesel VARCHAR(12),adres VARCHAR(200))
as
BEGIN
  if (substring(nm from 1 for 1) similar to '[[:DIGIT:]]')  then
    FOR SELECT t.ID_KONTRAHENCI, t.NAZWA_PELNA,t.PESEL,t.ADRES FROM KONTRAHENCI k LEFT JOIN kontrahent (k.id_kontrahenci) t on 0=0
    WHERE k.PESEL STARTING :nm  ORDER by 2
    into idapteka , nazwa ,pesel ,adres do 
        SUSPEND;
  ELSE      
    FOR SELECT t.ID_KONTRAHENCI, t.NAZWA_PELNA,t.PESEL,t.ADRES FROM KONTRAHENCI k LEFT JOIN kontrahent (k.id_kontrahenci) t on 0=0
    WHERE k.NAZWA_PELNA CONTAINING :nm  or t.ADRES CONTAINING :nm  ORDER by 2
    into idapteka , nazwa ,pesel ,adres do 
        SUSPEND;
END^

create or ALTER PROCEDURE ean_ok (ea VARCHAR (40))  
RETURNS (res char(1))
as
DECLARE len INTEGER;
DECLARE waga INTEGER;
DECLARE suma INTEGER;
DECLARE ck INTEGER  ;
BEGIN
   res = 'T';
   if(ea not similar to '[0-9]{13,14}') then res = 'N';
   else
    BEGIN  
     len = CHARACTER_LENGTH(ea)-1;
     if (len=12) THEN
       waga = 3;
     ELSE
       waga = 1;  
     Suma = 0;
     WHILE (len > 0) do
     BEGIN
      Suma = Suma + waga * CAST(SUBSTRING(ea from len for 1) AS integer);
      waga = 4 - waga;
      len = len - 1;
     END
     ck=  mod( 10- mod(Suma,10) ,10);
     if (ck <> RIGHT(ea,1)) THEN
     BEGIN
       res = 'N';
     END
    END
  SUSPEND;
END^

create or ALTER TRIGGER ins_upd_ZDST_KLAS for ZDST_KLAS ACTIVE
BEFORE INSERT OR UPDATE POSITION 1
AS
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

 if (new.id_klasyfikacje=6 and (select(SELECT typs from typ_skladnika(z.id_apteki,z.id_towary)) FROM ZDST z where z.id_zdst=new.id_zdst)=1
     and (SELECT res from ean_ok(new.wartosc))='N' and new.wartosc not similar to '222%') THEN
     exception blad 'Surowiec recepturowy 
EAN '''||new.wartosc||''' jest nieprawid³owy'; 
END^


create or ALTER TRIGGER ins_upd_ZDST for ZDST ACTIVE
BEFORE INSERT OR UPDATE POSITION 1
AS
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

 if (new.data_wazn>dateadd (10 year to new.data) and new.data<>'1/1/2000' and exists(select*from towary where id_apteki=new.id_apteki and id_towary=new.id_towary and smopl_rap='T')) THEN
     new.data_wazn=null;
     
 if (new.data_wazn is null and exists(select*from dostawy where id_apteki=new.id_apteki and id_dostawy=new.id_dostawy and status is not null)) THEN
     new.data_wazn=old.data_wazn;       
     
END^

ALTER TRIGGER UPD_ZDST1 ACTIVE
BEFORE UPDATE POSITION 1
as
DECLARE dsp timestamp;
DECLARE dzw timestamp;
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

  if (NEW.STAN is null or new.stan<=0) then
  BEGIN
    new.czynny='N';

    if (not EXISTS (select r.ID_ZDST FROM RZDST r LEFT JOIN SPRZEDAZ s on r.ID_SPRZEDAZ=s.ID_SPRZEDAZ and r.ID_APTEKI=s.ID_APTEKI
        where r.ID_APTEKI=new.ID_APTEKI and r.ID_ZDST = new.ID_ZDST and (r.DATA < '01.01.1990'  or s.DATA < '01.01.1990' )) and new.DATA_ZAMKN is DISTINCT from '01.01.3000' ) THEN
    BEGIN
      SELECT max(r.DATA) from RZDST r where r.ID_APTEKI=new.ID_APTEKI and r.ID_ZDST = new.ID_ZDST INTO dsp;
      SELECT max(r.DATA) from ZDST r where r.ID_APTEKI=new.ID_APTEKI and r.KOREKTA_DO = new.ID_ZDST INTO dzw;
      if (dsp is not NULL) THEN
      BEGIN
        if (dzw is not null) THEN
          dsp = MAXVALUE(dzw,dsp);
      END
      ELSE
      BEGIN
        if (dzw is not null) then
          dsp = dzw;
        ELSE
          dsp = COALESCE(new.DATA_ZAMKN,'today');
      END
      if (new.DATA_ZAMKN is not null and (new.DATA_ZAMKN <> old.DATA_ZAMKN or old.DATA_ZAMKN is null)) THEN
        dsp =  MAXVALUE(dsp,new.DATA_ZAMKN);
      new.DATA_ZAMKN = dsp;
    END
    ELSE
    BEGIN
      new.DATA_ZAMKN = null;
    end
  END
  else
  BEGIN
    new.czynny='T';
    new.DATA_ZAMKN = null;
  END
end
^

CREATE  OR ALTER TRIGGER CT_RZDST FOR RZDST
ACTIVE AFTER UPDATE POSITION 99
AS
DECLARE st DOUBLE PRECISION;
DECLARE dt date;
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

    IF (OLD.DATA IS DISTINCT FROM NEW.DATA)
    THEN
    BEGIN
       SELECT z.STAN,z.DATA_ZAMKN FROM ZDST z where z.ID_APTEKI=new.ID_APTEKI and z.ID_ZDST=new.ID_ZDST into st,dt;
       if (new.DATA < '01.01.1990') THEN
       BEGIN
         if (dt is not null) THEN
            UPDATE ZDST z set z.DATA_ZAMKN = NULL WHERE  z.ID_APTEKI=new.ID_APTEKI and z.ID_ZDST=new.ID_ZDST;
       END
       ELSE
       if (st <= 0 and (dt is null or dt < new.DATA) AND 
         not EXISTS (select r.ID_ZDST FROM RZDST r LEFT JOIN SPRZEDAZ s on r.ID_SPRZEDAZ=s.ID_SPRZEDAZ and r.ID_APTEKI=s.ID_APTEKI
         where r.ID_APTEKI=new.ID_APTEKI and r.ID_ZDST = new.ID_ZDST and (r.DATA < '01.01.1990'  or s.DATA < '01.01.1990' )) ) THEN
       BEGIN
         UPDATE ZDST z set z.DATA_ZAMKN = new.DATA WHERE  z.ID_APTEKI=new.ID_APTEKI and z.ID_ZDST=new.ID_ZDST;
       END 
    END
END^

/* do porownan a nastepnie usuniecia  */
create or ALTER PROCEDURE STAN_DZIEN1 (
    IA INTEGER,
    IT INTEGER,
    DT TIMESTAMP )
RETURNS (
    ST NUMERIC(15,5),
    IZ DOUBLE PRECISION )
AS
declare variable ss numeric(15,5);
begin
/* stan na dzien ksiegowy wg procedury nowyspis - do usuniecia po weryfikacji zgodnosci */
  for select id_zdst,stan from zdst where id_apteki=:ia and id_towary=:it and data<=:dt into iz,st do
  begin
    select sum(r.sztuk_jp) from rzdst r left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
      where r.id_apteki=:ia and r.id_zdst=:iz and (s.data>:dt or s.data<'01/01/1901') into :ss;
    if (not ss is null) then
       st=st+ss;
    ss=null;
    select sum(r.sztuk_jp) from zdst r left join dostawy d on r.id_apteki=d.id_apteki and r.id_dostawy=d.id_dostawy
        where r.id_apteki=:ia and r.korekta_do=:iz and r.data>:dt and d.status in ('Z','P') into :ss;
    if (not ss is null) then
       st=st-ss;
    if (st<>0) then
    suspend;
  end
end^


ALTER PROCEDURE STAN_DZIEN (
    IA INTEGER,
    IT INTEGER,
    DT TIMESTAMP )
RETURNS (
    ST NUMERIC(15,5),
    IZ DOUBLE PRECISION )
AS
declare variable ss numeric(15,5);
begin
/* stan na dzien ksiegowy wg procedury nowyspis */
  for select id_zdst,stan from zdst where (DATA_ZAMKN is NULL or DATA_ZAMKN >= :dt) AND  id_apteki=:ia and id_towary=:it and data<=:dt into iz,st do
  begin
    select sum(r.sztuk_jp) from rzdst r left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
      where r.id_apteki=:ia and r.id_zdst=:iz and (s.data>:dt or s.data<'01/01/1901') into :ss;
    if (not ss is null) then
       st=st+ss;
    ss=null;
    select sum(r.sztuk_jp) from zdst r left join dostawy d on r.id_apteki=d.id_apteki and r.id_dostawy=d.id_dostawy
        where r.id_apteki=:ia and r.korekta_do=:iz and r.data>:dt and d.status in ('Z','P') into :ss;
    if (not ss is null) then
       st=st-ss;
    if (st<>0) then
    suspend;
  end
end^

/* Restore proc. body: STAN_DZIENW */
ALTER PROCEDURE STAN_DZIENW(IA INTEGER,
IT INTEGER,
DT DATE)
 RETURNS(STAN NUMERIC(15,5),
WARTOSC NUMERIC(15,5))
 AS
declare variable st numeric(15,5);
declare variable IZ Double precision;
begin
  stan=0;
  wartosc=0;
  for select st,iz from stan_dzien(:ia,:it,:dt) into st,iz do
  begin
    stan=stan+st;
    wartosc=wartosc+st*(select cena_nt_jp from ceny_dostawy where id_apteki=:ia and id_zdst=:iz and id_ceny=1);        
  end
  suspend;
end
^

ALTER PROCEDURE SMOPL_STANY (
    IA INTEGER,
    IZ DOUBLE PRECISION,
    DT TIMESTAMP )
RETURNS (
    TDI DOUBLE PRECISION,
    SDI DOUBLE PRECISION,
    TWI DOUBLE PRECISION,
    SWI DOUBLE PRECISION,
    TDW DOUBLE PRECISION,
    SDW DOUBLE PRECISION,
    TWW DOUBLE PRECISION,
    SWW DOUBLE PRECISION )
AS
DECLARE it INTEGER;
DECLARE se VARCHAR(50);
BEGIN
  SELECT FIRST 1 z.ID_TOWARY,COALESCE(s.WARTOSC,'')
  FROM ZDST z
  LEFT JOIN ZDST_KLAS s on s.ID_APTEKI=z.ID_APTEKI and s.ID_ZDST=z.ID_ZDST and s.ID_KLASYFIKACJE=5
  WHERE  z.ID_APTEKI=:ia and z.ID_ZDST=:iz
  ORDER by 2 DESC INTO it,se  ;
  
  SELECT round(sum(CASE WHEN WARTOSC=:se THEN STAN + sprz - blokada ELSE 0 END),4) , round(sum(CASE WHEN WARTOSC=:se THEN (STAN + sprz - blokada) * cena ELSE 0 END),4) ,
  round(sum(CASE WHEN WARTOSC=:se THEN blokada ELSE 0 END),4) , round(sum(CASE WHEN WARTOSC=:se THEN blokada * cena ELSE 0 END),4) ,
  round(sum(STAN + sprz - blokada),4) , round(sum((STAN + sprz - blokada) * cena),4) ,  round(sum(blokada),4) , round(sum(blokada * cena),4) 
  from (
  SELECT z.STAN,case when coalesce(blokada,'N')='N' then 0 else coalesce(ile_blokada,z.stan) end blokada,COALESCE(s.WARTOSC,'') WARTOSC,
     c.cena_nt_jp cena,
      COALESCE((select sum(r.SZTUK_JP) from RZDST r
      LEFT JOIN SPRZEDAZ s on r.ID_SPRZEDAZ=s.ID_SPRZEDAZ and r.ID_APTEKI=s.ID_APTEKI
      LEFT JOIN TRANZAKCJE t on s.DATA=t.DATA and s.ID_TRANZAKCJE=t.ID_TRANZAKCJE and s.ID_APTEKI=t.ID_APTEKI 
      where r.ID_ZDST=z.ID_ZDST and r.ID_APTEKI=z.ID_APTEKI AND r.SZTUK_JP>0 AND (t.DATA + (coalesce(t.GODZINA,0) * (60*60) + t.ID_TRANZAKCJE)/(60*60*24) > :dt or s.DATA<'01/01/1901') ),0) sprz
  from ZDST z
  LEFT JOIN DOSTAWY d on z.ID_DOSTAWY=d.ID_DOSTAWY and z.ID_APTEKI=d.ID_APTEKI
  left join ceny_dostawy c on z.id_apteki=c.id_apteki and z.id_zdst=c.id_zdst and c.id_ceny=1
  LEFT JOIN ZDST_KLAS s on s.ID_APTEKI=z.ID_APTEKI and s.ID_ZDST=z.ID_ZDST and s.ID_KLASYFIKACJE=5
  where Z.ID_APTEKI=:ia and Z.ID_TOWARY=:it and (z.DATA_ZAMKN is null  or z.DATA_ZAMKN >= :dt)
  and d.DATA + (EXTRACT(HOUR FROM d.IFUPDDATE)*(60*60*1000)  + EXTRACT(MINUTE FROM d.IFUPDDATE)*(60*1000) + EXTRACT(SECOND FROM d.IFUPDDATE)*(1000) + mod(d.ID_DOSTAWY,1000))/(1000*60*60*24) - 0.001 <= :dt)
  INTO SDI,SDW,SWI,SWW,tdi,tdw,TWI,TWW;
  
  SUSPEND;
END
^

ALTER PROCEDURE ZAPLACONE (
    IDA INTEGER,
    IDD INTEGER,
    DT_OD TIMESTAMP,
    DT_DO TIMESTAMP,
    KONTO VARCHAR(12),
    TYP1  VARCHAR(1),
    TYP2  VARCHAR(1) )
RETURNS (
    DT_ZP TIMESTAMP,
    DT_ZK TIMESTAMP,
    DT_RV TIMESTAMP,
    KWZ DOUBLE PRECISION )
AS
declare variable idr integer;
declare variable kwt double precision;
declare variable dtz date;
declare variable dtd date;
DECLARE peln INT;
DECLARE sprz int;
DECLARE dtw date;
DECLARE atv INT;
DECLARE ffp INT;
begin
  select data,data_pl,COALESCE(d.DATA_WY,d.DATA),d.ATRVAT from dokumenty d where id_apteki=:ida and id_dokumenty=:idd into dtd,dtz,dtw,atv;
  
  if (bin_and(atv,bin_shl(1,29)) > 0) THEN 
    ffp = 1;
  ELSE
    ffp = 0;
  if (typ2 is DISTINCT FROM 'K' or ffp = 1 or dtz is null) THEN
  BEGIN
    if (ffp = 1) THEN
      dtd = dtw;
    dt_zp=dtd;
    dt_zk=dtd;
    dt_rv=dtd; 
  END
  ELSE
  BEGIN      
    if (konto STARTING 'SP' or typ1 in ('K','U','W','E','N','A','I','B','5','6','7')) THEN
      sprz = 1;
    ELSE
      sprz = 0;
    if (konto STARTING 'ZK' and sprz = 0) THEN
      peln = -1;
    ELSE
      peln = 0;
    select max(t.id_dekrety),sum(t.kwota)
     from dokumenty d
     left join dekrety t on d.id_apteki=t.id_apteki and d.id_dokumenty=t.id_dokumenty
     where d.id_apteki=:ida and  d.powiazany_z=:idd and t.konto like 'R%' into idr,kwt;
    if (idr is not null) then
    begin
      select sum(p.kwota),min(o.data),max(o.data)
        from pow_fk p
        left join dekrety d on p.id_apteki=d.id_apteki and p.id_dekrety = d.id_dekrety
        left join dokumenty o on d.id_apteki =o.id_apteki and d.id_dokumenty=o.id_dokumenty
      where p.id_a2=:ida and p.id_d2=:idr and o.data>=:dt_od and o.data<=:dt_do
        into :kwz,:dt_zp,:dt_zk;
      if (peln=-1 and abs(kwt) - abs(kwz) > 0.005) then
       begin
        dt_zp=null;
        dt_zk=null;
       end
    end
    if (peln>0 and (dt_zp is null or dt_zp>dtd+peln)) then
    begin
      dt_zp=dtd+peln;
      dt_zk=dt_zp;
    end
    if (sprz = 1) THEN
      dt_rv = dt_zp;
    ELSE
      dt_rv = dt_zk;  
  END
  suspend;
end^


ALTER PROCEDURE OSOZ_MAG(IA INTEGER,
IT INTEGER,
DT DATE,
IZ DOUBLE PRECISION)
 RETURNS(MAG_ID_POZ_APT VARCHAR(9),
MAG_ILOSC DOUBLE PRECISION,
MAG_CENA_NETTO_RABAT DOUBLE PRECISION,
MAG_CENA_BRUTTO_RABAT DOUBLE PRECISION,
MAG_CENA_NETTO DOUBLE PRECISION,
MAG_CENA_BRUTTO DOUBLE PRECISION,
MAG_CENA_DETAL_NETTO DOUBLE PRECISION,
MAG_CENA_DETAL_BRUTTO DOUBLE PRECISION,
MAG_DATA_STANU DATE,
MAG_ILOSC_SPR DOUBLE PRECISION,
ID_DOSTAWCY VARCHAR(9),
NAZWA_DOSTAWCY VARCHAR(300),
NIP_DOSTAWCY VARCHAR(30),
NUMER_ZEZWOLENIA VARCHAR(50),
SYMBOL_FAKT_ZAK VARCHAR(25),
SYMBOL_WEWN_FAKT_ZAK VARCHAR(25))
 AS
DECLARE id DOUBLE PRECISION;
BEGIN
  if (it<>0)  THEN
  BEGIN
    select right( round(min(z.ID_ZDST),0),9),COALESCE(round(sum(z.STAN),5),0),COALESCE(round(sum(z.STAN*r.CENA_NT),2),0),COALESCE(round(sum(z.STAN*r.CENA_BR),2),0),
      COALESCE(round(sum(z.STAN*c.CENA_NT),2),0),COALESCE(round(sum(z.STAN*c.CENA_BR),2),0),COALESCE(round(sum(s.CENA_NT*z.STAN),2),0),COALESCE(round(sum(s.CENA_BR*z.STAN),2),0),
      min(z.ID_ZDST),round(sum(z.STAN - IIF( coalesce(z.blokada,'N')='N' , 0 , coalesce(z.ile_blokada,z.stan))),5) 
    from ZDST z
    left JOIN CENY_DOSTAWY r on r.ID_APTEKI=z.ID_APTEKI and r.ID_ZDST=z.ID_ZDST and r.ID_CENY=2
    left JOIN CENY_DOSTAWY c on c.ID_APTEKI=z.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,:dt,z.id_zdst,'') s on 0=0
    where z.ID_APTEKI=:ia and z.ID_TOWARY=:it and z.CZYNNY='T' INTO
     mag_id_poz_apt,mag_ilosc,
     mag_cena_netto_rabat,mag_cena_brutto_rabat,
     mag_cena_netto,mag_cena_brutto,
     mag_cena_detal_netto,mag_cena_detal_brutto,id,mag_ilosc_spr;
    
    if (mag_id_poz_apt is null) THEN
    BEGIN
      SELECT FIRST 1 right( round(z.ID_ZDST,0),9),z.ID_ZDST from zdst z where z.ID_APTEKI=:ia and z.ID_TOWARY=:it
      ORDER by z.DATA DESC into mag_id_poz_apt,id;
      if (mag_id_poz_apt is null) THEN
        mag_id_poz_apt = it;
      mag_ilosc = 0;
      mag_cena_netto_rabat = 0;
      mag_cena_brutto_rabat = 0;
      mag_cena_netto = 0;
      mag_cena_brutto = 0;
      mag_cena_detal_netto = 0;
      mag_cena_detal_brutto = 0;
      mag_ilosc_spr = 0;
    end 
    if (iz is NULL) THEN    
      iz = id;
    mag_data_stanu = CURRENT_TIMESTAMP(1);
  END
  if (iz is not null) THEN
  BEGIN
    if ((SELECT COUNT(*) from OSOZ_USLUGI u WHERE u.OPCJA='RSFZ' AND u.WARTOSC = 'T')>0) THEN  
      SELECT LEFT(d.NR_FAKTURY,25),LEFT(CASE WHEN d.ID_KONTRAHENCI < 0 THEN 'MMP' ELSE CASE WHEN d.ID_KONTRAHENCI=0 THEN 'PW' ELSE 'PZ' END END || d.NR_REJ,25)
       FROM ZDST z LEFT JOIN DOSTAWY d on z.ID_DOSTAWY=d.ID_DOSTAWY and z.ID_APTEKI = d.ID_APTEKI
       WHERE z.ID_APTEKI = :ia and z.ID_ZDST = :iz  
      INTO symbol_fakt_zak,symbol_wewn_fakt_zak;
    if ((SELECT COUNT(*) from OSOZ_USLUGI u WHERE u.OPCJA='PHRT' AND u.WARTOSC = 'T')>0) THEN
    BEGIN
       SELECT u.ID_KS,u.NAZWA,COALESCE(u.NIP,y.NIP),u.ZEZWOLENIE
       FROM ZDST z 
       LEFT JOIN DOSTAWY d on d.ID_DOSTAWY=z.ID_DOSTAWY and d.ID_APTEKI=z.ID_APTEKI
       LEFT JOIN KONTRAHENCI y on d.ID_KONTRAHENCI = y.ID_KONTRAHENCI
       LEFT JOIN REJESTR_HURTOWNI u on u.ID = COALESCE(d.KOD_HURTOWNI,iif(y.SMOPL_MDIDP='SE' or y.SMOPL_MDIDP='IE',0,y.SMOPL_MDIDP))
       WHERE z.ID_APTEKI = :ia and z.ID_ZDST = :iz
       INTO ID_DOSTAWCY, NAZWA_DOSTAWCY , NIP_DOSTAWCY, NUMER_ZEZWOLENIA;
       

       if (NOT EXISTS (SELECT NIP FROM OSOZ_DOSTAWCY d where replace(d.NIP,'-','')= replace(:NIP_DOSTAWCY,'-',''))) THEN
       BEGIN
         ID_DOSTAWCY = NULL;
         NAZWA_DOSTAWCY = NULL;
         NIP_DOSTAWCY = NULL;
         NUMER_ZEZWOLENIA = NULL;
       END
    END  
  END
  SUSPEND;
end
^

create or alter PROCEDURE KLAS_TOW (
    IA INTEGER,
    IT INTEGER,
    IK INTEGER )
RETURNS (
    WARTKL VARCHAR(40) )
AS
BEGIN
  if (ik=6) then
  SELECT ean_ref from Towary WHERE ID_TOWARY=:it and ID_APTEKI=:ia into wartkl;
  if (char_length(coalesce(wartkl,''))<13) then 
  SELECT first 1 k.WARTOSC from TW_KLAS k WHERE k.ID_TOWARY=:it and k.ID_KLASYFIKACJE=:ik and k.ID_APTEKI=:ia
  ORDER by k.IFUPDDATE DESC into wartkl;
  SUSPEND;
END
^

ALTER PROCEDURE OSOZ_TRANSAKCJA (
    IA INTEGER,
    DT TIMESTAMP,
    IT INTEGER,
    PP CHAR(1),
    TR CHAR(1),
    TS CHAR(1),
    BR CHAR(1) )
RETURNS (
    ID_RECEPTA INTEGER,
    ATRYBUTY VARCHAR(12),
    DATA_WYST TIMESTAMP,
    DATA_PRZYJ TIMESTAMP,
    NR_W_DNIU INTEGER,
    NUMER VARCHAR(50),
    TRYB INTEGER,
    ID_TOWARY INTEGER,
    PACJENT VARCHAR(20),
    TYP_NR_PAC VARCHAR(1),
    WARTOSC DOUBLE PRECISION,
    ODPLATNOSC DOUBLE PRECISION,
    DOPLATA DOUBLE PRECISION,
    NIE_ZAMIENIAC VARCHAR(1),
    NAZWA VARCHAR(100),
    EAN VARCHAR(20),
    STAWKA_VAT DOUBLE PRECISION,
    SPTRYB VARCHAR(1),
    IOT VARCHAR(20),
    IOS VARCHAR(20),
    IOR VARCHAR(20),
    IOC VARCHAR(20),
    BLOZ7 VARCHAR(20),
    DATA TIMESTAMP,
    ID_APTEKI INTEGER,
    ILOSC DOUBLE PRECISION,
    CENA_ZAK DOUBLE PRECISION,
    CENA_ZAK_BU DOUBLE PRECISION,
    ID_ODPLATNOSC INTEGER,
    IFUPDDATE TIMESTAMP,
    ID_SPRZEDAZ INTEGER,
    DTTR TIMESTAMP,
    DTTK TIMESTAMP,
    MAG_ID_POZ_APT VARCHAR(9),
    MAG_ILOSC DOUBLE PRECISION,
    MAG_CENA_NETTO_RABAT DOUBLE PRECISION,
    MAG_CENA_BRUTTO_RABAT DOUBLE PRECISION,
    MAG_CENA_NETTO DOUBLE PRECISION,
    MAG_CENA_BRUTTO DOUBLE PRECISION,
    MAG_CENA_DETAL_NETTO DOUBLE PRECISION,
    MAG_CENA_DETAL_BRUTTO DOUBLE PRECISION,
    MAG_DATA_STANU TIMESTAMP,
    MAG_ILOSC_SPR DOUBLE PRECISION,
    ID_DOSTAWCY VARCHAR(9),
    NAZWA_DOSTAWCY VARCHAR(300),
    NIP_DOSTAWCY VARCHAR(30),
    NUMER_ZEZWOLENIA VARCHAR(50),
    SYMBOL_FAKT_ZAK VARCHAR(25),
    SYMBOL_WEWN_FAKT_ZAK VARCHAR(20),
    ID_USER INTEGER,
    JAKITRYB CHAR(1),
    NR_KOREKTY INTEGER,
    NR_WYSYLKI INTEGER,
    POZYCJA INTEGER,
    ILOSC_JP DOUBLE PRECISION,
    CENA DOUBLE PRECISION,
    ODPL_JP DOUBLE PRECISION,
    idzdst VARCHAr(9) )
AS
DECLARE dt_t_korygowanej date;
DECLARE id_t_korygowanej INTEGER;
DECLARE dtt date;
DECLARE recid INTEGER;
DECLARE idSp INTEGER;
DECLARE stare_korekty integer;
DECLARE idz DOUBLE PRECISION;
BEGIN  

SELECT COALESCE(t.IFINSDATE,t.DATA),t.KOR_DT,t.KOR_TR,t.ID_USER,t.ID_OSOZ,t.ID_OSOZ_OTC FROM TRANZAKCJE t WHERE t.DATA = :dt AND t.ID_TRANZAKCJE = :it and t.ID_APTEKI = :ia
INTO dttr,dt_t_korygowanej,id_t_korygowanej,id_user,iot,ioc;

if (id_t_korygowanej is null) THEN
BEGIN
  SELECT FIRST 1 s.TRYB from SPRZEDAZ s  where s.id_tranzakcje=:it and s.id_apteki=:ia and s.data=:dt  INTO sptryb;
  if (sptryb <> 'S') THEN
    SELECT FIRST 1 a.DATA,a.ID_TRANZAKCJE FROM SPRZEDAZ s
    LEFT JOIN ZMIANY z on s.ID_SPRZEDAZ = z.ID_SPRZEDAZ and z.ID_APTEKI = s.ID_APTEKI
    LEFT JOIN SPRZEDAZ a on z.POPRZEDNI = a.ID_SPRZEDAZ AND a.ID_APTEKI = z.ID_APTEKI
    WHERE s.id_tranzakcje=:it and s.id_apteki=:ia and s.data=:dt and s.TRYB = 'Z' INTO dt_t_korygowanej,id_t_korygowanej ;
END
stare_korekty = 0;
if (id_t_korygowanej is NOT null) THEN
BEGIN
  SELECT FIRST 1 s.ID_SPRZEDAZ FROM SPRZEDAZ s 
  LEFT JOIN TW_KLAS k on s.ID_TOWARY = k.ID_TOWARY and k.ID_KLASYFIKACJE = 3 and k.ID_APTEKI=s.ID_APTEKI
  LEFT JOIN OSOZ_BRAC_SP(k.WARTOSC,s.DATA,:tr,:ts,:pp) y on 0=0
  where s.id_tranzakcje=:it and s.id_apteki=:ia and s.data=:dt and (y.BS='T' or y.BM='T')
  ORDER by s.ID_SPRZEDAZ into idSp;

  SELECT COUNT(*)  FROM HIST_KOREKTY(:ia,:idsp) h 
  LEFT JOIN SPRZEDAZ s on s.ID_SPRZEDAZ = h.IDSP and s.ID_APTEKI = :ia
  LEFT JOIN TRANZAKCJE t on t.DATA=s.DATA and t.ID_TRANZAKCJE=s.ID_TRANZAKCJE AND t.ID_APTEKI=s.ID_APTEKI
  WHERE t.ID_OSOZ is not null and s.ID_SPRZEDAZ<:idSp and s.TRYB<>'Z' into NR_KOREKTY;
  
  SELECT FIRST 1 COALESCE(t.IFINSDATE,t.DATA),t.ID_OSOZ,t.ID_OSOZ_OTC,t.DATA,t.ID_USER,s.ID_OSOZ  FROM HIST_KOREKTY(:ia,:idsp) h LEFT JOIN SPRZEDAZ s on s.ID_SPRZEDAZ = h.IDSP and s.ID_APTEKI = :ia  
   LEFT JOIN TRANZAKCJE t on t.DATA=s.DATA and t.ID_TRANZAKCJE=s.ID_TRANZAKCJE AND t.ID_APTEKI=s.ID_APTEKI ORDER by h.WERSJA INTO dttk,IOT,IOC,dtt,id_user,ios;
  
  if (IOT STARTING 'B' OR IOT STARTING 'N') THEN  /* korekta do niewyslanej transakcji*/
    exit;
  
  if (ios is NOT NULL) THEN
  BEGIN
    stare_korekty = 1;
    ios = null;  
  end  

  if (dttr - dt > 1)  THEN
    dttr = dt;
  if (dttr < dttk) THEN
    dttr = dttk + 0.001;
    
  if ((SELECT count(*) FROM SPRZEDAZ s where s.id_tranzakcje=:it and s.id_apteki=:ia and s.data=:dt and s.TRYB = 'Z') =
      (SELECT count(*) FROM SPRZEDAZ s where s.id_tranzakcje=:it and s.id_apteki=:ia and s.data=:dt and (s.TRYB = 'P' or (s.TRYB = 'R' AND :BR = 'N')))) THEN
     EXIT ;  /* transakcja koryguj¹ca bez zmiany */
  
END
ELSE
BEGIN
  dtt = dt;
END

if (stare_korekty = 1) then
FOR  SELECT a.*,o.* FROM
       (select s.id_recepta,r.ATRYBUTY,r.DATA_WYST,r.DATA_PRZYJ,r.nr_w_dniu,r.numer,r.tryb,s.id_towary,r.PACJENT,r.TYP_NR_PAC,
        s.wartosc , s.odplatnosc, s.doplata ,s.NIE_ZAMIENIAC,t.nazwa, 
       (select max(wartosc) from tw_klas where id_apteki=s.id_apteki and id_towary=s.id_towary and id_klasyfikacje=6)  EAN,s.STAWKA_VAT,s.tryb SPTRYB,s.ID_OSOZ ios,r.ID_OSOZ ior,
       (select max(wartosc) from tw_klas where id_apteki=s.id_apteki and id_towary=s.id_towary and id_klasyfikacje=3) BLOZ7,s.data,s.id_apteki, 
       (select sum(SZTUK_jp) from rzdst where id_apteki=s.id_apteki and id_sprzedaz=s.id_sprzedaz) ILOSC,s.CENA_ZAK,s.id_odplatnosc,r.ifupddate,s.id_sprzedaz
       from  sprzedaz s
        left join recepta r on s.id_apteki=r.id_apteki and r.id_recepta=s.id_recepta 
        left join towary t on s.id_apteki=t.id_apteki and t.id_towary=s.id_towary 
        where s.id_tranzakcje=:it and s.id_apteki=:ia and s.data=:dt  and s.id_towary>0 and s.TRYB = 'Z' ) a 
        LEFT JOIN OSOZ_BRAC_SP(a.BLOZ7,:dtt,:tr,:ts,:pp) y on 0=0
        LEFT JOIN osoz_mag (a.id_apteki,IIF(y.BM='T',a.id_towary,0),a.data,(select first 1 id_zdst from rzdst where id_apteki=a.id_apteki and id_sprzedaz=a.id_sprzedaz)) o on 0=0
        order by sptryb desc, a.id_recepta nulls last
        
INTO  ID_RECEPTA, ATRYBUTY, DATA_WYST, DATA_PRZYJ, NR_W_DNIU, NUMER, TRYB, ID_TOWARY, PACJENT, TYP_NR_PAC, WARTOSC, ODPLATNOSC, DOPLATA, NIE_ZAMIENIAC, NAZWA, EAN, STAWKA_VAT, SPTRYB, IOS, IOR,  BLOZ7, DATA,
      ID_APTEKI, ILOSC, CENA_ZAK, ID_ODPLATNOSC, IFUPDDATE, ID_SPRZEDAZ, MAG_ID_POZ_APT, MAG_ILOSC, MAG_CENA_NETTO_RABAT, MAG_CENA_BRUTTO_RABAT, MAG_CENA_NETTO, 
      MAG_CENA_BRUTTO, MAG_CENA_DETAL_NETTO, MAG_CENA_DETAL_BRUTTO, MAG_DATA_STANU,mag_ilosc_spr ,ID_DOSTAWCY, NAZWA_DOSTAWCY ,
      NIP_DOSTAWCY, NUMER_ZEZWOLENIA, SYMBOL_FAKT_ZAK, SYMBOL_WEWN_FAKT_ZAK 
DO 
BEGIN
  CENA_ZAK_BU = CENA_ZAK;
  if (id_recepta is not null) THEN
    SELECT FIRST 1 r.ID_RECEPTA
        FROM SPRZEDAZ s LEFT JOIN ZMIANY z on z.ID_SPRZEDAZ = s.ID_SPRZEDAZ and z.ID_APTEKI = s.ID_APTEKI
        LEFT JOIN SPRZEDAZ n on z.NASTEPNY = n.ID_SPRZEDAZ and z.ID_APTEKI = n.ID_APTEKI LEFT JOIN RECEPTA r on n.ID_RECEPTA = r.ID_RECEPTA and n.ID_APTEKI = r.ID_APTEKI
        WHERE s.DATA = :dt and s.ID_TRANZAKCJE = :it and s.ID_APTEKI = :ia and s.ID_RECEPTA = :ID_RECEPTA AND r.ID_RECEPTA is not NULL
        INTO recid;
  ELSE
    recid = null;  
  JAKITRYB = 'U'; 
  if (id_recepta is NULL or recid is not NULL) THEN
      BEGIN
        if (EXISTS ( SELECT y.BS FROM SPRZEDAZ s 
        LEFT JOIN OSOZ_BRAC_SP((select max(wartosc) from tw_klas where id_apteki=s.id_apteki and id_towary=s.id_towary and id_klasyfikacje=3),:dtt,:tr,:ts,:pp) y on 0=0
        where  s.DATA = :dt and s.ID_TRANZAKCJE = :it and s.ID_APTEKI = :ia AND s.TRYB <> 'Z' and  s.ID_RECEPTA is not DISTINCT FROM :recid and y.BS='T') ) THEN
        jakitryb = 'M';    
  END

  SELECT FIRST 1 s.ID_OSOZ,r.ID_OSOZ  FROM HIST_KOREKTY(:ia,:id_sprzedaz) z LEFT JOIN SPRZEDAZ s on z.IDSP = s.ID_SPRZEDAZ and s.ID_APTEKI= :ia LEFT JOIN RECEPTA r on s.ID_RECEPTA = r.ID_RECEPTA and s.ID_APTEKI = r.ID_APTEKI
    ORDER by z.WERSJA
    INTO ios,ior;
  if (jakitryb = 'M' and ios is null) THEN
       jakitryb = 'D';
  if (ios is not null) THEN
    SUSPEND;         
END

FOR select s.id_recepta,r.ATRYBUTY,r.DATA_WYST,r.DATA_PRZYJ,r.nr_w_dniu,r.numer,r.tryb,z.id_towary,r.PACJENT,r.TYP_NR_PAC,
        s.WARTOSC , s.odplatnosc , s.doplata ,s.NIE_ZAMIENIAC,t.nazwa,ean.WARTKL EAN,s.STAWKA_VAT,s.tryb SPTRYB,z.ID_OSOZ ios,r.ID_OSOZ ior,
        blz.WARTKL  BLOZ7,s.data,s.id_apteki,s.SZTUK * jp.MNOZ / jp.DZIEL,round(c.CENA_NT_JP,2) cena_zak,s.id_odplatnosc,r.ifupddate,s.id_sprzedaz,o.*,z.POZYCJA,
        (s.odplatnosc + s.DOPLATA) * round(z.cena * (100 - COALESCE(s.UPUST ,0))*0.01,2)  * z.SZTUK_JP / s.WARTOSC, round(z.cena * (100 - COALESCE(s.UPUST ,0))*0.01,2)
         ,z.SZTUK_JP,z.ID_ZDST,b.CENA_NT
        from  sprzedaz s
        left join recepta r on s.id_apteki=r.id_apteki and r.id_recepta=s.id_recepta 
        left join ilosc_jp(s.id_apteki,s.id_towary,s.jednostka) jp on 0=0
        join rzdst z on z.ID_SPRZEDAZ=s.ID_SPRZEDAZ and z.ID_APTEKI=s.ID_APTEKI
        left join CENY_DOSTAWY c on z.ID_ZDST=c.ID_ZDST and c.ID_APTEKI=z.ID_APTEKI and c.ID_CENY=1 
        left join CENY_DOSTAWY b on z.ID_ZDST=b.ID_ZDST and b.ID_APTEKI=z.ID_APTEKI and b.ID_CENY=2 
        join  klas_tow (z.ID_APTEKI,z.ID_TOWARY,3) blz on 0=0
        left join  klas_tow (z.ID_APTEKI,z.ID_TOWARY,6) ean on 0=0
        join towary t on z.id_apteki=t.id_apteki and t.id_towary=z.id_towary 
        LEFT JOIN OSOZ_BRAC_SP(blz.WARTKL,:dtt,:tr,:ts,:pp) y on 0=0
        LEFT JOIN osoz_mag (z.id_apteki,IIF(y.BM='T',z.id_towary,0),z.data,z.ID_ZDST) o on 0=0
        where s.id_tranzakcje=:it and s.id_apteki=:ia and s.data=:dt  and s.id_towary<>0 and s.WARTOSC <> 0 and z.ID_ZDST <> -1
          AND ((((BS='T' and s.TRYB <> 'Z')  or (z.ID_OSOZ is not null and :stare_korekty = 0)) and (id_recepta is not null or y.BM='T' or 'P' ='P'))  or  o.NIP_DOSTAWCY is not NULL)
        order by sptryb desc, s.id_recepta nulls last,s.ID_SPRZEDAZ
        
INTO  ID_RECEPTA, ATRYBUTY, DATA_WYST, DATA_PRZYJ, NR_W_DNIU, NUMER, TRYB, ID_TOWARY, PACJENT, TYP_NR_PAC, WARTOSC, ODPLATNOSC, DOPLATA, NIE_ZAMIENIAC, NAZWA, EAN, STAWKA_VAT, SPTRYB, IOS, IOR,  BLOZ7, DATA,
      ID_APTEKI, ILOSC, CENA_ZAK, ID_ODPLATNOSC, IFUPDDATE, ID_SPRZEDAZ, MAG_ID_POZ_APT, MAG_ILOSC, MAG_CENA_NETTO_RABAT, MAG_CENA_BRUTTO_RABAT, MAG_CENA_NETTO, 
      MAG_CENA_BRUTTO, MAG_CENA_DETAL_NETTO, MAG_CENA_DETAL_BRUTTO, MAG_DATA_STANU,mag_ilosc_spr ,ID_DOSTAWCY, NAZWA_DOSTAWCY ,
      NIP_DOSTAWCY, NUMER_ZEZWOLENIA, SYMBOL_FAKT_ZAK, SYMBOL_WEWN_FAKT_ZAK,POZYCJA ,ODPL_JP,CENA,ILOSC_JP,idz,CENA_ZAK_BU
DO 
BEGIN
  if (SPTRYB = 'S' or (SPTRYB = 'K' and (SELECT z.POPRZEDNI FROM ZMIANY z WHERE z.ID_APTEKI = :ia and z.ID_SPRZEDAZ = :ID_SPRZEDAZ) is NULL )) THEN
  BEGIN
    if (iot is null or iot STARTING 'B'  OR IOT STARTING 'N') THEN
    BEGIN
       JAKITRYB = 'D';
       iot = null;
       ioc = null;
    END
    ELSE
    BEGIN
       JAKITRYB = 'M';   
       SPTRYB = 'X';
       if (NR_WYSYLKI is null) THEN
         SELECT COUNT( DISTINCT LEFT (s.ID_OSOZ,7))  from SPRZEDAZ s where s.id_tranzakcje=:it and s.id_apteki=:ia and s.data=:dt and s.ID_OSOZ is not NULL into nr_wysylki;
    END   
  END  
  ELSE
  BEGIN
    if (SPTRYB = 'Z') THEN
    BEGIN
      if (id_recepta is not null) THEN
        SELECT FIRST 1 r.ID_RECEPTA
        FROM SPRZEDAZ s LEFT JOIN ZMIANY z on z.ID_SPRZEDAZ = s.ID_SPRZEDAZ and z.ID_APTEKI = s.ID_APTEKI
        LEFT JOIN SPRZEDAZ n on z.NASTEPNY = n.ID_SPRZEDAZ and z.ID_APTEKI = n.ID_APTEKI LEFT JOIN RECEPTA r on n.ID_RECEPTA = r.ID_RECEPTA and n.ID_APTEKI = r.ID_APTEKI
        WHERE s.DATA = :dt and s.ID_TRANZAKCJE = :it and s.ID_APTEKI = :ia and s.ID_RECEPTA = :ID_RECEPTA AND r.ID_RECEPTA is not NULL
        INTO recid;
      ELSE
        recid = null;  
      JAKITRYB = 'U'; 
      if (id_recepta is NULL or recid is not NULL) THEN
      BEGIN
        if (EXISTS ( SELECT y.BS FROM SPRZEDAZ s 
        LEFT JOIN OSOZ_BRAC_SP((select max(wartosc) from tw_klas where id_apteki=s.id_apteki and id_towary=s.id_towary and id_klasyfikacje=3),:dtt,:tr,:ts,:pp) y on 0=0
        where  s.DATA = :dt and s.ID_TRANZAKCJE = :it and s.ID_APTEKI = :ia AND s.TRYB <> 'Z' and  s.ID_RECEPTA is not DISTINCT FROM :recid and y.BS='T') ) THEN
        jakitryb = 'M';    
      END
    END
    ELSE
    BEGIN
      jakitryb = 'M';
    END  
    SELECT FIRST 1 d.ID_OSOZ,r.ID_OSOZ  FROM HIST_KOREKTY(:ia,:id_sprzedaz) z LEFT JOIN SPRZEDAZ s on z.IDSP = s.ID_SPRZEDAZ and s.ID_APTEKI= :ia 
       LEFT JOIN RECEPTA r on s.ID_RECEPTA = r.ID_RECEPTA and s.ID_APTEKI = r.ID_APTEKI
       LEFT JOIN RZDST d on d.ID_SPRZEDAZ=s.ID_SPRZEDAZ and d.ID_APTEKI=s.ID_APTEKI
    WHERE d.ID_ZDST = :idz   
    ORDER by z.WERSJA
      INTO ios,ior;
    if (jakitryb = 'M' and ios is null) THEN
       jakitryb = 'D';
      
  END   
  idzdst =  right( round(idz,0),9);
  SUSPEND;         
END

end
^

ALTER PROCEDURE CBT_NAJM (
    ICT INTEGER )
RETURNS (
    ICN INTEGER,
    OPN INTEGER,
    NMO VARCHAR(30),
    DWK VARCHAR(100),
    OPA DOUBLE PRECISION,
    ICO INTEGER )

AS
declare variable iz integer;
declare variable ii integer;
declare variable mm integer;
declare variable ic integer;
declare variable ps integer;
declare variable kl varchar(40);
declare variable po varchar(100);
declare variable nc varchar(200);
declare variable dw varchar(100);
DECLARE zg VARCHAR(1);
DECLARE OP DOUBLE PRECISION;
begin
  icn=0;
  ico=0;
  select id_synzb,c.ID_INTERNM,postac,dawka,nazwa from cbt c where id_cbt=:ict into :iz,ii,:po,:dw,:nc;
  select mnoznik,nazwa,mnoznik/COALESCE(j.DZIELNIK,1) from cbt_jedn j where id_cbt=:ict and jednostka=2 into :opn,:nmo,opa;  
  SELECT k.WARTOSC from CBT_KLAS k where k.ID_KLASYFIKACJE = -10 and k.ID_CBT = :ict into kl;
  if (kl is null) THEN
  BEGIN
    SUSPEND;
    EXIT;
  END
  select min(wartosc) from cbt_klas where id_cbt=:ict and id_klasyfikacje=14 into kl;
  
  ps = position(' ' in nc);
  if (ps<=0) then ps = char_length(nc);
  if (iz is not null ) then
  begin
    for select c.id_cbt,IIF (EXISTS(select k.WARTOSC from cbt_klas k where k.id_cbt=c.id_cbt and k.id_klasyfikacje=14 and k.wartosc=:kl) ,'T','N')
      ,j.MNOZNIK,mnoznik/COALESCE(j.DZIELNIK,1)
    from cbt c 
    LEFT JOIN CBT_JEDN j on c.ID_CBT = j.ID_CBT and j.JEDNOSTKA = 2
    where c.id_synzb=:iz 
      and  upper(substring(:nc from 1 for :ps-1))=upper(substring(c.nazwa from 1 for :ps-1))
      and EXISTS(select k.WARTOSC from cbt_klas k where k.id_cbt=c.id_cbt and k.id_klasyfikacje=-10)
      and EXISTS(select k.WARTOSC from cbt_klas  k where k.id_cbt=c.id_cbt and k.id_klasyfikacje=7 and k.wartosc='7') 
      and not EXISTS(select k.WARTOSC from cbt_klas  k where k.id_cbt=c.id_cbt and k.id_klasyfikacje=7 and k.wartosc='f') 
      into ic,zg,mm,op do
      BEGIN
        if (zg = 'T' AND  mm<=opn) then
        begin
          opn=mm;
          icn=ic;
        end
        if (op<=opa) then
        begin
          opa=op;
          ico=ic;
        end
      END  
  end
  ELSE
  if (ii is not null ) then
  begin
    for select c.id_cbt,IIF (EXISTS(select k.WARTOSC from cbt_klas k where k.id_cbt=c.id_cbt and k.id_klasyfikacje=14 and k.wartosc=:kl) ,'T','N')
      ,j.MNOZNIK,mnoznik/COALESCE(j.DZIELNIK,1)
    from cbt c 
    LEFT JOIN CBT_JEDN j on c.ID_CBT = j.ID_CBT and j.JEDNOSTKA = 2
    where c.ID_INTERNM=:ii   and POSTAC=:po and c.dawka=:dw
      and  upper(substring(:nc from 1 for :ps-1))=upper(substring(c.nazwa from 1 for :ps-1))
      and EXISTS(select k.WARTOSC from cbt_klas k where k.id_cbt=c.id_cbt and k.id_klasyfikacje=-10)
      and EXISTS(select k.WARTOSC from cbt_klas  k where k.id_cbt=c.id_cbt and k.id_klasyfikacje=7 and k.wartosc='7') 
      and not EXISTS(select k.WARTOSC from cbt_klas  k where k.id_cbt=c.id_cbt and k.id_klasyfikacje=7 and k.wartosc='f') 
      into ic,zg,mm,op do
      BEGIN
        if (zg = 'T' AND  mm<=opn) then
        begin
          opn=mm;
          icn=ic;
        end
        if (op<=opa) then
        begin
          opa=op;
          ico=ic;
        end
      END
  end 
  suspend;
end
^

ALTER PROCEDURE LEK_INFO_HTML (
    IAP INTEGER,
    ITW INTEGER,
    DTA TIMESTAMP,
    ATR VARCHAR(10),
    KSR VARCHAR(20),
    FAST INTEGER,
    ICN INTEGER,
    NKA INTEGER,
    PIE INTEGER,
    WNU VARCHAR(30) DEFAULT '' )
RETURNS (
    LHTML VARCHAR(8196),
    LSPRZ VARCHAR(1024),
    ODP VARCHAR(20),
    CTN DOUBLE PRECISION,
    LIM DOUBLE PRECISION,
    KOLOR INTEGER,
    SUMA DOUBLE PRECISION,
    LISTA INTEGER,
    CENA DOUBLE PRECISION,
    KSOK INTEGER )
AS
declare cbr double precision;
declare lbr double precision;
declare cod double precision;
declare lod double precision;
declare opa double precision;
declare iod integer;
declare idcbt integer;
declare idl integer;
declare opo integer;
declare idOdplZb integer;
declare kol integer;
declare opis_w_tow varchar(256);
declare opis_z_prom varchar(1024);
declare nmo varchar(100);
declare spm varchar(1);
declare ipp integer;
declare mno integer;
declare rec_senior integer;
declare lek_senior integer;
declare odp_senior integer;
DECLARE styl VARCHAR(2048);
DECLARE listy VARCHAR(2048);
DECLARE opis VARCHAR(2048);
declare limnmo varchar(256);
DECLARE br varchar(2);
declare kdw integer;
declare isb integer;
declare mdw date;
DECLARE neucap char(1);
DECLARE neucaz char(1);
DECLARE neucar VARCHAR(128);
declare ciaza integer;
declare wbu char(1);
DECLARE mn int;
DECLARE dz int;
DECLARE wnGrupa int;
declare cena_liczenie char(1);
DECLARE neucak int;
begin

  br = ascii_char(13) || ascii_char(10);
  styl = '<link rel="stylesheet" type="text/css" href="usl.css">';
    
  lhtml = '<!DOCTYPE html><HTML> <head><meta charset="windows-1250">';
  lhtml = lhtml || styl;
  lhtml = lhtml || '</head><BODY>';
  
  odp = '0000000000';
  opis = '';
  listy = '';
  lsprz = '';
  
  select coalesce(LEK_INFO,'N'),o.KONTR_DAT_WAZN,coalesce(wnioski_bez_umowy,'N') from ogolne o where id_apteki=:iap into spm,kdw,wbu;
  
  select sum(stan),min(datwazn) from kartoteki(:iap, :itw,0,:nka,3,:dta,'T')
      where :fast < 0 or (datwazn>:dta or datwazn is null or datwazn<'01.01.1900') into suma,mdw;
  
  if (abs(fast)>=2) THEN
  BEGIN
    if (fast<0) THEN
    BEGIN
      lista = 1;
      fast = - fast;
    END
    ELSE
    BEGIN
       select max(l.id_listy) from tow_listy l
         LEFT JOIN LISTY_ODPL o on o.ID_LISTY=l.ID_LISTY AND cast(:atr as char(9)) like o.atrybuty and :dta between o.obowiazuje_od and o.obowiazuje_do
         where l.ID_APTEKI=:iap and l.ID_TOWARY=:itw and :dta between l.obowiazuje_od and l.obowiazuje_do and o.ID_ODPLATN is not NULL
        into lista;
    END
    
    if (pie = -1) then
    BEGIN
      if (wbu = 'T') then
         select count(*) from ceny_towary where id_apteki=:iap and id_towary=:itw and id_ceny=3  and obowiazuje_od <= :dta and (obowiazuje_do is null or obowiazuje_do>= :dta ) and WN_KOD=:ksr INTO  KSOK  ;
      ELSE
        SELECT count(*) from TOWARY_WNIOSKI t
          join PROD_HANDL h on h.ID_PROD = t.ID_PROD and h.ID_UMOWY = t.ID_UMOWY
          join WNIOSKI_UMOWY u on t.ID_UMOWY = u.KOD and :dta BETWEEN u.OD_DNIA and u.DO_DNIA and (:wnu = '' or u.KOD = :wnu)
          join PROD_ZPOSP z on h.KOD_SR = z.KOD_SRODKA and :dta BETWEEN z.DATA_OD and z.DATA_DO
          join PAKIET_ZAOP a on a.ID_PROD = h.ID_PROD and a.ID_UMOWY = h.ID_UMOWY
          join PLANY_MIES m on a.ID_PAKIET=m.ID_PAKIET and a.ID_UMOWY = m.ID_UMOWY and m.ID_KOM = u.id_kom  and m.MIESIAC = EXTRACT(MONTH from  :dta)
         where t.ID_TOWARY = :itw and t.ID_APTEKI = :iap and h.KOD_SR STARTING :ksr  and m.MIESIAC is not NULL
         into KSOK;   
    end  
    ELSE
      if (pie in (5,6)  ) THEN
        Select OK from pielegn_ok(:iap,:itw,:pie) into KSOK;
      ELSE
        KSOK = 1;
   
    if (icn < 0) THEN
    BEGIN
      icn =  - icn;
      select  c.CENA_NT,c.JAKA from akt_cena_sp(:iap,:itw,:icn,:dta,0,:ksr)  c into CENA,cena_liczenie;
    END
    ELSE
    BEGIN
      select  c.CENA_BR,c.JAKA from akt_cena_sp(:iap,:itw,:icn,:dta,0,:ksr)  c into CENA,cena_liczenie;
    END
  END
    
  select id_cbt,COALESCE(opis_eksp,''),kolor,coalesce(t.ID_SYNZB,-1) from towary t where id_apteki=:iap and id_towary=:itw  into idcbt,opis_w_tow,kolor,isb;
  
  SELECT r.AKT,r.OPIS,r.KOLOR from NEUCA_REKOMENDACJA(:itw,:dta) r into neucap,neucar,neucak;
  
  if (neucap = 'T') THEN
    neucap = '1';
  ELSE
    neucap = '0';   
    
  ciaza = 0;
  if (atr  like 'G______S%') then
    ciaza = 27;
  if (atr  like 'G______C%') then
    ciaza = 28;  
  if (atr  like 'G______D%') then
    ciaza = 29;  
  if (ciaza > 0) then
  BEGIN
    rec_senior = 1;
    select COUNT(*) from TOW_LISTY t
     where t.ID_APTEKI=:iap and t.ID_TOWARY=:itw and t.ID_LISTY = :ciaza and :dta BETWEEN t.OBOWIAZUJE_OD and t.OBOWIAZUJE_DO
    into lek_senior;
    mno = -1;
  END
  ELSE
  BEGIN
    rec_senior = 0;
    lek_senior = 0;
    mno = 1;
  end
  if (fast<2 and lek_senior=0) then
  begin
    if (left(atr,2)='GW') then
    begin
      if (ksr='XXX') then
         opis = 'Nie wybrano kodu œrodka';
      else
      begin
       if (wbu = 'T') then
         select first 1 cena_br from ceny_towary
         where id_apteki=:iap and id_towary=:itw and id_ceny=3 and wn_kod=:ksr and :dta >=obowiazuje_od and (obowiazuje_do >= :dta or obowiazuje_do is null)
         order by obowiazuje_od desc into cbr;
       ELSE 
       BEGIN
         mn=1;
         dz=1;
         if ((select upper(nazwa) from jednostki where id_apteki=:iap and id_towary=:itw and jednostka=1) not like 'SZT%') then
           select mnoznik,dzielnik from jednostki where id_apteki=:iap and id_towary=:itw and jednostka=2 into mn,dz;
         SELECT count(*)  from PROD_ZPOSP_GRUPY g where g.KOD_SRODKA = :ksr and :dta BETWEEN g.DATA_OD and g.DATA_DO into wnGrupa;
         begin
         SELECT round(a.CENA * iif(z.LIM_JEDN='T',:mn/:dz,1),2) from TOWARY_WNIOSKI t
          join PROD_HANDL h on h.ID_PROD = t.ID_PROD and h.ID_UMOWY = t.ID_UMOWY
          join WNIOSKI_UMOWY u on t.ID_UMOWY = u.KOD and :dta BETWEEN u.OD_DNIA and u.DO_DNIA  and (:wnu = '' or u.KOD = :wnu)
          join PROD_ZPOSP z on h.KOD_SR = z.KOD_SRODKA and :dta BETWEEN z.DATA_OD and z.DATA_DO
          join PAKIET_ZAOP a on a.ID_PROD = h.ID_PROD and a.ID_UMOWY = h.ID_UMOWY
          join PLANY_MIES m on a.ID_PAKIET=m.ID_PAKIET and a.ID_UMOWY = m.ID_UMOWY and m.ID_KOM = u.id_kom  and m.MIESIAC = EXTRACT(MONTH from  :dta)
         where t.ID_TOWARY = :itw and t.ID_APTEKI = :iap and (h.KOD_SR STARTING :ksr  || '.' and :wnGrupa>0 or h.KOD_SR = :ksr  and :wnGrupa = 0) and m.MIESIAC is not NULL
         into cbr;
         when any do EXCEPTION BLAD  (SELECT t.NAZWA||' Ident: '||t.id_towary from TOWARY t where t.ID_TOWARY = :itw and t.ID_APTEKI = :iap) || '
Jest przyporz¹dkowany do kilku produktów w umowie.
Popraw przyporz¹dkowanie w ''Towary'' - ''Id produktu'''  ;
         end
       end

       if (cbr>0) then
         opis = 'Cena z umowy : ' || round(cbr,2);
       else
         opis = 'Brak ceny z umowy ';
      end
      odp = '0000001000';
    end
    else
    begin
      if (atr<>'O' and idcbt>0) then
      begin
         select first 1 IDODPZB,NMODP,CenW,CNODPZB,LMODPZB,LimW,MINODPL,
           IIF( :rec_senior=0 , 0 ,
            (select COUNT(*) from cbt_LISTY t
             where  t.ID_CBT=idOdpZb and t.ID_LISTY=:ciaza and :dta BETWEEN t.OBOWIAZUJE_OD and t.OBOWIAZUJE_DO )) senior
           from CBT_ODP_REF(:dta,:idcbt * :mno)
           where idodpzb<>:idcbt
           ORDER by senior desc , cnodpzb-lmodpzb,cnodpzb
           into  opo,nmo,cbr,cod,lod,lbr,ctn,odp_senior;

         if (odp_senior>0) then
         BEGIN
           opis = nmo || ' jest na liœcie ' || iif(:ciaza=28,'Ci¹¿a',iif(:ciaza=27,'Senior 75+','Dziecko 18-'));
           odp = '0000001000';
         END
         else
         if (opo<>0 and cod<cbr-0.001) then
         begin
           select ido from odpl_cbt(:idcbt,:dta,'GZ U 00P ') into :idOdplZb;
           select first 1 oplata from cbt_odpl where id_cbt=:idcbt and id_ceny=3 and id_odplatn=:idOdplZb and obowiazuje_od<=:dta order by obowiazuje_od descending into opa;
           opis = nmo || ' tañszy o ' || round(cbr-cod,2) || ' op³ata ni¿sza o ' || round(opa-ctn,2);
           if (cod > lod + 0.001 or lbr < 0.001) then
           begin
             if (fast=0) then
               odp = '0000000000';
             else
               opis = '';
           end
           else
             odp = '0000001000';
         end
      end

      if (opis='') then
      begin
        opo=0;
        select first 1 id_odp,opod,OpTw from tanszy_odpowiednik(:iap, :itw,:dta,0, :atr)
        where id_odp<>:itw and ilod>0 and (OpOd<OpTw or OpOd=-100)
        order by opOd,ilod descending into opo,ctn,opa;
        if (opo<>0) then
        begin
          if (ctn=-100) then
          begin
            select 'Zaproponuj : ' ||  nazwa,(select cena_br from akt_cena_sp(id_apteki,id_towary,3,'today',0,'')) from towary  where ID_APTEKI=:iap and ID_TOWARY=:opo into opis,ctn;
            odp = '0000000001';
          end
          else
          if (fast=0) then
          begin

            if (opa>0 and opa>ctn+0.01) then
            begin
              select nazwa from towary  where ID_APTEKI=:iap and ID_TOWARY=:opo into opis;
              opis = opis || ' tañszy o ' || round(opa-ctn,2) || ' z³';
              odp = '0000000000';
            end
          end
        end
      end
    end
  end
  else
    if (fast=2) THEN
      spm='T';
    ELSE
      spm='N';


  if (kdw>0 and mdw>dta and dta+kdw > mdw ) THEN
  BEGIN
    kolor = 255;
    odp = '0000000001';
    if (opis>' ') THEN
      opis = opis || '<BR>';
    opis = opis || 'Krótka data wa¿noœci '  || RIGHT('0' || extract(day from mdw),2) || '-' || RIGHT('0' || extract(month from mdw),2)  || '-' || extract(year from mdw) ;  
  END
  ELSE 
    if (FAST=0 and kdw>0 and isb>0) THEN
    BEGIN
      mdw = null;
      SELECT first 1 t.NAZWA,z.DATA_WAZN FROM TOWARY t LEFT JOIN ZDST z on t.id_apteki=z.ID_APTEKI and t.ID_TOWARY=z.ID_TOWARY and z.CZYNNY='T'
      WHERE t.ID_APTEKI=:iap and t.ID_SYNZB=:isb and t.ID_TOWARY<>:itw AND z.DATA_WAZN>:dta and COALESCE(z.DATA_WAZN,'01.01.3000') < :dta + :kdw
      ORDER by z.DATA_WAZN 
      INTO nmo,mdw;
      if (mdw is not NULL) THEN
      BEGIN
        if (opis>' ') THEN
            opis = opis || '<BR>';
        opis = opis ||  nmo || ' data wa¿noœci '  || RIGHT('0' || extract(day from mdw),2) || '-' || RIGHT('0' || extract(month from mdw),2)  || '-' || extract(year from mdw) ;  
      END  
    END
  
  if ( SUBSTRING (ODP FROM 7 for 1)='1' or SUBSTRING (ODP FROM 10 for 1)='1' ) THEN
  BEGIN
    lsprz = replace(opis,'<BR>',br);
    opis = '<SPAN class="wazna">' || opis || '</SPAN>';
  END
  
  cbr = null;
  SELECT first 1 c.CENA from NEUCA_CENY_ZAW c 
    left join NEUCA_CENY e on c.ID_NEUCA_CENY=e.ID_NEUCA_CENY
  WHERE c.ID_TOWARY = :itw and e.AKTYWNA=1 and :dta BETWEEN e.DT_OD and e.DT_DO
  ORDER by c.CENA,e.PRIORYTET into cbr;
  if (cbr is not null) then 
  BEGIN
    opis_w_tow = COALESCE(opis_w_tow,'') || ' Neuca cena sugerowana : ' || round(cbr,2);
  end
  
  if (neucap = '1' and neucar is not null) THEN
  BEGIN
    opis_w_tow = COALESCE(opis_w_tow,'') || neucar;
  END 

  if (opis_w_tow>' ') then
  begin
    odp = left(odp,8) || '1' || right(odp,1);
    if (opis>' ') then
    BEGIN
      lsprz = lsprz || br || opis_w_tow;
      opis = opis || '<BR>' ||  iif(neucap = '1','<span class="neuca' || neucak || '">','<span>') || opis_w_tow || '</span>';
    END
    else
    begin
      opis = iif(neucap = '1','<span class="neuca' || neucak || '">','<span>') || opis_w_tow || '</span>';
      lsprz = opis_w_tow;
    END
  end


  if (idcbt>0 AND spm='T') then
  begin
    SELECT Left(list(DISTINCT c.NM_SHORT,'<BR>'),1024),max(p.AUTOMAT)
    from KOSZYKI k
    JOIN PROMOCJE p on k.ID_PROMOCJE=p.ID_PROMOCJE
    join KOSZYK_TOWARY t on k.ID_PROMOCJE=t.ID_PROMOCJE and k.NR_KOSZYKA=t.NR_KOSZYKA
    join cbt c on t.ID_TOWARY=c.ID_CBT
    join TOWARY y on y.id_cbt = c.ID_CBT and y.ID_APTEKI = :iap
    where k.ID_TOWARY = :idcbt and p.AUTOMAT in ('S','W') and :dta BETWEEN p.OBOWIAZUJE_OD and p.OBOWIAZUJE_DO 
    AND t.ID_TOWARY<> :idcbt
    and EXISTS(SELECT z.SZTUK from ZDST z where z.ID_TOWARY = y.ID_TOWARY and z.CZYNNY = 'T' and z.ID_APTEKI = :iap)
    into opis_z_prom,neucaz;
  
  
    if (opis_z_prom is null) THEN
    BEGIN
    neucaz = '1';
    select left(list(oppi,'<BR>'),1024) from
    (select cast(o.OPIS as varchar(256)) oppi from koszyki k LEFT join OPIS_KOSZYKA o on k.ID_PROMOCJE=o.ID_PROMOCJE and k.NR_KOSZYKA=o.NR_KOSZYKA left join PROMOCJE p on k.ID_PROMOCJE=p.ID_PROMOCJE
     where k.ID_TOWARY=:idcbt and 'today' between  coalesce(o.DATA_OD,p.OBOWIAZUJE_OD) and coalesce(o.DATA_DO,p.OBOWIAZUJE_DO)  and o.opis is not null
    union
       select cast(o.OPIS as varchar(256))
       from cbt_klas  c
       left join klas_sl l on c.id_klasyfikacje=l.id_klasyfikacje and c.wartosc=l.wartosc
        left join koszyki k on c.ID_KLASYFIKACJE=k.ID_KLASYFIKACJE and COALESCE(l.OPIS,c.WARTOSC)=k.WARTOSC
        LEFT join OPIS_KOSZYKA o on k.ID_PROMOCJE=o.ID_PROMOCJE and k.NR_KOSZYKA=o.NR_KOSZYKA
        left join PROMOCJE p on k.ID_PROMOCJE=p.ID_PROMOCJE
       where c.ID_CBT=:idcbt  and k.ID_KLASYFIKACJE is not null  and 'today' between  coalesce(o.DATA_OD,p.OBOWIAZUJE_OD) and 
         coalesce(o.DATA_DO,p.OBOWIAZUJE_DO) and o.opis is not null)
     into opis_z_prom;
   end  
   ELSE
   BEGIN
     odp = LEFT(odp,9) || '1';
     opis_z_prom = IIF(neucaz = 'S','Zaproponuj zamiast : <BR>','Zaproponuj dodatkowo : <BR>') || opis_z_prom;
   end
    if (opis_z_prom is not null) then
    begin
    odp = left(odp,7) || neucaz || right(odp,2);
    if (opis>' ') then
    BEGIN
       lsprz = left(lsprz || br ||  replace( opis_z_prom , '<BR>', br) ,512);
       opis = opis || '<BR>' || opis_z_prom;
    END
    else
    BEGIN
      lsprz = left(replace( opis_z_prom , '<BR>', br), 512);
      opis = opis_z_prom;
    END
    end
  end
  
  
  
  
 

  limnmo = '';
  if (atr<>'O' and fast<2) then
  begin
    select l.LIMIT from AKT_LIMIT(:iap,:itw,3,:dta,:ksr) l  into lim;
    if (lim  > 0 ) then
      limnmo = '<SPAN class="nalewy">Limit: <SPAN class="liczba">' || round(lim,2) || '</SPAN></SPAN>';

    kol = 0;
    ipp = 6;
    for select distinct l.ID_ODPLATN,l.KOLEJNOSC,l.ID_LISTY
     from tow_listy t
     left join listy_odpl l on t.id_listy=l.id_listy and :dta between l.obowiazuje_od and l.obowiazuje_do and cast(:atr as char(9)) like l.ATRYBUTY
     where t.id_apteki=:iap and t.id_towary=:itw and  :dta between t.obowiazuje_od and t.obowiazuje_do and l.id_listy is not null
    order by kolejnosc,id_odplatn descending into iod,opo,idl do
    if ((kol=0 or kol=opo) and iod between 1 and 6) then
    begin
      if (kol=0) then kol = opo;
      odp = left(odp,iod-1) || '1' || right(odp,10-iod);
      if (ipp=6) then ipp = iod;
    end
    odp = left(odp,ipp-1) || '2' || right(odp,10-ipp);
  end
  
   
  if (fast=0) THEN
  BEGIN
 
   
   select COALESCE(n.OPN,0), n.NMO from cbt_najm(:idcbt) n INTO idl,nmo;
   if (idl<>0)  THEN
     limnmo = limnmo || '<SPAN class="naprawy"> NZO: <SPAN class="liczba">' || idl || '</SPAN><SPAN class="malutka"> ' || lower(nmo) || '</SPAN></SPAN>';
   listy =  limnmo || '<TABLE class="tb100 opieka">';
   if (atr STARTING 'O') THEN  atr = 'G________';
   for select l.nm_listy || ' ' || w.KODSR, o.cena, o.UZYTY_ODPOWIEDNIK , c.JAKA
     from tow_listy t
     left join listy l on l.id_listy=t.id_listy
     left join WN_KODY_UM(t.ID_APTEKI,t.ID_TOWARY,t.ID_LISTY,:dta,:ksr) w on 0=0
     left join akt_cena_sp(:iap,:itw,:icn,:dta,0,w.KODSR) c on 0=0
     left join akt_odpl_podst(t.id_apteki,t.id_towary,:dta,l.id_listy,:atr,c.CENA_BR,c.LIMIT) o on 1=1
    where t.id_apteki=:iap and  t.id_towary=:itw and :dta between t.obowiazuje_od and t.obowiazuje_do
    INTO nmo,cbr,idl,cena_liczenie do
    BEGIN
      if (COALESCE(idl,0)<>0) THEN
        spm = '*';
      ELSE
        spm = '';
      listy = listy || '<TR><TD>' || spm || nmo || '</TD><TD class="liczba">' || round(cbr,2) || '</TD></TR>';
      
        
    END
   listy = listy || '</TABLE>';
  END
  LHTML = LEFT(LHTML || '<DIV class="rpanw nalewy">' || opis || '</DIV><DIV class="lpanw naprawy">' || listy || '</DIV></BODY></HTML>',8196);
  odp = odp || neucap;
  suspend;
end
^

ALTER PROCEDURE LEK_INFO_SPRZEDAZ (
    IAP INTEGER,
    ITW INTEGER,
    DTA TIMESTAMP,
    ATR VARCHAR(10),
    KSR VARCHAR(20),
    FAST INTEGER )
RETURNS (
    LKI VARCHAR(256),
    ODP VARCHAR(20),
    CTN DOUBLE PRECISION )

AS
declare cbr double precision;
declare lbr double precision;
declare cod double precision;
declare lod double precision;
declare opa double precision;
declare iod integer;
declare opo integer;
declare idOdplZb integer;
declare kol integer;
declare opt varchar(256)  CHARACTER SET WIN1250;
declare nmo varchar(100)  CHARACTER SET WIN1250;
declare spm varchar(1)  CHARACTER SET WIN1250;
declare ipp integer;
declare mno integer;
declare rec_senior integer;
declare lek_senior integer;
declare odp_senior integer;
declare ciaza integer;
DECLARE neucap char(1);
DECLARE mn int;
DECLARE dz int;
DECLARE wnGrupa int;
begin
  odp = '0000000000';
  lki = '';
  select id_cbt,opis_eksp from towary where id_apteki=:iap and id_towary=:itw  into iod,opt;
 
  
  if ((SELECT akt from NEUCA_REKOMENDACJA(:itw,:dta)) = 'T') THEN
    neucap = '1';
  ELSE
    neucap = '0';   
  
  ciaza = 0;
  if (atr  like 'G______S%') then
    ciaza = 27;
  if (atr  like 'G______C%') then
    ciaza = 28;  
  if (atr  like 'G______D%') then
    ciaza = 29;  
  if (ciaza > 0) then
  BEGIN
    rec_senior = 1;
    select COUNT(*) from TOW_LISTY t
     where t.ID_APTEKI=:iap and t.ID_TOWARY=:itw and t.ID_LISTY = :ciaza and :dta BETWEEN t.OBOWIAZUJE_OD and t.OBOWIAZUJE_DO
    into lek_senior;
    mno = -1;
  END
  ELSE
  BEGIN
    rec_senior = 0;
    lek_senior = 0;
    mno = 1;
  end

  if (fast<2 and lek_senior=0) then
  begin
    select coalesce(LEK_INFO,'N') from ogolne where id_apteki=:iap into spm;
    if (left(atr,2)='GW') then
    begin
      if (ksr='XXX') then
        lki = 'Nie wybrano kodu œrodka';
      else
      begin
       if ((SELECT coalesce(wnioski_bez_umowy,'N') from OGOLNE where id_apteki = :iap ) = 'T') then
       BEGIN
         select first 1 cena_br from ceny_towary
         where id_apteki=:iap and id_towary=:itw and id_ceny=3 and wn_kod=:ksr and :dta >=obowiazuje_od and (obowiazuje_do >= :dta or obowiazuje_do is null)
         order by obowiazuje_od desc into cbr;
       end
       ELSE
       BEGIN
         mn=1;
         dz=1;
         if ((select upper(nazwa) from jednostki where id_apteki=:iap and id_towary=:itw and jednostka=1) not like 'SZT%') then
           select mnoznik,dzielnik from jednostki where id_apteki=:iap and id_towary=:itw and jednostka=2 into mn,dz;

         SELECT count(*)  from PROD_ZPOSP_GRUPY g where g.KOD_SRODKA = :ksr and :dta BETWEEN g.DATA_OD and g.DATA_DO into wnGrupa;
         begin
         SELECT round(a.CENA * iif(z.LIM_JEDN='T',:mn/:dz,1),2) from TOWARY_WNIOSKI t
          left join PROD_HANDL h on h.ID_PROD = t.ID_PROD and h.ID_UMOWY = t.ID_UMOWY
          left join WNIOSKI_UMOWY u on t.ID_UMOWY = u.KOD
          left join PROD_ZPOSP z on h.KOD_SR = z.KOD_SRODKA and :dta BETWEEN z.DATA_OD and z.DATA_DO
          left join PAKIET_ZAOP a on a.ID_PROD = h.ID_PROD and a.ID_UMOWY = h.ID_UMOWY
          left join PLANY_MIES m on a.ID_PAKIET=m.ID_PAKIET and a.ID_UMOWY = m.ID_UMOWY and m.ID_KOM = u.id_kom  and m.MIESIAC = EXTRACT(MONTH from  :dta)
         where t.ID_TOWARY = :itw and t.ID_APTEKI = :iap and (h.KOD_SR STARTING :ksr || '.' and :wnGrupa>0 or h.KOD_SR = :ksr  and :wnGrupa = 0) and :dta BETWEEN u.OD_DNIA and u.DO_DNIA and m.MIESIAC is not NULL
         into cbr;
         when any do EXCEPTION BLAD  (SELECT t.NAZWA||' Ident: '||t.id_towary from TOWARY t where t.ID_TOWARY = :itw and t.ID_APTEKI = :iap) || '
Jest przyporz¹dkowany do kilku produktów w umowie.
Popraw przyporz¹dkowanie w ''Towary'' - ''Id produktu'''  ;
        end
       END  
       if (cbr>0) then
         lki = 'Cena z umowy : ' || round(cbr,2);
       else
         lki = 'Brak ceny z umowy ';
      end
    end
    else
    begin
      if (atr<>'O' and iod>0) then
      begin
         select first 1 IDODPZB,NMODP,CenW,CNODPZB,LMODPZB,LimW,MINODPL,
           case when :rec_senior=0 then 0 else
            (select COUNT(*) from cbt_LISTY t
             where  t.ID_CBT=idOdpZb and t.ID_LISTY=:ciaza and :dta BETWEEN t.OBOWIAZUJE_OD and t.OBOWIAZUJE_DO )
           end senior
           from CBT_ODP_REF(:dta,:iod * :mno)
           where idodpzb<>:iod
           ORDER by senior desc , cnodpzb-lmodpzb,cnodpzb
           into  opo,nmo,cbr,cod,lod,lbr,ctn,odp_senior;

         if (odp_senior>0) then
         BEGIN
           lki = left(nmo || ' jest na liœcie ' || iif(:ciaza=28,'Ci¹¿a',iif(:ciaza=27,'Senior 75+','Dziecko 18-')),256);
           odp = '0000001000';
         END
         else
         if (opo<>0 and cod<cbr-0.001) then
         begin
           select ido from odpl_cbt(:iod,:dta,'GZ U 00P ') into :idOdplZb;
           select first 1 oplata from cbt_odpl where id_cbt=:iod and id_ceny=3 and id_odplatn=:idOdplZb and obowiazuje_od<=:dta order by obowiazuje_od descending into opa;
           lki = left(nmo || ' tañszy o ' || round(cbr-cod,2) || ' op³ata ni¿sza o ' || round(opa-ctn,2),256);
           if (cod > lod + 0.001 or lbr < 0.001) then
           begin
             if (fast=0) then
               odp = '0000000000';
             else
               lki = '';
           end
           else
             odp = '0000001000';
         end

      end

      if (lki='') then
      begin
        opo=0;
        select first 1 id_odp,opod from tanszy_odpowiednik(:iap, :itw,:dta,0, :atr)
        where id_odp<>:itw and (select count(*) from zdst where id_apteki=:iap and id_towary=id_odp and czynny='T')>0
        order by opOd,ilod descending into opo,ctn;
        if (opo<>0) then
        begin
          if (ctn=-100) then
          begin
            select left('Zaproponuj : ' ||  nazwa,256),(select cena_br from akt_cena_sp(id_apteki,id_towary,3,'today',0,'')) from towary  where ID_APTEKI=:iap and ID_TOWARY=:opo into lki,ctn;
            odp = '0000000001';
          end
          else
          if (fast=0) then
          begin
            select cena_br from akt_cena_sp(:iap,:itw,3,'today',0,'') into opa;
            if (opa>0 and opa>ctn+0.01) then
            begin
              select nazwa from towary  where ID_APTEKI=:iap and ID_TOWARY=:opo into lki;
              lki = left(lki || ' tañszy o ' || round(opa-ctn,2) || ' z³',256);
              odp = '0000000000';
            end
          end
        end
      end
    end
  end
  else
    spm='T';

  if (opt is not null and opt>' ') then
  begin
    odp = left(odp,8) || '1' || right(odp,1);
    if (lki>' '  or fast=0) then
       lki = left(lki || ascii_char(13) || ascii_char(10) || opt,256);
    else
      lki = opt;
  end

  cbr = null;
  SELECT first 1 c.CENA from NEUCA_CENY_ZAW c 
    left join NEUCA_CENY e on c.ID_NEUCA_CENY=e.ID_NEUCA_CENY
  WHERE c.ID_TOWARY = :itw and e.AKTYWNA=1 and :dta BETWEEN e.DT_OD and e.DT_DO
  ORDER by c.CENA,e.PRIORYTET into cbr;
  if (cbr is not null) then 
  BEGIN
     opt = 'Neuca cena sugerowana : ' || round(cbr,2); 
     if (lki>' ') then
       lki = left(lki || ascii_char(13) || opt,256);
     else
       lki = opt;
  end    
     

  opt = null;
  if (spm='T') then
  begin
    select left(list(oppi,ascii_char(13) || ascii_char(10)),256) from
    (select cast(o.OPIS as varchar(256)) oppi from koszyki k LEFT join OPIS_KOSZYKA o on k.ID_PROMOCJE=o.ID_PROMOCJE and k.NR_KOSZYKA=o.NR_KOSZYKA left join PROMOCJE p on k.ID_PROMOCJE=p.ID_PROMOCJE
     where k.ID_TOWARY=:iod and 'today' between  coalesce(o.DATA_OD,p.OBOWIAZUJE_OD) and coalesce(o.DATA_DO,p.OBOWIAZUJE_DO)  and o.opis is not null
    union
       select cast(o.OPIS as varchar(256))
       from cbt_klas  c
       left join klas_sl l on c.id_klasyfikacje=l.id_klasyfikacje and c.wartosc=l.wartosc
        left join koszyki k on c.ID_KLASYFIKACJE=k.ID_KLASYFIKACJE and COALESCE(l.OPIS,c.WARTOSC)=k.WARTOSC
        LEFT join OPIS_KOSZYKA o on k.ID_PROMOCJE=o.ID_PROMOCJE and k.NR_KOSZYKA=o.NR_KOSZYKA
        left join PROMOCJE p on k.ID_PROMOCJE=p.ID_PROMOCJE
       where c.ID_CBT=:iod  and k.ID_KLASYFIKACJE is not null  and 'today' between  coalesce(o.DATA_OD,p.OBOWIAZUJE_OD) and coalesce(o.DATA_DO,p.OBOWIAZUJE_DO) and o.opis is not null)
     into opt;
  end
  if (opt is not null) then
  begin
    odp = left(odp,7) || '1' || right(odp,2);
    if (lki>' ' or fast=0) then
       lki = left(lki || ascii_char(13) || ascii_char(10) || opt,256);
    else
      lki = opt;
  end
  if (atr<>'O' and fast<2) then
  begin
    kol = 0;
    ipp = 6;
    for select distinct id_odplatn,kolejnosc from tow_listy t
    left join listy_odpl l on t.id_listy=l.id_listy and :dta between l.obowiazuje_od and l.obowiazuje_do and cast(:atr as char(9)) like l.ATRYBUTY
    where t.id_apteki=:iap and t.id_towary=:itw and  :dta between t.obowiazuje_od and t.obowiazuje_do and l.id_listy is not null
    order by kolejnosc,id_odplatn descending into iod,opo do
    if ((kol=0 or kol=opo) and iod between 1 and 6) then
    begin
      if (kol=0) then kol = opo;
      odp = left(odp,iod-1) || '1' || right(odp,10-iod);
      if (ipp=6) then ipp = iod;
    end
    odp = left(odp,ipp-1) || '2' || right(odp,10-ipp);
  end

  odp = odp || neucap;

  suspend;
end
^

ALTER PROCEDURE TW_FULL_INFO(IA INTEGER,
IT INTEGER,
D1 DATE,
D2 DATE)
 RETURNS(SI DOUBLE PRECISION,
SB DOUBLE PRECISION,
SN DOUBLE PRECISION,
SZ DOUBLE PRECISION,
PA INTEGER,
ZI DOUBLE PRECISION,
ZN DOUBLE PRECISION,
ZIZ DOUBLE PRECISION,
ZNZ DOUBLE PRECISION
)
 AS
 /* ew zmiany uwzglednic rowniez w tw_full_info_galen */
begin
  select sum(sztuk*dziel/mnoz),sum(wartosc),sum(wartosc/(1+stawka_vat*0.01)),sum(wart_zak),COUNT(DISTINCT s.DATA || s.ID_TRANZAKCJE) from sprzedaz  s
  left join tranzakcje t on s.id_apteki=t.Id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
  left join ilosc_jp(s.id_apteki,id_towary,jednostka) on 0=0
  left join kontrahenci k on k.id_kontrahenci=t.id_kontrahenci
  where s.id_towary=:it and s.id_apteki=:ia and s.data between :d1 and :d2 and coalesce(t.id_kontrahenci,1)>0 and coalesce(k.nie_brac,'N')<>'T'
  into si,sb,sn,sz,pa;

  select sum(sztuk_jp) zi,sum(sztuk_jp*cena_nt_jp),sum(iif(sztuk_jp<0,sztuk_jp,0)),sum(iif(sztuk_jp<0,sztuk_jp*cena_nt_jp,0))
  from zdst z left join ceny_dostawy y on y.id_apteki=z.id_apteki and y.id_zdst=z.id_zdst and y.id_ceny=1
  left join dostawy d on z.id_apteki=d.id_apteki and z.id_dostawy=d.id_dostawy
  left join kontrahenci k on k.id_kontrahenci=d.id_kontrahenci
  where z.id_apteki=:ia and z.id_towary=:it and  z.data between  :d1 and :d2  and d.id_kontrahenci>0 and coalesce(k.nie_brac,'N')<>'T'
  into zi,zn,ziz,znz;

  if (si is null) then si=0;
  if (sb is null) then  sb=0;
  if (sn is null) then  sn=0;
  if (sz is null) then   sz=0;
  if (zi is null) then   zi=0;
  if (zn is null) then   zn=0;
  suspend;
end
^

EXECUTE block as BEGIN
if ((SELECT rdb$get_context('SYSTEM', 'ENGINE_VERSION') from rdb$database)>'3') then execute statement "
create or ALTER PROCEDURE TW_FULL_INFO_galen(IA INTEGER,
IT INTEGER,
D1 DATE,
D2 DATE,
K int)
 RETURNS(SI DOUBLE PRECISION,
SB DOUBLE PRECISION,
SN DOUBLE PRECISION,
SZ DOUBLE PRECISION,
PA INTEGER,
ZI DOUBLE PRECISION,
ZN DOUBLE PRECISION,
ZIZ DOUBLE PRECISION,
ZNZ DOUBLE PRECISION,
DOST VARCHAR(120),
RODZAJ VARCHAR(8))
 AS
/* K nr kasy - wszystkie transakcje K=0, internetowa 5 ,  apteka stacjonarna -5 (kasy inne niz 5)
   tw_full wyczyszczona z dodatkow galenowych*/
begin
  select sum(sztuk*dziel/mnoz),sum(wartosc),sum(wartosc/(1+stawka_vat*0.01)),sum(wart_zak),COUNT(DISTINCT s.DATA || s.ID_TRANZAKCJE) from sprzedaz  s
  left join tranzakcje t on s.id_apteki=t.Id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
  left join ilosc_jp(s.id_apteki,id_towary,jednostka) on 0=0
  left join kontrahenci k on k.id_kontrahenci=t.id_kontrahenci
  where s.id_towary=:it and s.id_apteki=:ia and s.data between :d1 and :d2 and coalesce(t.id_kontrahenci,1)>0 and coalesce(k.nie_brac,'N')<>'T'
   and iif(:k>-1, iif(t.nr_kasy=:k,:k,0)=:k , t.nr_kasy<>abs(:k)) --nie da sie wgrac na fb2.5 tam zostaje iif(t.nr_kasy=:k,:k,0)=:k jesli bylo wgrane
   
  into si,sb,sn,sz,pa;

  select sum(sztuk_jp) zi,sum(sztuk_jp*cena_nt_jp),sum(iif(sztuk_jp<0,sztuk_jp,0)),sum(iif(sztuk_jp<0,sztuk_jp*cena_nt_jp,0))
  ,list(distinct k.id_kontrahenci) 
  ,decode(min(case when d.komentarz containing 'pakiet' then 'A' when d.id_braki>0 then 'B' else 'C' end),'A','Pakiet','B','Modem','Nieznany') 
  from zdst z left join ceny_dostawy y on y.id_apteki=z.id_apteki and y.id_zdst=z.id_zdst and y.id_ceny=1
  left join dostawy d on z.id_apteki=d.id_apteki and z.id_dostawy=d.id_dostawy
  left join kontrahenci k on k.id_kontrahenci=d.id_kontrahenci
  where z.id_apteki=:ia and z.id_towary=:it and  z.data between  :d1 and :d2  and d.id_kontrahenci>0 and coalesce(k.nie_brac,'N')<>'T'  
  into zi,zn,ziz,znz,dost,rodzaj;

  if (si is null) then si=0;
  if (sb is null) then  sb=0;
  if (sn is null) then  sn=0;
  if (sz is null) then   sz=0;
  if (zi is null) then   zi=0;
  if (zn is null) then   zn=0;  
  suspend;
end
";
END ^

ALTER PROCEDURE KASUJ_REZERWACJE (
    IAP INTEGER,
    NRKASY INTEGER,
    UPDSTANY CHAR(1) )

AS
declare variable idz Double precision;
 declare variable ile Double precision;
 DECLARE dta date;
begin
 RDB$SET_CONTEXT('USER_TRANSACTION','ZDSTZW',1); -- do czasu az nie beda istniec zdst STAN > SZTUK_JP
 if (:UPDSTANY in ('T','R','B')) then
 begin
   dta = 'today';
   if (updstany='R') THEN
     dta = dta + 30;
   if (updstany='B') THEN
     dta = '01.01.3000';
   for select ID_ZDST, ILOSC from rezerwacja where id_apteki=:iap and NRKASY=:NRKASY AND ILOSC<>0 into :idz, :ile do
     update zdst set STAN=STAN-:ile,data_zamkn = :dta where id_apteki=:iap and ID_ZDST=:idz and ID_ZDST<>-1;
 end
 delete from rezerwacja where id_apteki=:iap and NRKASY=:NRKASY;
 RDB$SET_CONTEXT('USER_TRANSACTION','ZDSTZW',0);
end
^


create or alter procedure zam_promg(ia integer,ib integer,ik integer,ih integer,io integer,ip integer)
as
BEGIN
  update or INSERT INTO ZAMINFO (ID_ZAM, ID_APTEKI, ID_BRAKI, ID_KONTRAHENCI, STAN, TYP, FORMAT, ID_HURTOWNI, ID_OSOZPP, ID_PROMOCJI) VALUES 
    (gen_id(SQ_ZAMINFO,1),:ia,:ib,:ik,1,6,3,:ih,:io,:ip);
   
  INSERT INTO BRAKZAW (ID_APTEKI, ID_BRAKI, ID_TOWARY, ZAMOWIENIE, SZTUK_JP,  JEDNOSTKA, WYLICZONE, CENA) 
    SELECT k.ID_APTEKI,:ib,k.ID_TOWARY,p.ILOSC,p.ILOSC,1,p.ILOSC,p.CENA_NETTO
    FROM KS_PROM_GLOB_ZAW p LEFT join TW_KLAS k on p.ID_TOWARU = k.WARTOSC and k.ID_KLASYFIKACJE = 3 and k.ID_APTEKI = :ia
    WHERE p.ID_PROMOCJI_GLOB = :ip and k.ID_TOWARY is not NULL  ;

END^

create or alter procedure podz_promg(ia integer,ib integer)
RETURNS (kom VARCHAR(1024))
as
DECLARE iz INTEGER;
DECLARE ip INTEGER;
DECLARE it INTEGER;
DECLARE za DOUBLE PRECISION;
DECLARE im DOUBLE PRECISION;
DECLARE ce DOUBLE PRECISION;
DECLARE kd VARCHAR(40);
DECLARE wa DOUBLE PRECISION;
DECLARE wm DOUBLE PRECISION;
DECLARE nm VARCHAR(50);
DECLARE df VARCHAR(1);
DECLARE rf VARCHAR(1);
BEGIN
  kom = '';
   
  SELECT i.ID_ZAM,i.ID_PROMOCJI,g.WARTOSC_MIN_NETTO FROM ZAMINFO i 
  LEFT JOIN KS_PROM_GLOB g on i.ID_PROMOCJI=g.ID_PROMOCJI_GLOB
  WHERE i.ID_APTEKI = :ia and i.ID_BRAKI = :ib into iz,ip,wm;
    
  wa = 0;
  
  for SELECT b.ID_TOWARY,b.ZAMOWIENIE,s.WARTOSC,IIF( z.CENA_NETTO>0, z.CENA_NETTO , w.CENA),z.ILOSC,left(t.NAZWA,50),m.REFUNDOWANY,m.DEFICYTOWY
  FROM BRAKZAW b 
  LEFT join tw_klas s on s.ID_APTEKI = b.ID_APTEKI and s.ID_TOWARY = b.ID_TOWARY and s.ID_KLASYFIKACJE = 3
  LEFT join KS_PROM_GLOB_ZAW z on z.ID_PROMOCJI_GLOB=:ip and  s.WARTOSC = z.ID_TOWARU
  LEFT JOIN TOWARY t on t.ID_APTEKI = b.ID_APTEKI and t.ID_TOWARY = b.ID_TOWARY
  left join zamzawinfo(t.id_apteki,t.id_towary,:iz,'today') m on 0=0
  LEFT JOIN STAN_WART(t.id_apteki,t.id_towary,1) w on 0=0
  where b.ID_APTEKI = :ia and b.ID_BRAKI = :ib and b.ZAMOWIENIE > 0
  into it,za,kd,ce,im,nm,rf,df do 
  BEGIN
    UPDATE OR INSERT INTO ZAM_POZ (ID_APTEKI, ID_ZAM, ID_TOWARY, KOD, ZAMOWIONE, ID_BRAKI, KOD_OF, w_cenie, MA_REF, MA_DEF)
    values (:ia,:iz,:it,:kd,:za,:ib,:kd,:ce,:rf,:df);
    if (za < im) THEN
      kom = kom || 'Dla ' || nm || ' minimalna iloœæ wynosi ' || im || ASCII_CHAR(13) || ASCII_CHAR(10);
    wa = wa + ce * za;  
  END
  if (wm > 0 and wa < wm) THEN
    kom = kom || ' Minimalna wartoœæ zamówienia ' || wm || ASCII_CHAR(13) || ASCII_CHAR(10);
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE DST_KOREKTA_CENY (
    IAP INTEGER,
    IDZ DOUBLE PRECISION )

AS
DECLARE idk DOUBLE precision;
DECLARE idn DOUBLE precision;
DECLARE stn DOUBLE precision;
DECLARE std DOUBLE precision;
DECLARE stj DOUBLE precision;
DECLARE idd INTEGER;
DECLARE poz INTEGER;
DECLARE dtd DATE;
BEGIN
  SELECT z.ID_DOSTAWY,z.KOREKTA_DO,z.DATA,z.POZYCJA,k.STAN,z.SZTUK_JP,z.SZTUK FROM ZDST z 
  left join zdst k on k.ID_ZDST = z.KOREKTA_DO and k.ID_APTEKI = z.ID_APTEKI
  where z.ID_APTEKI = :iap and z.ID_ZDST = :idz into idd,idk,dtd,poz,stn,std,stj;
  
  if (stn > 0.001) THEN
  BEGIN
    idn = GEN_ID(SQ_ZDST,1);
    
    UPDATE ZDST z set z.POZYCJA = :poz + 100,sztuk = :stn * z.SZTUK/z.SZTUK_JP,z.SZTUK_JP=:stn where z.ID_ZDST = :idz and z.ID_APTEKI = :iap;
    
    INSERT INTO ZDST (ID_APTEKI, ID_ZDST, ID_DOSTAWY,  DATA, ID_TOWARY,
      SZTUK, SZTUK_JP, JEDNOSTKA, DATA_WAZN, KOREKTA_DO,
      CZYNNY, POZYCJA, DATA_ZAMKN, STAN) 
    SELECT   ID_APTEKI, :idn, :idd,  :dtd, ID_TOWARY,
      -:stn * SZTUK / SZTUK_JP, -:stn, JEDNOSTKA, DATA_WAZN, :idk,
      'N', :poz , :dtd, 0
    FROM ZDST z where   z.ID_APTEKI = :iap and z.ID_ZDST = :idk;
  
    INSERT INTO ZDST_KLAS (ID_APTEKI, ID_ZDST, ID_KLASYFIKACJE, WARTOSC)
    SELECT ID_APTEKI, :idn, ID_KLASYFIKACJE, WARTOSC
    FROM ZDST_KLAS z where   z.ID_APTEKI = :iap and z.ID_ZDST = :idk and z.ID_KLASYFIKACJE <> 7;
  
    INSERT INTO CENY_DOSTAWY (ID_APTEKI, ID_ZDST, ID_CENY, OBOWIAZUJE_OD, MARZA,
      CENA_NT, CENA_BR, CENA_NT_JP, CENA_BR_JP)
    SELECT ID_APTEKI, :idn, ID_CENY, :dtd, MARZA,
      CENA_NT, CENA_BR, CENA_NT_JP, CENA_BR_JP
    FROM CENY_DOSTAWY z where   z.ID_APTEKI = :iap and z.ID_ZDST = :idk;    
    
    UPDATE ZDST z set z.KOREKTA_DO = :idn where z.ID_ZDST = :idz and z.ID_APTEKI = :iap;
    
  END
  
  if (stj - stn > 0.001) THEN
  BEGIN
    stj = stj - stn;
    if (stn > 0.001) THEN
    BEGIN
      idn = GEN_ID(SQ_ZDST,1);
      
      poz = poz + 200;
        
      INSERT INTO ZDST (ID_APTEKI, ID_ZDST, ID_DOSTAWY,  DATA, ID_TOWARY,
      SZTUK, SZTUK_JP, JEDNOSTKA, DATA_WAZN, KOREKTA_DO,
      CZYNNY, POZYCJA, DATA_ZAMKN, STAN) 
      SELECT   ID_APTEKI, :idn, :idd,  :dtd, ID_TOWARY,
      :stj * SZTUK / SZTUK_JP, :stj, JEDNOSTKA, DATA_WAZN, :idk,
      'N', :poz , :dtd, 0
      FROM ZDST z where   z.ID_APTEKI = :iap and z.ID_ZDST = :idz;
  
      INSERT INTO ZDST_KLAS (ID_APTEKI, ID_ZDST, ID_KLASYFIKACJE, WARTOSC)
      SELECT ID_APTEKI, :idn, ID_KLASYFIKACJE, WARTOSC
      FROM ZDST_KLAS z where   z.ID_APTEKI = :iap and z.ID_ZDST = :idz and z.ID_KLASYFIKACJE <> 7;
  
      INSERT INTO CENY_DOSTAWY (ID_APTEKI, ID_ZDST, ID_CENY, OBOWIAZUJE_OD, MARZA,
        CENA_NT, CENA_BR, CENA_NT_JP, CENA_BR_JP)
      SELECT ID_APTEKI, :idn, ID_CENY, :dtd, MARZA,
        CENA_NT, CENA_BR, CENA_NT_JP, CENA_BR_JP
      FROM CENY_DOSTAWY z where   z.ID_APTEKI = :iap and z.ID_ZDST = :idz;    
          
      idz = idn;
    END
    idn = GEN_ID(SQ_ZDST,1);
    poz = poz + 100;
        
    INSERT INTO ZDST (ID_APTEKI, ID_ZDST, ID_DOSTAWY,  DATA, ID_TOWARY,
      SZTUK, SZTUK_JP, JEDNOSTKA, DATA_WAZN, KOREKTA_DO,
      CZYNNY, POZYCJA, DATA_ZAMKN, STAN) 
      SELECT   ID_APTEKI, :idn, :idd,  :dtd, ID_TOWARY,
      -:stj * SZTUK / SZTUK_JP, -:stj, JEDNOSTKA, DATA_WAZN, :idz,
      'N', :poz , :dtd, 0
      FROM ZDST z where   z.ID_APTEKI = :iap and z.ID_ZDST = :idk;
  
    INSERT INTO ZDST_KLAS (ID_APTEKI, ID_ZDST, ID_KLASYFIKACJE, WARTOSC)
      SELECT ID_APTEKI, :idn, ID_KLASYFIKACJE, WARTOSC
      FROM ZDST_KLAS z where   z.ID_APTEKI = :iap and z.ID_ZDST = :idk and z.ID_KLASYFIKACJE <> 7;
  
    INSERT INTO CENY_DOSTAWY (ID_APTEKI, ID_ZDST, ID_CENY, OBOWIAZUJE_OD, MARZA,
        CENA_NT, CENA_BR, CENA_NT_JP, CENA_BR_JP)
      SELECT ID_APTEKI, :idn, ID_CENY, :dtd, MARZA,
        CENA_NT, CENA_BR, CENA_NT_JP, CENA_BR_JP
      FROM CENY_DOSTAWY z where   z.ID_APTEKI = :iap and z.ID_ZDST = :idk and z.OBOWIAZUJE_OD =
      (SELECT max(y.OBOWIAZUJE_OD) FROM CENY_DOSTAWY y where y.ID_APTEKI = :iap and y.ID_ZDST = :idk and y.ID_CENY = z.ID_CENY);
  END
  
    
  
END
^

ALTER PROCEDURE DOPISZ_DO_OFERTY (
    IKT INTEGER,
    IKL INTEGER,
    KOD VARCHAR(20),
    WEWN VARCHAR(20),
    BAZYL VARCHAR(20),
    BLOZ2 VARCHAR(20),
    BLOZ7 VARCHAR(20),
    EAN VARCHAR(20),
    NAZWA VARCHAR(128),
    CENA DOUBLE PRECISION,
    UPUST DOUBLE PRECISION,
    KIEDY TIMESTAMP,
    VAT DOUBLE PRECISION,
    ID_P_PROM VARCHAR(10) )
AS
begin
  update or insert into oferty (ID_DOSTAWCY,KOD,NAZWA,LASTOF,STAWKA_VAT) values (:ikt,:kod,:nazwa,:kiedy,:vat);
  if (cena>0) then
    update or insert into oferty_ceny (ID_DOSTAWCY, DATA, KOD, CENA, UPUST, ID_POZ_PROM) values (:ikt, :kiedy, :kod, :cena,:upust,:id_p_prom);
  if (wewn>' ') then
    update or insert into oferty_klas (ID_DOSTAWCY, KOD, ID_KLASYFIKACJE,WARTOSC) values (:ikt, :kod,:ikl,:wewn);
  else
    delete from oferty_klas where id_dostawcy=:ikt and  kod=:kod and  id_klasyfikacje=:ikl;

  if (bloz7>' ') then
    update or insert into oferty_klas (ID_DOSTAWCY, KOD, ID_KLASYFIKACJE,WARTOSC) values (:ikt, :kod,3,:bloz7);
  else
    delete from oferty_klas where id_dostawcy=:ikt and  kod=:kod and  id_klasyfikacje=3;
  if (ean>' ') then
    update or insert into oferty_klas (ID_DOSTAWCY, KOD, ID_KLASYFIKACJE,WARTOSC) values (:ikt, :kod,6,:ean);
  else
    delete from oferty_klas where id_dostawcy=:ikt and  kod=:kod and  id_klasyfikacje=6;
end
^


COMMIT^


CREATE or alter VIEW V_UTARGMIESIACBIEZACY (ROK, MIESIAC, ID_APTEKI, OPIS, KWOTA)
AS  
select null,null,null,'Od: '||
(select * from TYLKO_DATA((SELECT  cast(left(cast('today' as date),11) as date)-1-EXTRACT(DAY FROM cast(left(cast('today' as date),11) as date)-1)+1 fROM RDB$DATABASE))),null
fROM RDB$DATABASE

UNION 
select EXTRACT(year FROM w.data),EXTRACT(MONTH FROM w.data),w.id_apteki,o.nm_tranz_opisy  opis,sum(w.KWOTA) kwota 
from tranz_wplaty w left join tranz_opisy o on o.id_tranz_opisy=w.id_tranz_opisy  left join tranzakcje t on t.id_apteki=w.id_apteki and t.data=w.data and t.id_tranzakcje=w.id_tranzakcje 
where w.data >= (SELECT  cast(left(cast('today' as date),11) as date)-1-EXTRACT(DAY FROM cast(left(cast('today' as date),11) as date)-1)+1 fROM RDB$DATABASE)
   
group by EXTRACT(year FROM w.data),EXTRACT(MONTH FROM w.data),w.id_apteki,o.nm_tranz_opisy

union
select EXTRACT(year FROM w.data),EXTRACT(MONTH FROM w.data),w.id_apteki,'RAZEM WP£ATY' opis ,sum(w.KWOTA) kwota
from tranz_wplaty w left join tranz_opisy o on o.id_tranz_opisy=w.id_tranz_opisy  left join tranzakcje t on t.id_apteki=w.id_apteki and t.data=w.data and t.id_tranzakcje=w.id_tranzakcje 
where w.data >= (SELECT  cast(left(cast('today' as date),11) as date)-1-EXTRACT(DAY FROM cast(left(cast('today' as date),11) as date)-1)+1 fROM RDB$DATABASE)
  
group by EXTRACT(year FROM w.data),EXTRACT(MONTH FROM w.data),w.id_apteki

union
select EXTRACT(year FROM s.data),EXTRACT(MONTH FROM s.data),s.id_apteki,'Refundacja' opis, sum(WARTOSC+TAKSA-ODPLATNOSC-DOPLATA) kwota 
from sprzedaz s left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje 
where s.data >= (SELECT  cast(left(cast('today' as date),11) as date)-1-EXTRACT(DAY FROM cast(left(cast('today' as date),11) as date)-1)+1 fROM RDB$DATABASE)

 and (t.id_kontrahenci is null or t.id_kontrahenci>0)
group by EXTRACT(year FROM s.data),EXTRACT(MONTH FROM s.data),s.id_apteki

union
select EXTRACT(year FROM s.data),EXTRACT(MONTH FROM s.data),s.id_apteki,'Brutto' opis,sum(s.WARTOSC+s.TAKSA) 
from sprzedaz s left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
where s.data >= (SELECT  cast(left(cast('today' as date),11) as date)-1-EXTRACT(DAY FROM cast(left(cast('today' as date),11) as date)-1)+1 fROM RDB$DATABASE)
  
and (t.id_kontrahenci is null or t.id_kontrahenci>0)
group by EXTRACT(year FROM s.data),EXTRACT(MONTH FROM s.data),s.id_apteki


union
select EXTRACT(year FROM s.data),EXTRACT(MONTH FROM s.data),s.id_apteki,'Netto' opis,sum((s.WARTOSC+s.TAKSA)/(1+0.01*s.STAWKA_VAT)) 
from sprzedaz s left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
where s.data >= (SELECT  cast(left(cast('today' as date),11) as date)-1-EXTRACT(DAY FROM cast(left(cast('today' as date),11) as date)-1)+1 fROM RDB$DATABASE)
  
and (t.id_kontrahenci is null or t.id_kontrahenci>0)
group by EXTRACT(year FROM s.data),EXTRACT(MONTH FROM s.data),s.id_apteki

union
select EXTRACT(year FROM s.data),EXTRACT(MONTH FROM s.data),s.id_apteki,'Sprzeda¿ w cenie zakupu' opis,sum(WART_ZAK) WART_ZAK 
from sprzedaz s left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
where s.data >= (SELECT  cast(left(cast('today' as date),11) as date)-1-EXTRACT(DAY FROM cast(left(cast('today' as date),11) as date)-1)+1 fROM RDB$DATABASE)

and (t.id_kontrahenci is null or t.id_kontrahenci>0)
group by EXTRACT(year FROM s.data),EXTRACT(MONTH FROM s.data),s.id_apteki
^

ALTER TRIGGER UPD_CBT ACTIVE
BEFORE UPDATE POSITION 0
as
declare variable ap apteka;
begin
  if (RDB$GET_CONTEXT('USER_SESSION','BAZYL') = 1 AND  COALESCE(old.ID_SYNSZCZ,0)<0 and COALESCE(new.ID_SYNSZCZ,0)>=0) THEN
    new.ID_SYNSZCZ=old.ID_SYNSZCZ;
   
  if ((NEW.IFUPDDATE = OLD.IFUPDDATE or OLD.IFUPDDATE is null)
    and (new.nm_short is distinct from old.nm_short or new.nazwa is distinct from old.nazwa
    or new.postac is distinct from old.postac or new.dawka is distinct from old.dawka 
    or new.opakowanie is distinct from old.opakowanie or new.id_internm is distinct from old.id_internm
    or new.id_odpzl is distinct from old.id_odpzl or new.id_synszcz is distinct from old.id_synszcz
    or new.id_synzb is distinct from old.id_synzb or new.id_producenci is distinct from old.id_producenci
    or new.ilosc_ddd is distinct from old.ilosc_ddd /*zamawiaj zlikwidowane w zwi¹zku z problemami z cbt_kas_ean*/
    or new.ID_SYNWL is distinct from old.ID_SYNWL
    or new.promowany is distinct from old.promowany or new.prom_wg is distinct from old.prom_wg     
    or new.centralna is distinct from old.centralna
    or new.WWW_ULOTKA is distinct from old.WWW_ULOTKA or new.WWW_CHARAKT is distinct from old.WWW_CHARAKT 
    or new.WWW_URL is distinct from old.WWW_URL
    or old.DEFICYTOWY is distinct from new.DEFICYTOWY
    or old.ser_podl is distinct from new.ser_podl or old.smopl_podl is distinct from new.smopl_podl
    or old.REGL_DNI is distinct from new.REGL_DNI or old.REGL_ILE is distinct from new.REGL_ILE
    ))
   then
   begin
    NEW.IFUPDDATE='NOW';
    NEW.IFUPDUSER=USER;
    if (:ap=1 and new.centralna is distinct from 'N' or :ap=99 and old.id_cbt>1000000) then 
      begin 
      update cbt_ceny set IFUPDDATE='NOW' where id_cbt=old.id_cbt;
      update cbt_jedn set IFUPDDATE='NOW' where id_cbt=old.id_cbt;
      update cbt_klas set IFUPDDATE='NOW' where id_cbt=old.id_cbt; 
      update cbt_LISTY set IFUPDDATE='NOW' where id_cbt=old.id_cbt;
      update cbt_odpl set IFUPDDATE='NOW' where id_cbt=old.id_cbt;
      update cbt_PRZEWL set IFUPDDATE='NOW' where id_cbt=old.id_cbt; 
      update cbt_sklad set IFUPDDATE='NOW' where id_cbt=old.id_cbt;
      update cbt_uwagi set IFUPDDATE='NOW' where id_cbt=old.id_cbt; 
      update cbt_VAT set IFUPDDATE='NOW' where id_cbt=old.id_cbt;  
      update cbt_sklad set IFUPDDATE='NOW' where id_cbt=old.id_cbt; 
      end
     if (:ap=99) then update cbt_klas set IFUPDDATE='NOW' where id_cbt=old.id_cbt and id_klasyfikacje=18;  
    end
    
   if (:ap=99 and old.zamawiaj is distinct from new.zamawiaj) then new.zamclick='now';   
end^

ALTER PROCEDURE KOPIA_CBT (
    STARE Integer )
RETURNS (
    ID Integer )
AS
declare variable ap apteka;
begin
  select max(id_cbt) from cbt where id_cbt>=1000000 or 1=:ap and id_cbt>=500000 into id;
  if (id is null) then id=1000000;
  else id=id+1;
  insert into cbt (ID_CBT, NM_SHORT, NAZWA, POSTAC, DAWKA, OPAKOWANIE, ID_PRODUCENCI, ID_APTEKI, centralna,id_internm,id_synzb)
    select :id, NM_SHORT, NAZWA, POSTAC, DAWKA, OPAKOWANIE, ID_PRODUCENCI, ID_APTEKI,'N',iif(1=:ap,id_internm,null),iif(1=:ap,id_synzb,null)  from cbt where id_cbt=:stare;

  insert into cbt_jedn (ID_CBT, JEDNOSTKA, NAZWA, MNOZNIK, DZIELNIK, POCHODZI_OD, SPRZEDAZ, RECEPTURA, DOSTAWY, PODSTAWOWA)
    select :id, JEDNOSTKA, NAZWA, MNOZNIK, DZIELNIK, POCHODZI_OD, SPRZEDAZ, RECEPTURA, DOSTAWY, PODSTAWOWA from cbt_jedn  where id_cbt=:stare;
  insert into CBT_KLAS (ID_CBT, ID_KLASYFIKACJE, WARTOSC)
    select :id, ID_KLASYFIKACJE, WARTOSC from  cbt_klas  where id_cbt=:stare and id_klasyfikacje in (7,13,14,15,18,22,24);
  insert into CBT_LISTY (ID_CBT, ID_LISTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO)
    select :id, ID_LISTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO  from  cbt_listy  where id_cbt=:stare;
  insert into CBT_VAT (ID_CBT, DATA_OD, KOD)
    select :id, DATA_OD, KOD from  cbt_vat  where id_cbt=:stare;
  suspend;
end^


create or ALTER PROCEDURE DEL_DUBLE_BLOZ
AS
declare variable ap apteka;
declare variable dt timestamp;
declare variable it integer;
declare variable ic varchar(40);
declare variable s char(1);
DECLARE VARIABLE ik int;
begin    
 for select max(k.ifupddate),k.id_towary,c.wartosc from tw_klas k
  join towary t on t.id_towary=k.id_towary and t.id_apteki=k.id_apteki
  left join cbt_klas c on c.id_cbt=t.id_cbt and c.id_klasyfikacje=3
  where k.id_apteki=:ap and k.id_klasyfikacje=3 
  group by k.id_towary,c.wartosc having count(*)>1 into dt,it,ic DO
  BEGIN
   delete from tw_klas where id_apteki=:ap and id_klasyfikacje=3 and id_towary=:it and wartosc<>:ic;
   delete from tw_klas where id_apteki=:ap and id_klasyfikacje=3 and id_towary=:it and wartosc<>coalesce(:ic,'0') and ifupddate<:dt ;
  end

/*eany pdwójne kasujemy tylko dla spasowanych z istniejacym ean i raportowanych*/
 for select k.id_towary,k.wartosc,iif(t.smopl_rap='T' or t.ser_podl='T','T','') from tw_klas k
  join towary t on t.id_towary=k.id_towary and t.id_apteki=k.id_apteki
  join cbt_klas c on c.id_cbt=t.id_cbt and c.id_klasyfikacje=6
  where k.id_apteki=:ap and k.id_klasyfikacje=6 and k.wartosc<>c.wartosc into it,ic,s DO
  BEGIN
   if (:s='T') then
    delete from tw_klas where id_apteki=:ap and id_klasyfikacje=6 and id_towary=:it and wartosc=:ic;
   else
    begin    
     if (exists (select*from cbt_klas c join cbt on c.id_cbt=cbt.id_cbt where c.id_klasyfikacje=6 and c.wartosc=:ic and (smopl_podl='T' or ser_podl='T')))  then
     delete from tw_klas where id_apteki=:ap and id_klasyfikacje=6 and id_towary=:it and wartosc=:ic;    
    end
  end
  
 /*zasadniczo jednorazowo bo dodane w kas-ean */
 RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
 for select max(ifupddate),id_cbt,id_klasyfikacje from cbt_klas
  where id_klasyfikacje in (11,23,-12,-10,-11) and :ap>1
  group by id_cbt,id_klasyfikacje
  having count(*)>1 into dt,it,ik do
    delete from cbt_klas where id_cbt=:it and id_klasyfikacje=:ik and ifupddate<:dt;
 RDB$SET_CONTEXT('USER_SESSION','IFROZP',0);
  
end^

ALTER PROCEDURE DEL_DEK_DOST (
    IA INTEGER,
    DW TIMESTAMP,
    DD TIMESTAMP,
    DP TIMESTAMP,
    NF VARCHAR(100),
    IZ INTEGER )

AS
declare variable id integer;
declare variable ib integer;
declare variable ds integer;
DECLARE idz DOUBLE PRECISION;
DECLARE tt DOUBLE PRECISION;
DECLARE PRZYSZLO DOUBLE PRECISION;
begin
  for select id_dokumenty from dokumenty where id_apteki=:ia and data=:dd and data_wy =:dw and symb_zewn=:nf and symb_wewn like 'VAT%' into :id do
  begin    
    delete from dokumenty where id_apteki=:ia and powiazany_z=:id;            
    delete from dokumenty where id_apteki=:ia and id_dokumenty=:id;
    when any do EXCEPTION blad 'Dokument zap³acony - najpierw usuñ zap³atê z modu³u kasowego 
Kasa: '||(select o.opis||', '||(select*from TYLKO_DATA(o.DATA)) from dokumenty o1 
          left join dekrety d1 on o1.id_apteki=d1.id_apteki and o1.ID_DOKUMENTY=d1.ID_DOKUMENTY
          left join pow_fk p on p.id_apteki=d1.id_apteki and p.id_d2=d1.id_dekrety
          left join dekrety d on p.id_apteki=d.id_apteki and  p.id_dekrety=d.id_dekrety
          left join dokumenty o on o.id_apteki=d.id_apteki and d.id_dokumenty=o.id_dokumenty
          where o1.id_apteki=:ia and o1.powiazany_z=:id and o1.symb_wewn like 'R%' rows 1);     
  end

  update dostawy set status='P' where id_apteki=:ia and id_dostawy=:iz;

end
^

create or ALTER PROCEDURE NOWE_ZAM (
    LOGIN VARCHAR(100),
    NAZWISKO VARCHAR(151),
    IMIE VARCHAR(152),
    ADRES VARCHAR(153),
    MIASTO VARCHAR(100),
    KOD VARCHAR(80),
    TEL VARCHAR(125),
    EMAIL VARCHAR(130),
    PLATNOSC CHAR(1),
    PLOPIS VARCHAR(128),
    UWAGI VARCHAR(1024),
    DT TIMESTAMP,
    IDKZ INTEGER,
    IDAP INTEGER,
    IDTR VARCHAR(20),
    TROPIS VARCHAR(128),
    NRD VARCHAR(20),
    NRL VARCHAR(20),
    NM2 VARCHAR(100),
    ID2 VARCHAR(20),
    NIP VARCHAR(20) )
RETURNS (
    ID_ZAM INTEGER )


AS
declare variable idk integer;
declare variable poczta varchar(50);
begin
if (idkz<=0) then
  select GEN_ID(SQ_KZAM,1) from JEDEN_WIERSZ into :id_zam;
else
  id_zam=idkz;
select id_kontrahenci from kontrahenci where nm_kontrahenci=:login into :idk;
if (CHAR_LENGTH(kod)>6) then
begin
  poczta=substring(kod from 8 for 50);
  kod=substring(kod from 1 for 6);
end
else
  poczta=left(:miasto,50);
  
nip  = NULLIF(nip,'');
if (idk is null) then
begin
  select gen_id(sq_kontrahenci,1) from jeden_wiersz into :idk;
  insert into kontrahenci (id_kontrahenci, nm_kontrahenci, nazwa_pelna, email, telefon, nip) values (:idk,:login,left(:imie||' '||:nazwisko,256),left(:email,128),left(:tel,128),left(:nip,15));
  insert into adresy (id_kontrahenci,lp,kod,poczta,miasto,ulica,nr_domu,nr_lokalu) values (:idk,1,left(:kod,6),left(:poczta,50),left(:miasto,50),left(:adres,50),left(:nrd,10),left(:nrl,10));
end
else
begin
  update kontrahenci set nazwa_pelna=left(:imie||' '||:nazwisko,256), email=left(:email,128), telefon=left(:tel,128), NIP=left(:nip,15) where id_kontrahenci=:idk;
  update adresy set kod=left(:kod,6),poczta=left(:poczta,50),miasto=left(:miasto,50),ulica=left(:adres,50),nr_domu=left(:nrd,10),nr_lokalu=left(:nrl,10) where id_kontrahenci=:idk and lp=1;
end
if (idtr is not null) then
  UPDATE OR INSERT INTO WWW_ODBIORY (ID_APTEKI, ID_ODBIOR, NM_ODBIOR, AKTYWNY, RECEPTY) VALUES (:idap,:idtr,:tropis,'T','T');
if (platnosc > ' ')   then
  UPDATE OR INSERT INTO WWW_SPPL    (ID_APTEKI, ID_SPPL, NM_SPPL) VALUES (:idap,:platnosc,:plopis) ;
update or insert into kzam (id_kzam,login,data,platnosc,status,uwagi,id_apteki,id_kontrahenci,ID_ODBIOR,id2,nm2) values (:id_zam,:login,:dt,:platnosc,0,:uwagi,:idap,:idk,:idtr, :id2, :nm2);
suspend;
end
^


ALTER TRIGGER UPD_ZDST_XML ACTIVE
AFTER UPDATE POSITION 0
as
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
    
  if (old.sztuk<0 and old.korekta_do=0 and new.korekta_do<>0 --przypadek kiedy w korekcie xml wybiera zly lek i recznie poprawiamy korekta do
      and old.id_towary<>(select id_towary from zdst where id_apteki=new.id_apteki and id_zdst=new.korekta_do)) 
   then
   update zdst set id_towary=(select id_towary from zdst where id_apteki=new.id_apteki and id_zdst=new.korekta_do)
    where ID_APTEKI=old.id_apteki and id_zdst=OLD.id_zdst;
    
  /*zamowienia - zmiana pozycji*/  
  if (new.ID_ZAM is DISTINCT FROM old.ID_ZAM or new.ID_TOWARY <> old.ID_TOWARY) THEN
    if ((select d.STATUS from DOSTAWY d where d.ID_DOSTAWY = new.ID_DOSTAWY and d.ID_APTEKI = new.ID_APTEKI) in ('Z','P')) THEN
  BEGIN
     if (old.ID_ZAM is not null) THEN
       update zam_poz s set przyszlo=(SELECT sum(z.SZTUK_JP) from ZDST z  where z.ID_APTEKI = old.ID_APTEKI and z.ID_ZAM = old.ID_ZAM and z.ID_TOWARY = old.ID_TOWARY )
       where s.id_apteki=old.ID_APTEKI and s.id_zam=old.ID_ZAM and s.id_towary=old.ID_TOWARY;
     if (new.ID_ZAM is not null) THEN
       update zam_poz s set przyszlo=(SELECT sum(z.SZTUK_JP) from ZDST z  where z.ID_APTEKI = new.ID_APTEKI and z.ID_ZAM = new.ID_ZAM and z.ID_TOWARY = new.ID_TOWARY )
       where s.id_apteki=new.ID_APTEKI and s.id_zam=new.ID_ZAM and s.id_towary=new.ID_TOWARY;  
     update zaminfo set stan=6 where id_apteki=new.id_apteki and id_zam=new.id_zam and stan>3;
  END  
end
^

CREATE or alter TRIGGER DEL_ZDST_ZAM for ZDST ACTIVE
AFTER DELETE POSITION 1000
as
DECLARE st DOUBLE PRECISION;
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  if (old.id_zam is NOT NULL) THEN
    begin
     SELECT sum(z.SZTUK_JP) from ZDST z 
       left join dostawy d on d.ID_DOSTAWY = z.ID_DOSTAWY and d.ID_APTEKI = z.ID_APTEKI
       where z.ID_APTEKI = old.ID_APTEKI and z.ID_ZAM = old.ID_ZAM and z.ID_TOWARY = old.ID_TOWARY and d.STATUS in  ('Z','P') and z.ID_ZDST <> old.ID_ZDST
     INTO st;  
     if (st=0) THEN st = NULL;
     
     update zam_poz s set przyszlo=:st
       where s.id_apteki=old.ID_APTEKI and s.id_zam=old.ID_ZAM and s.id_towary=old.ID_TOWARY;
       
     if (not exists(select * from zam_poz z  where  z.ID_ZAM=old.id_zam and z.ID_APTEKI=old.id_apteki and PRZYSZLO is not NULL )) THEN
     begin
       update zaminfo set stan=4 where id_apteki=old.id_apteki and id_zam=old.id_zam and stan>5;
     end
    end
end^


CREATE OR ALTER TRIGGER CT_DOSTAWY FOR DOSTAWY
ACTIVE AFTER UPDATE POSITION 99
AS
declare sti int;
declare noi int;
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

    IF (OLD.ID_BRAKI IS DISTINCT FROM NEW.ID_BRAKI)
    THEN
    BEGIN
    if (OLD.ID_BRAKI is not null) THEN
       SELECT FIRST 1 z.id_zam FROM ZAMINFO z WHERE z.id_braki=old.id_braki and z.id_apteki=old.id_apteki and (z.id_kontrahenci=old.id_kontrahenci or z.id_hurtowni=old.id_kontrahenci) into sti;
     if (NEW.ID_BRAKI is not null) THEN
       SELECT FIRST 1 z.id_zam FROM ZAMINFO z WHERE z.id_braki=new.id_braki and z.id_apteki=new.id_apteki and (z.id_kontrahenci=new.id_kontrahenci or z.id_hurtowni=new.id_kontrahenci) into noi;

     update zdst set id_zam=:noi  where id_apteki=OLD.ID_APTEKI and id_dostawy=old.id_dostawy  and (id_zam = :sti or id_zam is null);
    END
END^

ALTER TRIGGER INS_UPD_RECEPTURA ACTIVE
BEFORE INSERT OR UPDATE POSITION 0
as
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

if (coalesce(new.proszkow,0)<=0) then new.proszkow=1;
if (new.proszkow>1 and not exists(select*from post_zl where ID_POST_ZL=new.ID_POST_ZL and nm_post_zl containing 'szt.'))  then new.proszkow=1;

if (INSERTING) THEN
  new.CENY_BRUTTO = (SELECT COALESCE(o.TAKSA_BR,'N') FROM OGOLNE o WHERE o.ID_APTEKI=new.ID_APTEKI);
  
if (new.dt_rozl>dateadd (minute, -2, new.dt_odb) or new.dt_rozl<new.dt_przyj) then
 begin
 if (dateadd (minute, -2, new.dt_odb)>dateadd (minute, 5, new.dt_przyj)) then 
  new.dt_rozl = dateadd (minute, -2, new.dt_odb);
  ELSE
  new.dt_rozl = maxvalue(minvalue(new.dt_odb,dateadd (minute, 1, new.dt_przyj)),dateadd (minute, -1, new.dt_odb));
 end   
end
^

ALTER PROCEDURE UP_Z_CBT (
    IAP INTEGER,
    IDC INTEGER,
    IDT INTEGER,
    NEW INTEGER )
RETURNS (
    PS VARCHAR(100),
    DW VARCHAR(100),
    OP VARCHAR(100),
    O1 INTEGER,
    O2 INTEGER,
    O3 INTEGER,
    O4 INTEGER,
    PR INTEGER,
    DP CHAR(1),
    IC INTEGER,
    EANR VARCHAR(20),
    DDD DOUBLE PRECISION,
    TE INTEGER )

AS
declare variable jd integer;
declare variable nm varchar(100);
declare variable os varchar(100);
declare variable mn integer;
declare variable jj integer;
declare variable dz integer;
declare variable po integer;
declare variable rc integer;
declare variable sp char(1);
declare variable re char(1);
declare variable ds char(1);


declare variable tjd integer;
declare variable tnm varchar(100);
declare variable tmn integer;
declare variable tdz integer;
declare variable tpo integer;
declare variable tsp char(1);
declare variable tre char(1);
declare variable tds char(1);
declare variable tpd char(1);



declare variable d1 char(1);
declare variable pd char(1);
declare variable ci char(1);
declare variable od timestamp;
declare variable dd timestamp;
declare variable cb double precision;
declare variable cl double precision;
declare variable mu integer;
declare variable dr timestamp;

declare variable dzis date;
declare variable dzak date;
declare variable dspr date;

declare variable     ipo char(1);
declare variable     ije char(1);
declare variable     ijr char(1);
declare variable     ijo char(1);
declare variable     ikl char(1);
declare variable     ili char(1);
declare variable     ice char(1);
declare variable     itc char(1);
declare variable     ivt char(1);

declare variable   tPS VARCHAR(100);
declare variable   tDW VARCHAR(100);
declare variable   tOP VARCHAR(100);
declare variable   tO1 INTEGER;
declare variable   tO3 INTEGER;
declare variable   tO4 INTEGER;
declare variable   tPR INTEGER;
declare variable   tDDD DOUBLE PRECISION;
declare variable   tEANR VARCHAR(20);
declare variable   tTE INTEGER;
declare variable   tet char(1);
declare variable   ttet char(1);
declare variable   nsp char(1);
declare variable   yps char(1);
declare variable   cps char(1);
declare variable   ysm char(1);
declare variable   csm char(1);

DECLARE rgd INTEGER;
DECLARE rgi INTEGER;

DECLARE rad INTEGER;
DECLARE rai INTEGER;

begin

  if (idt=0 or idt=-1) then
    exit;

  select imp_cbt_jedn,postac,dawka, opakowanie,ID_INTERNM,ID_SYNSZCZ,ID_SYNZB,ID_PRODUCENCI,ILOSC_DDD,ean_ref,xml_typ,ean_typ,t.SER_PODL,t.SMOPL_RAP,t.REGL_DNI,t.REGL_ILE from towary t where id_towary=:idt and id_apteki=:iap
  into ci,tps,tdw,top,to1,to3,to4,tpr,tddd,teanr,tte,ttet,yps,ysm,rad,rai;


  if (ci='A') then
    exit;

  dzis='TODAY';
  if (idc<=0 or idc is null) then
  begin
    execute procedure id_cbt(:iap,:idt) returning_values :idc;
    nsp='T';
  end
  else
    nsp='N';
  ic=idc;
  if (idc<=0 or idc is null) then
  begin
    select count(*) from tow_listy where id_apteki=:iap and id_towary=:idt and id_listy<>21 into :jd;
    if (jd=0) then
      insert into tow_LISTY (ID_APTEKI,id_towary,id_listy,obowiazuje_od,obowiazuje_do) values (:iap,:idt,1,'01/01/1990','01/01/3000');
    dp='T';
    exit;
  end

  if (NEW=1) then
    select CBT_POSTAC,CBT_JEDNOSTKI,CBT_JEDN_REC,CBT_JEDN_RYCZ,CBT_KLASYFIKACJE,CBT_LISTY,CBT_CENY,CBT_TYP_CENY,CBT_VAT from OGOLNE where id_apteki=:iap into
      ipo,ije,ijr,ijo,ikl,ili,ice,itc,ivt;
  else
  begin
    ipo='T';
    ije='T';
    ijr='T';
    ijo='T';
    ikl='T';
    ili='T';
    ice='T';
    itc='T';
    ivt='T';
  end

  if (ipo='T') then
  begin
    select POSTAC,DAWKA,OPAKOWANIE,ID_INTERNM,null,ID_SYNSZCZ,ID_SYNZB,ID_PRODUCENCI,ILOSC_DDD,c.SER_PODL,c.SMOPL_PODL,c.REGL_DNI,c.REGL_ILE from cbt c
      where c.id_cbt=:idc
      into :ps,:dw,:op,:o1,:o2,:o3,:o4,:pr,ddd,cps,csm,rgd,rgi;


    if (CHAR_LENGTH(trim(dw))=0) then dw=tdw;
    if (CHAR_LENGTH(trim(op))=0) then op=top;
    if (CHAR_LENGTH(trim(ps))=0) then ps=tps;
    
    select first 1 WARTOSC from  cbt_klas
     where id_cbt=:idc and id_klasyfikacje=6
     order by ifupddate desc
     into eanr ;

    select count(*) from  cbt_klas
      where id_cbt=:idc and id_klasyfikacje=7 and wartosc='l' into jj;

    if (jj>0) then
      te=3;
    else
    begin
      select count(*) from  cbt_klas
        where id_cbt=:idc and id_klasyfikacje=7 and wartosc='5' into jj;
      if (jj>0) then
        te=2;
      else
        te=0;
    end

    if (eanr is not null) then
    begin
      tet='0';
    end
    else
    begin
      eanr=teanr;
      if (tet is null) then tet='0';
    end

    if (ps is distinct from  tps or dw is distinct from  tdw or op is distinct from top or o1 is distinct from to1 or  o3 is distinct from  to3 or o4 is distinct from  to4 or pr is distinct from  tpr
       or ddd is distinct from  tddd or tte is distinct from  te or tte is null or eanr  is distinct from   teanr or nsp='T' or ttet is null or cps is DISTINCT from yps or csm is DISTINCT FROM ysm
       or rgd is DISTINCT FROM rad or rgi is DISTINCT FROM rai) then
       update towary set postac=:ps ,dawka=:dw, opakowanie=:op,ID_INTERNM=:o1,ID_SYNSZCZ=:o3,ID_SYNZB=:o4,ID_PRODUCENCI=:pr,ID_CBT=:idc,ILOSC_DDD=:ddd,xml_typ=:te,ean_ref=:eanr,ean_typ=:tet,ser_podl = :cps,SMOPL_RAP=:csm,
        REGL_DNI = :rgd,REGL_ILE = :rgi
        where id_apteki=:iap and id_towary=:idt;
  end

  if (NEW=1) then
  begin
    if (ci='T') then
    begin
      /*  sprawdzanie czy skladnik receptury*/
      select count(*) from cbt_klas where id_cbt=:idc and id_klasyfikacje=7 and (wartosc='z' or wartosc='n') into :rc;
      if (rc>0) then
      begin
        ije=ijr;
        ijo=ije;
      end
    end
    else
    begin
      ije='N';
      ijo='N';
    end
  end

  if (ije='T' or ijo='T') then
  begin
    select count(*) from jednostki where id_apteki=:iap and id_towary=:idt and jednostka=1 and nazwa='OP.' and mnoznik=1 and dzielnik=1
     and sprzedaz='T' and receptura='N' and podstawowa='T'  into jd;
    if (jd=0) then
      update or insert into jednostki (ID_APTEKI,ID_TOWARY,JEDNOSTKA,NAZWA,MNOZNIK,DZIELNIK,POCHODZI_OD,SPRZEDAZ,RECEPTURA,DOSTAWY,PODSTAWOWA)
      values (:iap,:idt,1,'OP.',1,1,null,'T','N','T','T');

    ijr='N';
    d1='N';
    ci='N';
    jd=0;
    for select c.JEDNOSTKA,c.NAZWA,c.MNOZNIK,c.DZIELNIK,c.POCHODZI_OD,c.SPRZEDAZ,c.RECEPTURA,c.DOSTAWY,c.PODSTAWOWA,
      t.JEDNOSTKA,t.NAZWA,t.MNOZNIK,t.DZIELNIK,t.POCHODZI_OD,t.SPRZEDAZ,t.RECEPTURA,t.DOSTAWY,t.PODSTAWOWA
      from cbt_jedn c
      left join jednostki t on t.id_apteki=:iap and t.id_towary=:idt and t.jednostka=c.jednostka
      where c.id_cbt=:idc and c.jednostka<>1 and (:ije='T' or c.jednostka=-1)
      order by c.jednostka
      into jd,nm,mn,dz,po,sp,re,ds,pd,tjd,tnm,tmn,tdz,tpo,tsp,tre,tds,tpd do
    begin
      if (jd=-1) then
      begin
        ijr='T';
        ds='N';
      end
      else
        if (tds is not null) then ds=tds;

      if (tjd is not null) then
      begin
        if (jd<> tjd or nm<>tnm or mn<>tmn or dz<>tdz or po<>tpo or sp<>tsp or re>tre or ds<>tds or pd<>tpd)then
        begin
          if (re='T' and (tre='N' or tre is null)) then
            update jednostki set receptura='N' where id_apteki=:iap and id_towary=:idt and receptura<>'N';
          update jednostki set NAZWA=:nm,MNOZNIK=:mn,DZIELNIK=:dz,POCHODZI_OD=:po,SPRZEDAZ=:sp,RECEPTURA=:re,DOSTAWY=:ds,PODSTAWOWA='N' where  id_apteki=:iap and id_towary=:idt and JEDNOSTKA=:jd;
        end
      end
      else
        insert into jednostki (ID_APTEKI,ID_TOWARY,JEDNOSTKA,NAZWA,MNOZNIK,DZIELNIK,POCHODZI_OD,SPRZEDAZ,RECEPTURA,DOSTAWY,PODSTAWOWA)
          values (:iap,:idt,:jd,:nm,:mn,:dz,:po,:sp,:re,:ds,'N');
    end
    if (ijr='N') then
      delete from jednostki where id_apteki=:iap and id_towary=:idt and jednostka=-1;
    if (jd>1) then
      delete from jednostki where id_apteki=:iap and id_towary=:idt and jednostka>:jd and (dostawy<>'T' or dostawy is null);
  end


  /* sprawdzanie czy dopuszczony  */
  select count(*) from cbt_klas where id_cbt=:idc and id_klasyfikacje=7 and wartosc='7' into :jd;
  if (jd>0) then
  begin
    select count(*) from cbt_klas where id_cbt=:idc and id_klasyfikacje=7 and wartosc='f' into :jd;
    if (jd>0) then dp='N'; else dp='T';
  end
  else
    dp='N';


  if (ikl='T') then
  begin
    for select t.ID_KLASYFIKACJE,t.wartosc from tw_klas t
    left join  klas_sl s on t.id_klasyfikacje=s.id_klasyfikacje and t.wartosc = substring(s.opis  from 1 for 40)
    left join  cbt_klas c on c.id_cbt=:idc and  t.id_klasyfikacje=c.id_klasyfikacje and c.wartosc=coalesce(s.wartosc,t.wartosc)
    where t.id_apteki = :iap and t.id_towary=:idt  and (t.id_klasyfikacje in (1,4,7,11,12,13,14,15,18,22,24) or (t.id_klasyfikacje in (3,6) and (:cps='T' or :csm='T')))
     and c.wartosc is null into jd,nm do
       delete from tw_klas where id_apteki=:iap and id_towary=:idt and id_klasyfikacje=:jd and wartosc=:nm;
  
    for select c.ID_KLASYFIKACJE,substring(coalesce(s.OPIS,c.wartosc) from 1 for 40) from cbt_klas c left join klas_sl s on c.id_klasyfikacje=s.id_klasyfikacje and c.wartosc = s.wartosc
    left join  tw_klas t on t.id_apteki=:iap and t.id_towary=:idt  and t.id_klasyfikacje =c.id_klasyfikacje and t.wartosc=substring(coalesce(s.OPIS,c.wartosc) from 1 for 40)
    where c.id_cbt=:idc  and c.id_klasyfikacje in (-10,-11,1,3,4,6,7,11,12,13,14,15,18,22,24) and t.wartosc is null into jd,nm do
      begin
        if (jd<>3 or (cps='T' or csm='T') or not exists (select * from tw_klas where id_apteki=:iap and id_towary=:idt and id_klasyfikacje=3)) 
         then update or insert into tw_klas (id_apteki,id_towary,id_klasyfikacje,wartosc) values (:iap,:idt,:jd,:nm);      
      end
      
    nm = null;  
    select c.WARTOSC,t.WARTOSC
    from CBT_KLAS c
    left join  tw_klas t on t.id_apteki=:iap and t.id_towary=:idt  and t.id_klasyfikacje =c.id_klasyfikacje and t.wartosc=c.wartosc
    where c.id_cbt=:idc  and c.id_klasyfikacje = -17
    into nm,os;  
    if (nm is null) THEN
      delete from tw_klas where id_apteki=:iap and id_towary=:idt and id_klasyfikacje=-17;
    else if (os is null) THEN
      insert into tw_klas (id_apteki,id_towary,id_klasyfikacje,wartosc) values (:iap,:idt,-17,:nm);        
    ELSE if (nm <> os) THEN
      UPDATE TW_KLAS t set t.WARTOSC = :nm where t.ID_TOWARY = :idt and t.ID_APTEKI = :iap and t.ID_KLASYFIKACJE = -17 and t.WARTOSC = :os;
  end


  /* Listy */
  dr='01/01/2000';
  if (ili='T') then
  begin


    for select c.id_listy,c.obowiazuje_od,c.obowiazuje_do,t.id_listy from cbt_listy c
      left join tow_listy t on t.id_apteki=:iap and t.id_towary=:idt and c.id_listy=t.id_listy and c.obowiazuje_od=t.obowiazuje_od and c.obowiazuje_do=t.obowiazuje_do
      where c.id_cbt=:idc
      into :jd,:od,:dd,tjd do
      begin
       if (jd not in (1,2,6,10,11,23,24,20) and dr<dd) then  /* 01.2012  dodane ZHK i AZ jako nierefundowane o ile nie sa dodakowo na innej liscie */
          dr=dd;
       if (tjd is null) then
         update or insert into tow_LISTY (ID_APTEKI,id_towary,id_listy,obowiazuje_od,obowiazuje_do) values (:iap,:idt,:jd,:od,:dd);
      end

    for select t.id_listy,t.obowiazuje_od,t.obowiazuje_do from tow_listy t
      left join cbt_listy c on c.id_cbt=:idc and c.id_listy=t.id_listy and c.obowiazuje_od=t.obowiazuje_od and c.obowiazuje_do=t.obowiazuje_do
      where t.id_apteki=:iap and t.id_towary=:idt and t.id_listy<>21 and t.id_listy<40 and c.id_listy is null
      into :jd,:od,:dd do
        delete from tow_listy where id_apteki=:iap and id_towary=:idt and id_listy=:jd and obowiazuje_od=:od;

  end


  mu=0;
  if (ice='T') then
  begin
    od=null;
    for select c.id_ceny,c.obowiazuje_od,c.CENA_BR,c.LIMIT,t.id_towary from cbt_ceny c
     left join ceny_towary t on t.id_apteki=:iap and t.id_towary=:idt and t.id_ceny=c.id_ceny and t.obowiazuje_od=c.obowiazuje_od and t.decyzyjna='U'
     and c.cena_br=t.cena_br and (c.limit=t.limit or c.limit is null)
     where c.id_cbt=:idc order by c.obowiazuje_od
     into :jd,:od,:cb,:cl,tjd do
     begin
       if (tjd is null) then
         update or insert into ceny_towary (ID_APTEKI,id_towary,id_ceny,obowiazuje_od,cena_br,limit,DECYZYJNA,wn_kod) values (:iap,:idt,:jd,:od,:cb,:cl,'U','');
       mu=1;
     end

    for select t.id_ceny,t.obowiazuje_od from ceny_towary t
      left outer join cbt_ceny c on c.id_cbt=:idc and t.id_ceny=c.id_ceny and t.obowiazuje_od=c.obowiazuje_od
      where t.id_apteki=:iap and t.id_towary=:idt and t.decyzyjna='U' and c.id_ceny is null
      into jd,dd do
        delete from ceny_towary where id_towary=:idt and id_apteki=:iap and id_ceny=:jd and obowiazuje_od=:dd;


    for select c.id_ceny,c.id_odplatn,c.obowiazuje_od,c.OPLATA,t.id_towary from cbt_odpl c
     left join odpl_towary t on t.id_apteki=:iap and t.id_towary=:idt and t.id_odplatn=c.id_odplatn and c.id_ceny=t.id_ceny and t.obowiazuje_od=c.obowiazuje_od
      and t.oplata=c.oplata
     where c.id_cbt=:idc order by c.obowiazuje_od
     into jd,jj,od,cb,tjd do
     begin
       if (tjd is null) then
         update or insert into odpl_towary (ID_APTEKI,id_towary,id_ceny,id_odplatn,obowiazuje_od,OPLATA) values (:iap,:idt,:jd,:jj,:od,:cb);
       mu=1;
     end
    for select t.id_ceny,t.obowiazuje_od,t.id_odplatn from odpl_towary t
      left outer join cbt_odpl c on c.id_cbt=:idc and t.id_ceny=c.id_ceny and t.obowiazuje_od=c.obowiazuje_od and t.id_odplatn=c.id_odplatn
      where t.id_apteki=:iap and t.id_towary=:idt  and c.id_ceny is null
      into jd,dd,jj do
        delete from odpl_towary where id_towary=:idt and id_apteki=:iap and id_ceny=:jd and obowiazuje_od=:dd and id_odplatn=:jj;

  end


  if (itc='T') then
  begin
    jd=null;

    od=null;
    select min(obowiazuje_od) from cbt_listy where id_cbt=:idc and obowiazuje_do>='01/01/2100' and id_listy in (3,4,5,7,8,9,12,13,14,15,16,17,18,19,25) into od;
    if (od is null or (cast('TODAY' as date)>od and new=1)) then od=cast('TODAY' as date);


    select typ_c from typ_ceny(:iap,:idt,:od) into :jd;
    if (mu>0) then
    begin
      if (dr<'01/01/2100') then   /*  Aktualnie nie jest refundowany ale byl*/
      begin
        dr=dr+1;
        select typ_c from typ_ceny(:iap,:idt,:dr) into :jd;
        if (jd is null) then
        begin
          /*  Ustawienie na marza umowna od nastepnego dnia  */
          delete from tw_typy_cen where id_apteki=:iap and id_towary=:idt and obowiazuje_od=:dr;
          insert into tw_typy_cen (ID_APTEKI,ID_TOWARY,OBOWIAZUJE_OD,ID_TYPY_CEN) values (:iap,:idt,:dr,2);
        end
        else
        if (jd=3) then
        begin
          delete from tw_typy_cen where id_apteki=:iap and id_towary=:idt and obowiazuje_od=:dr;
          insert into tw_typy_cen (ID_APTEKI,ID_TOWARY,OBOWIAZUJE_OD,ID_TYPY_CEN) values (:iap,:idt,:dr,2);
        end
      end
      else
      if (jd<>3 or jd is null) then
      begin
        if (jd is null and od>'TODAY') then
        begin
           if (EXISTS (select obowiazuje_od from cbt_listy where id_cbt=:idc and obowiazuje_do>='today' and id_listy in (3,4,5,7,8,9,12,13,14,15,16,17,18,19,25))) THEN
           BEGIN
             od = 'today';
           END
           else
           BEGIN
             delete from tw_typy_cen where id_apteki=:iap and id_towary=:idt and (obowiazuje_od='01/01/1990' or id_typy_cen=3);
             insert into tw_typy_cen (ID_APTEKI,ID_TOWARY,OBOWIAZUJE_OD,ID_TYPY_CEN) values (:iap,:idt,'01/01/1990',2);
           end
        end
        delete from tw_typy_cen where id_apteki=:iap and id_towary=:idt and obowiazuje_od=:od;
        insert into tw_typy_cen (ID_APTEKI,ID_TOWARY,OBOWIAZUJE_OD,ID_TYPY_CEN) values (:iap,:idt,:od,3);
      end
    end
    else
    begin
      if (jd is null or jd=3) then
      begin
         delete from tw_typy_cen where id_apteki=:iap and id_towary=:idt and (obowiazuje_od='01/01/1990' or id_typy_cen=3);
         insert into tw_typy_cen (ID_APTEKI,ID_TOWARY,OBOWIAZUJE_OD,ID_TYPY_CEN) values (:iap,:idt,'01/01/1990',2);
      end
    end
  end


  if (ivt='T') then
  begin
    select KOD_STAWKI from stawka_vat(:iap,:idt,:dzis) into :ds;
    if (new<>1) then
    begin
      select max(data) from zdst where id_apteki=:iap and id_towary=:idt into :dzak;
      select max(data) from rzdst where id_apteki=:iap and id_towary=:idt into :dspr;
      if (dspr is null)   then
      begin
        if (dzak is null)   then
          dzis='01/01/1990';
        else
          dzis=dzak;
      end
      else dzis=dspr;
      if (dzak is not null and dzak>dzis) then dzis=dzak;
      select max(data_od) from vat_towary where id_apteki=:iap and id_towary=:idt into :dspr;
      if (dzis<dspr) then dzis=dspr;
    end
    mu=0;
    for select DATA_OD,KOD from cbt_vat where id_cbt=:idc order by data_od desc into :od,:sp do
    begin
      if (mu=0 and (od > dzis or ds<>sp)) then
      begin
        if (od < dzis and new<>1) then od=dzis+1;
        delete from vat_towary where id_apteki=:iap and id_towary=:idt and data_od=:od;
        insert into vat_towary (id_apteki,id_towary,data_od,kod) values (:iap,:idt,:od,:sp);
        mu=1;
      end
      else
      begin
        mu=1;
      end
    end
  end
  suspend;
end
^

ALTER TRIGGER INS_UPD_TW_KLAS2 ACTIVE
BEFORE INSERT OR UPDATE POSITION 1
AS
DECLARE sm char(1);
DECLARE se char(1);
DECLARE ea varchar(20);
DECLARE ex int;
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  if (new.id_klasyfikacje in (3,6)) THEN
  BEGIN
    if (new.wartosc<>(select cyfry from tylko_cyfry(new.wartosc))) THEN
      new.wartosc=(select cyfry from tylko_cyfry(new.wartosc));  
    SELECT t.EAN_REF,t.SMOPL_RAP,t.SER_PODL from TOWARY t WHERE t.ID_TOWARY = new.ID_TOWARY and t.ID_APTEKI = new.ID_APTEKI INTO ea,sm,se;
    if (sm is not DISTINCT FROM 'T' or se is not DISTINCT FROM 'T') THEN
    BEGIN
      ex = 0;
      if (INSERTING) THEN
        if ((SELECT COUNT(*) FROM TW_KLAS t WHERE t.ID_TOWARY = new.ID_TOWARY and t.ID_APTEKI = new.ID_APTEKI and t.ID_KLASYFIKACJE = new.ID_KLASYFIKACJE) > 0) THEN ex=1;
      if (new.ID_KLASYFIKACJE = 6 and ea is not NULL AND new.WARTOSC<>ea) THEN ex=1;
      if (ex = 1) THEN
        EXCEPTION BLAD 'Towary raportowane do SMOPL lub KOWAL musz¹ mieæ dok³adnie jeden EAN i BLOZ oraz EAN musi pokrywaæ siê z wpisanym w ''Dane podstawowe'' karty.';    
    END  
  END    
end
^

ALTER TRIGGER UPD_TOWARY ACTIVE
BEFORE UPDATE POSITION 0
as
declare variable cn integer;
DECLARE ea VARCHAR(20);
begin
  if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

  if (NEW.IFUPDDATE = OLD.IFUPDDATE or OLD.IFUPDDATE is null) then begin NEW.IFUPDDATE='NOW'; NEW.IFUPDUSER=USER; end

  if ((NEW.WWW_LASTSYNC = OLD.WWW_LASTSYNC or OLD.WWW_LASTSYNC is null) and (NEW.NAZWA <> OLD.NAZWA )) then
    NEW.WWW_LASTSYNC='NOW';

  if (new.id_dostawcy is null) then new.tylko_u=null;
  
  if (new.SMOPL_RAP='N' and old.SMOPL_RAP = 'T') THEN
  BEGIN
    if ((SELECT count(*) FROM zdst z WHERE z.ID_APTEKI = new.ID_APTEKI and z.ID_TOWARY = new.ID_TOWARY and z.CZYNNY = 'T')>0) THEN
      new.SMOPL_RAP = 'T';
  END

  if (CHAR_LENGTH(new.nazwa)<11 and CHAR_LENGTH(old.nazwa)>10) then new.nazwa=old.nazwa; /* 9.6.20' */
  if (new.nazwa similar to '@[0-9]{10,}%') then new.nazwa=old.nazwa; /* 26.6.23' */
  if (new.DNI_MIN>30) then new.DNI_MIN=30; /* 1.12.22 130.46 */

  if (old.id_cbt is not null and old.id_cbt<>new.id_cbt) then
  begin
    select count(*) from koszyki where id_towary=old.id_cbt into :cn;
    if (cn=0) then
      select count(*) from koszyk_towary where id_towary=old.id_cbt into :cn;
    if (cn>0) then
      select count(*) from sprzedaz where id_apteki=old.id_apteki and  id_towary=old.id_towary and id_promocje is not null into :cn;
    if (cn>0) then
      exception PROMOCJE;
  end
  
  if ((new.SMOPL_RAP is DISTINCT from old.SMOPL_RAP and new.SMOPL_RAP = 'T') or (new.SER_PODL is DISTINCT FROM old.SER_PODL and new.SER_PODL = 'T')) THEN
  BEGIN
    if (
    (SELECT COUNT(*) FROM TW_KLAS t WHERE t.ID_TOWARY = new.ID_TOWARY and t.ID_APTEKI = new.ID_APTEKI and t.ID_KLASYFIKACJE = 3)>1 or
    (SELECT COUNT(*) FROM TW_KLAS t WHERE t.ID_TOWARY = new.ID_TOWARY and t.ID_APTEKI = new.ID_APTEKI and t.ID_KLASYFIKACJE = 6)>1 ) THEN
      EXCEPTION BLAD 'Towary raportowane do SMOPL lub KOWAL musz¹ mieæ dok³adnie jeden EAN i BLOZ oraz EAN musi pokrywaæ siê z wpisanym w ''Dane podstawowe'' karty.';
  end

end
^

ALTER TRIGGER UPD_TOWARY_ZM ACTIVE
AFTER UPDATE POSITION 0
as
begin
  if (old.NAZWA<>new.NAZWA) then INSERT INTO TOWARY_ZMIANY (ID_APTEKI, ID_TOWARY, NAZWA,IFUPDDATE) VALUES (old.ID_APTEKI, old.ID_TOWARY, old.NAZWA,cast('now' as date)+0.0000001);
  if (coalesce(old.ID_CBT,-1)<>coalesce(new.ID_CBT,-1)) then INSERT INTO TOWARY_ZMIANY (ID_APTEKI, ID_TOWARY, ID_CBT,IFUPDDATE) VALUES (old.ID_APTEKI, old.ID_TOWARY, coalesce(old.ID_CBT,-1),cast('now' as date)+0.0000002);
  if (coalesce(old.EAN_REF,-1)<>coalesce(new.EAN_REF,-1)) then INSERT INTO TOWARY_ZMIANY (ID_APTEKI, ID_TOWARY, EAN_REF,IFUPDDATE) VALUES (old.ID_APTEKI, old.ID_TOWARY, coalesce(old.EAN_REF,-1),cast('now' as date)+0.0000003);
  if (old.SP_ZAMAWIANIA<>new.SP_ZAMAWIANIA) then
   INSERT INTO TOWARY_ZMIANY (ID_APTEKI, ID_TOWARY, SP_ZAMAWIANIA,IFUPDDATE) VALUES (old.ID_APTEKI, old.ID_TOWARY, old.SP_ZAMAWIANIA,cast('now' as date)+0.0000004);
   
  if (new.EAN_REF is DISTINCT from old.EAN_REF and new.EAN_REF is not NULL AND (new.SMOPL_RAP='T' or new.SER_PODL='T')) THEN
    UPDATE TW_KLAS k set k.WARTOSC = new.EAN_REF WHERE k.ID_TOWARY=new.ID_TOWARY and k.ID_APTEKI=new.ID_APTEKI AND k.ID_KLASYFIKACJE=6;  
 end
^

ALTER TRIGGER UPD_DOSTAWCY ACTIVE
BEFORE UPDATE POSITION 0
as
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

  if (new.id_kontrahenci <> old.id_kontrahenci) then
    update towary set id_dostawcy=new.id_kontrahenci where id_apteki=new.id_apteki and id_dostawcy = old.id_kontrahenci;
    
  if (new.FORMAT_ZAM like 'XM_' and new.ZAM_OBSL_KODY<>'0010000000') then
   exception blad 'W zamówieniach XML mo¿na u¿ywaæ tylko kodów Bloz7';
    
end^

/*alter*/
/* Alter (NOWA_NAGRODA) */
ALTER PROCEDURE NOWA_NAGRODA(IA INTEGER,
IP INTEGER,
NM VARCHAR(100),
PU DOUBLE PRECISION,
IK INTEGER,
DT_OD DATE,
DT_DO DATE,
IC INTEGER)
 AS
declare variable cn integer;
declare variable pn integer;
begin

  if (ic > 0) then
  begin
    select count(*) from koszyk_towary  where id_promocje=:ip and id_towary=:ic into cn;
    if (cn>0) then exit;
  end
  else
  begin
    select count(*) from koszyk_towary left join cbt on id_towary=id_cbt where id_promocje=:ip and nazwa=:nm into cn;
    if (cn>0) then exit;
    cn=null;
    select id_cbt from cbt where nm_short=:nm into cn;
    if (cn is null) then
    begin
      select max(id_cbt) from cbt where id_cbt>=1000000 into :ic;
      if (ic<1000000) then ic = 1000000; else ic=ic+1;
      insert into cbt(id_cbt,nm_short,nazwa) values (:ic,substring(:nm from 1 for 40),:nm);
      insert into cbt_jedn (id_cbt,jednostka,nazwa,mnoznik,dzielnik,podstawowa,sprzedaz) values (:ic,1,'SZT.',1,1,'T','T');
    end
    else
      ic=cn;
  end
  select count(*) from towary where id_cbt=:ic into cn;
  if (cn=0) then
  begin
    if (ik is null or ik=0) then
      select gen_id(SQ_TOWARY,1) from jeden_wiersz into :cn;
    else
    begin
      select min(id_towary) from towary where id_apteki=:ia and id_towary<0 into cn;
      if (cn is null ) then cn=-3; else cn=cn-1;
    end
    insert into towary (id_apteki,id_towary,nazwa,usluga) values
      (:ia,:cn,:nm,'T');
    select 0 from  up_z_cbt(:ia,:ic,:cn,0) into pn;
  end
  if (ik is null or ik=0) then
  begin
    select max(nr_koszyka) from opis_koszyka where id_promocje=:ip into cn;
    if (cn is null ) then cn=0;
    cn=cn+1;
  end
  else
    cn=ik;
  insert into opis_koszyka (id_promocje,nr_koszyka,opis,ilosc,rodzaj,sumuj) values (:ip,:cn,:nm,1,'T','N');
  select min(id_towary) from koszyki where id_promocje=:ip into pn;
  if (pn is null) then pn =1000000*(ip-100);
  insert into koszyki (id_promocje,nr_koszyka,sztuk,id_towary) values (:ip,:cn,:pu,:pn);
  insert into koszyk_towary (id_promocje,nr_koszyka,id_towary,ilosc,cena) values (:ip,:cn,:ic,1,0);
end
^

/* Alter (NOWE_Z_CBT) */
ALTER PROCEDURE NOWE_Z_CBT(IA INTEGER,
IK1 INTEGER,
WK1 VARCHAR(40),
CT VARCHAR(1))
 RETURNS(ITW INTEGER,
NM VARCHAR(100))
 AS
declare variable icb integer;
declare variable cn  integer;
/* do zak³adania nieistniej¹cych kart z CBT wg podanej klasyfikacji (np 18) i wartoœci i/lub centralnej CBT <>'N'*/
begin
  if (CT<>'N') then
  for select id_cbt from cbt_klas where id_klasyfikacje=:ik1 and wartosc=:wk1
    union select id_cbt from cbt where centralna=:ct into :icb DO
  begin
    select count(*) from towary where id_apteki=:ia and id_cbt=:icb into :cn;
    if (cn=0) then
    begin
      select substring(NAZWA from 1 for 100) from cbt where id_cbt=:icb into :nm;
      select gen_id(SQ_TOWARY,1) from jeden_wiersz into :itw;
      insert into towary (id_apteki,id_towary,nazwa,id_cbt,centralna) values (:ia,:itw,:nm,:icb,'N');
      select 0 from  up_z_cbt(:ia,:icb,:itw,0) into :icb;
      suspend;
    end
  end
end
^

/* Alter (NOWY_Z_CBT) */
ALTER PROCEDURE NOWY_Z_CBT(IAP INTEGER,
IK1 INTEGER,
WK1 VARCHAR(40),
IK2 INTEGER,
WK2 VARCHAR(40),
IK3 INTEGER,
WK3 VARCHAR(40))
 RETURNS(ITW INTEGER,
NM VARCHAR(100))
 AS
declare variable icb integer;
begin
  if (ik1>0) then
    select max(id_cbt) from cbt_klas k where id_klasyfikacje=:ik1 and wartosc=:wk1 and EXISTS (select*from cbt_klas d where d.id_cbt=k.id_cbt and d.id_klasyfikacje=7 and d.wartosc='7') 
       and not EXISTS (select*from cbt_klas d where d.id_cbt=k.id_cbt and d.id_klasyfikacje=7 and d.wartosc='z') into :icb;
  if (icb is null and  ik3>0) then
    select max(id_cbt) from cbt_klas k where id_klasyfikacje=:ik3 and wartosc=:wk3 and EXISTS (select*from cbt_klas d where d.id_cbt=k.id_cbt and d.id_klasyfikacje=7 and d.wartosc='7') 
       and not EXISTS (select*from cbt_klas d where d.id_cbt=k.id_cbt and d.id_klasyfikacje=7 and d.wartosc='z') into :icb;
  if (icb is null and ik2>0) then
    select max(id_cbt) from cbt_klas k where id_klasyfikacje=:ik2 and wartosc=:wk2 and EXISTS (select*from cbt_klas d where d.id_cbt=k.id_cbt and d.id_klasyfikacje=7 and d.wartosc='7') 
       and not EXISTS (select*from cbt_klas d where d.id_cbt=k.id_cbt and d.id_klasyfikacje=7 and d.wartosc='z') into :icb;
      
  if (icb is not null) then
  begin
    SELECT t.ID_TOWARY,t.NAZWA FROM TOWARY t where t.ID_APTEKI=:iap and t.ID_CBT = :icb INTO itw,nm;
    if (itw is null) THEN
    begin
      select substring(NAZWA from 1 for 100) from cbt where id_cbt=:icb into :nm;
      select gen_id(SQ_TOWARY,1) from jeden_wiersz into :itw;
      insert into towary (id_apteki,id_towary,nazwa) values
        (:iap,:itw,:nm);
      select 0 from  up_z_cbt(:iap,:icb,:itw,0) into :icb;
      suspend;
      exit;
    end
  end
end
^

/* Alter (RPLPROM) */
ALTER PROCEDURE RPLPROM(IA INTEGER,
IPR INTEGER,
NM VARCHAR(100),
ILE DOUBLE PRECISION,
OD VARCHAR(1))
 AS
declare variable ile1 integer;
begin

select count(*) from promocje where id_promocje=:ipr into :ile1;

if (ile1>0) then
begin
  delete from sprzedaz where id_apteki=:ia and id_promocje=:ipr;
  delete from sprzedaz where id_apteki=:ia and id_promocje=:ipr + 100;
  delete from towary where id_apteki=:ia and id_cbt is not null and id_cbt>=1000000 and   id_cbt in (select id_towary from koszyk_towary where id_promocje=:ipr or id_promocje=:ipr + 100);
  delete from cbt where id_apteki=:ia and  id_cbt>=1000000 and  id_cbt in (select id_towary from koszyk_towary where id_promocje=:ipr or id_promocje=:ipr + 100);
  delete from promocje where id_promocje=:ipr or id_promocje=:ipr + 100;
end

update or insert into promocje (id_promocje,obowiazuje_od,obowiazuje_do,zakres,automat,uwzgl,nazwa,klas_neg) values
  (:ipr,'01/01/2005','12/31/2100','S','K','T','Punkty ' || :nm,'N');

update or insert into opis_koszyka (id_promocje,nr_koszyka,ilosc,rodzaj)
values (:ipr,1,:ile,:od);

delete from cbt where id_cbt=1000000*:ipr;
insert into cbt(id_cbt,nm_short,nazwa) values (1000000*:ipr,'Punkty promocyjne','Punkty promocyjne ' || :nm);
insert into cbt_jedn (id_cbt,jednostka,nazwa,mnoznik,dzielnik,podstawowa,sprzedaz) values (1000000*:ipr,1,'SZT.',1,1,'T','T');
select min(id_towary) from towary where id_apteki=:ia and id_towary<0 into ile1;
if (ile1 is null ) then ile1=-3; else ile1=ile1-1;
update or insert into  towary (id_apteki,id_towary,nazwa,usluga) values
      (:ia,:ile1,'Punkty promocyjne ' || :nm,'T');
select 0 from  up_z_cbt(:ia,1000000*:ipr,:ile1,0) into :ile1;
update or insert into  koszyk_towary (id_promocje,nr_koszyka,id_towary,ilosc,cena) values
  (:ipr,1,1000000*:ipr,1,0);
update or insert into  promocje (id_promocje,obowiazuje_od,obowiazuje_do,zakres,automat,uwzgl,nazwa,klas_neg) values
  (:ipr+100,'01/01/2005','12/31/2100','O','N','T',:nm || ' nagrody','N');
end
^

/* Alter (UP_ALL_Z_CBT) */
ALTER PROCEDURE UP_ALL_Z_CBT(IAP INTEGER)
 RETURNS(NDP CHAR)
 AS
declare variable it integer;
  declare variable NT VARCHAR(100) CHARACTER SET WIN1250;
  declare variable ic integer;
  declare variable PS VARCHAR(100) CHARACTER SET WIN1250;
  declare variable DW VARCHAR(100) CHARACTER SET WIN1250;
  declare variable OP VARCHAR(100) CHARACTER SET WIN1250;
  declare variable O1 INTEGER;
  declare variable O2 INTEGER;
  declare variable O3 INTEGER;
  declare variable O4 INTEGER;
  declare variable PR INTEGER;
  declare variable DP CHAR(1);
  declare variable EA VARCHAR(20) CHARACTER SET WIN1250;
  declare variable DDD double precision;
  declare variable TE INTEGER;
  DECLARE b7 INTEGER;
  declare BL CHAR(1);
begin
  ndp='N';
  for select id_towary,id_cbt,nazwa,bloz7,IMP_CBT_JEDN from towary  where id_apteki=:iap into :it,:ic,nt,b7,bl do
  begin
    if (bl <> 'B') THEN
    BEGIN 
      execute procedure up_z_cbt(:iap,:ic,:it,1) returning_values :ps,:dw,:op,:o1,:o2,:o3,:o4,:pr,:dp,:ic,:ea,:ddd,:te;
      if (dp<>'T') then ndp='T';
    END  
  end
  when any do
  begin
    exception upcbte '
B³¹d aktualizacji parametrów dla 
'|| nt ||'

Z regu³y problem powoduj¹ b³êdnie ustawione jednostki lub wiêcej ni¿ jeden EAN w klasyfikacjach.
WejdŸ w zak³adkê "Jednostki" wymienionej karty, usuñ wszystkie jednostki, wejdŸ w zak³adkê "Klasyfikacje" i usuñ EANy.
Wciœnij F2 i ponów aktualizacjê. 
Je¿eli problem siê powtórzy zadzwoñ do serwisu.
	';
  end
end
^

/* Alter (UP_TW_PROM) */
ALTER PROCEDURE UP_TW_PROM(IA INTEGER)
 AS
declare variable icb integer;
declare variable itw integer;
declare variable cn  integer;
declare variable nm varchar(100);
begin
  for select id_towary from koszyki union select id_towary from koszyk_towary into :icb  do
  begin
    select count(*) from towary where id_apteki=:ia and id_cbt=:icb into :cn;
    if (cn=0) then
    begin
      select substring(NAZWA from 1 for 100) from cbt where id_cbt=:icb into :nm;
      select gen_id(SQ_TOWARY,1) from jeden_wiersz into :itw;
      insert into towary (id_apteki,id_towary,nazwa,id_cbt,usluga) values
        (:ia,:itw,:nm,:icb,'T');
      insert into jednostki (id_apteki,id_towary,jednostka,podstawowa,mnoznik,dzielnik,nazwa)
        values
        (:ia,:itw,1,'T',1,1,'SZT.');
      select 0 from  up_z_cbt(:ia,:icb,:itw,0) into :icb;
    end
  end
end
^

ALTER TRIGGER INS_SKRYPTY_RANK 
ACTIVE AFTER UPDATE POSITION 1 
AS
declare variable il integer;
declare variable ap apteka;
BEGIN 
  if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  
 if (new.URUCHOMIONY='T') THEN
 begin
    il=(select ile from skrypty_RANK where ID_APTEKI=:ap and ID_skrypty=new.id_skrypty);
    update or INSERT INTO skrypty_RANK (ID_APTEKI, ID_skrypty, ILE, OSTATNIO) VALUES (:ap,new.id_skrypty,coalesce(:il,0)+1,'now');
 end   
END
^

ALTER PROCEDURE CN_DST_OK (
    IAP INTEGER,
    IDZ DOUBLE PRECISION,
    IDC INTEGER,
    DTO TIMESTAMP,
    ITW INTEGER )
RETURNS (
    JEST_OK CHAR(1),
    CE DOUBLE PRECISION,
    MA DOUBLE PRECISION )

AS
  declare variable cn DOUBLE PRECISION;
  declare variable cb DOUBLE PRECISION;
  declare variable od DOUBLE PRECISION;
  declare variable og DOUBLE PRECISION;
  declare variable cs DOUBLE PRECISION;
  declare variable tc integer;
begin
  jest_ok='T';
  select TYP_C from TYP_CENY(:iap,:itw,:dto) into tc;
  select d.cena_nt_jp,d.cena_br_jp from ceny_dostawy d
     where d.ID_APTEKI=:iap and d.ID_ZDST=:idz and d.ID_CENY=:idc and d.OBOWIAZUJE_OD=:dto
     into cn,cb;
  if (cn is not null and cn>0) then
  begin
    select ODCH_GORA,ODCH_DOL from z_typy_cen where ID_TYPY_CEN=:tc and ID_CENY=:idc into og,od;
    if (od is null) then od = 100;
    if (og is null) then og = 100;
    if (od<100 or og <100) then
    begin
        select CENA,c.MARZA from ost_cena(:iap,:itw,:dto,:idc) c into cs,ma;
        if (idc = 3) then cn = cb;
        if (cs is not null and cs>0) then
          if ((cn-cs)/cn > og*0.01 or (cs-cn)/cs > od*0.01) then jest_ok='N';
        ce = cs;
    end
    if (tc = 3) THEN
    BEGIN
      jest_ok='T';
      select first 1 CENA_BR from ceny_towary
       where id_apteki=:iap and id_towary=:itw and id_ceny=IIF(:idc<3,2,:idc) and obowiazuje_od<=:dto
       order by obowiazuje_od descending into cs;
      if (cs is not null and cs>0 and (  cs-cb>0.009 or cb-cs>0.009)) then
        jest_ok='N';
    END
  end
  suspend;
end
^


ALTER PROCEDURE CN_ZDST_OK (
    IAP INTEGER,
    IDZ DOUBLE PRECISION,
    IDT INTEGER )
RETURNS (
    CENA_OK CHAR(1),
    SERIA VARCHAR(40),
    EAN VARCHAR(14),
    EANT VARCHAR(14),
    CENASP DOUBLE PRECISION,
    STANL DOUBLE PRECISION,
    OST_C_Z DOUBLE PRECISION,
    OST_C_D DOUBLE PRECISION,
    OST_M_D DOUBLE PRECISION,
    EAN_TYP CHAR(1) )
AS
declare variable idc integer;
  declare variable dto TIMESTAMP;
  declare variable jok char(1);
  DECLARE cs DOUBLE PRECISION;
  DECLARE ma DOUBLE PRECISION;
begin
  cena_ok='T';
  for select ID_CENY,OBOWIAZUJE_OD from ceny_dostawy
  where ID_APTEKI=:iap and ID_ZDST=:idz into :idc,:dto do
  begin
     select jest_ok,c.Ce,c.MA from cn_dst_ok(:iap,:idz,:idc,:dto,:idt) c into :jok,cs,ma;
     if (idc = 1 ) THEN OST_C_Z = cs;
     if (idc = 3 ) THEN
     BEGIN
        OST_C_D = cs;
        OST_M_D = ma;
     END 
     if (jok='N') then cena_ok='N';
  end
  SELECT FIRST 1 z.WARTOSC from ZDST_KLAS z where z.ID_APTEKI=:iap and z.ID_ZDST=:idz and z.ID_KLASYFIKACJE=5 INTO seria;
  SELECT FIRST 1 left(z.WARTOSC,14) from ZDST_KLAS z where z.ID_APTEKI=:iap and z.ID_ZDST=:idz and z.ID_KLASYFIKACJE=6 INTO ean;
  SELECT s.STAN FROM STAN_WARTS(:iap,:idt,0) s into stanl;
  select CENA_BR from akt_cena_sp(:iap,:idt,3,:dto,:idz,'') into CENASP;
  if (OST_C_Z is null) THEN
    SELECT cena from OST_CENA(:iap,:idt,:dto,1) into OST_C_Z;
  if (OST_C_D is null) THEN
    SELECT cena,marza from OST_CENA(:iap,:idt,:dto,3) into OST_C_D,OST_M_D;  
  SELECT t.EAN_REF,t.EAN_TYP FROM TOWARY t WHERE t.ID_TOWARY = :idt and t.ID_APTEKI = :iap  into eant,ean_typ;
  suspend;
end
^


ALTER PROCEDURE CN_DOS_OK (
    IAP INTEGER,
    IDD INTEGER )

AS
declare variable idc double precision;
     declare variable jok char(1);
     declare variable jest_ok char(1);
     declare variable idt integer;
begin
  jest_ok='T';
  for select ID_ZDST,ID_TOWARY from zdst
  where ID_APTEKI=:iap and ID_DOSTAWY=:idd into :idc,:idt do
  begin
     select cena_ok from cn_zdst_ok(:iap,:idc,:idt) into :jok;
     if (jok='N') then  jest_ok='N';
  end
  update dostawy set ceny_ok=:jest_ok where id_apteki=:iap and id_dostawy=:idd;
end
^

/*alter*/
ALTER PROCEDURE CHK_DST
AS
declare variable idd integer;
declare variable iap integer;
begin
  for select id_apteki,id_dostawy from dostawy
    where (ceny_ok<>'T' and ceny_ok<>'N') or ceny_ok is null into :iap,:idd do
    execute procedure cn_dos_ok(:iap,:idd);
end^

ALTER TRIGGER INS_UPD_DOSTAWY ACTIVE
BEFORE INSERT OR UPDATE POSITION 1
AS
declare variable nr VARCHAR(20);
declare variable st CHAR(1);
begin
   if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
     
   if (new.nr_faktury<>(select cyfry from tylko_znaki(new.nr_faktury))) THEN new.nr_faktury=(select cyfry from tylko_znaki(new.nr_faktury));  
   if (extract(hour from new.data)+extract(second from new.data)<>0) then new.data=cast(left(new.data,11) as date);
   if (exists(select*from kontrahenci where id_kontrahenci=new.id_kontrahenci and smopl_typ='FZH')) then new.KOD_HURTOWNI=null;
   
   if (new.korekta_do is not null) THEN
    begin
     select left(nr_faktury,20),status from dostawy where id_apteki=new.id_apteki and id_dostawy=new.korekta_do into nr,st;
     if (st is distinct from 'Z') then
      EXCEPTION blad ' Nie mo¿na wczytaæ korekty do niezaksiêgowanej dostawy
 Najpierw zaksieguj dostawê '||nr;    
    end
end^

ALTER TRIGGER DEL_DOSTAWY1 ACTIVE
BEFORE DELETE POSITION 0
as
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  if (OLD.KOREKTA_DO is not null and old.korekta_do <> old.id_dostawy) then
    update dostawy set SKORYGOWANA_PRZEZ = null where id_apteki=OLD.ID_APTEKI and   id_dostawy=OLD.KOREKTA_DO;
    
  if (old.data<cast('today' as date)-30 and old.status in ('Z','P')) then EXCEPTION blad ' Dostawa starsza ni¿ 30 dni - kasowanie wy³¹czone'; 
    
  if (exists(select * from zdst a join rzdst b on a.id_apteki=b.id_apteki and a.id_zdst=b.id_zdst where a.id_apteki=old.id_apteki and a.id_dostawy=old.id_dostawy)) THEN
    EXCEPTION blad ' Dostawa rozchodowana';        
    
  if (exists(select * from zdst a join zdst b on a.id_apteki=b.id_apteki and a.id_zdst=b.korekta_do and a.id_apteki=old.id_apteki and a.id_dostawy=old.id_dostawy)) THEN
    begin
    if (old.status in ('Z','P')) 
    then EXCEPTION blad ' Istnieje korekta do dostawy - jeœli mo¿liwe najpierw usuñ korektê';
    else EXCEPTION blad ' Najpierw usuñ pozycje koryguj¹ce w zawartoœci dostawy';
    end
          
   Execute Procedure DEL_DEK_DOST(old.id_apteki,old.DT_WYST,old.data,old.DT_PLATN,old.NR_FAKTURY,old.ID_DOSTAWY); 
end^


ALTER TRIGGER UPD_DOSTAWY ACTIVE
BEFORE UPDATE POSITION 0
as
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  
  if (NEW.IFUPDDATE = OLD.IFUPDDATE or OLD.IFUPDDATE is null) then 
   begin 
    NEW.IFUPDDATE='NOW'; 
    if (not (old.status='Z' and (new.SKORYGOWANA_PRZEZ is distinct from old.SKORYGOWANA_PRZEZ or new.ID_OSOZ is distinct from old.ID_OSOZ))) then    
     NEW.IFUPDUSER=USER; 
   end
  
  if (OLD.KOREKTA_DO is not null and old.korekta_do <> old.id_dostawy) then
    update dostawy set SKORYGOWANA_PRZEZ = null where id_apteki=OLD.ID_APTEKI and  id_dostawy=OLD.KOREKTA_DO;
  if (NEW.KOREKTA_DO is not null) then
    update dostawy set SKORYGOWANA_PRZEZ = NEW.ID_dostawy where id_apteki=NEW.ID_APTEKI and   id_dostawy=NEW.KOREKTA_DO;
  if (new.data<>old.data) then
    update zdst set data=new.data where id_apteki=OLD.ID_APTEKI and   id_dostawy=old.id_dostawy;
end^

ALTER PROCEDURE GENERUJ_TRIGGERY (al smallint=1) RETURNS(SQD VARCHAR(2480),
SQU VARCHAR(2480),
SQB VARCHAR(2480))
 AS
DECLARE tb varchar(100);
DECLARE pl varchar(100);
DECLARE kl varchar(1500);
DECLARE kn varchar(1500);
DECLARE kz varchar(1500);
DECLARE cr VARCHAR(2);
DECLARE la varchar(5);
DECLARE lo varchar(5);
DECLARE lp varchar(5);
DECLARE ap apteka;
DECLARE noupd varchar(500);
DECLARE uu varchar(100);
DECLARE nodel varchar(500);
declare a1 char(6);
declare a2 char(6);
begin
/* domyslnie al=1 generuje wszystkie trig (jak poprzednio) 
   al=0 tylko brakujace (pojawi sie id_apteki lub ifupdate) czyli przy udatach zwyklych - jesli bedzie gdzies zmiana PK obowiazkowo =1  */

/* wykluczenia - similar - znak escape = #*/
noupd ='ADRESY|CBT|CBT_CENY|CBT_JEDN|CBT_LISTY|CBT_ODPL|CBT_SKLAD|CBT_UWAGI|CBT_VAT|CBT_KLAS|DOSTAWY|EPRUF_LEKI|EPRUF_RAPORTY|INTERNM|KONTA|KONTRAHENCI|PRODUCENCI|SYNCTOW|SYNSZCZ|SYNZB|TOWARY|SKASOWANE|SYNCREKORD';
nodel ='AANA%|TMP#_%|OFERTY|OFERTY_CENY|OFERTY_KLAS|PRZESUNIECIA|RAPORTY|REZERWACJA|EPRUF_USL|SYNCERR|SYNCLOGIN|SKASOWANE|SYNCREKORD|SYNCTOW|ZAOKR_SPOS'; --ZAOKR_SPOS wylatuje 'KLUCZ' w 'SKASOWANE' max 150

if (al=0) then begin a1='DELS_%'; a2='UPDB_%'; end
cr = ASCII_CHAR(13)||ASCII_CHAR(10);
for SELECT trim(s.RDB$RELATION_NAME) from RDB$RELATIONS s where s.RDB$SYSTEM_FLAG is DISTINCT FROM 1 and RDB$VIEW_BLR is null 
 and exists(select*from RDB$RELATION_FIELDS where RDB$FIELD_NAME in ('ID_APTEKI','IFUPDDATE') and RDB$RELATION_NAME=s.RDB$RELATION_NAME) 
 order by 1 INTO tb do 
 BEGIN
 
  if (exists(select*from RDB$RELATION_FIELDS f where f.RDB$RELATION_NAME=:tb and f.RDB$FIELD_NAME='IFUPDDATE')              
    and not exists(select*from RDB$TRIGGERS r where RDB$TRIGGER_NAME like :a2 and r.RDB$RELATION_NAME=:tb) and :tb not similar to noupd escape '#') THEN 
   BEGIN
     if ((SELECT count(*) from RDB$RELATION_FIELDS f where f.RDB$RELATION_NAME=:tb and f.RDB$FIELD_NAME='IFUPDUSER')>0) THEN
       uu = 'NEW.IFUPDUSER=USER;';
     ELSE
       uu = '';  
     sqb = '';  
     sqb = 'CREATE OR ALTER TRIGGER  UPDB_' || tb || ' FOR ' || tb || ' ACTIVE BEFORE UPDATE POSITION 10 AS';  
     sqb = sqb || cr || 'BEGIN' || cr || 'if (rdb$get_context(''USER_SESSION'',''IFROZP'')=1) then exit;';
     sqb = sqb || cr || 'if (NEW.IFUPDDATE = OLD.IFUPDDATE or OLD.IFUPDDATE is null) then begin NEW.IFUPDDATE=''NOW''; ' || uu || ' end';
     sqb = sqb || cr || 'END';
     EXECUTE STATEMENT sqb; 
   END 

  if (exists(select*from RDB$RELATION_FIELDS where RDB$FIELD_NAME='ID_APTEKI' and RDB$RELATION_NAME=:tb)
    and not exists(select*from RDB$TRIGGERS r where RDB$TRIGGER_NAME like :a1 and r.RDB$RELATION_NAME=:tb) and :tb not similar to nodel escape '#') then
   begin 
   sqd=''; squ=''; kl = ''; la = ''; lo = ''; kz = ''; kn = ''; lp = ''; 
   sqd = 'CREATE OR ALTER TRIGGER  DELS_' || tb || ' FOR ' || tb || ' ACTIVE AFTER DELETE POSITION 10 AS';
   squ = 'CREATE OR ALTER TRIGGER  UPDS_' || tb || ' FOR ' || tb || ' ACTIVE AFTER UPDATE POSITION 10 AS';
   sqd = sqd || cr || 'BEGIN' || cr || 'if (rdb$get_context(''USER_SESSION'',''IFROZP'')=1) then exit;';
   squ = squ || cr || 'BEGIN' || cr || 'if (rdb$get_context(''USER_SESSION'',''IFROZP'')=1) then exit;';      
   for select trim(i.RDB$FIELD_NAME)
   from RDB$RELATION_CONSTRAINTS c
   LEFT JOIN RDB$INDEX_SEGMENTS i on c.RDB$INDEX_NAME=i.RDB$INDEX_NAME
   where c.RDB$RELATION_NAME=:tb  and c.RDB$CONSTRAINT_TYPE='PRIMARY KEY'
   ORDER by i.RDB$FIELD_POSITION  into pl do    
    BEGIN     
     kl = kl || la || pl || '='''''' || old.' || pl || ' || ''''''';
     kn = kn || lp || pl || '='''''' || new.' || pl || ' || ''''''';
     kz = kz || lo || 'old.' || pl || ' <> new.' || pl;
     la = ' and ';
     lo = ' or ';
     lp = ',';
    END
    if (kl> ' ') then
    begin
     sqd = sqd || cr || 'update or insert into SKASOWANE (id_apteki,TABLICA,IFUPDDATE,KLUCZ) values (' || ap || ',''' || tb || ''',''NOW'',''' ||  kl || ''');';
     sqd = sqd || cr || 'END';
     EXECUTE STATEMENT sqd;      
     squ = squ || cr || 'if (' || kz || ') then ' || cr || 'update or insert into SKASOWANE (id_apteki,TABLICA,IFUPDDATE,KLUCZ,KLUCZN) values ('
       || ap || ',''' || tb || ''',''NOW'',''' ||  kl || ' '',''' || kn || ''');';
     squ = squ || cr || 'END';
     EXECUTE STATEMENT squ; 
    end
   end
   SUSPEND;
 END
end
^

ALTER TRIGGER DEL_SPRZEDAZDEL
AS
  declare variable nk integer;
  declare variable us integer;
  declare variable ktr integer;
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
 select nr_kasy,id_user,id_kontrahenci from tranzakcje where id_apteki=old.ID_APTEKI and data=old.data and ID_TRANZAKCJE=old.ID_TRANZAKCJE into :nk,:us,:ktr;
  if (:nk<10 and :nk>0 and COALESCE(:ktr,1)>0) THEN
  BEGIN
  update or INSERT INTO SPRZEDAZDEL (ID_APTEKI, ID_SPRZEDAZ, ID_TOWARY, DATA, ID_TRANZAKCJE, POZYCJA,SZTUK, JEDNOSTKA, ID_RECEPTA, WARTOSC, ODPLATNOSC, DOPLATA, TRYB, NR_KOSZYKA,ID_PROMOCJE,OLDIFUPDDATE, OLDIFUPDUSER,ID_OSOZ,nr_kasy,id_user)
   VALUES (old.ID_APTEKI, old.ID_SPRZEDAZ, old.ID_TOWARY, old.DATA, old.ID_TRANZAKCJE, old.POZYCJA,old.SZTUK, old.JEDNOSTKA, old.ID_RECEPTA, old.WARTOSC,  old.ODPLATNOSC, old.DOPLATA, old.tryb, old.NR_KOSZYKA,old.ID_PROMOCJE, old.ifupddate, old.IFUPDUSER,old.ID_OSOZ,:nk,:us);
  end
  
 DELETE from etaksacje where ID_SPRZEDAZ=old.ID_SPRZEDAZ and ID_APTEKI=old.ID_APTEKI and status is distinct from 'W'; 
 
end
^

create or ALTER PROCEDURE NIPP (
    NIP char(20) )
RETURNS (
    OK char(1))
AS
DECLARE waga varchar(9)='657234567';
  DECLARE suma int=0;
  DECLARE i int=1;
  DECLARE c char(1);
begin       
   ok='N';
   nip=(select cyfry from TYLKO_CYFRY(:NIP));
   if (char_length(trim(:nip))=10) then     
   begin
    WHILE (:i<=9) do
    BEGIN
      c=SUBSTRING(:nip from :i for 1);
      suma=:suma+CAST(SUBSTRING(:waga from :i for 1) as int)*:c;
      i=:i+1;
    END
   if (right(mod(suma,11),1)=right(trim(nip),1) and mod(suma,11)<>10) then ok='T'; 
   end
  suspend;
end^

ALTER TRIGGER INS_UPD_KONTRAHENCI
AS
declare variable nt VARCHAR(200) CHARACTER SET WIN1250;
declare variable it integer;
declare variable ap apteka;
begin
   if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

    if (new.NM_KONTRAHENCI is null) THEN
    exception BLAD ' Nazwa nie mo¿e byæ pusta';

    if (new.ID_KONTRAHENCI<>coalesce(old.ID_KONTRAHENCI,0)) THEN
    begin
    select ID_KONTRAHENCI from KONTRAHENCI where id_kontrahenci=new.id_kontrahenci  into :it;
    if (it>0) then
      BEGIN
      SELECT NM_KONTRAHENCI from kontrahenci where id_kontrahenci=:it into :nt;
      exception ZDUBLOWANA_KARTA 'B³¹d generacji ID kontrahenta na podstawie NIP lub PESEL
Kontrahent z podanym ID jest ju¿ za³o¿ony pod nazw¹

  '||nt||'

Anuluj zak³adanie kontrahenta (lewy Alt-Backspace)
Je¿eli musisz utworzyæ now¹ kartê po anulacji za³ó¿ nowego kontrahenta bez wpisywania NIP/PESEL';
      END
    end

    if (new.pesel>'0' and new.pesel<>coalesce(old.pesel,0)) THEN
    begin
    select max(ID_KONTRAHENCI) from KONTRAHENCI where pesel=new.pesel  into :it;
    if (it>0) then
      BEGIN
      SELECT NM_KONTRAHENCI from kontrahenci where id_kontrahenci=:it into :nt;
      exception BLAD ' Kontrahent z podanym PESEL jest ju¿ za³o¿ony pod nazw¹
  '||nt||'
 Popraw lub anuluj zmianê';
      END
    end   
      
    if (new.id_kontrahenci=0) then new.telefon=trim(new.telefon);
    if (new.id_kontrahenci=0 and (new.telefon<>(select cyfry from tylko_cyfry(new.telefon)) or char_length(new.telefon)<>9) )
    then exception BLAD 'Nr telefonu musi sk³adaæ siê z 9 cyfr bez spacji';
    
    new.NM_KONTRAHENCI=trim(new.NM_KONTRAHENCI);
    new.NAZWA_PELNA=trim(new.NAZWA_PELNA);
    
    if (new.nip is not null and (new.nip not similar to '[[:ALPHA:] ]{2}% *' or new.nip like 'PL%')) then
      begin
      if (CHARACTER_LENGTH((select*from TYLKO_CYFRY(new.NIP)))<>10) then exception BLAD 'NIP ma 10 znaków - wpisano '||CHARACTER_LENGTH((select*from TYLKO_CYFRY(new.NIP)));
      if ((select ok from NIPP(new.nip))<>'T') then exception BLAD 'Numer NIP jest nieprawid³owy. Nie spe³nia warunku cyfry kontrolnej'; 
      end 
    
    if ((INSERTING or UPDATING and new.nip is distinct from old.nip and coalesce(new.nip,'')<>'') and ap<>10425 and
     new.nip not similar to '([A-Z]{2}|(PL|[0-9]{2})([0-9]|[-]){7,})(U{0,1}|([0-9]|[A-Z]){0,2}|[0-9][0-9A-Z+*])[0-9]{1,}([A-Z]{0,1}|(B[0-9]{2}){0,1}) *' 
     ) then exception BLAD 'NIP mo¿e zawieraæ wy³¹cznie cyfry i ''-'' bez spacji

Europejski identyfikator musi byæ poprzedzony dwoma du¿ymi literami kodu pañstwa
i zawieraæ prawid³owy ci¹g znaków bez spacji i ''-'' ';
 /* https://poradnikprzedsiebiorcy.pl/-formaty-numerow-identyfikacyjnych-vat-w-krajach-czlonkowskich-2014 */    
    
end
^

ALTER PROCEDURE CHK_RPRZEWL (
    IA INTEGER,
    DT TIMESTAMP,
    IT INTEGER,
    IR INTEGER,
    PL CHAR(1),
    WI INTEGER )
RETURNS (
    ITW INTEGER,
    ICH INTEGER,
    IDO INTEGER )

AS
DECLARE IDC INTEGER;
BEGIN
  for select l.ID_PRZEWLEKLE,l.ID_ODPLATNOSC,t.ID_TOWARY,p.ID_CBT from sprzedaz s left join towary t on s.id_apteki=t.id_apteki and s.id_towary=t.id_towary
   left join cbt_przewl p on p.id_cbt=t.id_cbt
   LEFT JOIN PRZEWLEKLE l on p.ID_PRZEWLEKLE=l.ID_PRZEWLEKLE and s.ID_ODPLATNOSC=l.ID_ODPLATNOSC
  where s.id_apteki=:ia and s.id_recepta=:ir and s.data=:dt and s.id_tranzakcje=:it and s.id_odplatnosc<>6 and l.ID_PRZEWLEKLE is not null 
  and ((l.PLEC is not NULL and l.PLEC <> 'O' AND l.PLEC <> :pl) or
    (l.WIEK_OD is not NULL and :wi not between l.WIEK_OD and l.WIEK_DO))
  into ich,ido,itw,idc do
  BEGIN
    if (NOT EXISTS (SELECT l.ID_PRZEWLEKLE FROM CBT_PRZEWL p LEFT JOIN PRZEWLEKLE l ON p.ID_PRZEWLEKLE=l.ID_PRZEWLEKLE and :ido=l.ID_ODPLATNOSC
      WHERE  p.ID_CBT = :idc and (l.PLEC is NULL or l.PLEC = 'O' or l.PLEC = :pl) AND (l.WIEK_OD is NULL or :wi between l.WIEK_OD and l.WIEK_DO))) THEN
      SUSPEND;
  END  
  
END
^

ALTER PROCEDURE NOWYIDPROD (
    AP INTEGER,
    TW INTEGER,
    ID_PROD INTEGER,
    UM VARCHAR(100) )


AS
declare variable mn integer;
begin
  update towary set imp_cbt_jedn='A' where id_apteki=:ap and id_towary=:tw ;

  update or insert INTO TOWARY_WNIOSKI (ID_APTEKI, ID_TOWARY, ID_UMOWY, ID_PROD) values (:ap,:tw,:um,:id_prod);
 
  select typ_c from typ_ceny(:ap,:tw,'today') into :mn;
  if (mn is null) then
  begin
    delete from tw_typy_cen where id_apteki=:ap and id_towary=:tw and obowiazuje_od='TODAY';
    insert into tw_typy_cen (ID_APTEKI,ID_TOWARY,OBOWIAZUJE_OD,ID_TYPY_CEN) values (:ap,:tw,'today',3);
  end

  select count(*) from tow_listy where id_apteki=:ap and id_towary=:tw and id_listy=21  and obowiazuje_do>='TODAY' into mn;

  if (mn=0) then
    update or insert into tow_LISTY (ID_APTEKI,id_towary,id_listy,obowiazuje_od,obowiazuje_do) values (:ap,:tw,21,'today','01/01/3000');
 
  select count(*) from tow_listy where id_apteki=:ap and id_towary=:tw and id_listy=1  and obowiazuje_do>='TODAY' into mn;

  if (mn=0) then
    update or insert into tow_LISTY (ID_APTEKI,id_towary,id_listy,obowiazuje_od,obowiazuje_do) values (:ap,:tw,1,'today','01/01/3000');

end
^

ALTER PROCEDURE DUBEL_REC (
    IA INTEGER,
    IR INTEGER,
    NRR VARCHAR(50),
    ATR VARCHAR(2),
    MC INTEGER,
    RK INTEGER,
    IL INTEGER,
    UM VARCHAR(20) DEFAULT NULL,
    KS VARCHAR(20) DEFAULT NULL )
RETURNS (
    ND INTEGER,
    DT TIMESTAMP,
    IZ INTEGER )

AS
DECLARE mcod INTEGER;
DECLARE mcdo INTEGER;
DECLARE idsp INTEGER;
DECLARE idrp INTEGER;
DECLARE idss INTEGER;
DECLARE kore INTEGER;
DECLARE stsp CHAR(1);
DECLARE stko CHAR(1);
DECLARE twko INTEGER;
DECLARE dtko DATE;
DECLARE wako DOUBLE PRECISION;
begin
  mcod = rk * 100 + mc;
  mc = mc + il - 1;
  if (mc > 12)  THEN
  BEGIN
    rk = rk +1;
    mc = mc - 12;
  END
  mcdo = rk * 100 + mc;
  
  
  if (CHARACTER_LENGTH(nrr)<10 or CHARACTER_LENGTH(nrr)=44) THEN
    exit;
  for select nr_w_dniu,data_przyj,id_recepta from recepta r where id_apteki=:ia and numer=:nrr and id_recepta<>:ir and
    (nr_w_dniu<>-1 or (select count(*) from bufor_recept where id_apteki=r.id_apteki and id_recepta=r.id_recepta)>0 or r.ATRYBUTY like 'RZ%') 
    and (:atr<>'GW' or ((rok_od*100+mies_od+na_ile-1 >= :mcod and rok_od*100+mies_od<=:mcdo ) AND r.PRZYCZ_GL IS NOT DISTINCT FROM NULLIF(:um,'') AND r.KOD_SRODKA = :KS) )
    into :nd,:dt,:iz do
  BEGIN
    SELECT FIRST 1 s.ID_SPRZEDAZ,s.TRYB FROM SPRZEDAZ s WHERE s.ID_RECEPTA = :iz and s.ID_APTEKI = :ia  INTO idsp,stsp;
    kore = 0;  
    if (ir <> 0 and stsp<> 'S') THEN /* sprawdzamy czy znaleziona recepta nie jest korekta do sprawdzanej*/
      for SELECT s.ID_SPRZEDAZ FROM SPRZEDAZ s WHERE s.ID_RECEPTA = :iz and s.ID_APTEKI = :ia  INTO idsp do
      if (kore = 0) THEN
        SELECT COUNT(*) FROM hist_korekty(:ia,:idsp) h 
        LEFT JOIN SPRZEDAZ s on s.ID_SPRZEDAZ = h.IDSP and s.ID_APTEKI = :ia 
        WHERE s.ID_RECEPTA = :ir INTO kore;
     
    if (kore = 0) THEN
    BEGIN
      if (stsp<>'S') THEN
      BEGIN
        idss = 0;
        for SELECT s.ID_SPRZEDAZ FROM SPRZEDAZ s WHERE s.ID_RECEPTA = :iz and s.ID_APTEKI = :ia  INTO idsp do
        if (kore = 0) THEN  /* szukamy czy jakakolwiek pozycja recepty ma status nie zwrocona */
        BEGIN
          SELECT FIRST 1 s.TRYB,s.ID_TOWARY,s.WARTOSC,s.DATA  FROM hist_korekty(:ia,:idsp) h 
          LEFT JOIN SPRZEDAZ s on s.ID_SPRZEDAZ = h.IDSP and s.ID_APTEKI = :ia
          LEFT JOIN RECEPTA r on s.ID_RECEPTA=r.ID_RECEPTA and r.ID_APTEKI=s.ID_APTEKI
          WHERE r.NUMER = :nrr
          ORDER by h.WERSJA DESC into stko,twko,wako,dtko;
          if (stko not in ('Z','K') AND (twko<>0 or wako<>0 or dtko>'01.01.1900')) THEN
            kore = 1;          
          if (idss = 0) THEN  /* pierwsza SPRZEDAZ na recepte z tym nr */
            SELECT FIRST 1 h.IDSP FROM hist_korekty(:ia,:idsp) h 
            LEFT JOIN SPRZEDAZ s on s.ID_SPRZEDAZ = h.IDSP and s.ID_APTEKI = :ia
            LEFT JOIN RECEPTA r on s.ID_RECEPTA=r.ID_RECEPTA and r.ID_APTEKI=s.ID_APTEKI
            WHERE r.NUMER = :nrr
            ORDER by h.WERSJA INTO  idss;
        END  
      END  
      ELSE
      BEGIN
        idss = idsp;
        kore = 1;
      END  
      if (kore = 1) THEN
      BEGIN
        SELECT s.ID_RECEPTA from SPRZEDAZ s where s.ID_SPRZEDAZ = :idss and s.ID_APTEKI = :ia INTO idrp;
        SELECT COUNT(*) FROM SPRZEDAZ s LEFT JOIN ETAKSACJE e on s.ID_SPRZEDAZ=e.ID_SPRZEDAZ and s.ID_APTEKI=e.ID_APTEKI
        WHERE s.ID_RECEPTA=:idrp and s.ID_APTEKI=:ia and e.REALIZACJA='C' 
        INTO kore;  /* sprawdzamy czy nie jest realizacja czaesciowaa */
        if (kore=0) THEN
        BEGIN
          if (ir <> 0)  THEN
          BEGIN
            SELECT COUNT(*) FROM SPRZEDAZ s  WHERE s.ID_RECEPTA=:idrp and s.ID_APTEKI=:ia and s.ID_ODPLATNOSC <> 6 into kore;
          END
          ELSE
            kore = 1;
          if (kore>0) THEN  
          BEGIN
            SUSPEND;
            exit;
          END  
        END  
      END
    END
  END  
end
^

ALTER PROCEDURE GENZAMP (
    IZ INTEGER,
    AP VARCHAR(1024),
    PM INTEGER,
    D1 TIMESTAMP,
    D2 TIMESTAMP )
RETURNS (
    IA INTEGER )

AS
declare variable it integer;
   declare variable ib integer;
   declare variable tw integer;
   declare variable iap integer;
   declare variable ad integer;
   declare variable ds integer;
   declare variable iu integer;
   declare variable ma integer;
   declare variable st double precision;
   declare variable sp double precision;
   declare variable mss double precision;
   declare variable za double precision;
   declare variable zp double precision;
   declare variable cn double precision;
   declare variable bo double precision;
   declare variable bb double precision;
   declare variable ss double precision;
   declare variable wz double precision;
   declare variable so double precision;
   DECLARE VARIABLE kt VARCHAR(512);
   declare mno double precision;
   declare variable  iSNM integer;
   declare variable  iSSZ integer;
   declare variable  iSSS integer;
   declare variable  iSOW integer;
   declare variable  iSOZ integer;
   DECLARE VARIABLE stao VARCHAR(1);
   DECLARE stpa char(1);
   DECLARE stpi INTEGER;
   DECLARE spza char(1);
begin
  select id_zbiorcze,adni,prsub,COALESCE(stsub,'N'),COALESCE(ST_PAKIET,'N') from zampak where id_zampak=:iz into ia,ad,ds,stao,stpa;
  if (stpa = 'T') THEN
    stpi = 2 ;
  ELSE
    stpi = 1 ;  
  if (ad>0) then
    mno = ad / (d2 - d1);
  else
    mno = 1;
  if (ia is null) then
  begin
    ia = gen_id(sq_zbiorcze,1);
  end
  ELSE
  BEGIN
    delete from BRAKI where id_zbiorcze=:ia and :ap not containing id_apteki;
  END  
  for select id_apteki from ogolne where   (:ap containing id_apteki) and id_apteki>10000  into iap do
    for select z.id_cbt,max(t.stan_max),max(t.id_towary),
      case when z.snm ='T' then c.id_internm else -1 end,
      case when z.ssz ='T' then c.id_synzb   else -1 end,
      case when z.sss ='T' then c.id_synszcz else -1 end,
      case when z.sow ='T' then c.id_synwl   else -1 end,
      case when z.soz ='T' then c.id_odpzl   else -1 end,
      max(t.SP_ZAMAWIANIA)
    from zampza  z
    left join towary t on t.id_apteki=:iap and z.id_cbt=t.id_cbt
    left join cbt c on c.id_cbt=z.id_cbt
    where z.id_zampak=:iz  and t.id_cbt is not null
    group by z.id_cbt,z.ile,c.ID_INTERNM,c.ID_SYNZB,c.ID_SYNSZCZ,c.ID_SYNWL,c.ID_ODPZL, z.SNM,z.SOZ,z.SSZ,z.SSS,z.SOW,z.SOZ
    into it,st,tw,iSNM, iSSZ ,iSSS ,iSOW, iSOZ, spza do
     begin
       select stan from  STAN_WART(:iap,:tw,:stpi) into st;
       if (st is null) then st=0;
       if (spza is distinct from 'P') THEN
       BEGIN
       select sum(sztuk_jp) from rzdst r  left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
       left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
       where r.id_apteki=:iap and r.id_towary=:tw and r.data between :d1 and :d2 and (t.id_kontrahenci is null or t.id_kontrahenci>0) and (t.NIE_BIERZ<>'T' or t.nie_bierz is null)  into :sp;
       if (sp is null or sp<0) then sp=0;
       if (ds>0) then
       begin
          ss = 0;
          for select id_cbt from cbt where id_cbt<>:it and coalesce(zamawiaj,'N')='N' and (id_internm=:isnm or  id_synzb=:issz or id_synszcz=:isss or id_synwl=:isow or id_odpzl=:isoz) into iu do
          begin
            select COALESCE(sum(sprz),0) from (
              select     (select sum(sztuk_jp) from rzdst r  left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
              left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
              where r.id_apteki=o.id_apteki and r.id_towary=o.id_towary and r.data between :d1 and :d2 and (t.id_kontrahenci is null or t.id_kontrahenci>0) and (t.NIE_BIERZ<>'T' or t.nie_bierz is null)  ) sprz
            from towary o
            where o.id_cbt=:iu and o.id_apteki=:iap) into mss;
            ss = ss + mss;
            if (stao='T') THEN
            BEGIN
              select sum(w.STAN)
              from towary o
              LEFT JOIN  STAN_WART(o.ID_APTEKI,o.ID_TOWARY,:stpi) w on 0=0
               where o.id_cbt=:iu and o.id_apteki=:iap  into so;
              if (so is null) then so=0;
              st = st + so;
            END 
          end
          sp = sp + ss * 0.01 * ds;
       end
       END
       ELSE
         sp = 0;
       insert into tmp_nadnied (id_cbt,id_apteki,sztuk,id_towary,stan) values (:it,:iap,:sp*:mno,:tw,:st);
     end  /* koniec petli 1  */

   for select id_apteki from ogolne where   (:ap containing id_apteki  and id_apteki>10000) 
     UNION
     select DISTINCT o.MAGAZYN_REZERWOWY from ogolne o where   (:ap containing id_apteki  and id_apteki>10000)  and o.MAGAZYN_REZERWOWY is not null and (:pm > 0) 
   into iap do
   BEGIN
     ib = null;
     SELECT id_braki from braki where id_apteki=:iap and id_zbiorcze=:ia into ib;
     if (ib is null) THEN
     BEGIN
       select min(id_braki) from braki where id_apteki=:iap into ib;
       if (ib is null or ib>0) then ib=0;
       ib=ib-1;
       select list(id_kontrahenci,'|') from dostawcy d where  d.ZAZNACZ='T' and d.ID_APTEKI=:iap into  kt;
       kt='|'|| kt || '|';
       insert into braki (id_apteki,id_braki,data,dostawcy,id_zbiorcze) values (:iap,:ib,'now',:kt,:ia);
     END  
     ELSE
     BEGIN
       UPDATE BRAKZAW b SET b.ZAMOWIENIE=0,b.SZTUK_JP=0 WHERE b.ID_APTEKI=:iap AND b.ID_BRAKI=:ib;
     END
   end
   for select z.ID_CBT,z.ILE,z.CENA,z.bonus from ZAMPZA z
     where id_zampak=:iz and z.ile>0
    into it,st,cn,bo do
   BEGIN
     if (cn is null) then
     begin
       select cp from zampr(:iz,:it,'01/01/3000','01/01/3000') into cn;
       if (cn<99999) then
         cn=cast(cn * 100 as integer) * 0.01;

     end
     /* magazyn rezerwowy */
     SELECT sum(sztuk),sum(maxvalue(sztuk-stan,0)),count(*) from tmp_nadnied where (:ap containing id_apteki) and id_cbt=:it into sp,zp,ad;
     if (pm>0) THEN
     BEGIN
       ss=floor(st*0.01*pm);
       for 
        select o.MAGAZYN_REZERWOWY,sum(t.SZTUK),count(*) from ogolne o
        left join tmp_nadnied t on  t.id_cbt=:it and t.ID_APTEKI=o.ID_APTEKI
        where   (:ap containing o.id_apteki  and o.id_apteki>10000)  and o.MAGAZYN_REZERWOWY is not null 
        group by o.MAGAZYN_REZERWOWY into ma,wz ,ds
        do
       begin
         if (sp>0 and wz>0) THEN
           bb = wz/sp;  /*  podzial wg sprzedazy */
         ELSE
           bb = ds / ad ; /* podzial wg ilosci aptek */        
         mss = ceiling(bb * ss);  
         st=st-mss;
         select id_braki from braki where id_zbiorcze=:ia and id_apteki=:ma into :ib;
         select max(id_towary) from towary where id_apteki=:ma and id_cbt=:it into :tw;
         if (tw is not null) then
           update or insert into brakzaw(id_apteki,id_braki,id_towary,zamowienie,sztuk_jp,jednostka,cena)
             values (:ma,:ib,:tw,:mss,:mss,1,:cn);
       end 
     END
    ss = bo/st;
    
    if (st>zp) then
    begin
      /* Zamówienie przekracza (spzedaz -  stan) wtedy nadwyzke dzielimy wg sprzedazy  
      wz : wspolczynnik podzialu wg zapotrzebowania
      sp : wspolczynnik podzailu wg saprzedazy
      */
      wz = 1;
      if (sp<>0) then  sp=(st-zp)/sp; else sp=0;
    end
    else
    begin
      sp = 0;
      if (zp<>0) then wz = st / zp; else wz=0  ;
    end

    for SELECT id_apteki,sztuk,id_towary,sztuk-stan from tmp_nadnied where (:ap containing id_apteki) and id_cbt=:it
        order by sztuk desc  into ma,za,tw,zp do
    if (st>0) then
    BEGIN
      if (za=0) then za=1;
      select id_braki from braki where id_zbiorcze=:ia and id_apteki=:ma into :ib;
      za=maxvalue(ceiling(za*sp + zp*wz),0);
      if (ss>0 and bo>0) then
      begin
        bb = ceiling(za*ss);
        bo = bo - bb;
        if (bo<0) then
          bb = bb + bo;
      end
      else
        bb = null;
      st=st-za;
      if (st<0) then
        za=za+st;
      if (za>0) then
        update or insert into brakzaw(id_apteki,id_braki,id_towary,zamowienie,sztuk_jp,jednostka,cena,bonusy)
          values (:ma,:ib,:tw,:za,:za,1,:cn,:bb);
    END

   END
suspend;
end
^


ALTER PROCEDURE GENPAK (
    IP INTEGER,
    AP VARCHAR(1024),
    SNM CHAR(1),
    SOZ CHAR(1),
    SSZ CHAR(1),
    SSS CHAR(1),
    SOW CHAR(1),
    PRS INTEGER,
    PRU INTEGER,
    D1 TIMESTAMP,
    D2 TIMESTAMP,
    DNI INTEGER,
    NADW CHAR(1),
    ZERA CHAR(1),
    GRZA CHAR(1),
    STAO CHAR(1) )
RETURNS (
    IZZ INTEGER )
AS
declare variable it integer;
 declare variable tw integer;
 
 declare variable iu integer;
 declare variable ia integer;
 declare variable ib integer;
 declare variable st double precision;
 declare variable sp double precision;
 declare variable ss double precision;
 declare variable sm double precision;
 declare variable mst double precision;
 declare variable msp double precision;
 declare variable msp5 double precision;
 declare variable msm double precision;
 declare variable mno double precision;
 declare variable mss double precision;
 declare variable  iSNM integer;
 declare variable  iSOZ integer;
 declare variable  iSSZ integer;
 declare variable  iSSS integer;
 declare variable  iSOW integer;
 DECLARE ups DOUBLE PRECISION;
 declare variable osm double precision;
 declare variable osa double precision;
 DECLARE VARIABLE kt VARCHAR(512);
 DECLARE stpa char(1);
 DECLARE stpi INTEGER;
 
begin
  if (dni>0) then
    mno = dni / (d2 - d1);
  else
    mno = 1;
  select id_zbiorcze,COALESCE(ST_PAKIET,'N') from zampak where id_zampak=:ip into izz,stpa;  
  if (stpa = 'T') THEN
    stpi = 2 ;
  ELSE
    stpi = 1 ;  
  if (izz is null) then
  begin
    izz = gen_id(sq_zbiorcze,1);
  end
  ELSE
  BEGIN
    delete from BRAKI where id_zbiorcze=:izz and :ap not containing id_apteki;
  END  
  
  update zampak set adni=:dni,prsub=:prs,stsub = :stao,id_zbiorcze= :izz where id_zampak=:ip;
  for select id_apteki from ogolne where position(id_apteki in :ap) > 0 into ia do
    BEGIN
     ib = null;
     SELECT id_braki from braki where id_apteki=:ia and id_zbiorcze=:izz into ib;
     if (ib is null) THEN
     BEGIN
       select min(id_braki) from braki where id_apteki=:ia into ib;
       if (ib is null or ib>0) then ib=0;
       ib=ib-1;
       select list(id_kontrahenci,'|') from dostawcy d where  d.ZAZNACZ='T' and d.ID_APTEKI=:ia into  kt;
       kt='|'|| kt || '|';
       insert into braki (id_apteki,id_braki,data,dostawcy,id_zbiorcze) values (:ia,:ib,'now',:kt,:izz);
     END  
     ELSE
     BEGIN
       UPDATE BRAKZAW b SET b.ZAMOWIENIE=0,b.SZTUK_JP=0 WHERE b.ID_APTEKI=:ia AND b.ID_BRAKI=:ib;
     END
   end
  
  
  for select id_cbt,
    case when :snm='T' then id_internm else -1 end,
    case when :soz='T' then ID_ODPZL else -1 end,
    case when :ssz='T' then id_synzb else -1 end,
    case when :sss='T' then id_synszcz else -1 end,
    case when :sow='T' then id_synwl else -1 end
    from cbt where zamawiaj=:grza
    order by zamclick
    into it,iSNM,iSOZ, iSSZ ,iSSS ,iSOW do
    begin
      sp = 0;
      for select id_apteki from ogolne where position(id_apteki in :ap) > 0 into ia do
      begin
        tw = null;
        select /*coalesce(sum(coalesce(stan_max,0)),0)*/0,
             coalesce(sum(coalesce((select sum(sztuk_jp) from rzdst r  left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
             left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
             where r.id_apteki=o.id_apteki and r.id_towary=o.id_towary  and  r.data between :d1 and :d2 and (t.id_kontrahenci is null or t.id_kontrahenci>0) and (t.NIE_BIERZ<>'T' or t.nie_bierz is null)  ),0)),0),
             coalesce(sum(w.STAN),0) ,max(o.ID_TOWARY)
        from towary o
        left join STAN_WART(o.ID_APTEKI,o.ID_TOWARY,:stpi) w on 0=0
        where o.id_cbt=:it and o.id_apteki=:ia and  o.SP_ZAMAWIANIA is DISTINCT from 'P' into msm,msp,mst,tw;

        if (tw is null) THEN
          select max(o.ID_TOWARY)
          from towary o
          where o.id_cbt=:it and o.id_apteki=:ia into tw;
        
        /* dla galenu przeniesienie sprzedazy internetowej 
        select coalesce(sum(coalesce((select sum(sztuk_jp) from rzdst r  left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
             join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje and nr_kasy=5
             where r.id_apteki=o.id_apteki and r.id_towary=o.id_towary and r.data between :d1 and :d2 and (t.id_kontrahenci is null or t.id_kontrahenci>0) and (t.NIE_BIERZ<>'T' or t.nie_bierz is null)  ),0)),0)
        from towary o        
        where o.id_cbt=:it and o.id_apteki=10021 and :ia in (10021,10425) into msp5;       
        
        if (:ia=10021) then msp=msp-msp5;
        if (:ia=10425) then msp=msp+msp5;
        */
        
        select id_braki from braki where id_zbiorcze=:izz and id_apteki=:ia into :ib;
        
        /* Sprzedaz substytutow*/
        ss = 0;
        if (prs>0) then
        BEGIN
          for select id_cbt from cbt where id_cbt<>:it and coalesce(zamawiaj,'N')<>:grza and (id_internm=:isnm  or id_synzb=:issz or id_synszcz=:isss or id_synwl=:isow or id_odpzl=:isoz) into iu do
          begin
            select COALESCE(sum(sprz),0) from (
              select     (select sum(sztuk_jp) from rzdst r  left join sprzedaz s on r.id_apteki=s.id_apteki and r.id_sprzedaz=s.id_sprzedaz
              left join tranzakcje t on s.id_apteki=t.id_apteki and s.data=t.data and s.id_tranzakcje=t.id_tranzakcje
              where r.id_apteki=o.id_apteki and r.id_towary=o.id_towary and r.data between :d1 and :d2 and (t.id_kontrahenci is null or t.id_kontrahenci>0) and (t.NIE_BIERZ<>'T' or t.nie_bierz is null)  ) sprz
            from towary o
            where o.id_cbt=:iu and o.id_apteki=:ia  and o.SP_ZAMAWIANIA is DISTINCT from 'P') into mss;
            ss = ss + mss;
            if (stao='T') THEN
            BEGIN
              select /*coalesce(sum(coalesce(stan_max,0)),0)*/0,coalesce(sum(w.STAN),0)
                from towary o
                left join STAN_WART(o.ID_APTEKI,o.ID_TOWARY,:stpi) w on 0=0
                where o.id_cbt=:iu and o.id_apteki=:ia into osm,osa;
              msm = msm + osm;
              mst = mst + osa;  
            END
          end
        END
        msp = (msp + ss*prs*0.01) * mno;
        msp=maxvalue(msm,msp);
        st = ceil( msp - mst);
        if (nadw = 'N') then
           st = maxvalue(st,0);
        
        if (tw is not null) then   
          update or insert into brakzaw(id_apteki,id_braki,id_towary,zamowienie,sztuk_jp,jednostka)
          values (:ia,:ib,:tw,maxvalue(:st,0),maxvalue(:st,0),1);
        sp = sp + coalesce(st,0);
      end
      if (pru = 0) THEN
      BEGIN
        SELECT FIRST 1 z.UPUST
        FROM ZAMPZA z LEFT JOIN ZAMPAK p on z.ID_ZAMPAK=p.ID_ZAMPAK
        WHERE z.ID_CBT = :it ORDER by p.DATA DESC into ups;
      END
      ELSE
        ups = pru;  

      if (sp>=1 or zera='T') THEN
        UPDATE OR INSERT INTO ZAMPZA (ID_ZAMPAK, ID_CBT, ILE, TYP,  UPUST, SNM, SOZ, SSZ,  SSS, SOW , ILE_ORG)
         VALUES (:ip, :it,ceiling(:sp),'W',:ups,:SNM,:SOZ, :SSZ,  :SSS, :SOW, ceiling(:sp));
      ELSE
        for select id_apteki from ogolne where position(id_apteki in :ap) > 0 into ia do 
          for SELECT id_towary FROM TOWARY where id_apteki=:ia and id_cbt = :it INTO tw do
            DELETE FROM BRAKZAW WHERE id_apteki=:ia and id_braki = (SELECT id_braki from braki where id_zbiorcze = :izz and id_apteki=:ia) and id_towary = :tw;  
    
            
    end
end^

ALTER TRIGGER UPD_VAT_TOWARY ACTIVE
BEFORE UPDATE POSITION 0
as
declare variable cn integer;
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  if (new.KOD=old.KOD and new.data_od<old.data_od 
      and old.data_od=(select min(data_od) from vat_towary where id_apteki=new.id_apteki and id_towary=new.id_towary)) then exit;
  if (new.KOD<>old.KOD or new.data_od<>old.data_od) then
  begin
    cn=0;
    select count(*) from zdst z left join dostawy d on z.id_apteki=d.id_apteki and z.id_dostawy=d.id_dostawy
      where z.id_apteki=new.id_apteki and z.id_towary=new.id_towary and z.data>=minvalue(new.data_od,old.data_od) and d.status='Z' into :cn;
    if (cn=0) then
      select count(*) from rzdst where id_apteki=new.id_apteki and id_towary=new.id_towary and data>=minvalue(new.data_od,old.data_od) into :cn;
    if (cn=0) then
     select count(*) from vat_towary
      where id_apteki=new.id_apteki and id_towary=new.id_towary and  data_od<>old.data_od and data_od between minvalue(new.data_od,old.data_od) and maxvalue(new.data_od,old.data_od) into :cn;
    if (cn>0) then exception VAT;
  end

end^

create or ALTER TRIGGER INS_UPD_EPRUF_RAPORTY for EPRUF_RAPORTY ACTIVE
BEFORE INSERT OR UPDATE POSITION 1
AS
declare variable it integer;
begin
   if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
     
   if (new.zatw='T') then 
    begin
    NEW.IFUPDDATE='NOW'; NEW.IFUPDUSER=USER;
    if (abs(new.DOFIN -(select coalesce(sum(s.epruf_df),0) from sprzedaz s where s.id_apteki=new.id_apteki and s.data=new.data and s.epruf_df is not null))<0.01) THEN
    update tranzakcje set epruf_aut='T' where id_apteki=new.id_apteki and data=new.data and epruf_id is not null and coalesce(epruf_aut,'N')<>'T';
    end
   
end^

create or ALTER TRIGGER INS_UPD_SPRZEDAZA for sprzedaz ACTIVE 
after INSERT OR UPDATE POSITION 0
as
declare kods Varchar(20); 
declare ZL Varchar(50);
declare MC Integer;
begin
 if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
 
 if (new.id_recepta is not null
    and (select coalesce(PARAGON,'N') from tranzakcje where id_apteki=new.id_apteki and data=new.data and id_tranzakcje=new.id_tranzakcje)='N' ) THEN
  BEGIN --niestety to nie zabezpiecza w pelni, po wyslaniu realizcji mozna jeszcze zrobic cuda np zmienic kod srodka zapisywanie powinno byc w momencie wyslij i tylko wowczas
   select kod_srodka,numer,rok_od||lpad(mies_od,2,0) from recepta where id_apteki=new.id_apteki and id_recepta=new.id_recepta and atrybuty like 'GW%' into :kods,:zl,:mc;
   if (:kods>'') THEN 
   update rzdst set WN_IDP=new.id_zamiennik
   where id_apteki=new.id_apteki and id_sprzedaz=new.id_sprzedaz and (rzdst.WN_IDP is null or 7<>(SELECT*from STATUS_ZLECENIA(:zl,:mc)));    
  END

end^

ALTER PROCEDURE TYLKO_WIERSZE (
    IPARAM Blob sub_type 1,
    ZNAK_DEFAULT_CYFRY Char(1) DEFAULT '0' )
RETURNS (
    CYFRY Varchar(150) )
AS
declare I integer;
declare p char(1);
declare z char(1);
begin
/* zwraca wierszami ciagi ze stringa
dla z=0 cyfrowe
dla z=1 dzieli liniami 
dla z='znak'  wg podanego znaku ³amania np '|', ascii_char(9)
np do wylistowania eanow, znalezienia nieistniejacych rekordow  itd
*/
  z=znak_default_cyfry; -- dla alter pomietac o dodaniu DEFAULT '0'
  if (:z='1') then z=ascii_char(9);
  cyfry ='';  
  IPARAM=IPARAM||iif(z='0',' ',z);
  i = 1;
  while (i <= char_length(:iparam)) do
  begin  
   p=substring(:iparam from i for 1);  
   if (:p similar to '[[:DIGIT:]]' and :z='0' or ascii_val(:p) between 32 and 250 and :p not like z and :z<>'0')  
     then
      begin       
      cyfry = :cyfry || (:p);
      i = :i + 1;      
      end      
     else
      begin          
      if (trim(cyfry)>'') then suspend;
      cyfry='';
      i = :i + 1;
      end
  end  
end^


ALTER PROCEDURE DOPISZ_SMOPL (
    IA INTEGER )
AS
DECLARE dt date;
DECLARE ka CHAR(1);
DECLARE br CHAR(1);
DECLARE go INTEGER;
DECLARE dz INTEGER;
DECLARE dc VARCHAR(20);
DECLARE id INTEGER;
DECLARE dk date;
BEGIN
select COALESCE(SMOPL_18,'T'),COALESCE(SMOPL_BRA,'N') from ogolne where id_apteki=:ia INTO ka,br;
if (ka='N') THEN
BEGIN
  SELECT EXTRACT( WEEKDAY FROM cast('today' as date)) FROM RDB$DATABASE INTO dz;
  if (dz=0) THEN
    dz = 7;
  SELECT COALESCE(k.DO_GODZINY,'10') FROM USER_KALENDARZ k where k.ID_APTEKI=:ia and k.ID_USER=2 and k.DZIEN=:dz  into dc;
  dz = POSITION(':',dc)  ;
  if (dz>0) THEN
    dz = dz - 1 ;
  ELSE
    dz = 2;
  go = cast(SUBSTRING(dc from 1 FOR dz) as INTEGER);
END
ELSE
  go = 18;

for SELECT DISTINCT DATA FROM TRANZAKCJE t where t.DATA >= '01.04.2019' and COALESCE(t.ID_KONTRAHENCI,1) > 0 and t.ID_APTEKI = :ia
  and data<'today' or t.DATA = 'today' and EXTRACT(HOUR from cast('now' as TIMESTAMP))>=:go
UNION
  SELECT DISTINCT DATA FROM DOSTAWY t WHERE t.DATA >= '01.04.2019' and t.ID_APTEKI = :ia
  and data<'today' or t.DATA = 'today' and EXTRACT(HOUR from cast('now' as TIMESTAMP))>=:go

into dt do
BEGIN
  if ((SELECT COUNT (*) from SMOPL s WHERE s.DATA_OD = :dt and s.TYP = 'C')=0) THEN
  BEGIN
    INSERT INTO SMOPL (ID_SMOPL, ID_APTEKI, DATA_GEN, DATA_OD, DATA_DO, TYP) VALUES
     (gen_id(SQ_SMOPL,1), :ia, 'now', :dt, :dt, 'C');
    if (br='T') THEN
    BEGIN
      dk = dt + 0.999;
      if (exists(SELECT 1 FROM BRAKI b LEFT JOIN ZAMINFO i on i.ID_APTEKI = b.ID_APTEKI and i.ID_BRAKI = b.ID_BRAKI
          LEFT JOIN ZAM_POZ p on p.ID_APTEKI = i.ID_APTEKI and p.ID_ZAM   = i.ID_ZAM LEFT JOIN TOWARY  t on p.ID_APTEKI = t.ID_APTEKI and t.ID_TOWARY = p.ID_TOWARY
          where b.id_apteki = :ia and b.DATA BETWEEN :dt and :dk and t.SMOPL_RAP = 'T' and i.STAN >=4 and p.POTWIERDZONE = 0 and i.ID_PROMOCJI is NULL and t.EAN_REF is not NULL
          and (select typ from typ_leku(t.ID_APTEKI,t.ID_TOWARY,:dt)) <> 'OTC'
          and (SELECT count(*) from ZAMINFO o LEFT JOIN ZAM_POZ z on z.ID_APTEKI=o.ID_APTEKI and z.ID_ZAM=o.ID_ZAM where o.ID_APTEKI = b.ID_APTEKI
          and o.ID_BRAKI = b.ID_BRAKI and z.ID_TOWARY = p.ID_TOWARY and z.POTWIERDZONE>0 and o.STAN>=4) = 0 ))  THEN
      BEGIN
        INSERT INTO SMOPL (ID_SMOPL, ID_APTEKI, DATA_GEN, DATA_OD, DATA_DO, TYP) VALUES
            (gen_id(SQ_SMOPL,1), :ia, 'now', :dt, :dt, 'Z') RETURNING ID_SMOPL into id;
        INSERT INTO SMOPL_BRAKI (ID_SMOPL, ID_APTEKI, EAN, ILE) 
           SELECT :id, b.ID_APTEKI,t.EAN_REF,max(p.ZAMOWIONE) ile FROM BRAKI b LEFT JOIN ZAMINFO i on i.ID_APTEKI = b.ID_APTEKI and i.ID_BRAKI = b.ID_BRAKI
           LEFT JOIN ZAM_POZ p on p.ID_APTEKI = i.ID_APTEKI and p.ID_ZAM   = i.ID_ZAM LEFT JOIN TOWARY  t on p.ID_APTEKI = t.ID_APTEKI and t.ID_TOWARY = p.ID_TOWARY
           where b.id_apteki = :ia and b.DATA BETWEEN :dt and :dk and t.SMOPL_RAP = 'T' and i.STAN >=4 and p.POTWIERDZONE = 0 and i.ID_PROMOCJI is NULL and t.EAN_REF is not NULL
           and (select typ from typ_leku(t.ID_APTEKI,t.ID_TOWARY,:dt)) <> 'OTC'
           and (SELECT count(*) from ZAMINFO o LEFT JOIN ZAM_POZ z on z.ID_APTEKI=o.ID_APTEKI and z.ID_ZAM=o.ID_ZAM where o.ID_APTEKI = b.ID_APTEKI
           and o.ID_BRAKI = b.ID_BRAKI and z.ID_TOWARY = p.ID_TOWARY and z.POTWIERDZONE>0 and o.STAN>=4) = 0 GROUP by b.ID_APTEKI,t.EAN_REF;

      END
    END
  END
END
END^


ALTER PROCEDURE TYLKO_CYFRY_SUM(IPARAM VARCHAR(32))
 RETURNS(CYFRY INTEGER)
 AS
declare variable I integer;
declare variable cyfry0 integer;
begin
/* sumuje liczby ze stringa np '10,15, 20'= 45  */
  iparam=iparam||' ';
  cyfry = 0;
  cyfry0 =0;  
  i = 1;  
  while (i <= char_length(:iparam)) do
  begin
    if (substring(:iparam from i for 1) similar to '[[:DIGIT:]]')  then
      begin       
      cyfry0 = :cyfry0 || (substring(:iparam from i for 1));
      i = :i + 1;
      end
     else
      begin                
      cyfry = cyfry+cyfry0;
      if (cyfry>0) then cyfry0=0;
      i = :i + 1;
      end
  end
  suspend;
end
^

ALTER PROCEDURE UPD_OKRESY (
    IA Integer )
AS
DECLARE dt date;

DECLARE pnh char(1);
DECLARE pnd char(1);

DECLARE wth char(1);
DECLARE wtd char(1);

DECLARE srh char(1);
DECLARE srd char(1);

DECLARE czh char(1);
DECLARE czd char(1);

DECLARE pth char(1);
DECLARE ptd char(1);

DECLARE soh char(1);
DECLARE sod char(1);

DECLARE ndh char(1);
DECLARE ndd char(1);

DECLARE han char(1);
DECLARE dos char(1);

declare dow int;
declare kwa int;
declare dek int;
begin
  select max(data) from OKRESY where id_apteki=:ia into dt;

  if (dt is null) then
  begin
    /*dt='01.01.2015';*/
    dt= dateadd(year,-2,cast('today' as date)-EXTRACT(DAY FROM cast('today' as date))+1); --2lata wstecz od 1 danego miesiaca
    pnh = 'T';
    pnd = 'T';
    
    wth = 'T';
    wtd = 'T';
    
    srh = 'T';
    srd = 'T';
    
    czh = 'T';
    czd = 'T';

    pth = 'T';
    ptd = 'T';
    
    soh = 'T';
    sod = 'N';
    
    ndh = 'N';
    ndd = 'N';
    
  end  
  else
  begin  
    dt = dt + 1;
    select FIRST 1 o.HANDLOWY,o.DOSTAWA from OKRESY o where EXTRACT(WEEKDAY from data)=1 ORDER by o.DATA DESC into pnh,pnd;
    select FIRST 1 o.HANDLOWY,o.DOSTAWA from OKRESY o where EXTRACT(WEEKDAY from data)=2 ORDER by o.DATA DESC into wth,wtd;
    select FIRST 1 o.HANDLOWY,o.DOSTAWA from OKRESY o where EXTRACT(WEEKDAY from data)=3 ORDER by o.DATA DESC into srh,srd;
    select FIRST 1 o.HANDLOWY,o.DOSTAWA from OKRESY o where EXTRACT(WEEKDAY from data)=4 ORDER by o.DATA DESC into czh,czd;
    select FIRST 1 o.HANDLOWY,o.DOSTAWA from OKRESY o where EXTRACT(WEEKDAY from data)=5 ORDER by o.DATA DESC into pth,ptd;
    select FIRST 1 o.HANDLOWY,o.DOSTAWA from OKRESY o where EXTRACT(WEEKDAY from data)=6 ORDER by o.DATA DESC into soh,sod;
    select FIRST 1 o.HANDLOWY,o.DOSTAWA from OKRESY o where EXTRACT(WEEKDAY from data)=0 ORDER by o.DATA DESC into ndh,ndd;
  end  
  
  /* bylo dt<='31.12.2025' - obecnie 31.12 plus 3 do roku*/ 
  WHILE  (dt<=dateadd(year,3,cast('31.12.'||EXTRACT(year from cast('today' as date)) as date))) do 
          
  BEGIN
    dow = EXTRACT(WEEKDAY from dt) + 1;
          
    if (dow=2) THEN
    BEGIN
      han=pnh;
      dos=pnd;
    END

    if (dow=3) THEN
    BEGIN
      han=wth;
      dos=wtd;
    END

    if (dow=4) THEN
    BEGIN
      han=srh;
      dos=srd;
    END

    if (dow=5) THEN
    BEGIN
      han=czh;
      dos=czd;
    END

    if (dow=6) THEN
    BEGIN
      han=pth;
      dos=ptd;
    END

    if (dow=7) THEN
    BEGIN
      han=soh;
      dos=sod;
    END

    if (dow=1) THEN
    BEGIN
      han=ndh;
      dos=ndd;
    END

    kwa = ceiling(EXTRACT(MONTH from dt)   / 3);

    dek = minvalue( ceiling(EXTRACT(DAY from dt) / 10) ,3);

    INSERT INTO OKRESY (ID_APTEKI, DATA, MIESIAC, ROK, DOW, DEK, KWA, HANDLOWY,
    DOSTAWA, DYZUR, WAGA) VALUES (:ia,:dt,EXTRACT(MONTH from :dt),EXTRACT(YEAR from :dt),:dow,:dek,:kwa,:han,:dos,'N',1);

    dt = dt + 1;

  end
end ^

create or ALTER TRIGGER INS_UPD_ceny_towary for ceny_towary ACTIVE
BEFORE INSERT OR UPDATE POSITION 0
as
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
 
 if (new.WN_KOD is null) then new.WN_KOD='';
 
 if (new.WN_KOD not in ('','100%') and new.obowiazuje_od is distinct from old.obowiazuje_od 
    and not exists (select*from PROD_ZPOSP where new.obowiazuje_od between data_od and data_do and kod_srodka=new.wn_kod)) then
 exception blad ' Kod œrodka '''||new.WN_KOD||''' jest nieprawid³owy
 (Id Towaru '||new.id_towary||', ''Obowi¹zuje od '||(select*from tylko_data(new.obowiazuje_od))||''')
 Popraw lub anuluj zmianê';

end^

create or ALTER TRIGGER INS_UPD_WNIOSKI_UMOWY for WNIOSKI_UMOWY ACTIVE
BEFORE insert OR update POSITION 0
as
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit; 
 
 if (EXTRACT(year FROM new.do_dnia)>EXTRACT(year FROM cast('today' as timestamp))) then
  new.mc_start=1;
  
 if (new.do_dnia>cast('today' as timestamp) and new.mc_start>EXTRACT(MONTH FROM cast('today' as timestamp))+1) then
  new.mc_start=EXTRACT(MONTH FROM cast('today' as timestamp));

end^


create or ALTER TRIGGER INS_UPD_users for users ACTIVE
BEFORE INSERT OR UPDATE POSITION 0
as
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
 
 if (INSERTING and lower(new.nazwa) in 
 ('add','admin','all','alter','and','any','as','at','avg','begin','blob','both','by','case','cast','char','check','close','count','cross','date','day'
 ,'dec','drop','else','end','fetch','float','for','from','full','grant','group','hour','in','index','inner','int','into','is','join','left','like'
 ,'long','lower','max','merge','min','month','nchar','no','not','null','of','on','only','open','or','order','outer','plan','real','right','rows','set'
 ,'some','start','sum','table','then','time','to','trim','union','upper','user','using','value','view','when','where','while','with','year'))
 then exception blad 'Nazwa u¿ytkownika '''||new.nazwa||''' niedozwolona 
u¿yj innej lub dodaj jakiœ znak np '''||new.nazwa||'1''';

 if (INSERTING and new.nazwa not similar to '[[:ALPHA:]][[:ALNUM:]]*')  
  then exception blad 'Nazwa u¿ytkownika '''||new.nazwa||''' niedozwolona 
Nazwa nie mo¿e zawieraæ polskich znaków, spacji itp lub zaczynaæ siê od cyfr
U¿yj liter, cyfry mog¹ wyst¹piæ po min. 1 literze';

 if (new.rodzaj='T' and new.nazwisko is null) then begin new.nazwisko='technik farm. '; new.TYP_ID='2'; end
 if (new.rodzaj='M' and new.nazwisko is null) then begin new.nazwisko='mgr farm. '; new.TYP_ID='1'; end
 
 if (new.nazwisko is null) then exception blad 'Nazwa nie mo¿e byæ pusta
W przypadku farmaceutów i techników uzupe³nij 
''Tytu³, nazwisko imiê'' np.:
mgr farm. Kowalska-Nowak Janina *NS!!
(wszystkie znaki po * nie s¹ wysy³ane na DRR) ';

 if (lower(new.nazwisko) like 'tech.%') then new.nazwisko=replace(replace(replace(new.nazwisko,'tech.','technik '),'TECH.','technik '),'  ',' ');
 if (lower(new.nazwisko) like '% farm%' and lower(new.nazwisko) not like '% farm.%') then new.nazwisko=replace(replace(new.nazwisko,' farm',' farm.'),' FARM',' farm.');

 if (new.aktywny='T' and new.nfzid similar to '[/0-9]{5,}' and coalesce(new.PRZETW_OSOBOWYCH,'N')<>'T') then
 exception blad 'Brak uprawnieñ do przetwarzania danych osobowych
Brak mo¿liwoœci realizacji e-Recept
Usuñ identyfikator NFZ lub w³¹cz uprawnienia';

 if (new.TYP_ID='2' and new.NFZID<>'00000000000' and (select peseld from PESELP(new.nfzid)) is null) THEN
 exception blad 'B³êdny PESEL';

end^

ALTER TRIGGER ETAKSACJE_CT1
AS
BEGIN
  IF (new.STATUS = 'B' and new.bledy containing 'Dokument o podanym identyfikatorze ju¿ wystêpuje w systemie.' )
  THEN
  BEGIN
    new.STATUS = 'W' ;
    new.opis = 'Operacja wykonana prawid³owo. TR';
  END
  
  IF (new.STATUS = 'W' and old.status='K' and new.opis not like 'Operacja wykonana prawid³owo%')  THEN
   begin
   new.STATUS = 'Z';
   end
   
  IF (OLD.STATUS IS DISTINCT FROM NEW.STATUS and new.STATUS = 'N')
  THEN
  BEGIN    
    new.opis = null;
  END

END
^

ALTER PROCEDURE UP_ATC(IAP INTEGER)
 AS
declare variable wa varchar(1);
declare variable wn varchar(50);
declare variable it integer;
begin 
  for select max(left(WARTOSC,1)),ID_TOWARY from TW_KLAS
    where id_apteki=:iap and id_klasyfikacje=13
    group by ID_TOWARY
    into :wa,:it do
 begin  
   if ((select coalesce(MAX(left(WARTOSC,1)),'0') from TW_KLAS where id_klasyfikacje=17 and id_apteki=:iap and id_towary=:it)<>:wa) then   
  begin
    wn = null;
    delete from TW_KLAS where id_klasyfikacje=17 and id_towary=:it;
    if (wa like 'A%') then wn='A-Przewód pokarmowy i metabolizm';
    if (wa like 'B%') then wn='B-Krew i uk³ad krwiotwórczy';
    if (wa like 'C%') then wn='C-Uk³ad sercowo-naczyniowy';
    if (wa like 'D%') then wn='D-Leki dermatologiczne';
    if (wa like 'G%') then wn='G-Uk³ad moczowo p³ciowy i hormony p³.';
    if (wa like 'H%') then wn='H-Leki hormonalne dzia³aj¹ce ogólnie';
    if (wa like 'J%') then wn='J-Leki przeciwinfekcyjne,dzia³.ogólnie';
    if (wa like 'L%') then wn='L-Leki przeciwnowotworowe';
    if (wa like 'M%') then wn='M-Uk³ad miêœniowo-szkieletowy';
    if (wa like 'N%') then wn='N-Uk³ad nerwowy';
    if (wa like 'P%') then wn='P-Œrodki przeciw paso¿ytnicze';
    if (wa like 'R%') then wn='R-Uk³ad oddechowy';
    if (wa like 'S%') then wn='S-Narz¹dy zmys³ów';
    if (wa like 'V%') then wn='V-Varia';
    if (wn is not null) then
    insert into tw_klas (id_apteki,id_towary,id_klasyfikacje,wartosc) values (:iap,:it,17,:wn);
  end
 end

/*zalatwia to triger - zweryfikowac po jakims czasie
delete from tw_klas k where k.id_apteki=:iap and k.id_klasyfikacje=17 and not
  exists (select * from tw_klas where id_apteki=k.id_apteki and id_towary=k.id_towary and id_klasyfikacje=13);
*/  

end
^

ALTER PROCEDURE OSOZ_DOST (
    IA INTEGER,
    IT INTEGER,
    DT TIMESTAMP )
RETURNS (
    ID_DOSTAWCY VARCHAR(9),
    NAZWA_DOSTAWCY VARCHAR(300),
    NIP_DOSTAWCY VARCHAR(30),
    NUMER_ZEZWOLENIA VARCHAR(50),
    MAG_ID_POZ_APT VARCHAR(9),
    MAG_ILOSC DOUBLE PRECISION,
    MAG_CENA_NETTO_RABAT DOUBLE PRECISION,
    MAG_CENA_BRUTTO_RABAT DOUBLE PRECISION,
    MAG_CENA_NETTO DOUBLE PRECISION,
    MAG_CENA_BRUTTO DOUBLE PRECISION,
    MAG_CENA_DETAL_NETTO DOUBLE PRECISION,
    MAG_CENA_DETAL_BRUTTO DOUBLE PRECISION,
    MAG_DATA_STANU TIMESTAMP,
    MAG_ILOSC_SPR DOUBLE PRECISION )

AS
BEGIN
   if ((SELECT COUNT(*) from OSOZ_USLUGI u WHERE u.OPCJA='PHRT' AND u.WARTOSC = 'T')=0) THEN EXIT;
   if (not exists(select*from OSOZ_DOSTAWCY)) then exit;
    
   mag_data_stanu = 'now';
   for select right( round(min(z.ID_ZDST),0),9),round(sum(z.STAN),5),round(sum(z.STAN*r.CENA_NT),2),round(sum(z.STAN*r.CENA_BR),2),
      round(sum(z.STAN*c.CENA_NT),2),round(sum(z.STAN*c.CENA_BR),2),round(sum(s.CENA_NT*z.STAN),2),round(sum(s.CENA_BR*z.STAN),2),
      u.ID_KS,u.NAZWA,u.NIP,u.ZEZWOLENIE,round(sum(z.STAN - IIF( coalesce(z.blokada,'N')='N' , 0 , coalesce(z.ile_blokada,z.stan))),5)
    from ZDST z
    left JOIN CENY_DOSTAWY r on r.ID_APTEKI=z.ID_APTEKI and r.ID_ZDST=z.ID_ZDST and r.ID_CENY=2
    left JOIN CENY_DOSTAWY c on c.ID_APTEKI=z.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
    LEFT JOIN DOSTAWY d on d.ID_DOSTAWY=z.ID_DOSTAWY and d.ID_APTEKI=z.ID_APTEKI
    LEFT JOIN KONTRAHENCI y on d.ID_KONTRAHENCI = y.ID_KONTRAHENCI
    LEFT JOIN REJESTR_HURTOWNI u on cast(u.ID as varchar(25)) = COALESCE(d.KOD_HURTOWNI,y.SMOPL_MDIDP)
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,:dt,z.id_zdst,'') s on 0=0
    where z.ID_APTEKI=:ia and z.ID_TOWARY=:it and z.CZYNNY='T' 
    GROUP by u.ID_KS,u.NAZWA,u.NIP,u.ZEZWOLENIE
    INTO
     mag_id_poz_apt,mag_ilosc,
     mag_cena_netto_rabat,mag_cena_brutto_rabat,
     mag_cena_netto,mag_cena_brutto,
     mag_cena_detal_netto,mag_cena_detal_brutto,ID_DOSTAWCY, NAZWA_DOSTAWCY ,
     NIP_DOSTAWCY, NUMER_ZEZWOLENIA, mag_ilosc_spr  do
   BEGIN
     if (EXISTS (SELECT NIP FROM OSOZ_DOSTAWCY d where replace(d.NIP,'-','')= replace(:NIP_DOSTAWCY,'-',''))) THEN
       SUSPEND;
   END

end
^

CREATE or alter TRIGGER DEL_TW_KLAS FOR TW_KLAS
ACTIVE AFTER DELETE POSITION 1
AS
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
 
 delete from tw_klas where id_apteki=old.id_apteki and id_towary=old.id_towary and old.ID_KLASYFIKACJE=13 and ID_KLASYFIKACJE=17;
   
END^

CREATE or alter TRIGGER KLAS_SL_BI FOR KLAS_SL
ACTIVE before update or INSERT POSITION 0
AS
BEGIN
  /* dla tych id wczytywane sa opisy przy aktualizacji z cbt a nie powinny istniec */
  if (new.ID_KLASYFIKACJE in (24,22,18,13,12,11,6,4,3,1,-10,-11,-12)) then 
   begin 
   if (INSERTING) then delete from KLAS_SL where ID_KLASYFIKACJE=new.ID_KLASYFIKACJE;
   if (UPDATING) then new.ID_KLASYFIKACJE=old.ID_KLASYFIKACJE;
   end
END^

ALTER TRIGGER UPD_ZDST
as
declare variable ic integer;
declare variable dc date;
declare variable nz VARCHAR(50);
declare variable nr VARCHAR(50);
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  if (new.stan<0.00001 and new.stan>-0.00001) then new.stan=0;
  
  if (rdb$get_context('USER_TRANSACTION','ZDSTZW1') is distinct from 1 and old.stan=0 and new.stan<>0) then
   begin
    nz=(select left(nazwa,50) from towary where id_apteki=new.id_apteki and id_towary=new.id_towary);
    nr=(select left(nr_faktury,50) from dostawy where id_apteki=new.id_apteki and id_dostawy=new.id_dostawy);
    if (exists(select*from dostawy where id_apteki=new.id_apteki and id_dostawy=new.id_dostawy and status is null)) then 
     exception STAN :nz||ascii_char(10)||'Nie mo¿na zmieniæ stanu kartoteki, niezaksiêgowana dostawa'||ascii_char(10)||:nr||' z dnia '||(select*from TYLKO_DATA(new.data));
    if (new.sztuk_jp<0) then 
     exception STAN :nz||ascii_char(10)||'Nie mo¿na zmieniæ stanu kartoteki z korety dostawy'||ascii_char(10)||:nr||' z dnia '||(select*from TYLKO_DATA(new.data));
   end
   
  if (new.stan<0) then exception STAN (select left(nazwa,50) from towary where id_apteki=new.id_apteki and id_towary=new.id_towary)||ascii_char(10)||
   'Stan nie mo¿e byæ ujemny'||ascii_char(10)||'id_zdst '||mod(old.id_zdst,100000000000000)||' nowa iloœæ '||mod(new.stan,10000000000);  

  if (rdb$get_context('USER_TRANSACTION','ZDSTZW') is distinct from 1 and old.korekta_do is null and new.STAN > abs(new.SZTUK_JP) + 0.00001
      and exists(select*from towary where id_apteki=new.id_apteki and id_towary=new.id_towary and smopl_rap='T'))
  then exception STAN (select left(nazwa,50) from towary where id_apteki=new.id_apteki and id_towary=new.id_towary)||ascii_char(10)||
   'Dla leków raportowanych do SMOPL stan nie mo¿e wiêkszy od pierwotnego'||ascii_char(10)||
   'id_zdst '||mod(old.id_zdst,100000000000000)||' nowa iloœæ '||mod(new.stan,10000000000)||' iloœæ pierwotna '||mod(new.SZTUK_JP,10000000000);    
    
  if (coalesce(old.korekta_do,0) <> coalesce(new.korekta_do,0)) then
  begin
    if (OLD.KOREKTA_DO is not null) then
      update zdst set SKORYGOWANA_PRZEZ = null where ID_APTEKI=old.id_apteki and  id_zdst=OLD.KOREKTA_DO;
    if (NEW.KOREKTA_DO is not null) then
      update zdst set SKORYGOWANA_PRZEZ = NEW.ID_ZDST where ID_APTEKI=old.id_apteki and  id_zdst=NEW.KOREKTA_DO;
  end

   if (new.data<>old.data) then
   begin
    if (new.data>old.data) then
    begin
      select count(*) from rzdst where id_apteki=new.id_apteki and id_zdst=new.id_zdst and data<new.data and data>'01/01/2000' into ic;
      if (ic>0) then
        exception DOSTAWA_KORYGOWANA;
    end
    for select id_ceny,max(obowiazuje_od) from ceny_dostawy where id_apteki=new.id_apteki and id_zdst=new.id_zdst
     group by id_ceny into ic,dc do
     begin
       if (ic>2) then
         delete from ceny_dostawy where id_apteki=new.ID_APTEKI and  id_zdst=new.id_zdst and obowiazuje_od<>:dc and id_ceny=:ic;
       update ceny_dostawy set obowiazuje_od=new.data where id_apteki=OLD.ID_APTEKI and   id_zdst=old.id_zdst and id_ceny=:ic;
     end
   end
   if (new.ile_blokada>0 and coalesce(new.blokada,'N')='N') then new.ile_blokada=null;
   if (new.ile_blokada is not null and new.ile_blokada>new.stan) then
      new.ile_blokada=new.stan;
    if (old.ID_TOWARY=-1 and new.ID_TOWARY<>-1) THEN
    BEGIN
      if (
         (SELECT coalesce(y.IMPORTUJ_EAN,'N') FROM DOSTAWY d LEFT JOIN DOSTAWCY y on y.ID_APTEKI=d.ID_APTEKI and y.ID_KONTRAHENCI=d.ID_KONTRAHENCI where d.ID_APTEKI=new.ID_APTEKI and d.ID_DOSTAWY=new.ID_DOSTAWY) <> 'T'
         AND 
         (SELECT typs FROM typ_skladnika(new.id_apteki,new.id_towary)) NOT in (1,2)
         )
      THEN
        DELETE FROM ZDST_KLAS k WHERE k.ID_APTEKI=new.ID_APTEKI and k.ID_ZDST=new.ID_ZDST and k.ID_KLASYFIKACJE=6;
    END
end
^

ALTER PROCEDURE JEST_NARK (
    IAP INTEGER,
    IDT INTEGER,
    IDC INTEGER,
    EAN VARCHAR(20) )
RETURNS (
    JEST VARCHAR(1), typ VARCHAR(10))
AS
begin
  if (idc<=0) then
  begin
    if (idt<>0) then
      select max(id_cbt) from towary where id_apteki=:iap and id_towary=:idt into idc;
    else
      select max(id_cbt) from cbt_klas where id_klasyfikacje=6 and wartosc=:ean into idc;
  end
  if (idc is not null and idc>0) then
  begin
    select FIRST 1 LEFT(wartosc,10) from cbt_klas where id_cbt=:idc and id_klasyfikacje=22 INTO typ;
  end
  else
  begin
    jest ='N';
    SUSPEND;
    exit;
  end
  if (typ is null) then typ = 'x';
  if (typ in ('II-P','I-N')) then
     jest ='A';
  else
  BEGIN
    if (typ='II-P' or typ='I-P'  or typ like '%-N' or EXISTS(select wartosc from cbt_klas where id_cbt=:idc and id_klasyfikacje=15 and wartosc='A')) then
      jest ='T' ;
    else
    BEGIN
      if (typ <> 'x') then
        jest ='P' ;
      else
        jest ='N';
    END
  END
  suspend;
end
^

/*tylko alter*/
alter trigger DEL_RECEPTURA active
after delete position 0
AS
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
execute procedure na_stan(old.id_apteki,old.id_sprzedaz);
delete from sprzedaz where id_apteki=old.id_apteki and id_sprzedaz=old.id_sprzedaz;
execute procedure napraw_wplate(old.id_apteki,old.dt_tranz_przyj,old.id_tranz_przyj);
end^

ALTER PROCEDURE SALDO_ZMIANY(IA INTEGER,
IK INTEGER,
KONTO VARCHAR(100),
DT DATE)
 RETURNS(OPIS VARCHAR(150),
KWOTA DOUBLE PRECISION,
ID INTEGER)
 AS
DECLARE bo DOUBLE PRECISION;
DECLARE it integer;
DECLARE cn integer;
DECLARE kp DOUBLE PRECISION;
DECLARE op VARCHAR(10);
BEGIN
  for select id_tranzakcje from tranzakcje where id_apteki=:ia and data=:dt and (id_kontrahenci is null or id_kontrahenci>0) and nr_kasy=:ik
  and ((paragon <>'N') or (select count(*) from sprzedaz where id_apteki=tranzakcje.id_apteki and id_tranzakcje=tranzakcje.id_tranzakcje and data=tranzakcje.data)=0
   or (select count(*) from sprzedaz where id_apteki=tranzakcje.id_apteki and id_tranzakcje=tranzakcje.id_tranzakcje and data=tranzakcje.data and tryb='R')>0)
   into :it do
    execute procedure napraw_wplate(:ia,:dt,:it);
  select saldo from SALDO_PRZED(:ia,:konto,100000,:dt) into bo;
  opis = 'Saldo pocz¹tkowe ' ;
  id = 0 ;
  kp = 0 ;
  kwota = bo;
  suspend;
  for select o.id_tranz_opisy ID,o.nm_tranz_opisy OPIS,cast(sum(KWOTA) as double precision) KWOTA,count(*) ILOSC from tranz_wplaty w left join tranzakcje t on w.id_apteki=t.id_apteki and t.data=w.data and t.id_tranzakcje=w.id_tranzakcje left join tranz_opisy o on w.id_tranz_opisy=o.id_tranz_opisy
  where w.id_apteki=:ia and w.data=:dt and t.NR_KASY=:ik
  group by o.id_tranz_opisy,o.nm_tranz_opisy
  union
  select cast(11 as integer) ID,cast('Do bufora gotowka' as varchar(100)) OPIS,cast(sum(zaliczka) as double precision) KWOTA,count(*) from bufor_recept
  where id_apteki=:ia and data=:dt and p_kasa=:ik and (bufor_recept.id_tranz_opisy is null or bufor_recept.id_tranz_opisy<>2)
  union
  select cast(13 as integer) ID,cast('Do bufora karta' as varchar(100)) OPIS,cast(sum(zaliczka) as double precision) KWOTA,count(*) from bufor_recept
  where id_apteki=:ia and data=:dt and p_kasa=:ik and bufor_recept.id_tranz_opisy=2
  union
  select cast(12 as integer) ID,cast('Z bufora' as varchar(100)) OPIS,cast(sum(-zaliczka) as double precision) KWOTA,count(*) from bufor_recept
  where id_apteki=:ia and o_data=:dt and o_kasa=:ik into id,opis,kwota,cn do
  BEGIN
    if (id in (1,11,12)) THEN
      bo = bo + COALESCE(kwota,0);
    if (id in (2,13)) THEN
      kp = kp + COALESCE(kwota,0);  
    if (cn=1) THEN 
      op = ' pozycja';
    ELSE if (cn in (2,3,4)) THEN
      op = ' pozycje';
    ELSE
      op = ' pozycji';
            
    opis = opis || ' [ ' || cn || op || ' ]';
    SUSPEND;
  END 
  if (kp>0) THEN
  BEGIN
    id = 21;
    opis = 'Karty p³atnicze razem';
    kwota = kp;
    SUSPEND;
  END   
  id = 22;
  opis = 'Saldo koñcowe gotówki';
  kwota = bo;
  SUSPEND;
end
^


ALTER PROCEDURE EPRUF_PASUJ (
    IA integer )
AS
declare variable b7 char(7);
declare variable it integer;
declare variable ut integer;
begin

  for select t.id_towary,max(t.wartosc),min(u.id_towary) from tw_klas t      
   JOIN epruf_leki l on t.wartosc=l.bloz
   LEFT JOIN EPRUF_USL u on u.id_apteki=t.id_apteki and u.id_towary=t.id_towary    
   WHERE t.id_apteki=:ia and t.id_klasyfikacje=3 and (u.id_towary is null or l.bloz<>u.bloz)
   group by t.id_towary into :it,b7,ut do 
   begin
   if (ut is null) 
    then
     insert into epruf_usl (id_apteki,id_towary,bloz) values (:ia,:it,:b7);
    else  
     update epruf_usl set bloz=:b7 where id_apteki=:ia and id_towary=:it;
   end    

  for select t.id_towary,max(l.BLOZ) from tw_klas t 
   JOIN epruf_leki l on t.wartosc=l.ean
   LEFT JOIN EPRUF_USL u on u.id_apteki=t.id_apteki and u.id_towary=t.id_towary    
   WHERE t.id_apteki=:ia and t.id_klasyfikacje=6 and u.id_towary is null 
   group by t.id_towary into :it,b7 do 
   begin   
   insert into epruf_usl (id_apteki,id_towary,bloz) values (:ia,:it,:b7);
   if (not exists (select*from tw_klas where id_apteki=:ia and id_klasyfikacje=3 and id_towary=:it)) then
     INSERT into TW_KLAS (id_apteki,id_towary,id_klasyfikacje,wartosc) VALUES (:ia,:it,3,:b7);
   end

/* problemy sa takie: w epruf_leki sa blozy ktorych nie ma w blpr i w druga strone sa w blp a nie ma w epruf 
np 01.07.22 ep brak 7049332 jest 7030315 ktorego brak w blpr dla ean 5011091104725 za to karte nazwali 'OILATUM SOFT Szamp. (->7049332)'
*/

end^

CREATE or alter TRIGGER UPD_EPRUF_LEKI FOR EPRUF_LEKI
ACTIVE BEFORE UPDATE POSITION 10
AS
BEGIN
    IF (OLD.BLOZ IS DISTINCT FROM NEW.BLOZ        
        OR OLD.EAN IS DISTINCT FROM NEW.EAN
        OR OLD.NAZWA IS DISTINCT FROM NEW.NAZWA
        OR OLD.DAWKA IS DISTINCT FROM NEW.DAWKA
        OR OLD.POSTAC IS DISTINCT FROM NEW.POSTAC
        OR OLD.OPAKOWANIE IS DISTINCT FROM NEW.OPAKOWANIE
        OR OLD.PRODUCENT IS DISTINCT FROM NEW.PRODUCENT
        OR OLD.KRAJ IS DISTINCT FROM NEW.KRAJ)
    THEN
    BEGIN
        new.IFUPDDATE = 'now';
    END
END^

create or alter PROCEDURE NOWA_WERSJA_kontrole
AS
declare ap apteka;
declare gw varchar(75)='×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××';
declare il int=0;
declare il0 int=0;
declare il1 varchar(150)=null;
DECLARE cr CHAR(4);
declare kom varchar(2000);
DECLARE DB_UPD_LOG TYPE OF COLUMN OGOLNE.DB_UPD_LOG;
DECLARE erec_ile TYPE OF COLUMN OGOLNE.erec_ile;
DECLARE KOWAL_ILE TYPE OF COLUMN OGOLNE.KOWAL_ILE;
DECLARE ser_kasa TYPE OF COLUMN OGOLNE.ser_kasa;
DECLARE EPRUF_RAP_LAST TYPE OF COLUMN OGOLNE.EPRUF_RAP_LAST;
DECLARE wersja_wgrana TYPE OF COLUMN OGOLNE.wersja_wgrana;
begin

if(ap<1000) then exit;

execute procedure cbt_przed(:ap); 
/*przy ew zmianie powyzszej rekompilacja wymaga jesli by mialy tez sie zmienic kontrole*/

 cr = ASCII_CHAR(13)||ASCII_CHAR(10);
 kom=cr;
 select DB_UPD_LOG,erec_ile,KOWAL_ILE,ser_kasa,EPRUF_RAP_LAST,wersja_wgrana from ogolne where id_apteki=:ap into DB_UPD_LOG,erec_ile,KOWAL_ILE,ser_kasa,EPRUF_RAP_LAST,wersja_wgrana;
 
 if (erec_ile containing 'e') then 
 kom=kom|| cr ||'Znaleziono '||substring(erec_ile from position('e',erec_ile)+1 for 2)||' niezapisanych w eRecept w bazie, u¿yj analizy 10. -- Brakuj¹ce eRecepty w bazie'; 
   
 if (erec_ile similar to '%[A-Z]%') then 
 begin 
 il1=substring(erec_ile from 12 for iif(position('e',erec_ile)>0,position('e',erec_ile)-12,20));  
 kom=kom|| cr ||'Niewys³anych '||(select*from TYLKO_CYFRY_sum(:il1))||' DRR, w tym: '||:il1||' ';end 

 select count(*) from ETAKSACJE where id_apteki=:ap and opis starting 'Odtworzona' and status='K' and ifinsuser='SYSDBA' and ifinsdate>cast('today' as date) into il;
 if (il > 0) then
 kom=kom|| cr ||'Wykryto i dodano '||:il||' DRR ze statusem K ';
 
 select count(*),sum(IIF(status='W' and opis like 'Operacja wykonana prawid³owo%',1,0)) from etaksacje  where papier='F' and ifinsdate>cast('today' as date)-30 and id_apteki=:ap into il,il0;
 if (il0=0 or il/nullif(il0,0) > 1.2) then  
 kom=kom|| cr ||'W ostatnich 30 dniach wys³ano '||:il0||' i niewys³ano '||:il||' recept farmacetyczych '; else il=0;

 if (KOWAL_ILE like '%D:%') then
 kom=kom|| cr ||'Pobranie odpowiedzi zaleg³ych serializacji (-3) utknê³o '||(select*from tylko_cyfry(substring(:KOWAL_ILE from position('D:',:KOWAL_ILE)+2 for 3)))||' dni temu na kasie '||ser_kasa||' '; 
 
 if (KOWAL_ILE like '%-1:%') then
 kom=kom|| cr ||'Co najmniej '||(select*from tylko_cyfry(substring(:KOWAL_ILE from position('-1:',:KOWAL_ILE)+3 for 4)))||' niewys³anych serializacji opakowañ (-1) '; 

 if (substring(KOWAL_ILE from 1 for 10)<cast('today' as date)-5) then
 kom=kom|| cr ||'Brak potwierdzonych serializacji od piêciu dni. SprawdŸ Magazyn » Serializacja opakowañ ';
 
 select count(distinct z.id_towary) from zdst z join towary t on t.id_apteki=z.id_apteki and t.id_towary=z.id_towary and t.smopl_rap='T' 
 where z.id_apteki=:ap and z.czynny='T' and (coalesce(z.DATA_WAZN,'1.1.2000')<=cast('1.1.2000' as date) or t.EAN_REF is null
 or not exists (select*from ZDST_KLAS k where k.id_apteki=z.id_apteki and k.id_zdst=z.id_zdst and k.id_klasyfikacje=5 and k.wartosc>'' and char_length(k.wartosc)<21)) into il;
 if (il > 0) then
 kom=kom|| cr ||'ZSMOPL Znaleziono '||:il||' produktow bez nr serii/dat lub ean, nale¿y uzupe³niæ przy u¿yciu flitru w towarach ';

 select count(*) from SMOPL where (stan is null or stan like 'Oczekuje%') and data_od>'29.3.19' and typ='C' and dane is not null into il;
 if (il > 1) then
 kom=kom|| cr ||:il||' raportów bez pobranej odpowiedzi ZSOMPL ';

 select count(distinct data_od) from SMOPL s where stan = 'B³êdny' and typ in ('C','B') and data_od>'29.3.19' 
  and not exists (select*from SMOPL where s.data_od=data_od and s.typ=typ and stan like 'Poprawny%') into il;
 if (il > 0) then
 kom=kom|| cr ||:il||' niepoprawionych raportów ZSOMPL (B³êdny) ';

 select count(*) from users where id_apteki=:ap and aktywny='T' and nfzid similar to '[/0-9]{5,}' and coalesce(PRZETW_OSOBOWYCH,'N')<>'T' into il;
 if (il > 0) then
 kom=kom|| cr ||'Personel bez uprawnienia do przetwarzania danych osobowych - SprawdŸ filtr ''Aktywny brak uprawnieñ'' ';

 if (KOWAL_ILE like '%Os:%') then 
 begin 
 il=(select*from tylko_cyfry(substring(:KOWAL_ILE from position('Os:',:KOWAL_ILE)+3 for 4)));
 if (il > 100) then
 kom=kom|| cr ||:il||' niewys³anych OSOZ Zweryfikuj ustawienia wysy³ki w Tlo ';
 end
 
 select count(*) from tranzakcje where id_apteki=:ap and id_osoz='N' and data BETWEEN cast('today' as date)-30 and cast('today' as date)-1 and kor_tr is null into il;
 if (il > 15 and exists(select*from ogolne where id_apteki=:ap and OSOZ_SETR = 'A') or il > 5 and not exists(select*from ogolne where id_apteki=:ap and OSOZ_SETR = 'A'))  then
 kom=kom|| cr ||:il||' niewys³anych OSOZ ''N'' z ubieg³ych 30 dni. Zweryfikuj ustawienia wysy³ki w Tlo ';
 
 if (substring(EPRUF_RAP_LAST from 20)<>'SYSDBA' and nullif(substring(EPRUF_RAP_LAST from 1 for 10),'') > cast('today' as date)-30) then 
 kom=kom|| cr ||'Zweryfikuj/ustaw pobieranie ePRUF w Tlo Status, user: '||replace(substring(EPRUF_RAP_LAST from 18),'-','B')||' ';

 il1=null;
 select list(u) from (select distinct (select*from TYLKO_DATA(data))u from bufor_recept where id_apteki=:ap and (status<>'O' or status is null) and zaliczka>0  
 and not exists (select*from sprzedaz where id_apteki=bufor_recept.id_apteki and id_recepta=bufor_recept.id_recepta) order by data desc) into il1;
 if (il1 is not null) then
 kom=kom|| cr ||'W dniach '||:il1||' istniej¹ zaliczki w buforze bez pokrycia ';
 
 select count(*) from kontrahenci where (kontrahenci.smopl_mdidp is null or kontrahenci.smopl_idp is null) and coalesce(kontrahenci.smopl_typ,'') not in ('FP','PO') and exists (select*from dostawy d
  join zdst z on z.id_dostawy=d.id_dostawy
  join towary t on t.id_towary=z.id_towary and t.smopl_rap='T'
  where d.ID_KONTRAHENCI=kontrahenci.ID_KONTRAHENCI and d.data>cast('today' as date)-366
  ) or 
  (kontrahenci.smopl_typ='HU' and kontrahenci.smopl_mdidp is not null and 99<>:ap and 
  exists(select*from rejestr_hurtowni r where r.id=kontrahenci.smopl_mdidp and coalesce(aktywna,'N')='N' and exists(select*from rejestr_hurtowni r1 where r.nip=r1.nip and r1.aktywna='T'))) into :il;
 if (il > 0) then
 kom=kom|| cr ||'Hurtownia niespasowana lub spasowana z nieaktywn¹ w CSIOZ - filtr w kontrahentach ''SMOPL Dostawcy (..)'' ';

 if (DB_UPD_LOG = 'T') then 
 kom=kom|| cr ||'W ''Parametry ogólne'' w³¹czone zapisywanie historii modyfikacji - (rozrastanie i spowalnienie bazy) ';
 
 il1=null;
 select left(list(distinct opis,:cr),150) from logi where id_apteki=:ap and kategoria='UPD_WERSJI' and data>:wersja_wgrana into il1;
 if (il1 is not null) then
 kom=kom|| cr ||'SprawdŸ logi (''Przegl¹danie logów'') naprawa zapisa³a m.in.: '||cr||' '||:il1; 

 il1=null; 
 select list(id_towary) from (SELECT distinct id_towary from TOWARY_WNIOSKI t
     join PROD_HANDL h on h.ID_PROD = t.ID_PROD and h.ID_UMOWY = t.ID_UMOWY
     join WNIOSKI_UMOWY u on t.ID_UMOWY = u.KOD
     join PROD_ZPOSP z on h.KOD_SR = z.KOD_SRODKA and cast('today' as date) BETWEEN z.DATA_OD and z.DATA_DO 
     join PAKIET_ZAOP a on a.ID_PROD = h.ID_PROD and a.ID_UMOWY = h.ID_UMOWY
     join PLANY_MIES m on a.ID_PAKIET=m.ID_PAKIET and a.ID_UMOWY = m.ID_UMOWY and m.ID_KOM = u.id_kom  and m.MIESIAC = EXTRACT(MONTH from cast('today' as date))
     left join  PROD_ZPOSP_GRUPY g on cast('today' as date) BETWEEN g.DATA_OD and g.DATA_DO and z.KOD_SRODKA starting g.kod_srodka
    where t.id_apteki=:ap and cast('today' as date) BETWEEN u.OD_DNIA and u.DO_DNIA and m.MIESIAC is not NULL
    group by id_towary,iif(g.kod_srodka is null,z.kod_srodka,g.kod_srodka) having count(*)>1) into il1;
 if (il1 is not null) then
 kom=kom|| cr ||'Towary - ''Id produktu'' - przyporz¹dkowane do kilku produktów w umowie - usuñ b³êdne spasowania'||cr||' id_towary: '||:il1;     

 select count(*) from syncerr where id_sync=10 and tablica<>'HL7' and nr_sync=(select nr_sync from synclogin where id_sync=10 order by ifupddate desc rows 1) into il; 
 if (il > 0) then
 kom=kom|| cr ||'B³êdy przy ostatnim pobraniu CBT - SprawdŸ zak³adkê historia pobierania ';

if (char_length(:kom) < 5) then begin kom=''; gw=left(:gw,32); end

exception blad :gw||:kom||' 

 Koniec - Pobierz CBT 
 
 Wersja zaktualizowana poprawnie WCIŒNIJ "Tak"
 
'||:gw;
 
end^

create or alter PROCEDURE NOWA_WERSJA_naprawy
AS
declare ap apteka;
declare it INTEGER;
declare j1 INTEGER;
declare dt timestamp;
declare dtm timestamp;
declare il double PRECISION;
begin

  delete FROM RAPORTY a where not exists(select*from analizy where id_analizy=a.id_analizy); /*dodac kasowanie bardzo czesto uzywanych */
  update tablice set filtr_out=null where filtr_out is not null and tablica starting with 'CBT' and 99<>:ap;

  if (:ap>99) then 
  begin
  select data from wersja order by data desc rows 2 to 2 into dt;

  update tranzakcje set id_osoz='' where id_osoz='B' and data between :dt and cast('today' as date)-2 and id_apteki=:ap
  and (select count(*) from tranzakcje where id_osoz='B' and data>:dt and id_apteki=:ap)<10;  
  
  update tranzakcje set id_osoz='Z' where id_osoz='N' and data between :dt and cast('today' as date)-2 and id_apteki=:ap
  and (select count(*) from tranzakcje where id_osoz='N' and data between :dt and cast('today' as date)-1 and id_apteki=:ap)<8;
  
  if(exists(select*from ogolne where id_apteki=:ap and OSOZ_SETR = 'A')) then
   begin
   /*--bedzie do przerobki na :dt od ostatniej instalacji jak wyzej dopiero jak zostan¹ juz wyczyszczone wszystkie wszedzie albo do utargu raczej */
   dtm=(select min(data) from tranzakcje where id_osoz='N' and data between cast('07.03.2023' as date) and cast('today' as date)-1 and id_apteki=:ap) ;
   il=(select sum(w)/nullif(sum(n),0) from (select count(iif(id_osoz='N' ,1 ,null))n,count(iif(id_osoz='N' ,null ,1))w from tranzakcje where
      (id_osoz='N' or coalesce(id_osoz,'') similar to '[0-9]*') and data between :dtm and cast('today' as date)-1  group by iif(id_osoz='N' ,1 ,null),iif(id_osoz='N' ,null ,1)));
   if(il>20) then   
   update tranzakcje set id_osoz='Z' where id_osoz='N' and data between cast('07.03.2023' as date) and cast('today' as date)-2 and id_apteki=:ap; 
   end
       
  delete from skasowane where ifupddate<cast('today' as date)-90 and id_apteki=:ap;
  delete from SYNCREKORD where ifupddate<cast('today' as date)-30 and id_apteki=:ap;
  
  RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
  delete from updlog where ifupddate<cast('today' as date)-180 and id_apteki=:ap;
  delete from SYNCERR where ifupddate<cast('today' as date)-60 and id_apteki=:ap;
  delete from IMS_logi where data<cast('today' as date)-30 and id_apteki=:ap;
  delete from logi where data<cast('today' as date)-180 and id_apteki=:ap;
  RDB$SET_CONTEXT('USER_SESSION','IFROZP',0);

  update dostawy set status='Z' where status='P' and data<cast('1.1' as date) and cast('today' as date)-cast('1.1' as date)>90 and id_apteki=:ap;    
  begin
  update tranzakcje set paragon='Z', ifupduser='WERSJA' where id_kontrahenci<=0 and paragon ='N' and data<=cast('today' as date)-180 and kategoria is null and id_apteki=:ap;
  WHEN any do execute procedure WPISZ_LOG('UPD_WERSJI','niezaksiêgowane MMR starsze ni¿ 180 dni');
  end
  begin
  update tranzakcje set paragon='Z', ifupduser='WERSJA' where id_kontrahenci=0 and paragon ='N' and data<=cast('today' as date)-10 and kategoria<>'U' and id_apteki=:ap;
  WHEN any do execute procedure WPISZ_LOG('UPD_WERSJI','niezaksiêgowane RW starsze ni¿ 10 dni');
  end

  update towary set nazwa=trim(nazwa) where nazwa like ' %' and id_apteki=:ap;
  update adresy set kod=left(trim(kod),2)||'-'||substring(trim(kod) from 3 for 3) where CHAR_LENGTH(trim(kod))=5;
  
  delete from towary t where (CHAR_LENGTH(nazwa)<2 
    or id_towary>0 and usluga='N' and (not exists (select * from TW_TYPY_CEN where id_apteki=t.id_apteki and id_towary=t.id_towary)
    or not exists (select * from TOW_LISTY where id_apteki=t.id_apteki and id_towary=t.id_towary)
    or not exists (select * from JEDNOSTKI where id_apteki=t.id_apteki and id_towary=t.id_towary and podstawowa='T')
    or exists (select * from JEDNOSTKI j where id_apteki=t.id_apteki and j.id_towary=t.id_towary and j.pochodzi_od>0
    and not exists (select * from jednostki j2 where j2.id_apteki=j.id_apteki and j2.id_towary=j.id_towary and j2.jednostka=j.pochodzi_od))))
   and id_apteki=:ap
   and not exists(select * from zdst where id_apteki=t.id_apteki and id_towary=t.id_towary)
   and not exists(select * from rzdst where id_apteki=t.id_apteki and id_towary=t.id_towary)
   and not exists(select * from cbt where id_cbt=t.id_cbt)  ;
   /*and not exists(select * from brakzaw where zamowienie<>0 and id_apteki=t.id_apteki and id_towary=t.id_towary) spowalnia znacznie*/
    
  insert into tow_listy (id_apteki,id_towary,id_listy,obowiazuje_od,obowiazuje_do)
   select id_apteki,id_towary,1,'1/1/2000','1/1/3000' from towary
   where not exists(select * from tow_listy  where id_apteki=towary.id_apteki and id_towary=towary.id_towary)
   and id_towary>0 and usluga<>'T' and id_apteki=:ap; 
  
  INSERT INTO TW_TYPY_CEN (ID_APTEKI, ID_TOWARY, OBOWIAZUJE_OD, ID_TYPY_CEN) 
   select id_apteki,id_towary,'01.01.2000',2 from towary
   where not exists(select * from TW_TYPY_CEN  where id_apteki=towary.id_apteki and id_towary=towary.id_towary)
   and id_towary>0 and id_apteki=:ap; 

  delete from kontrahenci k where (select count(*) from kontrahenci)>10 and upper(NM_KONTRAHENCI)='' and coalesce(NAZWA_PELNA,'')=''
   and not exists (select * from klientkody where id_kontrahenci=k.id_kontrahenci) and not exists (select * from recepta where id_kontrahenci=k.id_kontrahenci)
   and not exists (select * from DOSTAWCY where id_kontrahenci=k.id_kontrahenci) and not exists (select * from FAKT_ZB where id_kontrahenci=k.id_kontrahenci)
   and not exists (select * from TRANZAKCJE where id_kontrahenci=k.id_kontrahenci);
  
  for select id_towary,jednostka from jednostki j where dostawy='T' and jednostka<>1 and id_apteki=:ap and 
  (not exists (select*from zdst where id_apteki=j.id_apteki and id_towary=j.id_towary and jednostka=j.jednostka) or
    exists (select*from jednostki where id_apteki=j.id_apteki and id_towary=j.id_towary and jednostka=1 and dostawy='T')
    and mnoznik=1 and dzielnik=1 and pochodzi_od=1)
  and not exists(select*from tw_klas where id_apteki=j.id_apteki and id_towary=j.id_towary and id_klasyfikacje=7 and wartosc='Surowiec recepturowy')
  and not exists (select*from jednostki where id_apteki=j.id_apteki and id_towary=j.id_towary and jednostka=1 and nazwa='G') into :it,:j1 do
  begin
  update jednostki set dostawy=null where id_apteki=:ap and id_towary=:it and jednostka=:j1;
  WHEN any do execute procedure WPISZ_LOG('UPD_WERSJI','exception jednostka dostawowa id_tow='||:it||' jedn='||:j1);
  end
  
  for select id_towary from towary t where id_apteki=:ap and id_towary>0 and 
    not exists (select*from JEDNOSTKI where id_apteki=t.id_apteki and id_towary=t.id_towary and podstawowa='T') into :it do
  begin
  update jednostki j set podstawowa='T' where id_apteki=:ap and id_towary=:it and jednostka=1;
  WHEN any do execute procedure WPISZ_LOG('UPD_WERSJI','exception jednostka podstawowa id_tow='||:it);
  end
  
  insert into bufor_recept (id_apteki,id_recepta,klient,zaliczka,data,ifupduser)
   select id_apteki,id_recepta,' Odtworzony nag³ówek bufora ',0,min(extract(month from ifupddate)||'/'|| extract(day from ifupddate)||'/'|| extract(year from ifupddate)),'NAPRBUF'
   from sprzedaz where data='1/9/1900' and not exists(select id_recepta from bufor_recept where id_recepta=sprzedaz.id_recepta and id_apteki=sprzedaz.id_apteki) and id_apteki=:ap
   group by id_apteki,id_recepta;
  INSERT INTO RECEPTURA (ID_APTEKI, ID_RECEPTURA, NR_BLOCZKA, DT_PRZYJ, ID_SPRZEDAZ,ifupduser) select s.ID_APTEKI, gen_id(SQ_RECEPTURA,1), 'NAPRROB',s.ifupddate,s.ID_SPRZEDAZ,'NAPRROB'
   from sprzedaz s where s.data='31.12.1899' and not exists (select * from receptura where id_apteki=s.id_apteki and id_sprzedaz=s.id_sprzedaz) and id_apteki=:ap;
  
  update ogolne set WNIOSKI_BEZ_UMOWY='N' where COALESCE(WNIOSKI_BEZ_UMOWY,'') not in ('N','T','U') and exists(select * from wnioski_umowy where id_apteki=:ap and do_dnia+15>=cast('today' as date)) and id_apteki=:ap; 
  update ogolne set WNIOSKI_BEZ_UMOWY='' where WNIOSKI_BEZ_UMOWY='N' and not exists(select * from wnioski_umowy where id_apteki=:ap and do_dnia>cast('today' as date)) and id_apteki=:ap; 
  update ogolne set KAS_DST='N' where KAS_DST is null and id_apteki=:ap;
  update ogolne set KAS_DST='T' where exists(SELECT 1 FROM RDB$RELATION_CONSTRAINTS rc WHERE rc.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and rc.RDB$CONSTRAINT_NAME='FK_ZDST_ZDST') and KAS_DST='N' and id_apteki=:ap;  
  update ogolne set dubel_z_cbt='N' where dubel_z_cbt is null and id_apteki=:ap and exists (select * from synclogout where id_sync=11 and ifupddate>cast('today' as date)-30);
  update ogolne set RECEPTURA='T' where COALESCE(RECEPTURA,'N')='N' and exists(select * from receptura where id_apteki=:ap and dt_odb>cast('today' as date)-30) and id_apteki=:ap;
  update ogolne set NFZ=iif('SKLEP'='T',(select right(XMLODBIORCA,2) from FAKTURY_REF  where id_faktury_ref=2 and id_apteki=:ap rows 1),(select X2IODZ from FAKTURY_REF  where id_faktury_ref=1 and id_apteki=:ap rows 1)) where nfz is null and id_apteki=:ap;
  update ogolne set id_ks=((select nullif((SELECT*from tylko_cyfry(id_ks)),'') from kontrahenci where id_kontrahenci=0)) WHERE id_ks is null and id_apteki=:ap;

  delete from analizy where id_analizy>800 and id_analizy<1000 and id_apteki=:ap;
  
  update zdst z set data_zamkn=(select max(data)from rzdst where ID_APTEKI=z.ID_APTEKI and id_zdst=z.id_zdst)
    where stan=0 and coalesce(data_zamkn,'1.1.1900')<(select max(data)from rzdst where ID_APTEKI=z.ID_APTEKI and id_zdst=z.id_zdst) and id_zdst<>-1 
     and not EXISTS (select r.ID_ZDST FROM RZDST r LEFT JOIN SPRZEDAZ s on r.ID_SPRZEDAZ=s.ID_SPRZEDAZ and r.ID_APTEKI=s.ID_APTEKI
        where r.ID_APTEKI=z.ID_APTEKI and r.ID_ZDST = z.ID_ZDST and (r.DATA < '01.01.1990'  or s.DATA < '01.01.1990' )) 
     and id_apteki=:ap and (ifupddate>:dt-30 or z.czynny='T');  --by³o ale czas skracac select min(data) from wersja where wersja>=130.12
  update zdst z set data_zamkn=null where data_zamkn is not null
    and EXISTS (select r.ID_ZDST FROM RZDST r LEFT JOIN SPRZEDAZ s on r.ID_SPRZEDAZ=s.ID_SPRZEDAZ and r.ID_APTEKI=s.ID_APTEKI
    where r.ID_APTEKI=z.ID_APTEKI and r.ID_ZDST = z.ID_ZDST and (r.DATA < '01.01.1990'  or s.DATA < '01.01.1990'))  
    and id_apteki=:ap and ifupddate>:dt-30; 
  
  end

 
end^

create or alter PROCEDURE NOWA_WERSJA_KONIEC
AS
declare ap apteka;
begin

INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC,ID_APTEKI)
  select 11,trim(RDB$RELATION_NAME),trim(RDB$FIELD_NAME),'O',(Select kolejnosc from tablice where tablica=RDB$RELATION_NAME),1
  from RDB$RELATION_FIELDS rf where rf.RDB$FIELD_NAME not in ('IFUPDDATE') and
  trim(RDB$RELATION_NAME)||trim(RDB$FIELD_NAME) not similar to 
  'KONTRAHENCISMOPL%|KONTRAHENCIID_KS|OGOLNEAUTO_ZAM|OGOLNEZAM_CBT|OGOLNESC_IMPORT|OGOLNEID_KONTRAHENCI|OGOLNEMAGAZYN_REZERWOWY|OGOLNESKR_APTEKI|SPRZEDAZOPIS|TRANZ_OPISYOPIS|BRAKIWIFINFO|ZAM_POZUWAGI|DOSTAWCYRABAT_GRANICZNY|ETAKSACJETAKSACJA|ETAKSACJEBLEDY|DOSTAWYDYSKIETKA|SMOPLDANE|SMOPLODPOWIEDZ|EPRUF_RAPORTYRAPORT' 
  and exists (select * from SYNCZTB s where s.ID_SYNC=11 and rf.RDB$RELATION_NAME = s.tablica) 
  and not exists (select * from SYNCZTB s where s.ID_SYNC=11 and rf.RDB$RELATION_NAME = s.tablica and rf.RDB$FIELD_NAME = s.pole);

INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC,ID_APTEKI)
  select 10,trim(RDB$RELATION_NAME),trim(RDB$FIELD_NAME),'O',(Select kolejnosc from tablice where tablica=RDB$RELATION_NAME),1
  from RDB$RELATION_FIELDS rf where (RDB$RELATION_NAME='OGOLNE' and trim(RDB$FIELD_NAME) similar to 
  'INFO_BAZA|LEK_INFO|DUBEL_Z_CBT|KONTROLA_EAN|DOSTAWY_WSTECZ|VATE_SC|VATE_FM|VATE_KN|NM_APTEKI|LAST_STANY|WERSJA|WERSJA_WGRANA|TAKSA_BR|PIECZATKA|IMS_KOD|IMS_LDT|IMS_TRYB|DOZ_IDAPT|EPRUF_USL_LAST|FAKT_NAGL|TRYB_NUMERACJI_F|METKA_FIRMA|METKA_FIRMA2|MARZA_REC|LASTINFO|LASTSYNC|EKSP_STANY|SPIS_WLASNE|ZALICZKA_ROBIONE|CBT_WGRANE|KAS_DST|WNIOSKI_BEZ_UMOWY|OFERTA_FORMAT|SPRZEDAZ_POWIETRZA|LICENCJA|F_ODR_VAT|SPRZEDAZ_DW|RECEPTURA|NFZ|EREC_KASY|EREC_ILE|SER_USID|EREC_IDB|SMOPL_18|DATA_STAWKI_MALEJACE|EREC_RPL|EWUS_LG|KOWAL_ILE|PARAGON_NIP|ID_KS|EPRUF_RAP_LAST|REFUS_LG|PROGN_KASA|OSOZ_SETR'
   or trim(RDB$RELATION_NAME) like '%_RANK') and rf.RDB$FIELD_NAME not in ('IFUPDDATE','IFINSUSER','IFINSDATE') 
  and not exists (select * from SYNCZTB s where s.ID_SYNC=10 and rf.RDB$RELATION_NAME = s.tablica and rf.RDB$FIELD_NAME = s.pole)
  and exists (select * from SYNCZTB s where s.ID_SYNC=10 and s.inout='O');

delete from SYNCZTB s where not exists (select * from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = s.tablica and rf.RDB$FIELD_NAME = s.pole);
delete from SYNCZTB s where not exists (select * from RDB$RELATION_FIELDS rf where rf.RDB$RELATION_NAME = s.tablica and rf.RDB$FIELD_NAME = 'IFUPDDATE');
  
update syncztb s set s.kolejnosc=(select kolejnosc from tablice t where t.tablica=s.tablica)
  where s.kolejnosc is distinct from (select kolejnosc from tablice t where t.tablica=s.tablica);

RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
  if (:ap=99) then 
  begin
  update SYNCREKORD set ifupddate='now' where aktywny='P';  
  Update SYNCZTB set inout='I' where id_sync=11;
  Update SYNCZTB set inout='O' where id_sync=11 and (tablica='CBT' or tablica like 'DST_%');
  Update SYNCZTB set inout='O' where id_sync=12 or id_sync=14 or id_sync=15 or id_sync=16;
  Update SYNCZTB set inout='I' where id_sync=12 and tablica='OGOLNE';
  Update SYNC set JEDNOLITE='T' where id_sync=11 or id_sync=12 or id_sync=14 or id_sync=15 or id_sync=16;
  Delete from SYNCZTB where id_sync=11 and tablica='ANALIZY';
  Delete from analizy where id_analizy<501 and (wpisany='T' or nm_analizy similar to '  ?[0-9]%') ;
  end
  
  if (:ap=1 )then
  begin
  Update SYNCZTB set inout='I' where id_sync=11 or id_sync=16;
  Update SYNCZTB set inout='O' where id_sync=11 and tablica='CBT';
  Update SYNCZTB set inout='O' where id_sync=10 or id_sync=13 or id_sync=17;
  Update SYNCZTB set inout='I' where id_sync=10 and (tablica='OGOLNE' or tablica='ANALIZY_RANK' or tablica='SKRYPTY_RANK');
  Update SYNCZTB set inout='O' where id_sync=10 and tablica='OGOLNE' and (pole like 'STSK%' or pole='SKLEP');
  Update SYNCZTB set inout='B' where id_sync=10 and tablica='OGOLNE' and pole='ID_APTEKI' or tablica='SYNCCBT';
  update tablice set filtr_out='ifupddate>:czas and id_promocje<0' where (tablica containing 'koszyk' or tablica containing 'promocje');
  end
RDB$SET_CONTEXT('USER_SESSION','IFROZP',0);

end^

ALTER PROCEDURE DOPISZ_POZ_ODMOWY (
    IA INTEGER,
    IZ VARCHAR(20),
    IO INTEGER,
    PO INTEGER,
    IT INTEGER,
    KM VARCHAR(250),
    IK INTEGER )
AS
declare idz int;
begin
  if (iz<>'0') THEN
  BEGIN
    select FIRST 1 id_zam from zaminfo z where z.ID_APTEKI=:ia and z.ID_ZAMOWIENIA=:iz and z.ID_KONTRAHENCI = :IK
    ORDER by z.IFINSDATE DESC NULLS LAST
     into idz;
  END
  ELSE
  BEGIN
   SELECT FIRST 1 p.id_zam from ZAM_POZ p WHERE p.ID_TOWARY=:it and p.POZYCJA=:po and p.ID_APTEKI=:ia and p.ID_ODMOWY is NULL
     ORDER by p.ID_ZAM DESC INTO idz;
  END
  if (idz is not null) then
  BEGIN
    if (po<>0) THEN
      update ZAM_POZ p set p.ID_ODMOWY=:io,p.UWAGI=COALESCE(NULLIF(:km,''),p.UWAGI) where p.ID_APTEKI=:ia and p.ID_ZAM=:idz and p.POZYCJA=:po;
    ELSE
      update ZAM_POZ p set p.ID_ODMOWY=:io,p.UWAGI=COALESCE(NULLIF(:km,''),p.UWAGI) where p.ID_APTEKI=:ia and p.ID_ZAM=:idz and p.ID_TOWARY=:it;
  end
end
^

ALTER PROCEDURE OSOZ_BRAC_SP (
    BL VARCHAR(10),
    DT TIMESTAMP,
    SP VARCHAR(2),
    MA VARCHAR(2),
    PP VARCHAR(2) )
RETURNS (
    BS VARCHAR(1),
    BM VARCHAR(1) )


AS
BEGIN
  if (PP='A') THEN
  BEGIN
    BS='T';
    BM='T';  
  END  
  ELSE
  BEGIN
    if ((SELECT count(*) FROM OSOZ_TOWARY o where o.BLOZ7=:bl and :dt BETWEEN o.OD_DNIA and o.DO_DNIA and (o.RODZAJ=:sp or :sp='H' and o.RODZAJ='S' and :dt<'today'))>0) THEN
      BS='T';  
    ELSE
      BS='N';
      
    if ((SELECT count(*) FROM OSOZ_TOWARY o where o.BLOZ7=:bl and :dt BETWEEN o.OD_DNIA and o.DO_DNIA and (o.RODZAJ=:ma or :ma='X' and o.RODZAJ='M' and :dt<'today'))>0) THEN
      BM='T';  
    ELSE
      BM='N';    
  END    
  SUSPEND;
end
^

alter trigger KZAM_POZ_AINSERT active
before insert position 0
AS
     declare variable it integer;
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
 if (new.id_towary is null) then
  begin
    if (new.typ_kod=0) then
      it=-1;
    if (new.typ_kod=1) then
      it=cast(new.kod_tow as integer);
    if (new.typ_kod=2) then
      select max(ID_TOWARY) from tw_klas where id_apteki=new.ID_APTEKI and id_klasyfikacje=1 and wartosc=new.kod_tow into :it  ;
    if (new.typ_kod=3) then
      select max(ID_TOWARY) from tw_klas where id_apteki=new.ID_APTEKI and id_klasyfikacje=6 and wartosc=new.kod_tow into :it ;
    if (new.typ_kod=4) then
      select max(ID_TOWARY) from tw_klas where id_apteki=new.ID_APTEKI and id_klasyfikacje=3 and wartosc=new.kod_tow into :it ;      
    if (:it is null) then
      it=-1;
    if (it>0) then  new.id_towary=:it;
  end

end^

ALTER PROCEDURE KOD_Z_OFERTY (
    IAP INTEGER,
    ITW INTEGER,
    IDS INTEGER )
RETURNS (
    KOD VARCHAR(80),
    TYP INTEGER )

AS
declare variable w varchar(80);
   declare variable k varchar(80);
   declare variable ok varchar(10);
   declare variable kl integer;
   declare variable dkl integer;
   declare variable oty char(1);
   declare variable odl timestamp;
   declare variable cn integer;
   declare wewn integer;
   declare variable fmz varchar(10);
   declare variable idapt apteka;
begin

KOD='';
typ=0;
select id_klasyfikacje,zam_obsl_kody,lastof,coalesce(oferta_tylko,'T'),format_zam from dostawcy where id_kontrahenci=:ids and id_apteki=:iap into :dkl,ok,odl,oty,fmz;
if (substring(ok from 10 for 1)='1') then
  wewn = 1;
else
  wewn = 0;


/* najpierw wewnêtrzne */
if (fmz<>'XMT') then
  for select WARTOSC from tw_klas
   where id_apteki=:iap and id_towary=:itw and id_klasyfikacje=:dkl and wartosc>' '
   order by ifupddate desc
   into w do
  begin
    kod=:w;
    if (oty <> 'N') then
    begin
      if (not EXISTS (select data from oferty_ceny where id_dostawcy=:ids and kod=:w and data>=:odl)) then kod='';
    end
    if (kod>' ') then
    begin
      typ=:dkl;
      break;
    end
  end
if (wewn=0) then typ=0;

/* nawet gdy mamy juz kod wewn. ale jest on ustawiony jako  nieobslugiwany szukamy wg bloz , bazyl, ean */
if (typ=0) then
 for select t.ID_KLASYFIKACJE,o.kod from tw_klas t
   left join oferty_klas o on o.id_dostawcy=:ids and o.wartosc=t.wartosc and o.id_klasyfikacje=t.id_klasyfikacje
   left join oferty_ceny c on c.id_dostawcy=o.id_dostawcy and c.kod=o.kod and c.data>=:odl
   where t.id_apteki=:iap and t.id_towary=:itw and t.id_klasyfikacje in (1,3,6) and o.kod is not null and (:oty='N' or c.kod is not null)
   order by t.id_klasyfikacje,c.cena asc nulls last, t.ifupddate desc into kl,kod do
 begin
   if (wewn=1) then
    begin
      /*na wszelki wypadek kasujemy stare przyporzadkowania
      2014.01.29 usuniete kasowanie kodów z innych , kasowa³o na przemian */
      if (idapt<>99) then
      begin
        select count(*)  from tw_klas where id_apteki=:iap and  id_klasyfikacje=:dkl and wartosc=:kod into cn;
        if (cn=0) then
        begin
          delete from tw_klas where id_apteki=:iap and  id_klasyfikacje=:dkl and id_towary=:itw ;
          begin
           update or insert into tw_klas (id_apteki, ID_TOWARY, ID_KLASYFIKACJE, WARTOSC) values (:iap,:itw,:dkl,:kod);
           when any do break;
          end 
        end
      end
      typ=dkl;
      break;
    end
    else
      if (substring(ok from kl for 1)='1') then
      begin
        typ=kl;
        break;
      end
 end

/* teraz dopisujemy do karty kody  BLOZ  wg kodu wewn.*/
if (kod>' ') then
  for select o.WARTOSC,o.id_klasyfikacje from oferty_klas o
  left join oferty_ceny c on c.id_dostawcy=o.id_dostawcy and c.kod=o.kod and c.data>=:odl
  where o.id_dostawcy=:ids and o.kod=:kod and o.id_klasyfikacje in (3) and c.kod is not null
  into k,kl do
  begin
    if (idapt<>99) then
    BEGIN
      select count(*) from tw_klas where id_apteki=:iap and id_towary=:itw and id_klasyfikacje=:kl into cn;
      if (cn=0) then
       insert into tw_klas (id_apteki, ID_TOWARY, ID_KLASYFIKACJE, WARTOSC) values (:iap,:itw,:kl,:k);
    end   
    if (substring(ok from kl for 1)='1' and typ=0) then
    begin
       typ = kl;
    end
  end

if (typ=0) then
begin
  kod='';
  typ=null;
end

suspend;
end
^


ALTER PROCEDURE CENA_OF_CBT (
    ID integer,
    IC integer,
    MS char(1) DEFAULT 'T' )
RETURNS (
    CNH double precision,
    CNB double precision,
    DTO timestamp )
AS
declare variable iap apteka;
declare variable ia integer;
declare variable it integer;
declare variable bl7 varchar(8);
declare variable bl2 varchar(13);
declare variable kod varchar(80);
declare variable upo double precision;
declare variable up1 double precision;
declare variable upr double precision;
declare variable cnt integer;
declare variable cz timestamp;
begin
/* id,ic moze byc null, dla ms='T' dopisuje cene -1 */

 if (ic is null or ic<=0 or id is null) THEN exit;

 select first 1 cena,cn_bu,czas from cbt_of_ceny where id_cbt=:ic and id_dst=:id
 order by czas desc into cnh,cnb,dto;

 if (dto>='TODAY') then
 begin
   if (cnh<0) then
     cnh=null;
   suspend;
   exit;
 end

 cnh=null;

 select wartosc from cbt_klas where id_cbt=:ic and id_klasyfikacje=3 into bl7;
 select wartosc from cbt_klas where id_cbt=:ic and id_klasyfikacje=2 into bl2;
 if (bl7 is not null) then
   for select KOD from oferty_klas where id_dostawcy=:id and ((id_klasyfikacje=3  and wartosc=:bl7) or (id_klasyfikacje=2  and wartosc=:bl2))
   into kod do
   begin
     cnh=null;
     upo=null;
     select first 1 cena,upust,data from oferty_ceny c
     where c.kod=:kod and c.id_dostawcy=:id
     order by c.data desc into cnh,upo,dto;
     if (upo is null) then upo=0;
     if (cnh is not null) then
     begin
       select coalesce(upust,0),coalesce(upust_ref,0) from dostawcy where id_kontrahenci=:id and id_apteki=99 into up1,upr;
       select count(*) from cbt_listy where id_cbt=:ic and id_listy in (3,4,5,7,8,9,12,13,14,15,16,17,18,19,25) and cast('TODAY' as date)  between obowiazuje_od and obowiazuje_do into cnt;
       if (cnt>0 and upr is not null) then up1=upr;
       if (up1 is null) then up1=0;
       up1=up1+upo;
       cnb=cnh;
       if (up1>0) then
         cnh=cnh-(cnh*:up1/100);
       insert into cbt_of_ceny (id_cbt,id_dst,czas,cena,cn_bu) values (:ic,:id,'NOW',:cnh,:cnb);
       suspend;
       exit;
     end
   end

 /* po kodach wewnetrznych pod warunkiem ze zaznaczone w dostawcy (oraz w przypadku ph musi wystapic w co najmniej 2-ch aptekach) */
  if (cnh is null and 1=(select substring(zam_obsl_kody from 10 for 1) from dostawcy where id_kontrahenci=:id and id_apteki=:iap)) then
 for select k.kod,min(t.id_apteki),count(*) li
 from towary t left join kod_z_oferty(t.id_apteki,t.id_towary,:id) k on 0=0
 where t.id_cbt=:ic and k.kod is not null and k.kod>' '
 group by kod having count(*)>iif(:iap=99,1,0) order by li desc rows 1
 into kod,ia,it do
 begin
     cnh=null;
     upo=null;
     select first 1 cena,upust,data from oferty_ceny c
     where c.kod=:kod and c.id_dostawcy=:id
     order by c.data desc into cnh,upo,dto;
     if (upo is null) then upo=0;
     if (cnh is not null) then
     begin
       if ((select count(*) from dostawcy where id_kontrahenci=:id and id_apteki=99)>0) then
         select upust,upust_ref from dostawcy where id_kontrahenci=:id and id_apteki=99 into up1,upr;
       else
         select upust,upust_ref from dostawcy where id_kontrahenci=:id and id_apteki=:ia into up1,upr;
       select count(*) from cbt_listy where id_cbt=:ic and id_listy in (3,4,5,7,8,9,12,13,14,15,16,17,18,19,25) and cast('TODAY' as date)  between obowiazuje_od and obowiazuje_do into cnt;
       if (cnt>0 and upr is not null) then up1=upr;
       if (up1 is null) then up1=0;
       up1=up1+upo;
       cnb=cnh;
       if (up1>0) then
         cnh=cnh-(cnh*:up1/100);
       insert into cbt_of_ceny (id_cbt,id_dst,czas,cena,cn_bu) values (:ic,:id,'NOW',:cnh,:cnb);
       suspend;
       exit;
     end
 end
 if (ms='T') THEN
  begin
   cnh=-1;
   select max(czas) from CBT_OF_CENY  WHERE ID_CBT=:ic AND ID_DST =:id AND cena=-1 into cz;
   if (cz is not null) then
    UPDATE CBT_OF_CENY SET CZAS = 'now' WHERE ID_CBT=:ic AND ID_DST =:id AND czas=:cz;
   else
    insert into cbt_of_ceny (id_cbt,id_dst,czas,cena) values (:ic,:id, 'now' ,-1);
  end  
 end
^

ALTER PROCEDURE PRIOR_ZAM (
    IAP INTEGER,
    ITW INTEGER,
    IBR INTEGER )
RETURNS (
    PRIORYTET INTEGER,
    ID_DOSTAWCY INTEGER,
    CENA DOUBLE PRECISION,
    DT_PROM TIMESTAMP,
    DT_CEN TIMESTAMP,
    Z_CZEGO VARCHAR(1),
    CN_OF DOUBLE PRECISION,
    UP_OF DOUBLE PRECISION,
    DT_OF TIMESTAMP,
    CN_DS DOUBLE PRECISION,
    UP_DS DOUBLE PRECISION,
    DT_DS TIMESTAMP,
    KOD VARCHAR(80), 
    ID_P_PROM VARCHAR(10))

AS
declare variable tylkou integer;
 declare variable cn Double precision;
 declare variable minc Double precision;
 declare variable odch Double precision;
 declare variable tu Char;
 declare variable ir Char;
 declare variable rf Char;
 declare variable maxc Double precision;
 DECLARE lds VARCHAR(2048);
 begin

SELECT COALESCE(import_r,'N') FROM OGOLNE WHERE id_apteki = :iap into ir;
select dostawcy from braki where id_apteki=:iap and id_braki=:ibr into lds;
select ID_DOSTAWCY,TYLKO_U from towary where id_apteki=:IAP and id_towary=:itw into tylkou, tu;
if (tu is null or tylkou is null) then tu='X';

minc=9999999;
maxc=0;

DELETE FROM prior_zamt;

INSERT INTO prior_zamt (CENA ,DT_PROM,z_czego,dt_cen,cn_of,up_of,dt_of,cn_ds,up_ds,dt_ds ,kod,id_ds,id_p_prom)
  select CENA,DT_PROM,z_czego,dt_cen,cn_of,up_of,dt_of,cn_ds,up_ds,dt_ds ,kod, id_ktr,id_p_prom
  from br_ktr(:lds) b LEFT JOIN cena_z_oferty(:iap,:itw,b.ID_KTR,'R') on 0=0;


for SELECT cena,z_czego FROM PRIOR_ZAMT INTO cn,z_czego do
BEGIN
  if (z_czego = 'R') THEN  
  BEGIN
    if ( ir in ('R','1')) THEN
    BEGIN
      SELECT REFUNDOWANY FROM JEST_REFUNDOWANY(:iap,:itw,'today',0) INTO rf;
      if (ir = 'R' AND rf = 'N' OR ir = '1' and rf ='T') THEN
        ir = 'N';
    END     
  END
  if (z_czego <> 'R' or ir <> 'N') THEN
  BEGIN
    if (cn > maxc) THEN
      maxc = cn;
    if (cn < minc) THEN
      minc = cn;  
  END
END

for select CENA,DT_PROM,z_czego,dt_cen,cn_of,up_of,dt_of,cn_ds,up_ds,dt_ds ,kod, id_ds,id_p_prom
FROM prior_zamt INTO
  CENA,DT_PROM,z_czego,dt_cen,cn_of,up_of,dt_of,cn_ds,up_ds,dt_ds ,kod, id_dostawcy,id_p_prom do
  
BEGIN
  if (tu='W') then
  begin
    if (id_dostawcy=tylkou) then
       priorytet=2000;
    ELSE  
        priorytet=-1;
  end
  else
  begin
    if (cena=0 or cena is null) then
      cn=9999999;
    ELSE
      cn = cena;
    odch=(cn-minc)/cn;
    priorytet=1000-round(odch*1000);
    if (id_p_prom <> '-1') THEN
      priorytet=priorytet+1;
    if (id_dostawcy=tylkou) then
        priorytet=priorytet+1000;
    if (z_czego = 'R' and ir = 'N' ) THEN
      priorytet=-1;    
  end
  suspend;
END
end
^

ALTER PROCEDURE BRAK_TO_ZAM (
    IAP INTEGER,
    IBR INTEGER,
    ITW INTEGER,
    IDS INTEGER,
    CN DOUBLE PRECISION,
    REF CHAR(1),
    DEF CHAR(1),
    KOD VARCHAR(80),
    ID_P_PROM VARCHAR(10) )
RETURNS (
    DODANE DOUBLE PRECISION )

AS
    declare variable idzam integer;
     declare variable ilezam Double precision;
     declare variable ilejest Double precision;
     declare variable poz integer;
     declare variable zam Double precision;
     declare variable potw Double precision;
     declare variable stan integer;
begin
select zamowienie from brakzaw where id_apteki=:iap and id_braki=:ibr and id_towary=:itw into :ilezam;
ilejest=0;
for select zamowione,potwierdzone,stan from zam_poz z left join zaminfo i on i.id_apteki=z.id_apteki and i.id_zam=z.id_zam
  where z.id_apteki=:iap and z.id_towary=:itw and z.id_braki=:ibr into :zam,:potw,:stan do
begin
  if (:potw>0) then
    ilejest=ilejest+potw;
  else
    if (:stan<4) then
      ilejest=ilejest+zam;
end
if (:ilejest is null) then ilejest=0;
if (:ilezam is null) then ilezam=0;

if (:ilejest>=:ilezam) then
begin
  dodane=0;
  suspend;
  exit;
end
dodane=:ilezam - :ilejest;

select ID_ZAM from zaminfo where id_apteki=:iap and id_braki=:ibr and id_kontrahenci=:ids and stan<=1 into :idzam;
if (:idzam is null) then
begin
  select GEN_ID(SQ_ZAMINFO,1) from JEDEN_WIERSZ into :idzam;
  insert into zaminfo (id_apteki,id_zam,id_braki,id_kontrahenci,stan) values (:iap,:idzam,:ibr,:ids,1);
end

insert into zam_poz (id_apteki,id_braki,id_towary,id_zam,zamowione,w_cenie,ma_ref,ma_def,kod_of,id_p_prom) values (:iap,:ibr,:itw,:idzam,:dodane,:cn,:ref,:def,:kod,:ID_P_PROM);
suspend;
end
^


ALTER PROCEDURE WPLATA (
    IAP INTEGER,
    KWOTA DOUBLE PRECISION,
    TYP INTEGER,
    IDT INTEGER,
    DT TIMESTAMP )
RETURNS (
    GOTOWKA DOUBLE PRECISION )
AS
declare variable kw Double precision;
 declare variable up Double precision;
 declare variable tp Integer;
 declare variable s Double precision;
 declare variable bu Double precision;
 declare variable lp Integer;
 declare wy Double precision;
begin

if (typ = -2) THEN
BEGIN
  select COALESCE(max(LP),0)+1 from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt into :lp;
  insert into tranz_wplaty (ID_APTEKI,DATA, ID_TRANZAKCJE, KWOTA, ID_TRANZ_OPISY, LP) values
         (:iap,:dt,:idt,:kwota,:typ,:lp);

END

select WART+RABAT_KW+EPRUF,bufor,RABAT_KW+EPRUF from tranz_odplatnosc(:iap,:idt, :dt) into :kw,bu,up;
select kwota from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt and ID_TRANZ_OPISY=:typ into :s;

if (ROUND(kw,2) = ROUND(kwota,2) and typ > 7 ) THEN
BEGIN
  delete from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt;
  insert into tranz_wplaty (ID_APTEKI,DATA, ID_TRANZAKCJE, KWOTA, ID_TRANZ_OPISY, LP) values
         (:iap,:dt,:idt,:kwota,:typ,1);  
  gotowka = 0;
  suspend;
  EXIT;       
end

/* dla zaplaty karta od kwoty odejmujemu odebrany bufor jego zawsze traktujemy jak gotowke ,
  jezeli jest tylko przekazanie do bufora platne karta zostawiamy kwote bo i tak edzie skasowana
  poprawione 2011.05.10 */
  
wy = 0;  
if (typ=2) THEN
BEGIN
  select COALESCE( sum(KWOTA),0) from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt and ID_TRANZ_OPISY=-2 into wy; 
  if (kwota>kw-bu and kw>0) then kwota=kw-bu-up;
  kwota = kwota - wy;
END 

if (s is not null) then
begin
  delete from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt and ID_TRANZ_OPISY=:typ;
  update tranz_wplaty set kwota=kwota+:s where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt and ID_TRANZ_OPISY=1;
end

select sum(KWOTA) from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt and ID_TRANZ_OPISY=1 into :s;

if ((s is null) or (s>0) or typ in (2,4,5,6)) then
begin
  if (s>0) then
    if (kwota>s) then
      kwota=s;
  if (s<0) then
    if (kwota<s) then
      kwota=s;

  if (s=0 and (typ=4 or typ=5  or typ=6)) then
    kwota=0;

  select max(LP) from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt into :lp;
  if (lp is null) then
    lp=1;
  else
    lp=lp+1;

  if (:kwota<>0 or (kw=0 and typ=2)) then
    insert into tranz_wplaty (ID_APTEKI,DATA, ID_TRANZAKCJE, KWOTA, ID_TRANZ_OPISY, LP) values
         (:iap,:dt,:idt,:kwota,:typ,:lp);

  /*nie gotowka*/
  if (typ<>1) then
  begin
    select sum(KWOTA) from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt and ID_TRANZ_OPISY<>1 into :s;
    update tranz_wplaty set KWOTA=:kw-:s where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt and ID_TRANZ_OPISY=1;
  end
end

select sum(KWOTA) from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt and ID_TRANZ_OPISY=1 into :gotowka;

suspend;
end
^

ALTER PROCEDURE NALICZ_UPUST(IAP INTEGER,
IDT INTEGER,
DT DATE,
UPUST_PROC DOUBLE PRECISION)
 RETURNS(UPUST DOUBLE PRECISION)
 AS
declare variable up Double precision;
     declare variable odpl Double precision;
     declare variable got Double precision;
     declare variable wpl Integer;
begin
upust=0;

up=:upust_proc;

if ((up<>0) and (not up is null)) then
begin
  select count(*) from tranz_wplaty where id_apteki=:iap and ID_TRANZAKCJE=:idt and DATA=:dt and ID_TRANZ_OPISY<>1 into :wpl;
  if (wpl=0) then
  begin
    select WART from tranz_odplatnosc(:iap,:idt,:dt) into :odpl;
    upust = odpl - odpl*(100-up)/100;
    upust=upust*100;
    upust=cast(upust as integer);
    upust=upust*0.01;

    if (upust>0) then
      execute procedure wplata(:iap,:upust,4,:idt,:dt) returning_values (:got);
  end
end
suspend;

end
^

alter trigger UPD_TOWARY_ZM active
after update position 0
as
begin
  if (old.NAZWA<>new.NAZWA) then INSERT INTO TOWARY_ZMIANY (ID_APTEKI, ID_TOWARY, NAZWA,IFUPDDATE) VALUES (old.ID_APTEKI, old.ID_TOWARY, old.NAZWA,cast('now' as date)+0.0000001);
  if (coalesce(old.ID_CBT,-1)<>coalesce(new.ID_CBT,-1)) then INSERT INTO TOWARY_ZMIANY (ID_APTEKI, ID_TOWARY, ID_CBT,IFUPDDATE) VALUES (old.ID_APTEKI, old.ID_TOWARY, coalesce(old.ID_CBT,-1),cast('now' as date)+0.0000002);
  if (coalesce(old.EAN_REF,-1)<>coalesce(new.EAN_REF,-1)) then INSERT INTO TOWARY_ZMIANY (ID_APTEKI, ID_TOWARY, EAN_REF,IFUPDDATE) VALUES (old.ID_APTEKI, old.ID_TOWARY, coalesce(old.EAN_REF,-1),cast('now' as date)+0.0000003);
  if (old.SP_ZAMAWIANIA<>new.SP_ZAMAWIANIA) then INSERT INTO TOWARY_ZMIANY (ID_APTEKI, ID_TOWARY, SP_ZAMAWIANIA,IFUPDDATE) VALUES (old.ID_APTEKI, old.ID_TOWARY, old.SP_ZAMAWIANIA,cast('now' as date)+0.0000004);
  if (old.DNI_MIN<>new.DNI_MIN or old.DNI_MAX<>new.DNI_MAX) then INSERT INTO TOWARY_ZMIANY (ID_APTEKI,ID_TOWARY,DNI_MIN,DNI_MAX,IFUPDDATE) VALUES (old.ID_APTEKI,old.ID_TOWARY,old.DNI_MIN,old.DNI_MAX,cast('now' as date)+0.0000005); 
 
  if (new.EAN_REF is DISTINCT from old.EAN_REF and new.EAN_REF is not NULL AND (new.SMOPL_RAP='T' or new.SER_PODL='T')) THEN
    UPDATE TW_KLAS k set k.WARTOSC = new.EAN_REF WHERE k.ID_TOWARY=new.ID_TOWARY and k.ID_APTEKI=new.ID_APTEKI AND k.ID_KLASYFIKACJE=6;  
 end^

ALTER PROCEDURE STATUS_ZLECENIA (
    ZL VARCHAR(50),
    MC INTEGER,
    MP INTEGER DEFAULT 100 )
RETURNS (
    STATUS INTEGER )
AS
DECLARE wn char(1);
BEGIN
  SELECT FIRST 1 e.OPERACJA,e.WYNIK from EZLECENIA e where e.NR = :zl and e.MCOD=:mc and e.WYNIK in ('P','N') and abs(e.OPERACJA)<:mp
   ORDER by abs(e.OPERACJA) DESC,e.LP DESC into status,wn;
   
  status = coalesce(status,-1) ; 
  if (status >= -1) THEN
  begin
    if (status in (1,2)) then status = 0;
    if (status = 3) then status = 1;
    if (status in (4,5)) then status = 2;
    if (status = 6) then 
    BEGIN
      if (wn = 'P') THEN
        status = 3;
      ELSE
        status = 1;  
    END
    if (status in (7,8)) then status = 4;
     if (status = 9) then 
    BEGIN
      if (wn = 'P') THEN
        status = 5;
      ELSE
        status = 3;  
    END  
    if (status = 10) then status = 6;
    status = status + 1;
  END
  ELSE 
  BEGIN
    if (status = -6) THEN status = 4;
    if (status = -10) THEN status = 7;
    SELECT status FROM STATUS_ZLECENIA(:zl,:mc,:status) into status;
  END  
  SUSPEND;
END^

create or alter trigger TOWARY_WNIOSKI_PASUJ for TOWARY_WNIOSKI active
AFTER update or insert POSITION 1
AS
declare nazwa varchar(2000);
begin
  if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  
  SELECT NAZWA||PRODUCENT||MODEL from PROD_HANDL where ID_APTEKI=new.ID_APTEKI and ID_UMOWY=new.ID_UMOWY and ID_PROD=new.ID_PROD into nazwa;
  
  begin 
  RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
  INSERT INTO TOWARY_WNIOSKI (ID_APTEKI, ID_TOWARY, ID_UMOWY, ID_PROD) 
   select new.ID_APTEKI, new.ID_TOWARY, new.ID_UMOWY, ID_PROD from PROD_HANDL a where ID_APTEKI=new.ID_APTEKI and ID_UMOWY=new.ID_UMOWY and NAZWA||PRODUCENT||MODEL=:nazwa
   and not EXISTS(select*from TOWARY_WNIOSKI where a.ID_APTEKI=ID_APTEKI and a.ID_UMOWY=ID_UMOWY and a.ID_PROD=ID_PROD and new.ID_TOWARY=ID_TOWARY)
   and not exists (select 1 from PROD_HANDL h 
join WNIOSKI_UMOWY u on h.ID_UMOWY = u.KOD
join PAKIET_ZAOP a on a.ID_PROD = h.ID_PROD and a.ID_UMOWY = h.ID_UMOWY
join PLANY_MIES m on a.ID_PAKIET=m.ID_PAKIET and a.ID_UMOWY = m.ID_UMOWY and m.ID_KOM = u.id_kom  and m.MIESIAC = EXTRACT(MONTH from cast('today' as date))
where ID_APTEKI=new.ID_APTEKI and ID_UMOWY=new.ID_UMOWY and cast('today' as date) BETWEEN u.OD_DNIA and u.DO_DNIA and NAZWA||PRODUCENT||MODEL=:nazwa
group by kod_sr||NAZWA||PRODUCENT||MODEL 
having count (*)>1) ;
  RDB$SET_CONTEXT('USER_SESSION','IFROZP',0);
  end
  
end
^

create or alter trigger PROD_HANDL_PASUJ for PROD_HANDL active
after insert position 1
AS
declare nazwa varchar(2000);
declare it integer;
declare IUM VARCHAR(100);
begin
  if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  
  select ID_UMOWY from TOWARY_WNIOSKI where ID_UMOWY=new.ID_UMOWY and ifinsdate<cast('today' as date) rows 1 into ium;
  if (ium is null) then 
  select kod from wnioski_umowy a where exists (select*from wnioski_umowy b where kod=new.ID_UMOWY and a.nip=b.nip) and a.kod<>new.ID_UMOWY order by do_dnia desc rows 1 into ium;
  
  SELECT NAZWA||PRODUCENT||MODEL from PROD_HANDL where ID_APTEKI=new.ID_APTEKI and ID_UMOWY=new.ID_UMOWY and ID_PROD=new.ID_PROD into nazwa;
  
  select id_towary from TOWARY_WNIOSKI t 
   join PROD_HANDL h on t.ID_APTEKI=h.ID_APTEKI and t.ID_UMOWY=h.ID_UMOWY and t.id_prod=h.id_prod
  where ID_UMOWY=:ium and NAZWA||PRODUCENT||MODEL=:nazwa rows 1 into it;   
  
  if (it>0) then  
  begin 
  RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
  INSERT INTO TOWARY_WNIOSKI (ID_APTEKI, ID_TOWARY, ID_UMOWY, ID_PROD) 
   select new.ID_APTEKI, :it , new.ID_UMOWY, ID_PROD from PROD_HANDL a where ID_APTEKI=new.ID_APTEKI and ID_UMOWY=new.ID_UMOWY and NAZWA||PRODUCENT||MODEL=:nazwa
   and not EXISTS(select*from TOWARY_WNIOSKI where a.ID_APTEKI=ID_APTEKI and a.ID_UMOWY=ID_UMOWY and a.ID_PROD=ID_PROD and ID_TOWARY=:it)
   and not exists (select 1 from PROD_HANDL h 
join WNIOSKI_UMOWY u on h.ID_UMOWY = u.KOD
join PAKIET_ZAOP a on a.ID_PROD = h.ID_PROD and a.ID_UMOWY = h.ID_UMOWY
join PLANY_MIES m on a.ID_PAKIET=m.ID_PAKIET and a.ID_UMOWY = m.ID_UMOWY and m.ID_KOM = u.id_kom  and m.MIESIAC = EXTRACT(MONTH from cast('today' as date))
where ID_APTEKI=new.ID_APTEKI and ID_UMOWY=new.ID_UMOWY and cast('today' as date) BETWEEN u.OD_DNIA and u.DO_DNIA and NAZWA||PRODUCENT||MODEL=:nazwa
group by kod_sr||NAZWA||PRODUCENT||MODEL 
having count (*)>1) ;
   RDB$SET_CONTEXT('USER_SESSION','IFROZP',0);
   end   
   
end^

create or alter TRIGGER DEL_TOWARY_WNIOSKI for TOWARY_WNIOSKI ACTIVE
AFTER DELETE POSITION 0
as
declare nazwa varchar(2000);
declare it integer;
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
    
  SELECT NAZWA||PRODUCENT||MODEL from PROD_HANDL where ID_APTEKI=old.ID_APTEKI and ID_UMOWY=old.ID_UMOWY and ID_PROD=old.ID_PROD into nazwa;
  
  for select id_prod from TOWARY_WNIOSKI t join PROD_HANDL h on t.ID_APTEKI=h.ID_APTEKI and t.ID_UMOWY=h.ID_UMOWY and t.id_prod=h.id_prod
  where t.ID_APTEKI=old.ID_APTEKI and t.id_towary=old.id_towary and t.ID_UMOWY=old.ID_UMOWY and NAZWA||PRODUCENT||MODEL=:nazwa into it do
   begin 
   delete from TOWARY_WNIOSKI where ID_APTEKI=old.ID_APTEKI and id_towary=old.id_towary and ID_UMOWY=old.ID_UMOWY and id_prod=:it;
   end
    
end^

create or alter trigger DEL_PLANY_MIES for PLANY_MIES active
after delete position 1
AS
BEGIN
 /* chyba mialo czyscic smietnik, ale ma 'rozwalac import umowy'
 delete from PAKIET_ZAOP where ID_UMOWY=old.ID_UMOWY and ID_PAKIET=old.ID_PAKIET;
 */
END^

alter trigger INS_RECEPTA active
before update or insert position 1
AS
BEGIN
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

 if (char_length(trim(new.atrybuty)) <8) 
 then 
 begin 
  if (exists(select*from wart_atr_rec where id_atr_rec=3 and wart_atr_rec=0||substring(new.ATRYBUTY from 6 for 1)))  
  THEN
  new.atrybuty=substring(new.ATRYBUTY from 1 for 5)||0||substring(new.ATRYBUTY from 6 for 5);
  ELSE
  EXCEPTION blad 'Popraw atrybuty recepty';  
 end 

 if (old.atrybuty like 'GW%00%') then new.atrybuty=replace(old.atrybuty,'00',(select nfz from ogolne where id_apteki=old.id_apteki));
 
END^


ALTER PROCEDURE ZWROT_POZYCJI (
    IAP INTEGER,
    OLD_SPRZ INTEGER,
    DATA TIMESTAMP,
    NEW_TRANZ INTEGER,
    ZWRACANA CHAR(1),
    NEW_REC INTEGER,
    TYP CHAR(1) )
RETURNS (
    ID_SP_MINUS INTEGER,
    ID_SP_PLUS INTEGER )


AS
declare variable tryb char(1);
     declare variable idSp_m Integer;
     declare variable idSp_p Integer;
     declare variable id Integer;
     declare variable wa double precision;
begin
/* typ przekazuje TRYB wpisywany do plusowanej pozycji z recepty noze byc 'R' gdy zwrot recepty
  'P' gdy zwrot w paragonie */
idsp_p=null;
idsp_m=gen_id(SQ_SPRZEDAZ,1);


insert into sprzedaz (ID_APTEKI,ID_SPRZEDAZ,ID_TRANZAKCJE, ID_TOWARY, DATA, SZTUK, JEDNOSTKA, ID_RECEPTA,
                        WARTOSC, CENA, ID_ODPLATNOSC, ODPLATNOSC, REFUNDATOR2, TAKSA, DOPLATA, TRYB, STAWKA_VAT, UPUST, WART_ZAK, CENA_ZAK, CENA_ZAK_BR, TYP_UPUSTU, KWOTA_UPUSTU,RABAT_W_GOTOWCE,id_promocje,
                        nr_koszyka,nie_zamieniac,epruf_id,epruf_df,NA100,id_zamiennik,poz_rec,opis, id_osoz,czesciowa)
              select  :iap,:idsp_m,:new_tranz, ID_TOWARY, :data, -SZTUK, JEDNOSTKA, ID_RECEPTA,
                        -WARTOSC, CENA, ID_ODPLATNOSC, -ODPLATNOSC, -REFUNDATOR2, -TAKSA, -DOPLATA, 'Z',STAWKA_VAT, UPUST, -WART_ZAK, CENA_ZAK, CENA_ZAK_BR, TYP_UPUSTU, -KWOTA_UPUSTU, -RABAT_W_GOTOWCE,id_promocje,nr_koszyka,
                        nie_zamieniac,epruf_id,-epruf_df,NA100,id_zamiennik,poz_rec,opis,s.ID_OSOZ,s.CZESCIOWA
              from sprzedaz s
              where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ;

insert into RZDST (ID_APTEKI,ID_SPRZEDAZ, ID_ZDST, POZYCJA, SZTUK_JP, ID_TOWARY, DATA, CENA, SZTUK_RP, ID_OSOZ)
             select :iap,:idsp_m, ID_ZDST, POZYCJA, -SZTUK_JP, ID_TOWARY, :data, CENA, -SZTUK_RP,ID_OSOZ
             from RZDST r where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ;

/*aktualizacja tryb w zwracanej pozycji*/
select TRYB from sprzedaz where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ into :tryb;
if ((:tryb='S') or (:tryb='P') or (:tryb='N') or (:tryb='R')) then
  update sprzedaz set TRYB='K' where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ;

select count(ID_SPRZEDAZ) from zmiany where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ into :id;
if (:id>0) then
  update zmiany set NASTEPNY=:idsp_m where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ;
else
  insert into zmiany (ID_APTEKI,ID_SPRZEDAZ, NASTEPNY) values (:iap,:OLD_SPRZ,:idsp_m);

if (:ZWRACANA='N') then
begin
  select id_promocje,wartosc  from sprzedaz s where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ  into idsp_p,wa;

  if (idsp_p is null or wa<>0) then
  begin
    idsp_p=gen_id(SQ_SPRZEDAZ,1);

    if (:NEW_REC = 0) then
    begin
      insert into sprzedaz (ID_APTEKI,ID_SPRZEDAZ,ID_TRANZAKCJE, ID_TOWARY, DATA, SZTUK, JEDNOSTKA, ID_RECEPTA,
                          WARTOSC, CENA, ID_ODPLATNOSC, ODPLATNOSC, REFUNDATOR2, TAKSA, DOPLATA, TRYB, STAWKA_VAT, UPUST, WART_ZAK, CENA_ZAK, CENA_ZAK_BR, TYP_UPUSTU, KWOTA_UPUSTU, RABAT_W_GOTOWCE,id_promocje,nr_koszyka,nie_zamieniac,
                          epruf_id,epruf_df,NA100,id_zamiennik,poz_rec,opis,czesciowa)
                select  :iap,:idsp_p,:new_tranz, ID_TOWARY, :data, SZTUK, JEDNOSTKA, ID_RECEPTA,
                          WARTOSC, CENA, ID_ODPLATNOSC, ODPLATNOSC, REFUNDATOR2, TAKSA, DOPLATA, 'P', STAWKA_VAT, UPUST, WART_ZAK, CENA_ZAK, CENA_ZAK_BR, TYP_UPUSTU, KWOTA_UPUSTU, RABAT_W_GOTOWCE,id_promocje,nr_koszyka,nie_zamieniac,
                          epruf_id,epruf_df,NA100,id_zamiennik,poz_rec,opis,czesciowa
                from sprzedaz s
                where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ;
    end
    else
    begin
      insert into sprzedaz (ID_APTEKI,ID_SPRZEDAZ,ID_TRANZAKCJE, ID_TOWARY, DATA, SZTUK, JEDNOSTKA, ID_RECEPTA,
                          WARTOSC, CENA, ID_ODPLATNOSC, ODPLATNOSC, REFUNDATOR2, TAKSA, DOPLATA, TRYB, STAWKA_VAT, UPUST, WART_ZAK, CENA_ZAK, CENA_ZAK_BR, TYP_UPUSTU, KWOTA_UPUSTU, RABAT_W_GOTOWCE,id_promocje,nr_koszyka,nie_zamieniac,
                          epruf_id,epruf_df,NA100,id_zamiennik,poz_rec,opis,czesciowa)
                select  :iap,:idsp_p,:new_tranz, ID_TOWARY, :data, SZTUK, JEDNOSTKA, :NEW_REC,
                          WARTOSC, CENA, ID_ODPLATNOSC, ODPLATNOSC, REFUNDATOR2, TAKSA, DOPLATA, :TYP , STAWKA_VAT, UPUST, WART_ZAK, CENA_ZAK, CENA_ZAK_BR, TYP_UPUSTU, KWOTA_UPUSTU, RABAT_W_GOTOWCE,id_promocje,nr_koszyka,nie_zamieniac,
                          epruf_id,epruf_df,NA100,id_zamiennik,poz_rec,opis,czesciowa
                from sprzedaz s
                where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ;
    end

    insert into RZDST (ID_APTEKI,ID_SPRZEDAZ, ID_ZDST, POZYCJA, SZTUK_JP, ID_TOWARY, DATA, CENA, SZTUK_RP)
               select :iap,:idsp_p, ID_ZDST, POZYCJA, SZTUK_JP, ID_TOWARY, :data, CENA, SZTUK_RP
               from RZDST r where ID_APTEKI=:iap and ID_SPRZEDAZ=:OLD_SPRZ;

    update receptura set id_sprzedaz=:idsp_p where id_apteki=:iap and id_sprzedaz=:old_sprz;


    insert into zmiany (ID_APTEKI,ID_SPRZEDAZ, POPRZEDNI, NASTEPNY) values (:iap,:idsp_m,:OLD_SPRZ,:idsp_p);
    insert into zmiany (ID_APTEKI,ID_SPRZEDAZ, POPRZEDNI) values (:iap,:idsp_p,:idsp_m);
    UPDATE OPAKOWANIA o set o.ID_SPRZEDAZ = :idsp_p where o.ID_SPRZEDAZ = :old_sprz and o.ID_APTEKI = :iap;
  end
  else
    idsp_p=null;
end
else
BEGIN
  insert into zmiany (ID_APTEKI,ID_SPRZEDAZ, POPRZEDNI) values (:iap,:idsp_m,:OLD_SPRZ);
  UPDATE OPAKOWANIA o set o.ID_SPRZEDAZ = :idsp_m, o.STATUS = 'Z' where o.ID_SPRZEDAZ = :old_sprz and o.ID_APTEKI = :iap;
END
ID_SP_MINUS=:idSp_m;
ID_SP_PLUS=:IdSp_p;
end
^

alter TRIGGER DEL_CBT
ACTIVE AFTER DELETE POSITION 0 
AS
declare ap apteka;
begin
if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
if (rdb$get_context('USER_SESSION','BAZYL')=1) then exit;

if (old.id_cbt<1000000 and ap<>1) then
  exception blad ' Kasowanie karty CBT < 1000000 zablokowane';
  
if (old.id_cbt<1000000 and ap=1 and coalesce(old.centralna,'N')<>'N') then
  exception blad ' Kasowanie karty CBT innej ni¿ centralna=N zablokowane';  

end ^

alter trigger INS_UPD_DOSTAWY active
before insert or update position 1
AS
declare variable nr VARCHAR(20);
declare variable st CHAR(1);
declare variable ap apteka;
begin
   if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
     
   if (new.nr_faktury<>(select cyfry from tylko_znaki(new.nr_faktury))) THEN new.nr_faktury=(select cyfry from tylko_znaki(new.nr_faktury));  
   if (extract(hour from new.data)+extract(second from new.data)<>0) then new.data=cast(left(new.data,11) as date);
   if (exists(select*from kontrahenci where id_kontrahenci=new.id_kontrahenci and smopl_typ='FZH')) then new.KOD_HURTOWNI=null;
   
   if (new.korekta_do is not null) THEN
    begin
     select left(nr_faktury,20),status from dostawy where id_apteki=new.id_apteki and id_dostawy=new.korekta_do into nr,st;
     if (st is distinct from 'Z') then
      EXCEPTION blad ' Nie mo¿na wczytaæ korekty do niezaksiêgowanej dostawy
 Najpierw zaksieguj dostawê '||nr;    
    end
    
   if (new.id_apteki in (10021,10023,10025,10026,10028,10056,10061,10121,10122,10125,10126,10127,10129,10130,10423,10425,10426,10430) --nm_apteki like 'Galen -%'
        and new.id_kontrahenci>0 and new.status='Z' and new.dt_platn is null and new.data>cast('today' as date)-60) then
     EXCEPTION blad ' Uzupe³nij datê p³atnoœci';
    
end^

ALTER TRIGGER RZDST_VAT ACTIVE
BEFORE INSERT OR UPDATE POSITION 0
AS
DECLARE ks CHAR(1);
DECLARE k1 CHAR(1);
BEGIN
 if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  if ((select s.ID_TOWARY from SPRZEDAZ s where s.ID_APTEKI=new.ID_APTEKI and s.ID_SPRZEDAZ=new.ID_SPRZEDAZ)=0) then exit;
  SELECT v.KOD_STAWKI FROM STAWKA_VAT(new.id_apteki,new.id_towary,new.data) v   into ks;
  for SELECT v.KOD_STAWKI FROM RZDST r LEFT JOIN STAWKA_VAT(r.id_apteki,r.id_towary,r.data) v on 0=0
  WHERE r.ID_APTEKI=new.ID_APTEKI and r.ID_SPRZEDAZ = new.ID_SPRZEDAZ   into k1 do
    if (ks<>k1) THEN
      EXCEPTION BLAD 'Ró¿ne stawki VAT';
  if (new.ID_TOWARY > 0 and EXISTS ( SELECT r.POZYCJA FROM RZDST r WHERE  r.ID_SPRZEDAZ=new.ID_SPRZEDAZ
    and r.ID_APTEKI=new.ID_APTEKI and r.POZYCJA=new.POZYCJA)) THEN
    BEGIN
      new.POZYCJA = COALESCE((SELECT max(r.POZYCJA) FROM RZDST r WHERE  r.ID_SPRZEDAZ=new.ID_SPRZEDAZ
        and r.ID_APTEKI=new.ID_APTEKI)+1,1);
    END
END
^

create or ALTER PROCEDURE NAPRAW_POZ_RZDST
AS
DECLARE id int;
DECLARE ia int;
DECLARE po int;
DECLARE VARIABLE v_KEY CHAR(8) CHARACTER SET OCTETS;
BEGIN
  RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
  for SELECT r.ID_SPRZEDAZ,r.ID_APTEKI FROM RZDST r where r.ID_TOWARY > 0 and r.DATA >= '01.01.2022'
   GROUP by r.ID_SPRZEDAZ,r.ID_APTEKI,r.POZYCJA
   HAVING COUNT(*) > 1 into id,ia do
   BEGIN
     po = 1000;
     for SELECT RDB$DB_KEY FROM RZDST r WHERE r.ID_SPRZEDAZ = :id and r.ID_APTEKI = :ia ORDER by RDB$DB_KEY INTO v_KEY do
     BEGIN
       UPDATE rzdst r set pozycja = :po WHERE r.ID_SPRZEDAZ = :id and r.ID_APTEKI = :ia and r.rdb$db_key = :v_key;
       po = po + 1;
     END
     po = 1;
     for SELECT RDB$DB_KEY FROM RZDST r WHERE r.ID_SPRZEDAZ = :id and r.ID_APTEKI = :ia ORDER by RDB$DB_KEY INTO v_KEY do
     BEGIN
       UPDATE rzdst r set pozycja = :po WHERE r.ID_SPRZEDAZ = :id and r.ID_APTEKI = :ia and r.rdb$db_key = :v_key;
       po = po + 1;
     END
   END
   RDB$SET_CONTEXT('USER_SESSION','IFROZP',0);
end
^


ALTER PROCEDURE DOSTAWA_CZYTNIKIEM (
    IA INTEGER,
    ID INTEGER,
    KOD VARCHAR(20),
    SERIA VARCHAR(20),
    IDENT VARCHAR(20),
    DWS VARCHAR(6),
    DATAW TIMESTAMP )
RETURNS (
    IZ DOUBLE PRECISION,
    SZT DOUBLE PRECISION,
    NRD VARCHAR(50),
    BS INTEGER )
AS
DECLARE it INTEGER;
DECLARE tt INTEGER;
Declare zz DOUBLE PRECISION;
declare dw TIMESTAMP;
DECLARE sn VARCHAR(20);
DECLARE dd INTEGER;
BEGIN
 SELECT FIRST 1 k.ID_TOWARY FROM TOWARY k
   WHERE k.ID_APTEKI=:ia and k.EAN_REF = :kod and  EXISTS (SELECT z.ID_ZDST FROM ZDST z WHERE z.ID_APTEKI=:ia and z.ID_DOSTAWY = :id and z.ID_TOWARY = k.ID_TOWARY) 
 INTO it;

 if (it is null) THEN
   SELECT first 1 k.ID_TOWARY FROM TW_KLAS k
   WHERE k.ID_APTEKI=:ia and k.ID_KLASYFIKACJE=6 and k.WARTOSC = :kod 
   and  EXISTS (SELECT z.ID_ZDST FROM ZDST z WHERE z.ID_APTEKI=:ia and z.ID_DOSTAWY = :id and z.ID_TOWARY = k.ID_TOWARY) 
 INTO it;  

 if (it is null) THEN
   SELECT FIRST 1 t.ID_TOWARY FROM CBT_KLAS k JOIN TOWARY t on k.ID_CBT=t.ID_CBT and t.ID_APTEKI = :ia
   WHERE k.ID_KLASYFIKACJE=6 and k.WARTOSC = :kod 
   and  EXISTS (SELECT z.ID_ZDST FROM ZDST z WHERE z.ID_APTEKI=:ia and z.ID_DOSTAWY = :id and z.ID_TOWARY = t.ID_TOWARY) 
 INTO it;
   
 if (it is null) THEN
   SELECT FIRST 1 z.ID_TOWARY FROM ZDST z JOIN ZDST_KLAS k on z.ID_APTEKI = k.ID_APTEKI and z.ID_ZDST = k.ID_ZDST AND k.ID_KLASYFIKACJE=6 and k.WARTOSC = :kod
   WHERE z.ID_APTEKI=:ia and z.ID_DOSTAWY = :id INTO it;  

 if (it is not null) THEN
 BEGIN
   bs = 0;
   for SELECT z.ID_ZDST, z.SZTUK_JP - COALESCE(z.ILE_CZYTNIK ,0),z.DATA_WAZN,k.WARTOSC
   FROM ZDST z left join ZDST_KLAS k on k.ID_ZDST=z.ID_ZDST and k.ID_APTEKI = z.ID_APTEKI and k.ID_KLASYFIKACJE = 5
   WHERE z.ID_APTEKI = :ia and z.ID_DOSTAWY = :id AND z.ID_TOWARY = :it  order by 2 desc
   INTO zz,szt,dw,sn do
   if (iz is null or szt > 0 and (ident < ' ' or dw = dataw and seria = sn)) THEN
   BEGIN
     iz = zz;
     if (dw = dataw and seria = sn) THEN
       bs = 1;
   end
   
   IF (iz is not null and IDENT is not null and IDENT > ' ')  THEN
   BEGIN
     SELECT d.NR_FAKTURY,d.ID_DOSTAWY FROM opakowania o LEFT JOIN ZDST z on z.ID_ZDST=o.ID_ZDST and z.ID_APTEKI = o.ID_APTEKI
     LEFT JOIN dostawy d on d.ID_DOSTAWY=z.ID_DOSTAWY and d.ID_APTEKI = z.ID_APTEKI
     where o.KOD = :kod and o.SERIA=:seria and o.IDENT=:ident
     INTO nrd,dd;
     
     if (nrd is null) then
       UPDATE OR INSERT INTO OPAKOWANIA (KOD,SERIA,IDENT,DATAW,ID_APTEKI,ID_ZDST,STATUS,DWS)
       VALUES (:KOD,:SERIA,:IDENT,:DATAW,:IA,:IZ,'D',:DWS);
     
   END
 END
 SUSPEND;
END
^



ALTER TRIGGER RZDST_VAT ACTIVE
BEFORE INSERT OR UPDATE POSITION 0
AS
DECLARE ks CHAR(1);
DECLARE k1 CHAR(1);
BEGIN
 if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;
  if ((select s.ID_TOWARY from SPRZEDAZ s where s.ID_APTEKI=new.ID_APTEKI and s.ID_SPRZEDAZ=new.ID_SPRZEDAZ)=0) then exit;
  SELECT v.KOD_STAWKI FROM STAWKA_VAT(new.id_apteki,new.id_towary,new.data) v   into ks;
  for SELECT v.KOD_STAWKI FROM RZDST r LEFT JOIN STAWKA_VAT(r.id_apteki,r.id_towary,r.data) v on 0=0
  WHERE r.ID_APTEKI=new.ID_APTEKI and r.ID_SPRZEDAZ = new.ID_SPRZEDAZ   into k1 do
    if (ks<>k1) THEN
      EXCEPTION BLAD 'Ró¿ne stawki VAT';
  if (new.ID_TOWARY > 0 and EXISTS ( SELECT r.POZYCJA FROM RZDST r WHERE  r.ID_SPRZEDAZ=new.ID_SPRZEDAZ
    and r.ID_APTEKI=new.ID_APTEKI and r.POZYCJA=new.POZYCJA)) THEN
    BEGIN
      new.POZYCJA = COALESCE((SELECT max(r.POZYCJA) FROM RZDST r WHERE  r.ID_SPRZEDAZ=new.ID_SPRZEDAZ
        and r.ID_APTEKI=new.ID_APTEKI and r.POZYCJA=new.POZYCJA),1);
    END
END
^

ALTER TRIGGER DEL_BRAKI ACTIVE
BEFORE delete POSITION 0
AS
     declare variable dt Date;
     declare variable it integer;
     declare variable ile Double precision;
begin
  if (rdb$get_context('USER_SESSION','IFROZP')=1) then exit;

  if (old.TYP = 'A' and old.ID_ZBIORCZE >0) then
    exception Blad 'Zamówienie pochodzi z systemu zewnêtrznego, kasowanie zablokowane. 
Oznacz zamówienie jako anulowane';
if (old.data>'12.07.2015') then
  select count(*) from zaminfo where id_apteki=old.id_apteki and id_braki=old.id_braki and stan>1 into it;
else
  it = 0;
if (it>0) then
  exception kasbraki;
select data from braki where id_apteki=old.id_apteki and id_braki=old.id_braki into :dt;
if (cast('today' as date)-dt<1) then
begin
  update kzam set id_braki=null where id_braki=old.id_braki;
  for select id_towary from brakdef where id_apteki=old.id_apteki and id_braki=old.id_braki into :it do
  begin
    select zamowienie from brakdef where id_apteki=old.id_apteki and id_braki=0 and id_towary=:it into :ile;
    if (ile is not null) then
    begin
      delete from brakdef where id_apteki=old.id_apteki and id_braki=0 and id_towary=:it;
      update brakdef set zamowienie=zamowienie+:ile, id_braki=0 where id_apteki=old.id_apteki and id_braki=old.id_braki and id_towary=:it;
    end
    else
    begin
      update brakdef set id_braki=0 where id_apteki=old.id_apteki and id_braki=old.id_braki and id_towary=:it;
    end
  end
end
end
^

ALTER PROCEDURE UP_Z_BLOZ (
    IAP INTEGER,
    IDT INTEGER,
    IDB INTEGER,
    STA VARCHAR(500) )
AS
DECLARE nm VARCHAR(100);
DECLARE ps VARCHAR(100);
DECLARE dw VARCHAR(100);
DECLARE op VARCHAR(100);
DECLARE pr INTEGER;
DECLARE dd DOUBLE PRECISION;
DECLARE ea VARCHAR(15);
DECLARE sm VARCHAR(1);
DECLARE te VARCHAR(1);
DECLARE dwl DOUBLE PRECISION;
DECLARE dwj VARCHAR(20);
DECLARE opl DOUBLE PRECISION;
DECLARE opj VARCHAR(20);
DECLARE dwd INTEGER;
DECLARE opd INTEGER;
DECLARE vt INTEGER;
DECLARE dt DATE;
DECLARE nw TIMESTAMP;
DECLARE dj DATE;
DECLARE cd DOUBLE PRECISION;
DECLARE ch DOUBLE PRECISION;
DECLARE zb DOUBLE PRECISION;
DECLARE zr DOUBLE PRECISION;
DECLARE z3 DOUBLE PRECISION;
DECLARE z5 DOUBLE PRECISION;
DECLARE lm DOUBLE PRECISION;
DECLARE dk DATE;
DECLARE n1 VARCHAR(1);
DECLARE n2 VARCHAR(1);
DECLARE n3 VARCHAR(1);
DECLARE ex INTEGER;
begin
   if (idb<0) THEN
   BEGIN
     ex = 1;
     idb = -idb;
   END
   ELSE
   BEGIN
     ex = 0;
   END
  
   SELECT FIRST 1 upper(left(b.NAZWA_PELNA,100)),upper(b.POSTAC),upper(b.DAWKA),upper(b.OPAKOWANIE),p.ID_PRODUCENCI,b.KOD_PASKOWY,b.ZSMOPL,b.dawka_l_p,UPPER(b.dawka_j_p),b.OPAKOWANIE_L_P,upper(b.OPAKOWANIE_J_P) ,
    b.VAT,b.CU_OD,b.CENA_DETALICZNA,b.CENA_HURTOWA,b.ZAPLATA_B,b.ZAPLATA_R,b.ZAPLATA_3,b.ZAPLATA_5,b.LIMIT_CENOWY,b.CU_DO,b.NARKOTYK,b.PSYCHOTROP,b.PREKURSOR
    FROM BLPR b
    LEFT JOIN PRODUCENCI p on b.PODMIOT_ODP = p.NAZWA
    WHERE b.BLOZ7 = :idb INTO  nm,ps,dw,op,pr,ea,sm,dwl,dwj,opl,opj,vt,dt,cd,ch,zb,zr,z3,z5,lm,dk,n1,n2,n3;

   if (CHARACTER_LENGTH(trim(ea))>10)  THEN
     update or insert into tw_klas (id_apteki,id_towary,id_klasyfikacje,wartosc) values (:iap,:idt,6,:ea); 
   DELETE FROM TW_KLAS k WHERE k.ID_APTEKI = :iap and k.ID_KLASYFIKACJE = 3 and k.ID_TOWARY = :idt AND k.WARTOSC <> :idb;
   update or insert into tw_klas (id_apteki,id_towary,id_klasyfikacje,wartosc) values (:iap,:idt,3,:idb);      
   
   if (ex = 1) THEN exit; 

   update towary set nazwa=:nm, postac=:ps ,dawka=:dw, opakowanie=:op,ID_PRODUCENCI=:pr,ILOSC_DDD=:dd,ean_ref=:ea,SMOPL_RAP=:sm,xml_typ=:te,zbloz = 'T'
        where id_apteki=:iap and id_towary=:idt;
        
   dwd = 1;     
   while (round(dwl) <> dwl and  dwd < 10000) do
   BEGIN
     dwd = dwd * 10;
     dwl = dwl * 10;
   END
   
   opd = 1;     
   while (round(opl) <> opl and  opd < 10000) do
   BEGIN
     opd = opd * 10;
     opl = opl * 10;
   END
   
   update or insert into jednostki (ID_APTEKI,ID_TOWARY,JEDNOSTKA,NAZWA,MNOZNIK,DZIELNIK,POCHODZI_OD,SPRZEDAZ,RECEPTURA,DOSTAWY,PODSTAWOWA)
          values (:iap,:idt,2,:opj,:opl,:opd,1,'T','N','N','N');
 
   if (dwl>0) THEN         
     update or insert into jednostki (ID_APTEKI,ID_TOWARY,JEDNOSTKA,NAZWA,MNOZNIK,DZIELNIK,POCHODZI_OD,SPRZEDAZ,RECEPTURA,DOSTAWY,PODSTAWOWA)
           values (:iap,:idt,3,:dwj,:dwl,:dwd,2,'T','T','N','N');       
  
   
   SELECT FIRST 1 s.KOD FROM STAWKI_VAT s WHERE s.WARTOSC = :vt ORDER by s.DATA_OD DESC INTO sm;
   if ((SELECT FIRST 1 v.KOD FROM VAT_TOWARY v where v.id_apteki=:iap and v.id_towary=:idt ORDER by v.DATA_OD DESC) is DISTINCT FROM sm ) THEN
     update or insert into vat_towary (id_apteki,id_towary,data_od,kod) values (:iap,:idt,'today',:sm);     
   
   
   if (dt is null) THEN
     dt = 'today';
   
   UPDATE TOW_LISTY t set t.OBOWIAZUJE_DO = :dt - 1 WHERE t.ID_APTEKI  = :iap and t.ID_TOWARY = :idt and t.OBOWIAZUJE_DO >= :dt;
   for SELECT o.RCP,o.UPR,o.ODP FROM BLOD o WHERE o.BLOZ7 = :idb and o.UPR in ('U','P','A','S','H','C','D') INTO ea,sm,te do
   BEGIN
     if (sm='A') THEN
       vt = 10;
     else if (sm='S') THEN  
       vt = 27;
     else if (sm='C') THEN  
       vt = 28;  
     else if (sm='D') THEN  
       vt = 29;  
     else if (sm='H') THEN  
       vt = 11;  
     ELSE
     BEGIN  
     if (ea='R') THEN
     BEGIN
       if (sm='U') THEN
       BEGIN
         if (te='R') THEN
           vt = 7;
         if (te='U') THEN
           vt = 8;
         if (te='Z') THEN
           vt = 9;
         if (te='P') THEN
           vt = 20;        
       END
       ELSE
       BEGIN
         if (te='D') THEN
           vt = 16;
         if (te='R') THEN
           vt = 17;
         if (te='U') THEN
           vt = 18;
         if (te='Z') THEN
           vt = 19;
       END
     END
     if (ea='O') THEN
     BEGIN
       vt = 1;
     END
     if (ea='B') THEN
     BEGIN
       if (sm='U') THEN
       BEGIN
         if (te='R') THEN
           vt = 3;
         if (te='U') THEN
           vt = 4;
         if (te='Z') THEN
           vt = 5;
         if (te='P') THEN
           vt = 6;        
       END
       ELSE
       BEGIN
         if (te='D') THEN
           vt = 12;
         if (te='R') THEN
           vt = 13;
         if (te='U') THEN
           vt = 14;
         if (te='Z') THEN
           vt = 15;
       END
     END
     if (ea='W') THEN
     BEGIN
       vt = 21;
     END
     END
     dj = NULL;
     SELECT FIRST 1 t.OBOWIAZUJE_OD  FROM TOW_LISTY t WHERE t.ID_APTEKI  = :iap and t.ID_TOWARY = :idt and t.ID_LISTY=:vt and t.OBOWIAZUJE_DO = :dt - 1 INTO dj;
     if (dj is null) then dj = dt;
     update or insert into tow_LISTY (ID_APTEKI,id_towary,id_listy,obowiazuje_od,obowiazuje_do) values (:iap,:idt,:vt,:dj,'01.01.3000');
   END
   
    dj=null;
    select min(obowiazuje_od) from TOW_LISTY where  ID_APTEKI  = :iap and ID_TOWARY = :idt  and obowiazuje_do>='today' and id_listy in (3,4,5,7,8,9,12,13,14,15,16,17,18,19,25) into dj;
    if (dj is null) then 
    BEGIN
      dj=cast('TODAY' as date);
      vt = 0;
    END  
    ELSE
      vt = 1;
    select typ_c from typ_ceny(:iap,:idt,:dj) into :pr;
    
    if (vt = 1 and pr <> 3) then
    begin
      update or insert into tw_typy_cen (ID_APTEKI,ID_TOWARY,OBOWIAZUJE_OD,ID_TYPY_CEN) values (:iap,:idt,:dj,3);  
    end
     
    if (cd is null) THEN
    BEGIN
      UPDATE CENY_TOWARY t  set t.OBOWIAZUJE_DO = :dt - 1 WHERE t.ID_APTEKI  = :iap and t.ID_TOWARY = :idt and t.OBOWIAZUJE_DO >= :dt;
     END
    ELSE
    BEGIN
      update or insert into ceny_towary (ID_APTEKI,id_towary,id_ceny,obowiazuje_od,cena_br,limit,DECYZYJNA,wn_kod,obowiazuje_do) values (:iap,:idt,3,:dt,:cd,:lm,'U','',:dk);
      update or insert into ceny_towary (ID_APTEKI,id_towary,id_ceny,obowiazuje_od,cena_br,limit,DECYZYJNA,wn_kod,obowiazuje_do) values (:iap,:idt,2,:dt,:ch,NULL,'U','',:dk);
      if (zb is not NULL) THEN
        update or insert into odpl_towary (ID_APTEKI,id_towary,id_ceny,id_odplatn,obowiazuje_od,OPLATA) values (:iap,:idt,3,2,:dt,:zb);
      if (zr is not NULL) THEN
        update or insert into odpl_towary (ID_APTEKI,id_towary,id_ceny,id_odplatn,obowiazuje_od,OPLATA) values (:iap,:idt,3,3,:dt,:zr);
      if (z3 is not NULL) THEN
        update or insert into odpl_towary (ID_APTEKI,id_towary,id_ceny,id_odplatn,obowiazuje_od,OPLATA) values (:iap,:idt,3,4,:dt,:z3);
      if (z5 is not NULL) THEN
        update or insert into odpl_towary (ID_APTEKI,id_towary,id_ceny,id_odplatn,obowiazuje_od,OPLATA) values (:iap,:idt,3,5,:dt,:z5);      
    END 
    if (n1 is not NULL) THEN
    BEGIN
     if (n1=1) THEN  opj = 'I-N';
     if (n1=2) THEN  opj = 'II-N';
     if (n1=3) THEN  opj = 'II-N';
     if (n1=4) THEN  opj = 'IV-N';
     update or insert into tw_klas (id_apteki,id_towary,id_klasyfikacje,wartosc) values (:iap,:idt,22,:opj);       
    END   
    if (n2 is not NULL) THEN
    BEGIN
     if (n2=1) THEN  opj = 'I-P';
     if (n2=2) THEN  opj = 'II-P';
     if (n2=3) THEN  opj = 'II-P';
     if (n2=4) THEN  opj = 'IV-P';
     update or insert into tw_klas (id_apteki,id_towary,id_klasyfikacje,wartosc) values (:iap,:idt,22,:opj);       
    END   
    if (n3 is not NULL) THEN
    BEGIN
     if (n3=1) THEN  opj = 'I-R';
     if (n3=2) THEN  opj = 'II-R';
     if (n3=3) THEN  opj = 'II-R';
     if (n3=4) THEN  opj = 'IV-R';
     update or insert into tw_klas (id_apteki,id_towary,id_klasyfikacje,wartosc) values (:iap,:idt,22,:opj);       
    END   
end^

CREATE or ALTER TRIGGER OPAKOWANIA_IU FOR OPAKOWANIA
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
declare tid int;
declare zid int;
BEGIN
    if (new.ID_ZDST is not null) THEN
    BEGIN 
      SELECT first 1 t.ID_TOWARY from towary t where t.EAN_REF = new.KOD and t.ID_APTEKI = new.ID_APTEKI into tid;
      SELECT t.ID_TOWARY from ZDST t where t.ID_ZDST = new.ID_ZDST and t.ID_APTEKI = new.ID_APTEKI into zid;
      if (tid is not null and tid <> zid) THEN
      if (not EXISTS(SELECT t.ID_TOWARY from towary t where t.EAN_REF = new.KOD and t.ID_APTEKI = new.ID_APTEKI and t.ID_TOWARY = :zid) ) then      
      BEGIN
        execute procedure WPISZ_LOG ('OPAK_ZDST',new.ID_ZDST || '-' || coalesce(new.KOD,'') || '-' || coalesce(new.SERIA,'') || '-' || coalesce(new.IDENT,'')  );
        if (UPDATING) THEN
          new.ID_ZDST = old.ID_ZDST;
        ELSE
          new.ID_ZDST = null;
      END
    end
END^

ALTER PROCEDURE BARKOD_TO_TOW (
    IAP INTEGER,
    BKOD VARCHAR(40),
    IDKLAS INTEGER,
    KASA INTEGER,
    SERIA VARCHAR(20) DEFAULT null,
    IDENT VARCHAR(20) DEFAULT null,
    IDTR INTEGER DEFAULT -1,
    DTTR TIMESTAMP DEFAULT null )
RETURNS (
    IDTOW INTEGER,
    IDZDST DOUBLE PRECISION )

AS
declare stan numeric(15,5);
 declare ilr numeric(15,5);
 declare bk char(12);
 declare bl char(1);
 declare dw date;
 declare ilebl double precision;
 declare sa char(1);
 Declare it int;
 DECLARE ns VARCHAR(40);
begin

if (ident is not null and ident>' ') THEN
BEGIN
  SELECT o.ID_ZDST,z.ID_TOWARY,z.STAN,coalesce(z.BLOKADA,'N'),o.DATAW, coalesce(z.ile_blokada,z.stan), o.STATUS ,k.wartosc
  FROM opakowania o 
  LEFT JOIN ZDST z on z.ID_ZDST=o.ID_ZDST and z.ID_APTEKI = o.ID_APTEKI
  left join ZDST_KLAS k ON z.ID_ZDST=k.ID_ZDST and z.ID_APTEKI = k.ID_APTEKI and k.id_klasyfikacje = 5
  where o.KOD = :bkod and o.SERIA = :seria and o.IDENT = :ident INTO idzdst,IDTOW, stan,bl,dw,ilebl,sa,ns;
  
  
  
  if (sa is not null and sa in ('S','A','U') ) THEN
  BEGIN
    idtow = -1;
    idzdst = -2;
    execute procedure WPISZ_LOG ('OPAK_WYD',:bkod || '-' || :seria || '-' || :ident || '-' || :sa );
    SUSPEND;
    exit;
  END

  
  if (idzdst is not null) THEN
  BEGIN
    SELECT first 1 t.ID_TOWARY from TOWARY t where t.EAN_REF = :bkod and t.ID_APTEKI = :iap into it;
    if ((it is not null and it <> idtow) or (seria is not null AND ns is not NULL and seria <> ns)) THEN
    BEGIN
      idtow = null;
      idzdst = null;
    END
  END
  
  if (idzdst is not null) THEN
  BEGIN
    if (bl<>'N' and ilebl>=stan) then
    begin
      idtow=-1;
      suspend;
      exit;
    end
    select ILOSC from rezerwacja where id_apteki=:iap and ID_ZDST=:IDZDST and NRKASY<>:KASA into :ilr;
    if (:ilr is null) then ilr=0;
    if (:stan-:ilr>0) then
    begin
      if (dw is not null and dw>cast('01/01/1990'  as date) and dw<'today' and kasa between 1 and 9) then
      begin
        idtow  = -1;
        idzdst = -1;
      end
      suspend;
      exit;
    end
  END
  for SELECT ID_ZDST,ID_TOWARY,STAN,DATA_WAZN FROM
    (SELECT ID_ZDST,ID_TOWARY,STAN,DATA_WAZN,IIF(stan>=1, iif(seria is not null ,2, 1) , 0 ) duzo FROM
    (select z.ID_ZDST,z.ID_TOWARY,IIF (coalesce(z.BLOKADA,'N')='N' , z.STAN , z.STAN -  coalesce(z.ile_blokada,z.stan) )
    - iif(r.ILOSC is null,0,MINVALUE(r.ILOSC,(
    SELECT COUNT(*) from OPAKOWANIA a join SPRZEDAZ s on s.ID_SPRZEDAZ=a.ID_SPRZEDAZ and a.ID_APTEKI=s.ID_APTEKI
     where a.ID_ZDST = r.ID_ZDST and a.ID_APTEKI=r.ID_APTEKI and (r.NRKASY <> :kasa or s.ID_TRANZAKCJE=:idtr and s.DATA = :dttr)
    ))) STAN, z.DATA_WAZN , k.WARTOSC seria
    from TOWARY t left join ZDST z on t.ID_TOWARY = z.ID_TOWARY and t.ID_APTEKI=z.ID_APTEKI and z.CZYNNY = 'T'
    left JOIN ZDST_KLAS k on k.ID_ZDST=z.ID_ZDST and k.ID_KLASYFIKACJE=5 and k.ID_APTEKI=z.ID_APTEKI AND k.WARTOSC = :seria
    left join REZERWACJA r on r.id_apteki=z.ID_APTEKI and r.ID_ZDST=z.ID_ZDST
    where t.id_apteki=:iap and  t.EAN_REF=:BKOD  
    )
    ) order by DUZO DESC,ID_ZDST
  
   into idzdst,IDTOW,stan,dw do
   BEGIN
    if (stan>0 AND (dw is NULL or dw<=cast('01/01/1990'  as date) or dw>='today')) then
    begin
      SUSPEND;
      EXIT;
    END
   END
   if (idtow is not null) THEN
   BEGIN
     idzdst = 0;
     SUSPEND;
     Exit;
   END
END
/*najpierw szukamy kodu jako kodu zwiazanego z dostawa*/
bk=substring(bkod from 1 for 12);
for select ID_ZDST from ZDST_KLAS where id_apteki=:iap and ID_KLASYFIKACJE=:IDKLAS and WARTOSC starting with :BK into :IDZDST  do
begin
  select ID_TOWARY,STAN,coalesce(BLOKADA,'N'),DATA_WAZN , coalesce(ile_blokada,stan) from zdst where id_apteki=:iap and ID_ZDST=:IDZDST  into :IDTOW, stan,bl,dw,ilebl;
  if (bl<>'N' and ilebl>=stan) then
  begin
    idtow=-1;
    suspend;
    exit;
  end
  select ILOSC from rezerwacja where id_apteki=:iap and ID_ZDST=:IDZDST and NRKASY<>:KASA into :ilr;
  if (:ilr is null) then ilr=0;
  if (:stan-:ilr>0) then
  begin
    if (dw is not null and dw>cast('01/01/1990'  as date) and dw<'today' and kasa between 1 and 9) then
    begin
      idtow  = -1;
      idzdst = -1;
    end
    suspend;
    exit;
  end
end
/*jak nie ma to szukamy kod dla towarow*/
IDZDST=0;
for select ID_TOWARY,stan from TW_KLAS t left join stan_wart(t.id_apteki,t.id_towary,1) on 0=0
 where t.id_apteki=:iap and t.ID_KLASYFIKACJE=:IDKLAS and t.WARTOSC=:BKOD into IDTOW,ilr do
  if (ilr>0) then
  begin
    suspend;
    exit;
  end
suspend;
exit;
end
^

CREATE OR ALTER PROCEDURE ROZBIJ_SPRZEDAZ (
    IA INTEGER,
    ID INTEGER,
    IL INTEGER )
RETURNS (
    WYNIK CHAR(1) )

AS
DECLARE szt DOUBLE PRECISION;
DECLARE inw INTEGER;
DECLARE itw INTEGER;
DECLARE itr INTEGER;
DECLARE dtr TIMESTAMP;
DECLARE ijd INTEGER;
declare ose VARCHAR(20);
declare oid VARCHAR(20);
declare oea VARCHAR(20);
DECLARE ile INTEGER;
DECLARE riz DOUBLE PRECISION;
DECLARE rsz DOUBLE PRECISION;
DECLARE wod DOUBLE PRECISION;
DECLARE wdp DOUBLE PRECISION;
DECLARE wwa DOUBLE PRECISION;
DECLARE wwz DOUBLE PRECISION;
DECLARE rpo INTEGER;
BEGIN
  wynik = 'N';
  
  SELECT sum(r.SZTUK_JP) from RZDST r where r.ID_SPRZEDAZ = :id and r.ID_APTEKI = :ia into szt;
  if (szt - il < 1)  THEN
  BEGIN
    SUSPEND;
    exit;
  end
  
  insert into SPRZEDAZ (ID_APTEKI, ID_SPRZEDAZ, ID_TOWARY, DATA, ID_TRANZAKCJE,
    POZYCJA, SZTUK, JEDNOSTKA, ID_RECEPTA, WARTOSC, CENA,
    ID_ODPLATNOSC, ODPLATNOSC, REFUNDATOR2, TAKSA, DOPLATA, TRYB,
    STAWKA_VAT, UPUST, WART_ZAK, CENA_ZAK, CENA_ZAK_BR, TYP_UPUSTU,
    ID_PROMOCJE, NIE_ZAMIENIAC, NA100, ID_ZAMIENNIK, POZ_REC, OPIS,
    CZESCIOWA, ID_WYDAL)
  SELECT ID_APTEKI, GEN_ID(SQ_SPRZEDAZ,1), ID_TOWARY, DATA, ID_TRANZAKCJE,
    POZYCJA, SZTUK, JEDNOSTKA, ID_RECEPTA, WARTOSC, CENA,
    ID_ODPLATNOSC, ODPLATNOSC, REFUNDATOR2, TAKSA, DOPLATA, TRYB,
    STAWKA_VAT, UPUST, WART_ZAK, CENA_ZAK, CENA_ZAK_BR, TYP_UPUSTU,
    ID_PROMOCJE, NIE_ZAMIENIAC, NA100, ID_ZAMIENNIK, POZ_REC, OPIS,
    CZESCIOWA, ID_WYDAL
  FROM SPRZEDAZ  
  WHERE
    ID_APTEKI = :ia AND 
    ID_SPRZEDAZ = :id
  RETURNING ID_sprzedaz,id_towary,data,id_tranzakcje,jednostka
  into inw,itw,dtr,itr,ijd  ;

  ile = 0;
  for SELECT r.IDENT,r.KOD,r.SERIA from OPAKOWANIA r
  where r.ID_SPRZEDAZ = :id and r.ID_APTEKI = :ia 
  into oid,oea,ose DO
  BEGIN
    update OPAKOWANIA r set r.ID_SPRZEDAZ = :inw where r.IDENT = :oid and r.KOD = :oea and r.SERIA = :ose;
    ile = ile + 1;
    if (ile >= il) THEN
      BREAK;
  end
  
  ile = il;
  
  for SELECT r.ID_ZDST,r.SZTUK_JP,r.POZYCJA from RZDST r
  where r.ID_SPRZEDAZ = :id and r.ID_APTEKI = :ia 
  order by r.SZTUK_JP
  into riz,rsz,rpo DO
  BEGIN
    if (rsz <= ile) THEN
    BEGIN
      UPDATE RZDST r SET r.ID_SPRZEDAZ = :inw where r.ID_SPRZEDAZ=:id and r.ID_APTEKI=:ia and r.ID_ZDST=:riz and r.POZYCJA=:rpo;
      ile = ile - rsz;
      if (ile <= 0.001) THEN
        BREAK;
    END
    ELSE
    BEGIN
      INSERT INTO RZDST (ID_APTEKI, ID_SPRZEDAZ, ID_ZDST, POZYCJA, SZTUK_JP, ID_TOWARY, DATA, CENA, SZTUK_RP, WN_IDP, ID_OSOZ)
      SELECT ID_APTEKI, :inw, ID_ZDST, POZYCJA, :ile,ID_TOWARY, DATA, CENA, SZTUK_RP, WN_IDP, ID_OSOZ   
      from RZDST r where r.ID_SPRZEDAZ=:id and r.ID_APTEKI=:ia and r.ID_ZDST=:riz and r.POZYCJA=:rpo;
      
      UPDATE RZDST r SET r.SZTUK_JP = :rsz - :ile where r.ID_SPRZEDAZ=:id and r.ID_APTEKI=:ia and r.ID_ZDST=:riz and r.POZYCJA=:rpo;
      BREAK;
    END
  end
  
  SELECT sum(r.SZTUK_JP) from RZDST r where r.ID_SPRZEDAZ = :id and r.ID_APTEKI = :ia into szt;
  update SPRZEDAZ s set s.SZTUK = :szt,s.JEDNOSTKA = 1 where s.ID_SPRZEDAZ = :id and s.ID_APTEKI = :ia;
  
  SELECT sum(r.SZTUK_JP) from RZDST r where r.ID_SPRZEDAZ = :inw and r.ID_APTEKI = :ia into szt;
  update SPRZEDAZ s set s.SZTUK = :szt,s.JEDNOSTKA = 1 where s.ID_SPRZEDAZ = :inw and s.ID_APTEKI = :ia;

  SELECT  ODPLATNOSC, DOPLATA, WARTOSC , WART_ZAK  FROM WYCENA_SPRZEDAZY(:ia,:id,0) into wod,wdp,wwa,wwz;
  update SPRZEDAZ s set s.ODPLATNOSC = :wod,s.DOPLATA=:wdp,s.WARTOSC=:wwa,s.WART_ZAK=:wwz where s.ID_SPRZEDAZ = :id and s.ID_APTEKI = :ia;
  
  SELECT  ODPLATNOSC, DOPLATA, WARTOSC , WART_ZAK  FROM WYCENA_SPRZEDAZY(:ia,:inw,0) into wod,wdp,wwa,wwz;
  update SPRZEDAZ s set s.ODPLATNOSC = :wod,s.DOPLATA=:wdp,s.WARTOSC=:wwa,s.WART_ZAK=:wwz where s.ID_SPRZEDAZ = :inw and s.ID_APTEKI = :ia;

  wynik = 'T';  
  SUSPEND;
END
^

ALTER PROCEDURE CBT_DANE_Z_APTEK (
    IC INTEGER,
    TP INTEGER )
RETURNS (
    IA INTEGER,
    IT INTEGER,
    CDB DOUBLE PRECISION,
    CDN DOUBLE PRECISION,
    MKJ DOUBLE PRECISION,
    MPR DOUBLE PRECISION,
    CZN DOUBLE PRECISION,
    STA DOUBLE PRECISION,
    TCD VARCHAR(20),
    ILE INTEGER,
    TLK VARCHAR(3),
    STD DOUBLE PRECISION )
AS
BEGIN
  SELECT typ from TYP_LEKU_CBT(:ic,'today') into tlk;
  if (tp=1) THEN
  for SELECT o.ID_APTEKI FROM OGOLNE o WHERE o.AUTO_ZAM='T' into ia do
  begin
    ile = 0;
    for SELECT t.ID_TOWARY FROM TOWARY t WHERE t.ID_CBT=:ic  and t.ID_APTEKI=:ia
    into it do
    BEGIN
      ile = ile + 1;
      SELECT sum(a.CENA_BR*COALESCE(z.STAN,z.SZTUK_JP)),sum(a.CENA_NT*COALESCE(z.STAN,z.SZTUK_JP)),SUM(COALESCE(z.STAN,z.SZTUK_JP)),
        sum(c.CENA_NT_JP*COALESCE(z.STAN,z.SZTUK_JP)),LIST(DISTINCT a.JAKA),SUM(z.STAN - iif(coalesce(z.blokada,'N')='N',0,coalesce(z.ile_blokada,z.stan)) )
      FROM zdst z
      LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
      LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
      WHERE z.ID_APTEKI=:ia and z.ID_TOWARY=:it AND z.CZYNNY='T'
      INTO cdb,cdn,sta,czn,tcd,std;
      if (sta>0.001) THEN
      BEGIN
        mkj = round((cdn - czn) / sta,2);
        if (cdn > 0) THEN
          mpr = round(100 * (cdn - czn) / cdn,2);
        ELSE
          mpr = null;
        cdb = round(cdb/sta,2);
        cdn = round(cdn/sta,2);
        czn = round(czn/sta,2);
      END
      ELSE
      BEGIN
        SELECT  first 1 a.CENA_BR,a.CENA_NT,c.CENA_NT_JP,a.JAKA
          FROM zdst z
          LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
          LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
        WHERE z.ID_APTEKI=:ia and z.ID_TOWARY=:it AND z.SZTUK>0
        ORDER by z.DATA DESC
        INTO cdb,cdn,czn,tcd;
        mkj = round((cdn - czn),2);
        if (cdn > 0) THEN
          mpr = round(100 * (cdn - czn)/cdn,2);
        ELSE
          mpr = null;
      END
      SUSPEND;
    END
    if (ile=0) THEN 
    BEGIN
  
      IT  = null;
      CDB = null;
      CDN = null;
      MKJ = null;
      MPR = null;
      CZN = null;
      STA = null;
      TCD = null;
      STD = null;
      SUSPEND;
    END
  end
  if (tp=2) THEN
  BEGIN
    SELECT sum(a.CENA_BR*COALESCE(z.STAN,z.SZTUK_JP)),sum(a.CENA_NT*COALESCE(z.STAN,z.SZTUK_JP)),SUM(COALESCE(z.STAN,z.SZTUK_JP)),sum(c.CENA_NT_JP*COALESCE(z.STAN,z.SZTUK_JP)),
      LIST(DISTINCT a.JAKA),max(mod(t.ID_APTEKI,1000) * 1000000 + t.ID_TOWARY),SUM(z.STAN - iif(coalesce(z.blokada,'N')='N',0,coalesce(z.ile_blokada,z.stan)) )
    FROM TOWARY t
    LEFT JOIN OGOLNE o on o.ID_APTEKI=t.ID_APTEKI
    LEFT JOIN zdst z on t.ID_APTEKI=z.ID_APTEKI and t.ID_TOWARY=z.ID_TOWARY AND z.CZYNNY='T' 
    LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
    WHERE t.ID_CBT=:ic and o.AUTO_ZAM='T'
    INTO cdb,cdn,sta,czn,tcd,ia,std;
    if (sta>0.001) THEN
    BEGIN
      mkj = round((cdn - czn) / sta,2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn) / cdn,2);
      ELSE
        mpr = null;  
      cdb = round(cdb/sta,2);
      cdn = round(cdn/sta,2);
      czn = round(czn/sta,2);
    END
    ELSE
    BEGIN
      it = mod(ia,1000000);
      ia = 10000 + ia / 1000000 ;
      SELECT  first 1 a.CENA_BR,a.CENA_NT,c.CENA_NT_JP,a.JAKA
        FROM zdst z
        LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
        LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
      WHERE z.ID_APTEKI=:ia and z.ID_TOWARY=:it AND z.SZTUK>0
      ORDER by z.DATA DESC
      INTO cdb,cdn,czn,tcd;
      mkj = round((cdn - czn),2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn)/cdn,2);
      ELSE
        mpr = null;    
    END
    SUSPEND;
  END  
  if (tp=3) THEN
  BEGIN
    SELECT c.ID_INTERNM FROM CBT c WHERE c.ID_CBT=:ic INTO it;
    if (it is NULL) then exit;
    SELECT sum(a.CENA_BR*COALESCE(z.STAN,z.SZTUK_JP)),sum(a.CENA_NT*COALESCE(z.STAN,z.SZTUK_JP)),SUM(COALESCE(z.STAN,z.SZTUK_JP)),sum(c.CENA_NT_JP*COALESCE(z.STAN,z.SZTUK_JP)),
      LIST(DISTINCT a.JAKA),max(mod(t.ID_APTEKI,1000) * 1000000 + t.ID_TOWARY),SUM(z.STAN - iif(coalesce(z.blokada,'N')='N',0,coalesce(z.ile_blokada,z.stan)) )
    FROM CBT x  
    LEFT JOIN TOWARY t on t.ID_CBT=x.ID_CBT
    LEFT JOIN OGOLNE o on o.ID_APTEKI=t.ID_APTEKI
    LEFT JOIN zdst z on t.ID_APTEKI=z.ID_APTEKI and t.ID_TOWARY=z.ID_TOWARY AND z.CZYNNY='T' 
    LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
    WHERE x.ID_INTERNM = :it  and o.AUTO_ZAM='T'
    INTO cdb,cdn,sta,czn,tcd,ia,std;
    if (sta>0.001) THEN
    BEGIN
      mkj = round((cdn - czn) / sta,2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn) / cdn,2);
      ELSE
        mpr = null;  
      cdb = round(cdb/sta,2);
      cdn = round(cdn/sta,2);
      czn = round(czn/sta,2);
    END
    ELSE
    BEGIN
      it = mod(ia,1000000);
      ia = 10000 + ia / 1000000 ;
      SELECT  first 1 a.CENA_BR,a.CENA_NT,c.CENA_NT_JP,a.JAKA
        FROM zdst z
        LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
        LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
      WHERE z.ID_APTEKI=:ia and z.ID_TOWARY=:it AND z.SZTUK>0
      ORDER by z.DATA DESC
      INTO cdb,cdn,czn,tcd;
      mkj = round((cdn - czn),2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn)/cdn,2);
      ELSE
        mpr = null;    
    END
    SUSPEND;
  END  
  if (tp=4) THEN
  BEGIN
    SELECT c.ID_SYNZB FROM CBT c WHERE c.ID_CBT=:ic INTO it;
    if (it is NULL) then exit;
    SELECT sum(a.CENA_BR*COALESCE(z.STAN,z.SZTUK_JP)),sum(a.CENA_NT*COALESCE(z.STAN,z.SZTUK_JP)),SUM(COALESCE(z.STAN,z.SZTUK_JP)),sum(c.CENA_NT_JP*COALESCE(z.STAN,z.SZTUK_JP)),
      LIST(DISTINCT a.JAKA),max(mod(t.ID_APTEKI,1000) * 1000000 + t.ID_TOWARY),SUM(z.STAN - iif(coalesce(z.blokada,'N')='N',0,coalesce(z.ile_blokada,z.stan)) )
    FROM CBT x  
    LEFT JOIN TOWARY t on t.ID_CBT=x.ID_CBT
    LEFT JOIN OGOLNE o on o.ID_APTEKI=t.ID_APTEKI
    LEFT JOIN zdst z on t.ID_APTEKI=z.ID_APTEKI and t.ID_TOWARY=z.ID_TOWARY AND z.CZYNNY='T' 
    LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
    WHERE x.ID_SYNZB = :it  and o.AUTO_ZAM='T'
    INTO cdb,cdn,sta,czn,tcd,ia,std;
    if (sta>0.001) THEN
    BEGIN
      mkj = round((cdn - czn) / sta,2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn) / cdn,2);
      ELSE
        mpr = null;  
      cdb = round(cdb/sta,2);
      cdn = round(cdn/sta,2);
      czn = round(czn/sta,2);
    END
    ELSE
    BEGIN
      it = mod(ia,1000000);
      ia = 10000 + ia / 1000000 ;
      SELECT  first 1 a.CENA_BR,a.CENA_NT,c.CENA_NT_JP,a.JAKA
        FROM zdst z
        LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
        LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
      WHERE z.ID_APTEKI=:ia and z.ID_TOWARY=:it AND z.SZTUK>0
      ORDER by z.DATA DESC
      INTO cdb,cdn,czn,tcd;
      mkj = round((cdn - czn),2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn)/cdn,2);
      ELSE
        mpr = null;    
    END
    SUSPEND;
  END  
  if (tp=5) THEN
  BEGIN
    SELECT c.ID_SYNSZCZ FROM CBT c WHERE c.ID_CBT=:ic INTO it;
    if (it is NULL) then exit;
    SELECT sum(a.CENA_BR*COALESCE(z.STAN,z.SZTUK_JP)),sum(a.CENA_NT*COALESCE(z.STAN,z.SZTUK_JP)),SUM(COALESCE(z.STAN,z.SZTUK_JP)),sum(c.CENA_NT_JP*COALESCE(z.STAN,z.SZTUK_JP)),
      LIST(DISTINCT a.JAKA),max(mod(t.ID_APTEKI,1000) * 1000000 + t.ID_TOWARY),SUM(z.STAN - iif(coalesce(z.blokada,'N')='N',0,coalesce(z.ile_blokada,z.stan)) )
    FROM CBT x  
    LEFT JOIN TOWARY t on t.ID_CBT=x.ID_CBT
    LEFT JOIN OGOLNE o on o.ID_APTEKI=t.ID_APTEKI
    LEFT JOIN zdst z on t.ID_APTEKI=z.ID_APTEKI and t.ID_TOWARY=z.ID_TOWARY AND z.CZYNNY='T' 
    LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
    WHERE x.ID_SYNSZCZ = :it  and o.AUTO_ZAM='T'
    INTO cdb,cdn,sta,czn,tcd,ia,std;
    if (sta>0.001) THEN
    BEGIN
      mkj = round((cdn - czn) / sta,2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn) / cdn,2);
      ELSE
        mpr = null;  
      cdb = round(cdb/sta,2);
      cdn = round(cdn/sta,2);
      czn = round(czn/sta,2);
    END
    ELSE
    BEGIN
      it = mod(ia,1000000);
      ia = 10000 + ia / 1000000 ;
      SELECT  first 1 a.CENA_BR,a.CENA_NT,c.CENA_NT_JP,a.JAKA
        FROM zdst z
        LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
        LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
      WHERE z.ID_APTEKI=:ia and z.ID_TOWARY=:it AND z.SZTUK>0
      ORDER by z.DATA DESC
      INTO cdb,cdn,czn,tcd;
      mkj = round((cdn - czn),2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn)/cdn,2);
      ELSE
        mpr = null;
    END
    SUSPEND;
  END  
  if (tp=6) THEN
  BEGIN
    SELECT c.ID_SYNWL FROM CBT c WHERE c.ID_CBT=:ic INTO it;
    if (it is NULL) then exit;
    SELECT sum(a.CENA_BR*COALESCE(z.STAN,z.SZTUK_JP)),sum(a.CENA_NT*COALESCE(z.STAN,z.SZTUK_JP)),SUM(COALESCE(z.STAN,z.SZTUK_JP)),sum(c.CENA_NT_JP*COALESCE(z.STAN,z.SZTUK_JP)),
      LIST(DISTINCT a.JAKA),max(mod(t.ID_APTEKI,1000) * 1000000 + t.ID_TOWARY),SUM(z.STAN - iif(coalesce(z.blokada,'N')='N',0,coalesce(z.ile_blokada,z.stan)) )
    FROM CBT x  
    LEFT JOIN TOWARY t on t.ID_CBT=x.ID_CBT
    LEFT JOIN OGOLNE o on o.ID_APTEKI=t.ID_APTEKI
    LEFT JOIN zdst z on t.ID_APTEKI=z.ID_APTEKI and t.ID_TOWARY=z.ID_TOWARY AND z.CZYNNY='T' 
    LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
    WHERE x.ID_SYNWL = :it  and o.AUTO_ZAM='T'
    INTO cdb,cdn,sta,czn,tcd,ia,std;
    if (sta>0.001) THEN
    BEGIN
      mkj = round((cdn - czn) / sta,2);
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn) / cdn,2);
      ELSE
        mpr = null;  
      cdb = round(cdb/sta,2);
      cdn = round(cdn/sta,2);
      czn = round(czn/sta,2);
    END
    ELSE
    BEGIN
      it = mod(ia,1000000);
      ia = 10000 + ia / 1000000 ;
      SELECT  first 1 a.CENA_BR,a.CENA_NT,c.CENA_NT_JP,a.JAKA
        FROM zdst z
        LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
        LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
      WHERE z.ID_APTEKI=:ia and z.ID_TOWARY=:it AND z.SZTUK>0
      ORDER by z.DATA DESC
      INTO cdb,cdn,czn,tcd;
      mkj = round((cdn - czn),2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn)/cdn,2);
      ELSE
        mpr = null;    
    END
    SUSPEND;
  END  
  if (tp=7) THEN
  BEGIN
    SELECT c.ID_ODPZL FROM CBT c WHERE c.ID_CBT=:ic INTO it;
    if (it is NULL) then exit;
    SELECT sum(a.CENA_BR*COALESCE(z.STAN,z.SZTUK_JP)),sum(a.CENA_NT*COALESCE(z.STAN,z.SZTUK_JP)),SUM(COALESCE(z.STAN,z.SZTUK_JP)),sum(c.CENA_NT_JP*COALESCE(z.STAN,z.SZTUK_JP)),
      LIST(DISTINCT a.JAKA),max(mod(t.ID_APTEKI,1000) * 1000000 + t.ID_TOWARY),SUM(z.STAN - iif(coalesce(z.blokada,'N')='N',0,coalesce(z.ile_blokada,z.stan)) )
    FROM CBT x  
    LEFT JOIN TOWARY t on t.ID_CBT=x.ID_CBT
    LEFT JOIN OGOLNE o on o.ID_APTEKI=t.ID_APTEKI
    LEFT JOIN zdst z on t.ID_APTEKI=z.ID_APTEKI and t.ID_TOWARY=z.ID_TOWARY AND z.CZYNNY='T'
    LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
    LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
    WHERE x.ID_ODPZL = :it  and o.AUTO_ZAM='T'
    INTO cdb,cdn,sta,czn,tcd,ia,std;
    if (sta>0.001) THEN
    BEGIN
      mkj = round((cdn - czn) / sta,2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn) / cdn,2);
      ELSE
        mpr = null;  
      cdb = round(cdb/sta,2);
      cdn = round(cdn/sta,2);
      czn = round(czn/sta,2);
    END
    ELSE
    BEGIN
      it = mod(ia,1000000);
      ia = 10000 + ia / 1000000 ;
      SELECT  first 1 a.CENA_BR,a.CENA_NT,c.CENA_NT_JP,a.JAKA
        FROM zdst z
        LEFT JOIN CENY_DOSTAWY c on z.ID_APTEKI=c.ID_APTEKI and c.ID_ZDST=z.ID_ZDST and c.ID_CENY=1
        LEFT JOIN AKT_CENA_SP(z.id_apteki,z.id_towary,3,'today',z.id_zdst,'') a on 0=0
      WHERE z.ID_APTEKI=:ia and z.ID_TOWARY=:it AND z.SZTUK>0
      ORDER by z.DATA DESC
      INTO cdb,cdn,czn,tcd;
      mkj = round((cdn - czn),2); 
      if (cdn > 0) THEN
        mpr = round(100 * (cdn - czn)/cdn,2);
      ELSE
        mpr = null;    
    END
    SUSPEND;
  END  
end
^

SET TERM ; ^

COMMIT;
 /*  koniec procedur */
 
SET TERM ^ ;
EXECUTE block as BEGIN /*

                naciœnij Enter - nale¿y dograæ index-pk-vat
                mo¿na pracowaæ bez rejestrów VAT   
*/
if (exists(select 1 from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$relation_name = 'VAT7ATR')) then 
begin
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('1', 'GTU_01', 'Dostawa napojów alkoholowych - alkoholu etylowego, piwa, wina, napojów fermentowanych i wyrobów poœrednich, w rozumieniu przepisów o podatku akcyzowym', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('2', 'GTU_02', 'Dostawa towarów, o których mowa w art. 103 ust. 5aa ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('3', 'GTU_03', 'Dostawa oleju opa³owego w rozumieniu przepisów o podatku akcyzowym oraz olejów smarowych, pozosta³ych olejów o kodach CN od 2710 19 71 do 2710 19 99, z wy³¹czeniem wyrobów o kodzie CN 2710 19 85 (oleje bia³e, parafina ciek³a) oraz smarów plastycznych zaliczanych do kodu CN 2710 19 99, olejów smarowych o kodzie CN 2710 20 90, preparatów smarowych objêtych pozycj¹ CN 3403, z wy³¹czeniem smarów plastycznych objêtych t¹ pozycj¹', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('4', 'GTU_04', 'Dostawa wyrobów tytoniowych, suszu tytoniowego, p³ynu do papierosów elektronicznych i wyrobów nowatorskich, w rozumieniu przepisów o podatku akcyzowym', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('5', 'GTU_05', 'Dostawa odpadów - wy³¹cznie okreœlonych w poz. 79-91 za³¹cznika nr 15 do ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('6', 'GTU_06', 'Dostawa urz¹dzeñ elektronicznych oraz czêœci i materia³ów do nich, wy³¹cznie okreœlonych w poz. 7-9, 59-63, 65, 66, 69 i 94-96 za³¹cznika nr 15 do ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('7', 'GTU_07', 'Dostawa pojazdów oraz czêœci samochodowych o kodach wy³¹cznie CN 8701 - 8708 oraz CN 8708 10', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('8', 'GTU_08', 'Dostawa metali szlachetnych oraz nieszlachetnych - wy³¹cznie okreœlonych w poz. 1-3 za³¹cznika nr 12 do ustawy oraz w poz. 12-25, 33-40, 45, 46, 56 i 78 za³¹cznika nr 15 do ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('9', 'GTU_09', 'Dostawa leków oraz wyrobów medycznych - produktów leczniczych, œrodków spo¿ywczych specjalnego przeznaczenia ¿ywieniowego oraz wyrobów medycznych, objêtych obowi¹zkiem zg³oszenia, o którym mowa w art. 37av ust. 1 ustawy z dnia 6 wrzeœnia 2001 r. - Prawo farmaceutyczne (Dz. U. z 2019 r. poz. 499, z póŸn. zm.)', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('10', 'GTU_10', 'Dostawa budynków, budowli i gruntów', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('11', 'GTU_11', 'Œwiadczenie us³ug w zakresie przenoszenia uprawnieñ do emisji gazów cieplarnianych, o których mowa w ustawie z dnia 12 czerwca 2015 r. o systemie handlu uprawnieniami do emisji gazów cieplarnianych (Dz. U. z 2018 r. poz. 1201 i 2538 oraz z 2019 r. poz. 730, 1501 i 1532)', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('12', 'GTU_12', 'Œwiadczenie us³ug o charakterze niematerialnym - wy³¹cznie: doradczych, ksiêgowych, prawnych, zarz¹dczych, szkoleniowych, marketingowych, firm centralnych (head offices), reklamowych, badania rynku i opinii publicznej, w zakresie badañ naukowych i prac rozwojowych', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('13', 'GTU_13', 'Œwiadczenie us³ug transportowych i gospodarki magazynowej - Sekcja H PKWiU 2015 symbol ex 49.4, ex 52.1', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('14', 'SW', 'Dostawa w ramach sprzeda¿y wysy³kowej z terytorium kraju, o której mowa w art. 23 ustawy', '2010-01-01 00:00:00', '2021-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('15', 'EE', 'Œwiadczenie us³ug telekomunikacyjnych, nadawczych i elektronicznych, o których mowa w art. 28k ustawy', '2010-01-01 00:00:00', '2021-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('14', 'WSTO_EE', 'Wewn¹trzwspólnotowa sprzeda¿y na odleg³oœæ towarów, które w momencie rozpoczêcia ich wysy³ki lub transportu znajduj¹ siê na terytorium kraju, oraz œwiadczenie us³ug telekomunikacyjnych', '2022-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('15', 'IED', 'Dostawa towarów, o której mowa w art. 7a ust. 1 i 2 ustawy, dokonana przez podatnika u³atwiaj¹cego tê dostawê, który nie korzysta z procedury szczególnej, o której mowa w dziale XII w rozdziale 6a lub 9 ustawy lub w odpowiadaj¹cych im regulacjach, dla której miejscem dostawy jest terytorium kraju.', '2022-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('16', 'TP', 'Istniej¹ce powi¹zania miêdzy nabywc¹ a dokonuj¹cym dostawy towarów lub us³ugodawc¹, o których mowa w art. 32 ust. 2 pkt 1 ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('17', 'TT_WNT', 'Wewn¹trzwspólnotowe nabycie towarów dokonane przez drugiego w kolejnoœci podatnika VAT w ramach transakcji trójstronnej w procedurze uproszczonej, o której mowa w dziale XII rozdziale 8 ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('18', 'TT_D', 'Dostawa towarów poza terytorium kraju dokonana przez drugiego w kolejnoœci podatnika VAT w ramach transakcji trójstronnej w procedurze uproszczonej, o której mowa w dziale XII rozdziale 8 ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('19', 'MR_T', 'Œwiadczenie us³ug turystyki opodatkowane na zasadach mar¿y zgodnie z art. 119 ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('20', 'MR_UZ', 'Dostawa towarów u¿ywanych, dzie³ sztuki, przedmiotów kolekcjonerskich i antyków, opodatkowana na zasadach mar¿y zgodnie z art. 120 ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('21', 'I_42', 'Wewn¹trzwspólnotowa dostawa towarów nastêpuj¹ca po imporcie tych towarów w ramach procedury celnej 42 (import)', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('22', 'I_63', 'Wewn¹trzwspólnotowa dostawa towarów nastêpuj¹ca po imporcie tych towarów w ramach procedury celnej 63 (import)', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('23', 'B_SPV', 'Transfer bonu jednego przeznaczenia dokonany przez podatnika dzia³aj¹cego we w³asnym imieniu, opodatkowany zgodnie z art. 8a ust. 1 ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('24', 'B_SPV_DOSTAWA', 'Dostawa towarów oraz œwiadczenie us³ug, których dotyczy bon jednego przeznaczenia na rzecz podatnika, który wyemitowa³ bon zgodnie z art. 8a ust. 4 ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('25', 'B_MPV_PROWIZJA', 'Œwiadczenie us³ug poœrednictwa oraz innych us³ug dotycz¹cych transferu bonu ró¿nego przeznaczenia, opodatkowane zgodnie z art. 8b ust. 2 ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('26', 'MPP', 'Transakcja objêta obowi¹zkiem stosowania mechanizmu podzielonej p³atnoœci', '2010-01-01 00:00:00', '2021-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('26', '---', '---', '2022-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('27', 'IMP', 'Oznaczenie dotycz¹ce podatku naliczonego z tytu³u importu towarów, w tym importu towarów rozliczanego zgodnie z art. 33a ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('28', 'RO', 'Dokument zbiorczy wewnêtrzny zawieraj¹cy sprzeda¿ z kas rejestruj¹cych', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('29', 'WEW', 'Dokument wewnêtrzny', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('30', 'FP', 'Faktura, o której mowa w art. 109 ust. 3d ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('31', 'MK', 'Faktura wystawiona przez podatnika bêd¹cego dostawc¹ lub us³ugodawc¹, który wybra³ metodê kasow¹ rozliczeñ okreœlon¹ w art. 21 ustawy', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
UPDATE OR INSERT INTO VAT7ATR (ID, KOD, OPIS, DT_OD, DT_DO) VALUES ('32', 'VAT_RR', 'Faktura VAT RR, o której mowa w art. 116 ustawy (Sprzeda¿ nie uwzglêdniaj w JPK-VAT)', '2010-01-01 00:00:00', '2100-12-31 00:00:00');
end
END ^
SET TERM ; ^

update FAKTURY_REF set FORMAT_EKSP = 'F' where ID_APTEKI=#ID_APTEKI# and ID_FAKTURY_REF=2;

update FAKTURY_REF set FORMAT_EKSP = 'G' where ID_APTEKI=#ID_APTEKI# and ID_FAKTURY_REF=1 and cast('today' as date)>'11.9.20';

UPDATE OR INSERT INTO WYDRUKI (ID_WYDRUKI, FORMA, NAZWA, NAGLOWEK, POLA, SUMOWANE, TYLKO_SUMA, LP, POLAZ, SUMAZ, STR_DET, OPIS, DR_F_CAPTION, DR_DATA_WYK, UZYJ_FILTR, NOWA_STR, IFUPDDATE, IFUPDUSER, ID_APTEKI, ORIENTACJA, PL_GRUP, JEDEN_W, DR_PIECZ, WERSJA,
 ID_KL_AP, IFINSUSER, IFINSDATE) VALUES ('40', 'FWzRw', 'Specyf. do zapotrzebowania', NULL, '', '', NULL, '''', '', '', '-1', 'Wydruk specyfikacji do zapotrzebowania', NULL, NULL, NULL, NULL, 'now', 'SYSDBA', '1', NULL, '1',
  NULL, NULL, NULL, NULL, NULL, NULL);

UPDATE OR INSERT INTO WYDRUKI (ID_WYDRUKI, FORMA, NAZWA, NAGLOWEK, POLA, SUMOWANE, TYLKO_SUMA, LP, POLAZ, SUMAZ, STR_DET, OPIS, DR_F_CAPTION, DR_DATA_WYK, UZYJ_FILTR, NOWA_STR, IFUPDDATE, IFUPDUSER, ID_APTEKI, ORIENTACJA, PL_GRUP, JEDEN_W, DR_PIECZ, WERSJA,
 ID_KL_AP, IFINSUSER, IFINSDATE) VALUES ('41', 'FWzRw', 'Zapotrzebowanie wzór 2', NULL, '', '', NULL, '''', '', '', '-1', 'Wydruk zapotrzebowania', NULL, NULL, NULL, NULL, 'now', 'SYSDBA', '1', NULL, '1',
  NULL, NULL, NULL, NULL, NULL, NULL);

UPDATE SZABL_DEK SET STOSUJ_DO = 'C' WHERE ID_SZABL_DEK = 1;
UPDATE SZABL_DEK SET STOSUJ_DO = 'B' WHERE ID_SZABL_DEK = 2;
UPDATE SZABL_DEK SET STOSUJ_DO = 'KAO' WHERE ID_SZABL_DEK = 3; /* --700 KA , O f korygujace 
select STOSUJ_DO , ID_SZABL_DEK from SZABL_DEK  
UPDATE SZABL_DEK SET STOSUJ_DO = 'DTSGOE' WHERE ID_SZABL_DEK=4; 
'DTSZGOE' 'Z' fv kasowe gotowkowe bez nip (zbiorczo) w³¹czenie tego spowoduje dodawanie zapisów na plus i minus 'fv bez NIP' przy ksiegowaniu dnia, 
potrzebne gdyby trafialy sie faktury paragonowe z odroczonym terminem platnosci bo te teraz trafiaja do ksi¹zki zawsze i brakuje wowczas wpisu na '-'*/
UPDATE SZABL_DEK SET STOSUJ_DO = NULL WHERE ID_SZABL_DEK = 5;
UPDATE SZABL_DEK SET STOSUJ_DO = 'W' WHERE ID_SZABL_DEK = 6;
update ogolne set F_ODR_VAT='T' where id_apteki=#ID_APTEKI#; /* --700 nul */


SET TERM ^ ;
EXECUTE BLOCK as
DECLARE dt TIMESTAMP;
DECLARE ap apteka;
DECLARE it INTEGER;
BEGIN  
RDB$SET_CONTEXT('USER_SESSION','KS_FA',1);
  if (not exists(select 1 from ogolne where wersja>=130.042 and id_apteki=#ID_APTEKI#)) THEN
  BEGIN    
    UPDATE TRANZAKCJE t SET t.PARAGON='T' where t.DATA>='01.10.2020' and t.PARAGON='X' and t.KOR_TR is null and t.ID_APTEKI=#ID_APTEKI#
      and exists (select * from kontrahenci where id_kontrahenci=t.id_kontrahenci and char_length(trim(coalesce(nip,'')))<10);
    UPDATE TRANZAKCJE t SET t.PARAGON='K' where t.DATA>='01.10.2020' and t.PARAGON='V' and t.ID_APTEKI=#ID_APTEKI#
      and exists (select * from kontrahenci where id_kontrahenci=t.id_kontrahenci and char_length(trim(coalesce(nip,'')))<10);  
    FOR SELECT t.DATA, t.ID_TRANZAKCJE
    FROM TRANZAKCJE t WHERE t.DATA>= '01.10.2020' and t.PARAGON in ('T','K') and t.ID_KONTRAHENCI>0 and t.ID_APTEKI=#ID_APTEKI#
    INTO dt,it do 
    EXECUTE PROCEDURE ks_fa(ap,it,dt);
  END
RDB$SET_CONTEXT('USER_SESSION','KS_FA',0);  
end^
SET TERM ; ^


update opakowania set status=null where status='S' and id_sprzedaz is null and id_zdst is not null and st_wysl=-2 and ID_APTEKI=#ID_APTEKI#;

update sl_lekarz set opis=(select cyfry from trim_pole(opis)) where ID_APTEKI=#ID_APTEKI#;

/* to obecnie zalatwia 'koniec wersji' - poki w update modyfikowac procedure - przy okazji przerobic ze nie modyfikowalo zawsze Update SYNCZTB 
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'OGOLNE', 'PROGN_KASA', 'O', '0', '1');
*/

UPDATE POST_ZL SET POST_POD = '10201000' WHERE ID_POST_ZL = '1';
UPDATE POST_ZL SET POST_POD = '10517000' WHERE ID_POST_ZL = '2';
UPDATE POST_ZL SET POST_POD = '11013000' WHERE ID_POST_ZL = '5';
UPDATE POST_ZL SET POST_POD = '10107000' WHERE ID_POST_ZL = '7';
UPDATE POST_ZL SET POST_POD = '10512000' WHERE ID_POST_ZL = '8';
UPDATE POST_ZL SET POST_POD = '10504000' WHERE ID_POST_ZL = '9';
UPDATE POST_ZL SET POST_POD = '50019500' WHERE ID_POST_ZL = '10';
UPDATE POST_ZL SET POST_POD = '10122000' WHERE ID_POST_ZL = '11';
UPDATE POST_ZL SET POST_POD = '10231000' WHERE ID_POST_ZL = '12';
UPDATE POST_ZL SET POST_POD = '10515000' WHERE ID_POST_ZL = '13';
UPDATE POST_ZL SET POST_POD = '50019500' WHERE ID_POST_ZL = '14';
UPDATE POST_ZL SET POST_POD = '10504000' WHERE ID_POST_ZL = '15';
UPDATE POST_ZL SET POST_POD = '10512000' WHERE ID_POST_ZL = '16';
UPDATE POST_ZL SET POST_POD = '11013000' WHERE ID_POST_ZL = '17';
UPDATE POST_ZL SET POST_POD = '10107000' WHERE ID_POST_ZL = '18';
UPDATE POST_ZL SET POST_POD = '10201000' WHERE ID_POST_ZL = '19';

UPDATE OR INSERT INTO WART_ATR_REC (ID_ATR_REC, WART_ATR_REC, NM_WART_ATR_REC,  ID_APTEKI) VALUES (3, '00', 'Nie podano oddzia³u NFZ', 1);
UPDATE OR INSERT INTO WART_ATR_REC (ID_ATR_REC, WART_ATR_REC, NM_WART_ATR_REC,  ID_APTEKI) VALUES (3, '0X', 'Oddzia³ X - p³atne 100%', 1);

UPDATE FAKTURY_REF SET 
LISTA_REF = '00;01;02;03;04;05;06;07;08;09;10;11;12;13;14;15;16;AT;BE;BG;CH;CY;CZ;DE;DK;EE;ES;FI;FR;GB;GR;HU;IE;IS;IT;LI;LT;LU;LV;MT;NL;NO;PT;RO;SE;SI;SK;'
WHERE ID_APTEKI = #ID_APTEKI# AND ID_FAKTURY_REF in (1,2);

update or INSERT INTO LISTY_ODPL (ID_LISTY, ID_ODPLATN, ATRYBUTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO, KOLEJNOSC, IFUPDUSER, ID_APTEKI) VALUES ('2', '1', 'G__WE____', '01.01.2021', '01.02.3000', '10', 'USER', '1');
update or INSERT INTO LISTY_ODPL (ID_LISTY, ID_ODPLATN, ATRYBUTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO, KOLEJNOSC, IFUPDUSER, ID_APTEKI) VALUES ('3', '1', 'G__WE____', '01.01.2021', '01.01.3000', '10', 'USER', '1');
update or INSERT INTO LISTY_ODPL (ID_LISTY, ID_ODPLATN, ATRYBUTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO, KOLEJNOSC, IFUPDUSER, ID_APTEKI) VALUES ('4', '1', 'G__WE____', '01.01.2021', '01.01.3000', '10', 'USER', '1');
update or INSERT INTO LISTY_ODPL (ID_LISTY, ID_ODPLATN, ATRYBUTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO, KOLEJNOSC, IFUPDUSER, ID_APTEKI) VALUES ('5', '1', 'G__WE____', '01.01.2021', '01.01.3000', '10', 'USER', '1');
update or INSERT INTO LISTY_ODPL (ID_LISTY, ID_ODPLATN, ATRYBUTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO, KOLEJNOSC, IFUPDUSER, ID_APTEKI) VALUES ('6', '1', 'G__WE____', '01.01.2021', '01.01.3000', '10', 'USER', '1');
update or INSERT INTO LISTY_ODPL (ID_LISTY, ID_ODPLATN, ATRYBUTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO, KOLEJNOSC, IFUPDUSER, ID_APTEKI) VALUES ('21', '2', 'GW_WE____', '01.01.2021', '01.01.3000', '10', 'USER', '1');
update or INSERT INTO LISTY_ODPL (ID_LISTY, ID_ODPLATN, ATRYBUTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO, KOLEJNOSC, IFUPDUSER, ID_APTEKI) VALUES ('24', '1', 'G__WE____', '01.01.2021', '01.01.3000', '10', 'USER', '1');
update or INSERT INTO LISTY_ODPL (ID_LISTY, ID_ODPLATN, ATRYBUTY, OBOWIAZUJE_OD, OBOWIAZUJE_DO, KOLEJNOSC, IFUPDUSER, ID_APTEKI) VALUES ('25', '1', 'G__WE____', '01.01.2021', '01.01.3000', '10', 'USER', '1');

update or INSERT INTO WART_ATR_REC (ID_ATR_REC, WART_ATR_REC, NM_WART_ATR_REC, IFUPDUSER, ID_APTEKI) VALUES ('2', 'WE', 'Weteran poszkodowany', 'SYSDBA', '1');

SET TERM ^ ;
EXECUTE block as BEGIN 
if (#ID_APTEKI#<10800) then 
begin
update or INSERT INTO WZR_Z_WIERSZ (ID_WZR_ZEST, WIERSZ, NAPIS, NAPIS2, ATRYBUTY, ID_ODPLATNOSC, IFUPDUSER, ID_APTEKI) VALUES ('7', '30', 'Z', 'WE', '_V_WE____', NULL, 'SYSDBA', '1');
update or INSERT INTO WZR_Z_WIERSZ (ID_WZR_ZEST, WIERSZ, NAPIS, NAPIS2, ATRYBUTY, ID_ODPLATNOSC, IFUPDUSER, ID_APTEKI) VALUES ('7', '31', 'N', 'WE', '_N_WE____', NULL, 'SYSDBA', '1');
end
END ^
SET TERM ; ^



delete from rzdst where data<'1.1.1901' and sztuk_jp=0;
commit;


SET TERM ^ ;
EXECUTE block as declare ia integer;
BEGIN 
if (not exists(select*from zdst where data_zamkn is not null))then 
 /*for select id_apteki from ogolne into ia do  --rezyguje z pharmoni*/
 EXECUTE PROCEDURE ustaw_data_zamkn(#ID_APTEKI#);  
END^


EXECUTE block as BEGIN
if (not exists(select*from zdst where id_zam is not null))then 
begin
RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
execute statement "
merge into zdst t using 
(SELECT z.id_zam,d.ID_DOSTAWY,d.ID_APTEKI FROM  DOSTAWY d JOIN ZAMINFO z on z.id_braki=d.id_braki and z.id_apteki=d.id_apteki and (z.id_kontrahenci=d.id_kontrahenci or z.id_hurtowni=d.id_kontrahenci) ) d
 on t.ID_ZAM is NULL and d.ID_DOSTAWY = t.ID_DOSTAWY and d.ID_APTEKI = t.ID_APTEKI
 WHEN MATCHED THEN UPDATE SET t.ID_ZAM=d.id_zam
 ";
RDB$SET_CONTEXT('USER_SESSION','IFROZP',0); 
end
END^
SET TERM ; ^

COMMIT;

delete from filtry where NAZWA = 'Zakres' and BAZA = 'DOKUMENTY' and ID_FILTRY <> '508';

UPDATE TABLICE SET 
FILTR_OUT = '((id_skrypty between 1 and 900000 and 1=:Jestem) or (id_skrypty between 900001 and 1000000 and 99=:Jestem)) and
ifupddate+3>:czas and (SELECT COUNT(*) FROM SKRYPTY_DLA d LEFT JOIN APT_SL s on d.PO_SL_STALE = s.PO_SL_STALE and s.ID_SL_STALE=-1  WHERE d.ID_SKRYPTY=SKRYPTY.ID_SKRYPTY AND s.ID_APTEKI=:User)>0 or id_skrypty=1000001'
WHERE TABLICA = 'SKRYPTY';

update or INSERT INTO UPROBJ (ID_UPROBJ, ID_UPROBJ_GROUP, NAZWA, OPIS, OBJ, IFUPDDATE, IFUPDUSER, ID_APTEKI, IFINSUSER, IFINSDATE)
 VALUES (67, 6, 'Ekspedycja: Dopuszczone przekroczenie efedryny', 'Ekspedycja - blokada przekroczenia iloœci psychoaktywnych
Nadrzêdn¹ jest blokada w ''Parametry ogólne'' » ''Sprzeda¿'' - 
''Blokuj przekroczenie sprzeda¿y Pseudoepherinum''', 'EkspEfed', '2012-10-12 18:05:12', 'SYSDBA', '0', NULL, NULL);

INSERT INTO PRAWA (ID_APTEKI, ID_USER, ID_OBJ, PRAWO)
SELECT u.ID_APTEKI,u.ID_USERS,67,12 from USERS u
where grupa=1 and not EXISTS(SELECT p.ID_USER FROM  PRAWA p WHERE u.ID_APTEKI  = p.ID_APTEKI and u.ID_USERS = p.ID_USER and p.ID_OBJ = 67);


SET TERM ^ ;
EXECUTE block as BEGIN
if (not exists(select 1 from wersja where wersja>130.11) and #ID_APTEKI#>99) then 
 begin
 execute statement "
/* chwilowo wracam czy cos nie wyjdzie starego*/
insert into ETAKSACJE  (ID_SPRZEDAZ,ID_APTEKI,KLUCZ,status,kasa,opis)
select s.ID_SPRZEDAZ,s.ID_APTEKI,'','K',t.NR_KASY,'zwrot zlozonej'
 from sprzedaz s LEFT join TRANZAKCJE t on t.DATA = s.DATA and t.ID_TRANZAKCJE =  s.ID_TRANZAKCJE and t.ID_APTEKI = s.ID_APTEKI
where s.id_apteki=#ID_APTEKI# and s.data>'1.1.2019' and id_towary=0 and sztuk<0 and s.id_recepta is not null
 and not exists (select*from ETAKSACJE e where s.id_apteki=e.id_apteki and s.id_sprzedaz=e.id_sprzedaz)
 and (select idsp from HIST_KOREKTY(s.ID_APTEKI,s.ID_SPRZEDAZ) order by wersja desc rows 2 to 2)=s.ID_SPRZEDAZ
 and exists (select*from sprzedaz e where s.id_apteki=e.id_apteki and data='31.12.1899' and (select idsp from HIST_KOREKTY(s.ID_APTEKI,s.ID_SPRZEDAZ) order by wersja desc rows 1)=e.id_sprzedaz) 
 and exists (select*from HIST_KOREKTY(s.ID_APTEKI,s.ID_SPRZEDAZ) join ETAKSACJE e on e.status='W' and s.id_apteki=e.id_apteki and e.id_sprzedaz=idsp)";
 
 execute statement "
/*etaksacje*/ 
insert into ETAKSACJE  (ID_SPRZEDAZ,ID_APTEKI,KLUCZ,status,kasa,opis,tryb)   
select s.ID_SPRZEDAZ,s.ID_APTEKI,r.numer,iif(r.numer='9','Z','K'),t.NR_KASY,'Odtworzona, Ref: '||trim(TRAILING 0 from round(s.WARTOSC + s.TAKSA - s.ODPLATNOSC - s.DOPLATa,2)),s.tryb 
 from sprzedaz s LEFT join TRANZAKCJE t on t.DATA = s.DATA and t.ID_TRANZAKCJE =  s.ID_TRANZAKCJE and t.ID_APTEKI = s.ID_APTEKI
 join recepta r on s.id_apteki=r.id_apteki and s.id_recepta=r.id_recepta and r.kod_srodka is null and numer is not null and r.ATRYBUTY NOT similar to 'GW%|GP%'
where s.id_apteki=#ID_APTEKI# and s.data>'1.1.20' and s.tryb in ('S','R','N') and id_recepta is not null and t.PARAGON <> 'B' and not exists
 (select*from ETAKSACJE e where s.id_apteki=e.id_apteki and s.id_sprzedaz=e.id_sprzedaz)" ;

 execute statement "
 /*korekty - zwroty */
insert into ETAKSACJE  (ID_SPRZEDAZ,ID_APTEKI,KLUCZ,status,kasa,opis,tryb)  
select ID_SPRZEDAZ,ID_APTEKI,K,s,NR_KASY,op,tryb from (
select (select max(wersja) from  hist_korekty(s.ID_APTEKI,s.ID_SPRZEDAZ)) mawer,
 s.ID_SPRZEDAZ,s.ID_APTEKI,r.numer k,'K' s,t.NR_KASY,'Odtworzona, Ref: '||trim(TRAILING 0 from round(s.WARTOSC + s.TAKSA - s.ODPLATNOSC - s.DOPLATa,2)) op,s.tryb 
 from sprzedaz s LEFT join TRANZAKCJE t on t.DATA = s.DATA and t.ID_TRANZAKCJE =  s.ID_TRANZAKCJE and t.ID_APTEKI = s.ID_APTEKI 
 join recepta r on s.id_apteki=r.id_apteki and s.id_recepta=r.id_recepta and kod_srodka is null and numer<>'9' and r.ATRYBUTY NOT similar to 'GW%|GP%'
where s.id_apteki=#ID_APTEKI# and s.data>'1.1.20' and s.tryb in ('Z') and id_recepta is not null and t.PARAGON <> 'B' and not exists
 (select*from ETAKSACJE e where s.id_apteki=e.id_apteki and s.id_sprzedaz=e.id_sprzedaz)  
) z where exists (select*from  hist_korekty(z.ID_APTEKI,z.ID_SPRZEDAZ) where IDSP=z.id_sprzedaz and wersja=z.mawer ) 
and exists (select*from hist_korekty(z.ID_APTEKI,z.ID_SPRZEDAZ) mi left join ETAKSACJE e on mi.idsp=e.id_sprzedaz where e.id_sprzedaz is not null)";
 end

END^

EXECUTE block as BEGIN
if (not exists(select 1 from wersja where wersja>130.49) and #ID_APTEKI#>99) then 
begin -- cuz okazuje sie ze moga byc puste przypadek kubala   od .50 do usuniecia
RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
execute statement "
merge into rzdst t using 
(select distinct r.id_apteki,r.atrybuty,r.kod_srodka,s.data,rz.id_towary,rz.id_sprzedaz from recepta r
join sprzedaz s on r.id_apteki=s.id_apteki and r.id_recepta=s.id_recepta
join rzdst rz on r.id_apteki=rz.id_apteki and rz.id_sprzedaz=s.id_sprzedaz
where r.kod_srodka>'' and r.atrybuty like 'GW%') d
 on d.id_towary = t.id_towary and d.ID_APTEKI = t.ID_APTEKI and t.id_sprzedaz=d.id_sprzedaz and t.WN_IDP is null 
 
 WHEN MATCHED THEN UPDATE SET t.WN_IDP=(select WN_IDP from ceny_towary where ID_APTEKI=d.ID_APTEKI and id_towary=d.id_towary 
    and id_ceny=3 and DECYZYJNA='U' and wn_kod=d.kod_srodka and obowiazuje_od<=d.data order by obowiazuje_od desc rows 1) 
 ";
RDB$SET_CONTEXT('USER_SESSION','IFROZP',0); 
end
END^

/* musi byc po del duble bloz , ale zasadniczo to chyba byla jednorazowa akcja - na razie wylaczam
EXECUTE block as BEGIN
execute statement "
merge into tw_klas k using 
(SELECT t.id_apteki,t.id_towary,c.wartosc from towary t 
  join cbt_klas c on c.id_cbt=t.id_cbt and c.id_klasyfikacje=3
  where (t.smopl_rap='T' or t.ser_podl='T') and t.id_apteki=#ID_APTEKI#) t  
  on t.id_towary=k.id_towary and t.id_apteki=k.id_apteki and k.id_klasyfikacje=3 and k.wartosc<>t.wartosc
WHEN MATCHED THEN UPDATE SET k.wartosc=t.wartosc
";
END^
*/
SET TERM ; ^
commit;


update epruf_raporty set ifinsdate=data,ifinsuser='START' where id_apteki=#ID_APTEKI# and data<cast('today' as date) and ifinsdate is null
 and data=(select max(data) from epruf_raporty where id_apteki=#ID_APTEKI# and data<cast('today' as date));

update dostawcy d set faktura_maska=trim(iif(id_kontrahenci=525240957,'*.XML','*V*.XML')) /* if,case daje ten sam rozmiar pola bez trim robi³o '*.XML  ' */
where d.id_apteki=#ID_APTEKI# and d.zaznacz='T' /*and upper(faktura_maska) is distinct from '*V*.XML'*/
and 1=(select iif(dyskietka like '%<?xml%',1,0) from dostawy y where  y.id_kontrahenci=d.id_kontrahenci and y.data>'today'-60 and char_length(dyskietka)>0 order by data desc rows 1);
/* pojedyczne przypadki z mejl? przestawialo
and exists (select 'XML' from dostawy y where y.id_apteki=d.id_apteki and y.id_kontrahenci=d.id_kontrahenci and y.data>'today'-60 and dyskietka like '%<?xml%');
*/

select RDB$SET_CONTEXT('USER_SESSION','IFROZP',1) from rdb$database;
update dostawcy set zam_typ=null where id_apteki=#ID_APTEKI# and zam_typ=5 and zaznacz is distinct from 'T';
select RDB$SET_CONTEXT('USER_SESSION','IFROZP',0) from rdb$database;

update Z_TYPY_CEN SET ODCH_DOL = null, ODCH_GORA = null where id_typy_cen=3;

update ogolne set datafarm=replace(datafarm,'IndeksBazyl=Kod.Wart/1
','') where id_apteki=#ID_APTEKI#;

update ogolne set datafarm=replace(datafarm,'CenaZakupu=Cen.Netto/4','CenaZakupu=Cen.Netto/2') where id_apteki=#ID_APTEKI#;
update ogolne set datafarm=replace(datafarm,'CenaZakupuB=Cen.Brutto/4','CenaZakupuB=Cen.Brutto/2') where id_apteki=#ID_APTEKI#;

/* nie wiem czy to dzia³a a na galenie moze nie przechdzic z powodu daty platnosci w 130.512*/
update dostawy set IFUPDUSER=IFINSUSER,ifupddate='now' where IFUPDUSER='SYSDBA' and data>'1.1.2021' and coalesce(IFINSUSER,'SYSDBA')<>'SYSDBA' and id_apteki=#ID_APTEKI#;

update users set ifupddate='now' where id_apteki=#ID_APTEKI# and ifupddate>(select ifinsdate from SYNCZTB s where s.ID_SYNC=11 and pole='OSTRZEZENIA');

delete from cbt_klas where  id_klasyfikacje in(3,6) and wartosc='0';

update or INSERT INTO TABLICE (TABLICA, KOLEJNOSC, GLOBALNA) VALUES ('SYNCCBT', '1', 'T');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'SYNCCBT', 'ID_CBT', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'SYNCCBT', 'ID_APTEKI', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'SYNCCBT', 'K3', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'SYNCCBT', 'K6', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'SYNCCBT', 'K7', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'SYNCCBT', 'K15', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'SYNCCBT', 'K22', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'SYNCCBT', 'K24', 'B', '1', '1');

update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('16', 'SYNCCBT', 'ID_CBT', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('16', 'SYNCCBT', 'ID_APTEKI', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('16', 'SYNCCBT', 'K3', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('16', 'SYNCCBT', 'K6', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('16', 'SYNCCBT', 'K7', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('16', 'SYNCCBT', 'K15', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('16', 'SYNCCBT', 'K22', 'B', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('16', 'SYNCCBT', 'K24', 'B', '1', '1');


update or INSERT INTO TABLICE (TABLICA, KOLEJNOSC, GLOBALNA) VALUES ('CBT_ZAPYTANIA', '2', 'N');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'CBT_ZAPYTANIA', 'ID_APTEKI', 'O', '2', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'CBT_ZAPYTANIA', 'ID_CBT', 'O', '2', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'CBT_ZAPYTANIA', 'IFINSDATE', 'O', '2', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'CBT_ZAPYTANIA', 'IFINSUSER', 'O', '2', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'CBT_ZAPYTANIA', 'IFUPDUSER', 'O', '2', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'CBT_ZAPYTANIA', 'ILOSC', 'O', '2', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'CBT_ZAPYTANIA', 'KOMENTARZ', 'O', '2', '1');

update or INSERT INTO TABLICE (TABLICA, KOLEJNOSC, GLOBALNA) VALUES ('OPAKOWANIA', '6', 'N');
update or INSERT INTO TABLICE (TABLICA, KOLEJNOSC, GLOBALNA) VALUES ('ETAKSACJE', '6', 'N');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'ETAKSACJE', 'ID_APTEKI', 'O', '6', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'OPAKOWANIA', 'ID_APTEKI', 'O', '6', '1');

DELETE FROM SYNCZTB WHERE ID_SYNC = '11' AND TABLICA = 'DOSTAWY' AND POLE = 'DYSKIETKA';

UPDATE OGOLNE set AUTO_AKT_GEN = 'N' where id_apteki=#ID_APTEKI#; /*wylaczenie aktualizacji generatorow przy synchornizacji*/

update or INSERT INTO CENY_TOWARY (id_apteki,ID_TOWARY, ID_CENY, OBOWIAZUJE_OD, DECYZYJNA, WN_KOD) VALUES (#ID_APTEKI#,'-1', '3', '01.12.2021', 'D', 'P.100.PL');
update or INSERT INTO CENY_TOWARY (id_apteki,ID_TOWARY, ID_CENY, OBOWIAZUJE_OD, DECYZYJNA, WN_KOD) VALUES (#ID_APTEKI#,'-1', '3', '01.12.2021', 'D', 'P.101.PL');
update or INSERT INTO CENY_TOWARY (id_apteki,ID_TOWARY, ID_CENY, OBOWIAZUJE_OD, DECYZYJNA, WN_KOD) VALUES (#ID_APTEKI#,'-1', '3', '01.12.2021', 'D', 'P.100.WK');
update or INSERT INTO CENY_TOWARY (id_apteki,ID_TOWARY, ID_CENY, OBOWIAZUJE_OD, DECYZYJNA, WN_KOD) VALUES (#ID_APTEKI#,'-1', '3', '01.12.2021', 'D', 'P.101.WK');


/* pobranie synccbt*/
DELETE from SYNCLOGIN WHERE ID_SYNC=10 and IFUPDDATE > '21.10.2021' and #ID_APTEKI# <> 1
 and exists(select*from ogolne where id_apteki=#ID_APTEKI# and wersja<130.279); 

delete FROM PROD_ZPOSP a where data_od='1.1.21' and data_do='31.12.21'
 and exists(select*FROM PROD_ZPOSP where kod_srodka=a.kod_srodka and data_od='1.1.21' and data_do='30.11.21');
update PROD_ZPOSP a set data_do='30.11.21' where kod_srodka like 'P.10%PM'  and data_od='1.1' and data_do='31.12' and #ID_APTEKI#>1;
update PROD_ZPOSP a set data_do='30.11.21' where kod_srodka in ('P.096','P.096.H','P.096.Z')  and data_od='1.1' and data_do='31.12' and #ID_APTEKI#>1;

update kontrahenci set nip=(select*from trim_pole(replace(replace(nip,' ',''),',',''))) where 
 nip not similar to '([A-Z]{2}|(PL|[0-9]{2})([0-9]|[-]){7,})(U{0,1}|([0-9]|[A-Z]){0,2}|[0-9][0-9A-Z+*])[0-9]{1,}([A-Z]{0,1}|(B[0-9]{2}){0,1}) *'
 and nip<>(select*from trim_pole(replace(replace(nip,' ',''),',','')))
 and id_kontrahenci=left((select*from TYLKO_CYFRY(coalesce(nullif(nip,''),-1))),9) ;

/* obowiazkowy za 2p/marca ew juz od 2p/stycznia */
update FAKTURY_REF set FORMAT_EKSP = 'H' where ID_APTEKI=#ID_APTEKI# and ID_FAKTURY_REF=1 and cast('today' as date)>'26.3.22';

select RDB$SET_CONTEXT('USER_SESSION','IFROZP',1) from rdb$database;
update ceny_towary set obowiazuje_do='30.11.2021' where wn_kod like 'P.10%.PM' and id_towary=-1 and obowiazuje_do<>'30.11.2021';
update ceny_towary set obowiazuje_do='30.11.2021' where wn_kod like 'P.10%.PM' and obowiazuje_do is null and id_apteki=#ID_APTEKI# and cast('today' as date)>'1.12.21';

update ceny_towary c set obowiazuje_do=cast('today' as date)-1 where ID_APTEKI=#ID_APTEKI# and ID_APTEKI<>100 and obowiazuje_od>='1.12.2021' 
 and coalesce(obowiazuje_do,timestamp'1.1.3000')>'today' and wn_kod not in ('','100%') 
 and not exists (select*from PROD_ZPOSP where c.obowiazuje_od between data_od and data_do and kod_srodka=c.wn_kod);
select RDB$SET_CONTEXT('USER_SESSION','IFROZP',0) from rdb$database;

update users set PASS_DATE = '1.1.3000',LAST_PASS=null,PRZETW_OSOBOWYCH=NULL,nazwa='oferty' where lower(nazwa)='oferty' and ID_APTEKI = #ID_APTEKI#;
update users set id_users=100 where nazwa='oferty' and id_users<>100 and ID_APTEKI = #ID_APTEKI# and not exists(select*from users where id_users=100 and ID_APTEKI = #ID_APTEKI#);
UPDATE USERS SET PRZETW_OSOBOWYCH = NULL, NFZID  = NULL WHERE ID_APTEKI = #ID_APTEKI# AND ID_USERS in (2,3);

update jednostki j set nazwa='OP.' where  upper(j.nazwa) similar to '(O|0)P.?' and j.nazwa<>'OP.' and j.ID_APTEKI = #ID_APTEKI#; /*dodac jako trig*/

update etaksacje set status='Z' where papier='G' and status in ('S') and char_length(klucz)<15 and id_apteki=#ID_APTEKI# ; /*jw?*/

delete from klas_sl where id_klasyfikacje in (24,22,18,13,12,11,6,4,3,1,-10,-11,-12);

UPDATE TAKSY SET MAX_RYCZ = '10' WHERE ID_POST_ZL = '15' AND OBOWIAZUJE_OD = '04.10.2014';

update or INSERT INTO TRANZ_OPISY (ID_TRANZ_OPISY, NM_TRANZ_OPISY, ID_APTEKI, SKROT) VALUES ('-3', 'Blik', '1', 'b');

update users set nazwisko=replace(replace(replace(nazwisko,'tech.','technik '),'TECH.','technik '),'  ',' ') where lower(nazwisko) like 'tech.%' and aktywny='T' and id_apteki=#ID_APTEKI#; 
update users set nazwisko=replace(replace(nazwisko,' farm',' farm.'),' FARM',' farm.') where lower(nazwisko) like '% farm%' and lower(nazwisko) not like '% farm.%' and aktywny='T' and id_apteki=#ID_APTEKI#; 

update ogolne set napr_dtzamk=(select min(data) from wersja where wersja>=130.12) where napr_dtzamk is null and id_apteki=#ID_APTEKI# ;

update opakowania set st_wysl=-5 where st_wysl=-1 and dataw<'today' and status<>'U' and id_apteki=#ID_APTEKI#; 
update opakowania set st_wysl=-5 where st_wysl=-1 and (KOD='' or SERIA='' or IDENT='' or DWS='') and id_apteki=#ID_APTEKI#; 
update opakowania set st_wysl=-6 where st_wysl in (-1,-2,-3) and id_sprzedaz is not null and IFINSDATE<'1.1.21' and opis not like 'Pomy%' and id_apteki=#ID_APTEKI#;

update or INSERT INTO TABLICE (TABLICA, KOLEJNOSC, GLOBALNA) VALUES ('EPRUF_LEKI', '1', 'T');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'EPRUF_LEKI', 'DAWKA', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'EPRUF_LEKI', 'EAN', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'EPRUF_LEKI', 'ID_APTEKI', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'EPRUF_LEKI', 'BLOZ', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'EPRUF_LEKI', 'NAZWA', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'EPRUF_LEKI', 'POSTAC', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'EPRUF_LEKI', 'OPAKOWANIE', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'EPRUF_LEKI', 'KRAJ', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'EPRUF_LEKI', 'PRODUCENT', 'I', '1', '1');

update or INSERT INTO TABLICE (TABLICA, KOLEJNOSC, GLOBALNA) VALUES ('RAP_GIF', '1', 'T');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'RAP_GIF', 'DAWKA', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'RAP_GIF', 'EAN', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'RAP_GIF', 'NAZWA', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'RAP_GIF', 'ID', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'RAP_GIF', 'IDZB', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'RAP_GIF', 'ID_APTEKI', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'RAP_GIF', 'POSTAC', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'RAP_GIF', 'OPAKOWANIE', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'RAP_GIF', 'DATA', 'I', '1', '1');


UPDATE DOSTAWCY SET ZORZ_MASKA = 'od*.xml' WHERE ID_KONTRAHENCI = '879001716' AND ZORZ_MASKA is null and id_apteki=#ID_APTEKI# ;
UPDATE DOSTAWCY SET ZORZ_MASKA = 'oz_gif*.xml' WHERE ID_KONTRAHENCI = '634012544' AND ZORZ_MASKA is null and id_apteki=#ID_APTEKI# ;
UPDATE DOSTAWCY SET ZORZ_MASKA = 'zorz*.xml' WHERE ID_KONTRAHENCI = '646289243' AND ZORZ_MASKA is null and id_apteki=#ID_APTEKI# ;
UPDATE DOSTAWCY SET ZORZ_MASKA = 'zorz*.xml' WHERE ID_KONTRAHENCI = '946240959' AND ZORZ_MASKA is null and id_apteki=#ID_APTEKI# ;

update or INSERT INTO TABLICE (TABLICA, KOLEJNOSC, GLOBALNA) VALUES ('PROD_ZPOSP_GRUPY', '1', 'T');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'PROD_ZPOSP_GRUPY', 'KOD_SRODKA', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'PROD_ZPOSP_GRUPY', 'DATA_OD', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'PROD_ZPOSP_GRUPY', 'DATA_DO', 'I', '1', '1');
update or insert INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'PROD_ZPOSP_GRUPY', 'ID_APTEKI', 'I', '1', '1');

UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.089.00', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.089.01', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.096.00', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.096.01', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.097', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.098P', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.100', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.101', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.123', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.129.00', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.129A.01', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.135', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.138', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.139', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.139A', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.140', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.140A', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.140B', '2023-01-01', '2023-12-31');
UPDATE OR INSERT INTO PROD_ZPOSP_GRUPY (KOD_SRODKA, DATA_OD, DATA_DO) VALUES ('P.095', '01.01.2023', '31.12.2023');


/*to zadziala przy kolejnym wgrywaniu*/
delete from epruf_leki where id_apteki is distinct from 1 and raport is distinct from 'T' and exists(select*from epruf_leki where id_apteki=1) and #ID_APTEKI#>99;

delete from SYNCZTB where tablica='PRZESUNIECIA';

delete from filtry where #ID_APTEKI#<>1 and BAZA = 'BRAKI' and nazwa containing 'defektariu' and coalesce(ifinsdate,'1.1.2000')<'31.10.2022';

UPDATE KONTRAHENCI set NM_KONTRAHENCI = 'ASPEN PHARMA IRELAND LIMITED', NIP = '5263116808', NAZWA_PELNA = 'ASPEN PHARMA IRELAND LIMITED', PESEL = NULL, UPUST = NULL, EMAIL = NULL, TELEFON = NULL, KARTA_WNIOSKI = NULL, KARTAW_OD = NULL, KARTAW_DO = NULL, KIMPORT = NULL, TYP_CENY = '3', DNI_PLATN = NULL, NIE_BRAC = NULL, KARTAW_KODSR = NULL, KARTAW_MIEJSCE = NULL, HASLO = NULL, POTWIERDZONY = NULL, FV_TYP = NULL, SMOPL_TYP = 'FZH', SMOPL_IDP = '5263116808', SMOPL_MDTYP = NULL, SMOPL_MDIDP = 'IE', ID_KS = '857936' 
WHERE ID_KONTRAHENCI = '526311680' and nip like '%26311680%'  and (nip<>'5263116808' or coalesce(SMOPL_TYP,'') <> 'FZH') and (coalesce(centralny,'N')='N' or 99=#ID_APTEKI#);
insert into adresy (ID_KONTRAHENCI) select ID_KONTRAHENCI from KONTRAHENCI where ID_KONTRAHENCI = '526311680' and not exists(select*from adresy where ID_KONTRAHENCI = '526311680') ;
UPDATE ADRESY a SET LP = '1', KOD = '', POCZTA = '', WOJEWODZTWO = NULL, POWIAT = NULL, GMINA = NULL, MIASTO = 'One George’s Quay Plaza, Dublin 2, Ireland', ULICA = '', NR_DOMU = '', NR_LOKALU = '' 
WHERE ID_KONTRAHENCI = '526311680' AND LP = '1' and coalesce(miasto,'') not like 'One George’s%' and exists(select*from kontrahenci where id_kontrahenci=a.id_kontrahenci and nip like '%26311680%'); 
UPDATE KONTRAHENCI SET NM_KONTRAHENCI = 'ASTRAZENECA AB', NIP = 'PL5263241726', NAZWA_PELNA = 'ASTRAZENECA AB', PESEL = NULL, UPUST = NULL, EMAIL = NULL, TELEFON = NULL, KARTA_WNIOSKI = NULL, KARTAW_OD = NULL, KARTAW_DO = NULL, KIMPORT = NULL, TYP_CENY = '3', DNI_PLATN = NULL, NIE_BRAC = NULL, KARTAW_KODSR = NULL, KARTAW_MIEJSCE = NULL, HASLO = NULL, POTWIERDZONY = NULL, FV_TYP = NULL, SMOPL_TYP = 'FZH', SMOPL_IDP = '5263241726', SMOPL_MDTYP = NULL, SMOPL_MDIDP = 'SE', ID_KS = '914333'
WHERE ID_KONTRAHENCI = '526324172' and nip like '%26324172%'  and (nip<>'PL5263241726' or coalesce(SMOPL_TYP,'') <> 'FZH') and (coalesce(centralny,'N')='N' or 99=#ID_APTEKI#);
insert into adresy (ID_KONTRAHENCI) select ID_KONTRAHENCI from KONTRAHENCI where ID_KONTRAHENCI = '526324172' and not exists(select*from adresy where ID_KONTRAHENCI = '526324172') ;
UPDATE ADRESY a SET LP = '1', KOD = '', POCZTA = '', WOJEWODZTWO = NULL, POWIAT = NULL, GMINA = NULL, MIASTO = '15185 Sodertalje, Szwecja', ULICA = '', NR_DOMU = '', NR_LOKALU = '' 
WHERE ID_KONTRAHENCI = '526324172' AND LP = '1' and coalesce(miasto,'') not like '15185 Sodertalje%' and exists(select*from kontrahenci where id_kontrahenci=a.id_kontrahenci and nip like '%26324172%');


commit;

SET TERM ^ ;
EXECUTE block as
declare st varchar(50);
declare st1 varchar(50);
BEGIN
  for select RDB$TRIGGER_NAME,RDB$RELATION_NAME from RDB$TRIGGERS r where RDB$TRIGGER_NAME similar to 'DELS#_%|UPDS#_%' escape '#' and 
  (not exists(select *  from RDB$RELATION_FIELDS where RDB$FIELD_NAME = 'ID_APTEKI' and RDB$VIEW_CONTEXT is null and RDB$RELATION_NAME=r.RDB$RELATION_NAME)
   or trim(RDB$RELATION_NAME) similar to 'AANA%|TMP#_%|OFERTY|OFERTY_CENY|OFERTY_KLAS|PRZESUNIECIA|RAPORTY|REZERWACJA|EPRUF_USL|SYNCERR|SYNCLOGIN|SKASOWANE|SYNCREKORD|SYNCTOW|ZAOKR_SPOS' escape '#') 
 into st,st1 do
	begin
    execute statement 'DROP TRIGGER ' || st; 
    execute statement 'delete from skasowane where tablica=''' ||st1|| ''''; 
	end
END^

EXECUTE block as BEGIN
if (not exists(select*from ogolne where id_apteki=#ID_APTEKI# and WERSJA>130.479)) then 
execute statement 'merge into cbt using (select id_cbt,iif(typ=''REF'',''T'',''N'') typ from cbt left join typ_leku_cbt (id_cbt,''today'') on 0=0) t
on #ID_APTEKI# not in (1,99) and cbt.id_cbt=t.id_cbt and COALESCE(zamawiaj,''N'')<>typ WHEN MATCHED THEN UPDATE SET zamawiaj=typ';
END^

EXECUTE block as BEGIN
execute statement 'merge into sprzedaz s using 
(select DISTINCT id_apteki,id_sprzedaz,wn_idp from rzdst where wn_idp is not null and data>=''1.1.2023'') r
 on s.ID_APTEKI=r.ID_APTEKI and s.id_sprzedaz=r.id_sprzedaz and s.data>=''1.1.2023'' and s.ID_ZAMIENNIK is NULL 
 WHEN MATCHED THEN UPDATE SET s.ID_ZAMIENNIK=wn_idp';
END^
SET TERM ; ^

commit;

update towary set dni_min=30 where dni_min>30 and id_apteki=#ID_APTEKI#;

delete from oferty_klas where id_klasyfikacje in (1,2);
delete from tw_klas where id_klasyfikacje in (2) and id_apteki=#ID_APTEKI#;



delete from CENY_TOWARY where id_apteki=#ID_APTEKI# and ID_TOWARY=-1 and obowiazuje_do is null and wn_kod>'' and wn_kod<>'100%'
 and exists (select*from ogolne where id_apteki=#ID_APTEKI# and WNIOSKI_BEZ_UMOWY='N'); 

DELETE FROM WART_ATR_REC WHERE ID_ATR_REC = '2' AND WART_ATR_REC = 'E '; 

select RDB$SET_CONTEXT('USER_SESSION','IFROZP',1) from rdb$database;
insert INTO TOWARY_WNIOSKI (
  ID_APTEKI,
  ID_TOWARY,
  ID_UMOWY,
  ID_PROD)
SELECT DISTINCT c.ID_APTEKI,c.ID_TOWARY,p.ID_UMOWY, c.WN_IDP
from CENY_TOWARY c
LEFT join PROD_HANDL p on p.ID_PROD = c.WN_IDP
WHERE c.WN_IDP is not null and p.ID_UMOWY is not null
and exists(select*from WNIOSKI_UMOWY r where r.od_dnia>='1.1.2023' and r.kod=p.ID_UMOWY)
and not exists (select*from TOWARY_WNIOSKI where ID_TOWARY<>-1);
select RDB$SET_CONTEXT('USER_SESSION','IFROZP',0) from rdb$database;

update or INSERT INTO TOWARY_WNIOSKI (ID_APTEKI, ID_TOWARY, ID_UMOWY, ID_PROD) VALUES (#ID_APTEKI#, '-1', '', '0');


update FAKTURY_REF set xmlnadawca=id_apteki,KOD_W_KASIE=(select X2IAPT from FAKTURY_REF  where id_faktury_ref=1 and id_apteki=#ID_APTEKI#)
  where ID_FAKTURY_REF=2 and nullif(xmlnadawca,'kod apteki') is null and id_apteki=#ID_APTEKI#;

UPDATE OGOLNE o SET o.WNIOSKI_TYP = 'S' where o.WNIOSKI_TYP not in ('S','P','E') and o.id_apteki=#ID_APTEKI#;
UPDATE OGOLNE o SET o.WNIOSKI_TYP = 'P' where cast('today' as date)>='1.7.2023' and o.id_apteki=#ID_APTEKI#;

SET TERM ^ ;
EXECUTE block as BEGIN if (exists(select 1 from RDB$EXCEPTIONs where RDB$EXCEPTION_NAME='KASCBT')) then begin
execute statement 'DROP EXCEPTION KASCBT';
RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
delete from cbt where id_cbt<1000000 and not exists (select*from cbt_vat where id_cbt=cbt.id_cbt) and not exists (select*from cbt_listy where id_cbt=cbt.id_cbt);
RDB$SET_CONTEXT('USER_SESSION','IFROZP',0);
end end^

EXECUTE block as BEGIN
if (not exists(select*from ogolne where id_apteki=#ID_APTEKI# and WERSJA>130.559)) then 
begin
RDB$SET_CONTEXT('USER_SESSION','IFROZP',1);
execute statement "merge into opakowania o using 
(select distinct r.id_apteki,r.id_sprzedaz,min(r.id_zdst)id_zdst from zdst z
left join dostawy d on z.id_apteki=d.id_apteki and z.id_dostawy=d.id_dostawy and d.korekta_do is null
left join rzdst r on z.id_apteki=r.id_apteki and z.id_zdst=r.id_zdst
where z.id_apteki=#ID_APTEKI# and z.data>='1.6.2023' 
group by r.id_apteki,r.id_sprzedaz having count(*)=1) r  
  on o.id_apteki=r.id_apteki and o.id_sprzedaz=r.id_sprzedaz and o.id_zdst is null
WHEN MATCHED THEN UPDATE SET o.id_zdst=r.id_zdst , o.IFUPDDATE=o.IFUPDDATE+0.000001";
RDB$SET_CONTEXT('USER_SESSION','IFROZP',0);
end
END^

SET TERM ; ^


delete from opakowania where seria||ident similar to '%[a-z]%'  and id_sprzedaz is null and ifinsdate between '1.1.2023' and '25.6.2023' and id_apteki=#ID_APTEKI#;

UPDATE TRANZAKCJE SET NR_KASY='-1',ID_USER='-1' WHERE DATA='09.01.1900' AND ID_TRANZAKCJE='1' AND ID_APTEKI=#ID_APTEKI#
  and (NR_KASY is distinct from -1 or ID_USER is distinct from -1);


update or INSERT INTO FILTRY (ID_FILTRY, NAZWA, BAZA, SQL, ROZWIN, FILTR_SZCZ, ID_APTEKI) VALUES 
('178', 'NEUCA rekomendowane', 'Towary', 'qw@T NEUCA_REKOMENDACJA.AKT = :AKT1 ', 'N', 'N', 1);

update or INSERT INTO ZAW_FILTRY (ID_FILTRY, KOLUMNA, POLE, OPERATOR, WARTOSC, LACZNIK, POLE2, ROZWIJAJ, ZAPRZECZ, ID_APTEKI, WERSJA, ID_KL_AP)
 VALUES ('178', '1', 'AKT', '=', 'T', NULL, NULL, 'N', 'N', '1', NULL, NULL);

Update or INSERT INTO LISTY (ID_LISTY, NM_LISTY, ID_APTEKI) VALUES (27, 'Senior 65+',1);
update or INSERT INTO LISTY (ID_LISTY, NM_LISTY, ID_APTEKI) VALUES (29, 'Dzieci 18- bezp³atnie', 1);
update or INSERT INTO WART_ATR_REC (ID_ATR_REC, WART_ATR_REC, NM_WART_ATR_REC,  ID_APTEKI) VALUES (4, 'D ', 'Dziecko 18-', 1);
UPDATE WART_ATR_REC SET NM_WART_ATR_REC = 'Senior 65+' WHERE ID_ATR_REC = '4' AND WART_ATR_REC = 'S ';

DELETE from SYNCLOGIN WHERE ID_SYNC=10 and IFUPDDATE > '31.08.2023' and #ID_APTEKI# <> 1
 and exists(select*from ogolne where id_apteki=#ID_APTEKI# and wersja<130.56999); 

/* obowiazkowy za '09.23 */
update FAKTURY_REF set FORMAT_EKSP = 'I' where ID_APTEKI=#ID_APTEKI# and ID_FAKTURY_REF=1 and cast('today' as date)>'11.9.23';

delete from TOW_LISTY t where id_listy=21 and OBOWIAZUJE_OD <> '01.01.2000' and ID_APTEKI=#ID_APTEKI#
and exists (select*from TOW_LISTY t2 where t.id_apteki=t2.id_apteki and t.id_towary=t2.id_towary and t2.id_listy=21 and OBOWIAZUJE_OD='01.01.2000' and OBOWIAZUJE_DO='01.01.3000');


UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '10.00', '35.000000', '0.35', '1', '01.11.2023');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '20.00', '25.000000', '3.85', '1', '01.11.2023');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '40.00', '15.000000', '6.35', '1', '01.11.2023');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '80.00', '10.000000', '9.35', '1', '01.11.2023');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '160.00', '5.000000', '13.35', '1', '01.11.2023');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '640.00', '2.7500000', '17.35', '1', '01.11.2023');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '9999999999.00', '2.0000', '30.55', '1', '01.11.2023');
/*
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '10.00', '35.000000', '0.45', '1', '01.01.2025');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '20.00', '25.000000', '3.95', '1', '01.01.2025');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '40.00', '15.000000', '6.45', '1', '01.01.2025');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '80.00', '10.000000', '9.45', '1', '01.01.2025');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '160.00', '5.000000', '13.45', '1', '01.01.2025');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '640.00', '2.7500000', '17.45', '1', '01.01.2025');
UPDATE OR  INSERT INTO DEGRESJA (DEGRESJA, GRANICA, MARZA, KWOTA, ID_APTEKI, OBOWIAZUJE_OD) VALUES ('-1', '9999999999.00', '2.0000', '30.65', '1', '01.01.2025');
*/

update or INSERT INTO TABLICE (TABLICA, KOLEJNOSC, GLOBALNA) VALUES ('TOWARY_WNIOSKI', '1', 'N');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'TOWARY_WNIOSKI', 'ID_APTEKI', 'O', '1', '1');
update or INSERT INTO TABLICE (TABLICA, KOLEJNOSC, GLOBALNA) VALUES ('SMOPL', '0', 'N');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'SMOPL', 'ID_APTEKI', 'O', '0', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('11', 'EPRUF_RAPORTY', 'ID_APTEKI', 'O', '1', '1');

update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'KLAS_SL', 'ID_APTEKI', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'KLAS_SL', 'ID_KLASYFIKACJE', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'KLAS_SL', 'WARTOSC', 'I', '1', '1');
update or INSERT INTO SYNCZTB (ID_SYNC, TABLICA, POLE, INOUT, KOLEJNOSC, ID_APTEKI) VALUES ('10', 'KLAS_SL', 'OPIS', 'I', '1', '1');
	
DELETE from SYNCLOGIN WHERE ID_SYNC=10 and IFUPDDATE > '30.11.2023' and #ID_APTEKI# <> 1
 and exists(select*from ogolne where id_apteki=#ID_APTEKI# and wersja<130.63); 
  
execute procedure napraw_poz_rzdst; 

 
/* ****************** koniec czesci zasadniczej ****************** */
execute procedure upr_all; 
select 1 from GENERUJ_TRIGGERY(0); /* uwaga na zmiany PK w tablicach wowczas (1) */
execute procedure nowa_wersja_koniec;
Update or Insert into WERSJA (wersja) values (130.64);
commit;

SELECT rdb$set_context('USER_SESSION', 'v','1') FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Uruchamiam procedury naprawcze i kontrolne - mo¿na pracowaæ') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14(44);


UPDATE TABLICE SET FILTR_OUT = '99=:user' WHERE TABLICA = 'SMOPL';
UPDATE TABLICE SET FILTR_OUT = '99=:user' WHERE TABLICA = 'TOWARY_WNIOSKI';
UPDATE TABLICE SET FILTR_OUT = '99=:user and DT_WAZN is not null' WHERE TABLICA = 'RECEPTURA';
UPDATE TABLICE SET FILTR_OUT = '99=:user and alerty>''''' WHERE TABLICA = 'OPAKOWANIA';
UPDATE TABLICE SET FILTR_OUT = '99=:user' WHERE TABLICA = 'TOWARY_WNIOSKI';
UPDATE TABLICE SET FILTR_OUT = '99=:user and ID_OSOZ is not null' WHERE TABLICA = 'RZDST';
UPDATE TABLICE SET FILTR_OUT = '99=:user' WHERE TABLICA = 'EPRUF_RAPORTY';
commit;
SELECT rdb$set_context('USER_SESSION', 'v',(
select 1 from(select*from WERSJA order by wersja desc rows 2 to 2) where wersja<130.63 
 and exists (select*from synclogout where id_apteki<>99 and id_sync=11 and data>'today'-5)
 and #ID_APTEKI# in (10021,10026,10028,10056,10423,10023,10025,10061,10122,10121,10125,10126,10127,10425,10129,10130,10426,10430)
)) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Wyœlij jednorazowo brakuj¹ce dane do Pharmonii

 (Pharmonia musi byæ w wersji co najmniej 130.64) 

 Uruchom teraz drug¹ Apteka+ wyœlij "Dane operacyjne [11]", po wys³aniu powróæ tutaj aby kontynuowaæ
 (musisz wcisn¹æ TAK)') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14(0);
SELECT rdb$set_context('USER_SESSION', 'v',(
select 1 from(select*from WERSJA order by wersja desc rows 2 to 2) where wersja<130.63 
 and exists (select*from synclogout where id_apteki<>99 and id_sync=11 and data>'today'-5)
 and #ID_APTEKI# in (10021,10026,10028,10056,10423,10023,10025,10061,10122,10121,10125,10126,10127,10425,10129,10130,10426,10430)
 and not exists (select*from synclogout where id_apteki<>99 and id_sync=11 and data>'now'-0.02)
)) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k','         NIE WYS£A£EŒ DANYCH !!!

 Uruchom teraz drug¹ Apteka+ wyœlij "Dane operacyjne [11]", po wys³aniu powróæ tutaj aby kontynuowaæ
 (musisz wcisn¹æ TAK)') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14(0);
UPDATE TABLICE SET FILTR_OUT = null WHERE TABLICA = 'OPAKOWANIA';
UPDATE TABLICE SET FILTR_OUT = null WHERE TABLICA = 'RECEPTURA';
UPDATE TABLICE SET FILTR_OUT = null WHERE TABLICA = 'SMOPL';
UPDATE TABLICE SET FILTR_OUT = null WHERE TABLICA = 'TOWARY_WNIOSKI';
UPDATE TABLICE SET FILTR_OUT = '(ID_APTEKI=:User and ifupddate>:czas and id_sprzedaz>=200000000) 
 or (ID_APTEKI=:Jestem and ID_APTEKI<>99 and (ifupddate>:czas or data=''09.01.1900'' or data=''31.12.1899''))'
WHERE TABLICA = 'RZDST';
UPDATE TABLICE SET FILTR_OUT = null WHERE TABLICA = 'EPRUF_RAPORTY';
commit;


select 1 from na_fb3(0);
execute procedure NAPRRPE('1.1.2020'); /*od ostatniej wersji*/
execute procedure del_duble_bloz;
execute procedure nowa_wersja_naprawy;
commit;
execute procedure nowa_wersja_kontrole; 

SELECT rdb$set_context('USER_SESSION', 'v',(select 1 from AKT_STAWKI_VAT ('today') where kod='C' and vat=5)) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Uwaga b³êdnie ustawiona stawka VAT 5% - sprawdŸ stawki') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

SELECT rdb$set_context('USER_SESSION', 'v',(select 1 from RDB$database where not exists(select 1 from RDB$INDEX_SEGMENTS where RDB$INDEX_NAME='ZDST_DTZ'))) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Mo¿na pracowaæ - nale¿y jeszcze dodaæ indeksy ZDST 
zamknij program, uruchom ponownie i WCZYTAJ SKRYPT index-zdst.sql') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

SELECT rdb$set_context('USER_SESSION', 'v',(select 1 from RDB$database where not exists(select 1 from RDB$INDEX_SEGMENTS where RDB$INDEX_NAME='ETAKSACJE_SYNC'))) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Mo¿na pracowaæ - nale¿y jeszcze dodaæ indeksy eTaksacje
 praktycznie mo¿liwe tylko przy wy³¹czonych stanowiskach
zamknij program, uruchom ponownie i WCZYTAJ SKRYPT index-etaks.sql') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

SELECT rdb$set_context('USER_SESSION', 'v',(select 1 from RDB$database where not exists(select 1 from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$relation_name = 'VAT7ATR'))) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Mo¿na pracowaæ bez rejestrów VAT - nale¿y jeszcze dodaæ PK VAT7ATR 
 praktycznie mo¿liwe tylko przy wy³¹czonych stanowiskach
 zamknij program, uruchom ponownie i WCZYTAJ SKRYPT index-pk-vat.sql') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;


SELECT rdb$set_context('USER_SESSION', 'v',(select cast(abs(35-(select count(*) from VAT7ATR))as int) from RDB$database)) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Nieprawid³owa liczba wierszy w s³owniku VAT7ATR '||rdb$get_context('USER_SESSION', 'v') ) FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

SELECT rdb$set_context('USER_SESSION', 'v',(select 1 from RDB$database where 2<>(select count(*) from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$constraint_name similar to 'PROD_HANDL_PK *|OSOZ_TOWARY_PK *'))) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Mo¿na pracowaæ - nale¿y jeszcze dodaæ PROD_HANDL_PK i OSOZ_TOWARY_PK
 praktycznie mo¿liwe tylko przy wy³¹czonych stanowiskach
 zamknij program, uruchom ponownie i WCZYTAJ SKRYPTY index-prodhandl.sql, index-osoz.sql') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

SELECT rdb$set_context('USER_SESSION', 'v',(select 1 from RDB$database where 2<>(select count(*) from rdb$relation_constraints where rdb$constraint_type='PRIMARY KEY' and rdb$constraint_name similar to 'PLANY_MIES_PK *|OFERTY_CENY_PK *'))) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Mo¿na pracowaæ - aby prawid³owo dzia³a³ modu³ zamówieñ
 nale¿y jeszcze dodaæ OFERTY_CENY_PK praktycznie mo¿liwe przy wy³¹czonych stanowiskach
 zamknij program, uruchom ponownie i WCZYTAJ SKRYPTY index-ofertyceny.sql') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

SELECT rdb$set_context('USER_SESSION', 'v',(select 1 from wnioski_umowy where do_dnia>'today' and id_kom is null rows 1)) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Nowa wersja realizacji wniosków na umowê - wykonaj procedury opisane w instrukcji' ) FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

/*
SELECT rdb$set_context('USER_SESSION', 'v',(select 1 from wnioski_umowy where do_dnia+15>'today' rows 1)) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Uwaga od wersji 130.55 na realizacji zleceñ wysy³any/drukowany jest EAN z karty
 towaru - nale¿y zweryfikowaæ zgodnoœæ EAN ze spasowanym ''Id produktu'' 
 w przypadku w¹tpliwoœci usun¹æ EAN (lepiej bez ni¿ z b³êdnym!)
 EAN/UDI niewymagane do 30.09.2023' ) FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;
*/

SELECT rdb$set_context('USER_SESSION', 'v',(SELECT rdb$get_context('USER_SESSION', 'k1o') FROM RDB$DATABASE)) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Zmieniono strukturê OSOZ_TOWARY 
Wymagane ponowne pobrania raportowanych  
Zarz¹dzanie » e-PRUF i OSOZ » OSOZ lista raportowanych leków' ) FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

SELECT rdb$set_context('USER_SESSION', 'v',(SELECT rdb$get_context('USER_SESSION', 'k2o') FROM RDB$DATABASE)) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Zmieniono strukturê OFERTY 
Wymagane ponowne pobranie ofert hurtowni' ) FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

SELECT rdb$set_context('USER_SESSION', 'v',(select 1 from(select*from WERSJA order by wersja desc rows 2 to 2) where wersja<=130.4999 and exists (select*from tranzakcje t where id_osoz is not null and data>'today'-15))) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',' Od wersji 130.50 zmieniony sposób wysy³ki OSOZ
 upewnij siê ¿e w Tlo s¹ dodane zadania OSOZWYSLIJ (ew. zwiêksz czêstotliwoœæ)') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;

SELECT rdb$set_context('USER_SESSION', 'v',(select count(*) from receptura r left join sprzedaz s on  s.id_apteki=r.id_apteki and s.id_sprzedaz=r.id_sprzedaz join etaksacje e on e.ID_APTEKI=s.ID_APTEKI and e.id_sprzedaz=s.id_sprzedaz and e.status='W' where r.id_apteki=#ID_APTEKI# and dt_odb is not null and dt_odb>=cast('TODAY' as date)-1000 and s.data<dt_odb-1 and s.data<>'31.12.1899')) FROM RDB$DATABASE;
SELECT rdb$set_context('USER_SESSION', 'k',rdb$get_context('USER_SESSION', 'v') ||' z³o¿one (data odbioru) do poprawy') FROM RDB$DATABASE;
execute procedure nowa_wersja_p14;



