*    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *    *
*
* program cte transakce z datastore a podle cisel uctu zapise eskacka na datastore
*
*  2019-02-14 - producty se stahnou komplet a patchuji/postuji se jen potrebne
*  2022-04-05 - GET transaction filtruje kind#"DTC" a isnull(bill_header) a description#"VYUCT"
*             - transakce se nectou po jednotlivych dnech, jsou filtrovany na datum > date()-POCET_DNI
*             - do sk_pol se posilaji jen polozky s nenulovou cenou
*  2022-12-07 - nazvy se posilaji z ktexty.meno1
*  2022-12-07 - nazvy produktu se posilaji v delce 64 zn. (protoze datastore vic nevezme), uvozovka nahrazena apostrofem 
*
*    *    *    *    *    *    *    *    *    *    *    *      #> ver. 2022-12-12 <#       *    *    *    *    *    *    *    *    *    *    *    *    *
#DEFINE PGM_VERZE                                               "ver. 2022-12-12"


* proc se patchuje do historic-transactions? protoze transactions opravit nejde
* zrusen patch produktu
* mezi dvojitymi komentovymi radky ********************** jsou upravy pro velim

#DEFINE POCET_DNI    7
#DEFINE CRLF         CHR(13)+CHR(10)
#DEFINE PAGESIZE     555
#DEFINE JMENOLOGU    "SK2DATASTORE"

small_log(PGM_VERZE, JMENOLOGU)
DO (LOWER(JUSTPATH(sys(16))) + "\ppgm_http")

SET REPROCESS TO AUTOMATIC
DO clos_data
o_set_point = SET("POINT")
SET POINT TO "."
ACTIVATE SCREEN 

stahni_transakce()


******************************************************************************************************************************
******************************************************************************************************************************
SELECT transactions
DELETE FOR amount = 0
******************************************************************************************************************************
******************************************************************************************************************************


vezmi_data_konzumaci()

*? http_get("sk/crud/bill_headers")
*? http_get("sk/crud/bill_payments")
*? http_get("sk/crud/bill_items")

posli_receptury()

posli_eskacka()

SET POINT TO (m.o_set_point)
oznam_hotovo()
small_log("hotovo", JMENOLOGU)


*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
PROCEDURE vezmi_data_konzumaci

small_log(PROGRAM(), JMENOLOGU)
IF m.issql

    DO open_database    
    rv("ktexty", "ktexty")
    
    min_uzaverka = LEFT(TTOC(DATE() - POCET_DNI-3, 1), 10)  &&  20221030

    lsql =             "SELECT uzaverka      ,   u_cis     , u_cas      , stul       , autor     , text_sleva   FROM food600.sk_fin WHERE c_data=?m.cdata AND uzaverka>?m.min_uzaverka"
    sql_select(lsql, "ssfin", "uzaverka C(22), u_cis C(7), u_cas c(16), stul N(6,1), autor C(3), text_sleva C(11)")

    lsql =              "SELECT uzaverka     ,   u_cis    , druh_pl,       cena_pl        , mena   FROM food600.sk_plt WHERE c_data=?m.cdata AND uzaverka>?m.min_uzaverka"
    sql_select(lsql, "ssplt", "uzaverka C(22), u_cis C(7), druh_pl c(10), cena_pl N(14,2), mena C(3)")

    lsql =             "SELECT uzaverka      , u_cis     , c_karty  , nazev      , mnozstvi        , prachy        , dan       , k_odpoctu    FROM food600.sk_pol WHERE c_data=?m.cdata AND uzaverka>?m.min_uzaverka"
    sql_select(lsql, "sspol", "uzaverka C(22), u_cis C(7), c_karty I, nazev C(30), mnozstvi N(12,3), prachy N(12,2), dan N(5,3), k_odpoctu c(1) ")

    SELECT uzaverka, u_cis, LEFT(u_cas, 4) + "-" + SUBSTR(u_cas, 5,2) + "-" + SUBSTR(u_cas, 7,2) as u_cas, stul, autor, text_sleva ;
           FROM ssfin INTO CURSOR fin READWRITE

    SET RELATION TO u_cis INTO transactions
    DELETE FOR EMPTY(transactions.u_cis)
*    DELETE FOR transactions.bill_hdr # 0
    SET RELATION TO 
    INDEX on uzaverka + u_cis TAG uz_ucet

    SELECT u_cis, uzaverka, c_karty, nazev, mnozstvi, prachy, dan*100-100 as dan_sazba, prachy - (prachy / dan) as dan ;
           WHERE uzaverka + u_cis IN (SELECT uzaverka + u_cis FROM fin) AND (NOT EMPTY(k_odpoctu)) FROM sspol INTO CURSOR pol READWRITE 


******************************************************************************************************************************
******************************************************************************************************************************
DELETE FOR prachy = 0
******************************************************************************************************************************
******************************************************************************************************************************


    SELECT u_cis, uzaverka, druh_pl, cena_pl, mena ;
           WHERE uzaverka + u_cis IN (SELECT uzaverka + u_cis FROM fin) FROM ssplt INTO CURSOR plt READWRITE 

ELSE

    USE (m.fn_karty)   IN 0 NOUPDATE ALIAS karty   ORDER c_karty 
    USE (m.fn_sk_fin)  IN 0 NOUPDATE ALIAS sk_fin
    USE (m.fn_sk_plt)  IN 0 NOUPDATE ALIAS sk_plt
    USE (m.fn_sk_pol)  IN 0 NOUPDATE ALIAS sk_pol

    SELECT uzaverka, u_cis, LEFT(u_cas, 4) + "-" + SUBSTR(u_cas, 5,2) + "-" + SUBSTR(u_cas, 7,2) as u_cas, stul, autor, text_sleva ;
           WHERE uzaverka > SUBSTR(TTOC(DATE() - POCET_DNI-3, 1), 3) FROM (m.fn_sk_fin) INTO CURSOR fin READWRITE
    DELETE FOR LEFT(u_cas, 10) < LEFT(TTOC(DATE() - POCET_DNI-2, 3), 10)
    SET RELATION TO u_cis INTO transactions
    DELETE FOR EMPTY(transactions.u_cis)
    DELETE FOR transactions.bill_hdr # 0
    SET RELATION TO 
    INDEX on uzaverka + u_cis TAG uz_ucet

    SELECT u_cis, uzaverka, c_karty, nazev, mnozstvi, prachy, dan*100-100 as dan_sazba, prachy - (prachy / dan) as dan ;
           WHERE uzaverka + u_cis IN (SELECT uzaverka + u_cis FROM fin) AND (NOT EMPTY(k_odpoctu)) FROM (m.fn_sk_pol) INTO CURSOR pol READWRITE 

    SELECT u_cis, uzaverka, druh_pl, cena_pl, mena ;
           WHERE uzaverka + u_cis IN (SELECT uzaverka + u_cis FROM fin) FROM (m.fn_sk_plt) INTO CURSOR plt READWRITE 

ENDIF 
small_log(PROGRAM() + " hotovo", JMENOLOGU)


*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
PROCEDURE posli_eskacka
SELECT transactions
ACTIVATE SCREEN 
small_log(PROGRAM(), JMENOLOGU)
? "bills "
SCAN FOR EMPTY(bill_hdr)
    pocitej(20)

    SELECT fin 
    LOCATE FOR u_cis = transactions.u_cis
    IF FOUND()
        SCATTER MEMVAR 
        hdr = '"header":{ "c_kas":-111, "typ":"U", "stul":' + nx(stul,1) + ', "u_cis":' + tx(u_cis) + ', "autor":' + tx(autor) + ', "info_text":' + tx(text_sleva) + ', "c_uctu":' + nx(VAL(RIGHT(u_cis, 5))) + '}'

        SELECT plt
        pmts = '"payments":[ '
        SCAN FOR uzaverka = m.uzaverka .and. u_cis = m.u_cis
            pmts = pmts + '{"druh_pl":' + tx(druh_pl) + ', "cena_pl":' + nx(cena_pl,2) + ', "mena":' + tx(mena) + '},'
        ENDSCAN 
        pmts = LEFT(pmts, LEN(pmts)-1) + ' ]'

        SELECT pol
        itms = '"items":[ '
        SCAN FOR uzaverka = m.uzaverka .and. u_cis = m.u_cis
            itms = itms + '{"c_karty":' + nx(c_karty) + ', "prachy":' + nx(prachy,2) + ', "prachy_puv":' + nx(prachy,2) + ', "c_stredisk":88, "dan":' + nx(dan,2) + ', "dan_sazba":' + nx(dan_sazba,1) + ', "mnozstvi":' + nx(mnozstvi,3) + '},'
        ENDSCAN 
        itms = LEFT(itms, LEN(itms)-1) + ' ]'

        json = http_request("sk/write_bill", "POST", "{" + m.hdr + ", " + m.pmts + ", " + m.itms + "}")
        hdr      = get_object_item  (m.json, "header")
        bill_hdr = get_integer_item (m.hdr , "id"    )
        SELECT transactions
        GATHER FIELDS bill_hdr MEMVAR 
        json = http_request("kredit/crud/historic_transactions/" + ALLTRIM(STR(transactions.id)), "PATCH", '{"bill_header":' + nx(transactions.bill_hdr) + '}')
    ELSE
        ? "nenalezen ucet " + transactions.u_cis + " z " + SUBSTR(transactions.trans_at, 6) 
        SELECT transactions
        REPLACE u_cas WITH "neni v SK"
    ENDIF 
ENDSCAN 
small_log(PROGRAM() + " hotovo", JMENOLOGU)


*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
PROCEDURE stahni_transakce

CREATE TABLE (m.gcpri_path + "transactions") FREE ;
       (id I, client I, kind C(9), amount N(9,2), balance N(9,2), u_cis C(7), trans_at C(16), client_id C(11), bill_hdr I, u_cas C(14) )
INDEX on  id   TAG  id
INDEX on u_cis TAG u_cis

mesicek = LEFT(TTOC(DATE() - POCET_DNI, 3), 10)  && 2018-11-15
small_log(PROGRAM() + " od " + m.mesicek, JMENOLOGU)
ACTIVATE SCREEN 
? "transactions (" + ALLTRIM(STR(PAGESIZE)) + ") " + m.mesicek + "  "
FOR page_no = 1 TO 9999
    json = http_get("kredit/crud/transactions?page_size=" + ALLTRIM(STR(PAGESIZE)) + "&page=" + ALLTRIM(STR(m.page_no)) ;
         + "&filter{transacted_at.gte}=" + m.mesicek + "&filter{bill_header.isnull}=true&filter{-kind}=DTC&filter{-description}=VYUCT")    && odfiltrovany pepinova pocitadla dotaci

    next_page = get_string_item (m.json, "next")
    pocet_radku = json_rowcount(json)
    ?? nx(m.page_no) + " "
    FOR ii = 1 TO PAGESIZE+3
       id       =    get_integer_item (m.json, "id"            , ii)
       client   =    get_integer_item (m.json, "client"        , ii)
       bill_hdr =    get_integer_item (m.json, "bill_header"   , ii)
       u_cis    =    get_string_item  (m.json, "description"   , ii)
       trans_at =    get_string_item  (m.json, "transacted_at" , ii)
       kind     =    get_string_item  (m.json, "kind"          , ii)
       amount   = - VAL(get_string_item (m.json, "amount"      , ii))
       balance  = - VAL(get_string_item (m.json, "balance"     , ii))
       IF m.id # 0 .and. ATC("VYUCT", m.u_cis) + ATC("DTC", m.kind) = 0
           u_cis = LEFT(ALLTRIM(m.u_cis), 7)
           INSERT INTO transactions FROM MEMVAR 
       ENDIF 
    ENDFOR 

    IF ISNULL(m.next_page)
        EXIT 
    ENDIF 
ENDFOR 
small_log(PROGRAM() + " hotovo ", JMENOLOGU)


********** vraci formatovane cislo s pevnou delkou **********
FUNCTION nx2____ (nxcislo, nxdelka, nxdes_mist)
IF EMPTY(m.nxdes_mist)
    nxdes_mist = 0
ENDIF 
RETURN PADL(STRTRAN(ALLTRIM(STR(IIF(ISNULL(m.nxcislo), 0, m.nxcislo), 12, m.nxdes_mist)), ",", "."), nxdelka)


*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  
PROC posli_receptury

small_log(PROGRAM(), JMENOLOGU)
SELECT DISTINCT c_karty, PADR(nazev, 64) as nazev, 00000000000 as id, "POST  " as co_s_tim FROM pol INTO CURSOR pol_karty READWRITE 

ACTIVATE SCREEN 
? "products (" + ALLTRIM(STR(PAGESIZE)) + ") "
FOR page_no = 1 TO 9999
    json = http_get("food/crud/products?page_size=" + ALLTRIM(STR(PAGESIZE)) + "&page=" + ALLTRIM(STR(m.page_no)))
    next_page = get_string_item (m.json, "next")
    ?? nx(m.page_no) + " "
    FOR ii = 1 TO PAGESIZE+3
       id       = get_integer_item (m.json, "id"                , ii)
       c_karty  = get_integer_item (m.json, "stock_card_number" , ii)
       nazev    = get_string_item  (m.json, "name"              , ii)
       IF m.c_karty # 0
           LOCATE FOR c_karty = m.c_karty
           IF FOUND()
               REPLACE id WITH m.id, co_s_tim WITH IIF(  nazev = m.nazev, "nic", "PATCH" )
           ELSE
               co_s_tim = "PATCH"
               INSERT INTO pol_karty FROM MEMVAR 
           ENDIF 
       ENDIF 
    ENDFOR 

    IF ISNULL(m.next_page)
        EXIT 
    ENDIF 
ENDFOR 

******************************************************************************************************************************
******************************************************************************************************************************
*                 nahrazeni nazvu z ktexty.meno1
SELECT pol_karty
SCAN
    SCATTER FIELDS c_karty MEMVAR 
    SELECT ktexty
    LOCATE FOR c_karty = m.c_karty
    IF FOUND() .and. .not. ISNULL(meno1)
        SELECT pol_karty
        REPLACE nazev WITH STRTRAN(ALLTRIM(ktexty.meno1), '"', "'")
    ENDIF 
ENDSCAN 
******************************************************************************************************************************
******************************************************************************************************************************

SELECT pol_karty
SCAN
    radek_productu = '{ "stock_card_number":' + ALLTRIM(STR(c_karty, 13)) + ', "name": "' + ALLTRIM(nazev) + '", "price": 99.9, "tax_rate": 21, "range":0 } '
    DO CASE
    CASE co_s_tim = "PATCH"
*        ?? "U" &&& + nazev
*        json = http_request("food/crud/products/" + ALLTRIM(STR(pol_karty.id)), "PATCH", m.radek_productu)

    CASE co_s_tim = "POST"
        ?? "I" &&& + nazev
        json = http_request("food/crud/products/"                             , "POST" , m.radek_productu)
        id = get_integer_item(m.json, "id")
        REPLACE id WITH m.id

    ENDCASE 
ENDSCAN 
small_log(PROGRAM() + " hotovo", JMENOLOGU)
