campo-sirio/src/bs/bs0300.cpp
Mattia Tollari d6f1411baf Patch level : 12.0 638
Files correlati     : bs
Commento            : Aggiunti riferimenti fatturazione elettronica
2018-10-23 16:46:34 +02:00

1720 lines
49 KiB
C++
Raw Blame History

#include "bs0300b.h"
#include <applicat.h>
#include <automask.h>
#include <config.h>
#include <ODBCrset.h>
#include <progind.h>
#include <reputils.h>
#include <tabutil.h>
#include <utility.h>
#include <validate.h>
#include "../mg/mglib.h"
#include "../cg/cglib01.h"
#include "../ve/velib.h"
#include <doc.h>
#include <rdoc.h>
#include "bs0.h"
#include "../fe/felib.h"
#include <clifo.h>
#include <cfven.h>
#include <rcausali.h>
#include <map>
#include <vector>
#include "bsutility.h"
#include "urldefid.h"
#define BS_DTULTAGG "DtUltAgg"
///////////////////////////////////////////////////////////
// Utility
///////////////////////////////////////////////////////////
const TString my_origin()
{
static const TString my_orig = ini_get_string(CONFIG_DITTA, "BS", "Origine", "2");
return my_orig;
}
const TString their_origin()
{
static const TString their_orig(1, (ini_get_int(CONFIG_DITTA, "BS", "Origine", 1) == 1 ? 2 : 1) + '0');
return their_orig;
}
const TString clifo_add_note(TLocalisamfile& cfv, TString& note)
{
TString codnote = cfv.get(CFV_CODNOTE);
// Parto da un valore altissimo! Prima di questa modifica la dimensione di questo campo era 2
TLocalisamfile tabcom(LF_TABCOM);
static int cod = 0;
if (cod == 0)
{
TRectype n(LF_TABCOM);
n.put("COD", "NOT");
if (n.read(tabcom, _isgteq) == NOERR)
{
// Vado a prendere l'ultimo valore in NOT
while (n.get("COD") == "NOT")
n.next(tabcom);
n.prev(tabcom);
cod = n.get_int("CODTAB") + 1;
}
else
cod = 1;
}
TRectype nota(LF_TABCOM);
nota.put("COD", "NOT");
if (codnote.blank())
{
codnote.cut(0) << cod++;
}
nota.put("CODTAB", codnote);
for (int i = 0; i <= 12; i++)
{
TString field = "S"; field << i;
nota.put(field, note.left(tabcom.curr().length(field)));
note.ltrim(tabcom.curr().length(field));
if (note.blank())
break;
}
nota.write_rewrite(tabcom);
return codnote;
}
TObject* TSknet_cache::key2obj(const char* key)
{
const char tipo = *key;
const long codice = atol(key + 1);
return new TAnagrafica(LF_CLIFO, tipo, codice);
}
const TAnagrafica& TSknet_cache::anag(char tipo, long codice)
{
CHECKD((tipo == 'C' || tipo == 'F') && codice > 0L, "Codice cli/for non valido", codice);
TString8 key;
key.format("%c%06ld", tipo, codice);
const TAnagrafica* a = (const TAnagrafica*)objptr(key);
return *a;
}
///////////////////////////////////////////////////////////
// TSknet_mask
///////////////////////////////////////////////////////////
bool TSknet_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
{
if (e == fe_modify && !o.empty())
{
const TFieldref* fr = o.field();
if (fr && fr->name() == "CODCAUSC")
{
// Configura righe aggiuntive causale corrispettivi
TRecord_array rcaus(o.get(), LF_RCAUSALI);
if (!rcaus.exist(15) && yesno_box(TR("Si desidera configurare la causale per il collegamento a BeeStore?")))
{
const char* codice[] = { "BEECN", "BEEBM", "BEECC", "BEEAS", "BEEAL", NULL };
const char* descr[] = { "Contanti", "Bancomat", "Carta di credito", "Assegni", "Altro", NULL };
TTable dpn("%DPN");
for (int i = 0; codice[i]; i++)
{
dpn.put("CODTAB", codice[i]);
dpn.put("S0", descr[i]);
dpn.write();
TRectype& row = rcaus.row(15 + i, true);
row.put(RCA_CODDESC, codice[i]);
row.put(RCA_DESC, descr[i]);
}
rcaus.rewrite();
TRectype caus(LF_CAUSALI);
caus.put(RCA_CODCAUS, o.get());
caus.edit();
}
}
}
if (e == fe_button)
{
if (o.dlg() == DLG_EDIT)
bss().clean();
else if(o.dlg() == DLG_RECALC)
{
static TMask m ("Reset data importazione", 1, 30, 5);
m.add_button_tool(DLG_OK, "~Conferma", TOOL_OK);
m.add_button_tool(DLG_CANCEL, "Annulla", TOOL_CANCEL);
// Avevo voglia di scrivere spaghetti code stamattina
int start = 101;
static const int date = start++, hours = start++, minutes = start++, seconds = start++;
m.add_date(date, 0, "Data", 1, 1);
m.add_string(hours, 0, "Ora ", 1, 2, 2);
m.add_string(minutes, 0, ":", 8, 2, 2);
m.add_string(seconds, 0, ":", 12, 2, 2);
time_t rt = time(NULL);
struct tm * now = localtime(&rt);
m.set(date, TDate(TODAY));
m.set(hours, now->tm_hour);
m.set(minutes, now->tm_min);
m.set(seconds, "00");
while (m.run() == K_ENTER)
{
if(yesno_box("Sei sicuro di voler resettare la data di importazione?"))
{
char new_date[50];
sprintf_s(new_date, sizeof(new_date),
"%d%02d%02d %02d:%02d:%02d.999",
m.get_date(date).year(),
m.get_date(date).month(),
m.get_date(date).day(),
m.get_int(hours),
m.get_int(minutes),
m.get_int(seconds));
ini_set_string(CONFIG_DITTA, "BS", "LAST_IMPORT", new_date);
break;
}
}
}
}
return true;
}
void TSknet_mask::autoload()
{
// Carica i valori default dei parametri dal [bs] in ditta,ini
FOR_EACH_MASK_FIELD(*this, i, f)
{
const TFieldref* fr = f->field();
if (fr != NULL)
f->set(ini_get_string(CONFIG_DITTA, "bs", fr->name()));
}
}
void TSknet_mask::autosave() const
{
// Salva i valori dei parametri in [bs] in ditta,ini
FOR_EACH_MASK_FIELD(*this, i, f)
{
const TFieldref* fr = f->field();
if (fr != NULL)
ini_set_string(CONFIG_DITTA, "bs", fr->name(), f->get());
}
}
///////////////////////////////////////////////////////////
// TSknet_sync
///////////////////////////////////////////////////////////
typedef bool TFieldEvaluator(const TISAM_recordset& rec, const char* fldname, const char* expr, TVariant& var);
// Carica da BeeStore i record con Origine=their_origin(), cio<69> generati da lui ed eventualmente aggiorna i corrispondenti in Campo
void TSknet_sync::load_their_origine(TISAM_recordset& out_set, const char* in_table, const TString_array& pairs)
{
TString str(255);
str << "SELECT ";
FOR_EACH_ARRAY_ROW(pairs, f, row)
str << row->get(0) << ',';
str.rtrim(1); // toglie ultima virgola
str << "\nFROM " << in_table << " WHERE (Origine=" << their_origin() << ") AND " << where_time_import() << ";";
//_log->log(0, str);
TODBC_recordset odbc(str);
odbc.connect(_dsn, _usr, _psw);
const TRecnotype n = odbc.items();
if (n > 0)
{
TLocalisamfile& file = out_set.cursor()->file();
const RecDes& rd = file.curr().rec_des();
TToken_string key_fields;
for (int i = 0; i < rd.Ky->NkFields; i++)
{
const int nf = rd.Ky[0].FieldSeq[i] % MaxFields;
key_fields.add(rd.Fd[nf].Name);
}
str.format(TR("Importazione %ld record dalla tabella %s"), n, in_table);
_log->log(0, "");
_log->log(0, str);
TProgress_monitor pi(n, str);
for (bool ok = odbc.move_first(); ok; ok = odbc.move_next())
{
if(!pi.add_status())
break;
file.zero();
TString80 cfld, bfld, def; // Campo field, BeeStore field e cut field
int ffld, tfld;
FOR_EACH_ARRAY_ROW(pairs, p, row)
{
bfld = row->get(0);
cfld = row->get();
ffld = row->get_int(); ffld--;
tfld = row->get_int(); tfld--;
def = row->get();
const int pos = key_fields.get_pos(cfld);
if (pos >= 0)
{
const TVariant& var = !odbc.get(bfld).is_empty() ? odbc.get(bfld) : (def.blank() ? NULL_VARIANT : def);
if (!var.is_null())
{
if (tfld > 0)
file.put(cfld, var.as_string().mid(ffld, tfld - ffld));
else
file.put(cfld, var.as_string());
}
if (pos == key_fields.items() - 1)
break;
}
}
int err = file.read(_isequal, _lock);
if (err == NOERR)
{
bool dirty = false;
const TDate dataagg = file.get(CLI_DATAAGG);
TDate dtultagg = odbc.get(BS_DTULTAGG).as_date();
if (!dtultagg.ok()) dtultagg = TODAY;
str = "record";
FOR_EACH_TOKEN(key_fields, f)
str << ' ' << file.get(f);
if (dtultagg >= dataagg)
{
FOR_EACH_ARRAY_ROW(pairs, r, row)
{
bfld = row->get(0);
cfld = row->get();
ffld = row->get_int(); ffld--;
tfld = row->get_int(); tfld--;
def = row->get();
if (cfld[0] >= 'A' && cfld.find("->") < 0 && key_fields.get_pos(cfld) < 0) // Aggiorno solo i campi NON chiave
{
const TString& vec = file.get(cfld);
const TString& nov = !odbc.get(bfld).is_empty() ? odbc.get(bfld).as_string() : (def.blank() ? "" : def);
if (nov != vec)
{
if (!dirty)
str << ' ' << bfld << "='" << nov << '\'';
if (tfld > 0)
file.put(cfld, nov.mid(ffld, tfld - ffld));
else
file.put(cfld, nov);
dirty = true;
}
}
}
if (dirty)
{
TRectype& rec = file.curr();
if (rec.exist(CLI_UTENTE))
rec.put(CLI_UTENTE, ini_get_string(CONFIG_DITTA, "bs", "SKImportUser"));
if (rec.exist(CLI_DATAAGG))
rec.put(CLI_DATAAGG, dtultagg);
}
else
str << " Nessuna variazione pertinente";
}
else
str << " Data di ultimo aggiornamento obsoleta";
if (dirty)
{
if (file.rewrite() != 0)
{
TString80 err; err << TR("ERRORE ") << err << TR(" aggiornando il ");
str.insert(err);
_log->log(2, str);
}
}
else
{
file.reread(_unlock);
}
}
else
if (err == _iskeynotfound)
{
bool keyfull = true;
file.zero();
FOR_EACH_ARRAY_ROW(pairs, r, row)
{
bfld = row->get(0);
cfld = row->get();
ffld = row->get_int(); ffld--;
tfld = row->get_int(); tfld--;
def = row->get();
// Controllo che il campo sia corretto
if (key_fields.get_pos(cfld) >= 0 && odbc.get(bfld).is_empty())
{
keyfull = false;
break;
}
if (cfld[0] >= 'A' && cfld.find("->"))
{
const TString& nov = !odbc.get(bfld).is_empty() ? odbc.get(bfld).as_string() : (def.blank() ? "" : def);
if (tfld > 0)
file.put(cfld, nov.mid(ffld, tfld - ffld));
else
file.put(cfld, nov);
}
}
if (keyfull && file.write() == 0)
_log->log(1, str);
else
{
TString80 msg; msg << TR("ERRORE ") << err << TR(" inserendo il ");
str.insert(msg);
_log->log(2, str);
}
}
}
}
}
void TSknet_sync::sync_table(TISAM_recordset& in_set, const char* out_table, const TString_array& fields)
{
load_their_origine(in_set, out_table, fields);
}
static TString& build_query(const char* table)
{
TString& q = get_tmp_string();
q << "USE " << table;
return q;
}
static TString& build_query(const int logicnum)
{
const TRectype rec(logicnum);
TString& q = get_tmp_string();
q << "USE " << logicnum;
if (rec.exist(CLI_UTENTE))
q << " SELECT (UTENTE!=\"" << ini_get_string(CONFIG_DITTA, "bs", "SKImportUser") << "\")";
return q;
}
void TSknet_sync::sync_table(const char* table, const char* out_table,
const TString_array& fields)
{
const TString& q = build_query(table);
TISAM_recordset set(q);
sync_table(set, out_table, fields);
}
void TSknet_sync::sync_table(const int logicnum, const char* out_table,
const TString_array& fields)
{
const TString& q = build_query(logicnum);
TISAM_recordset set(q);
sync_table(set, out_table, fields);
}
void TSknet_sync::sync_ums()
{
TString_array fields;
fields.add("CodUntMis|CODTAB");
fields.add("DSUntMis|S0");
sync_table("%UMS", "tieUntMisura", fields);
}
void TSknet_sync::sync_iva()
{
TString_array fields;
fields.add("CodIva|CODTAB");
fields.add("CodIvaSt|CODTAB");
fields.add("DSIva|S0");
fields.add("Aliquota|R0");
sync_table("%IVA", "tieIva", fields);
}
void TSknet_sync::sync_anamag()
{
TString_array fields;
fields.add("CodPadre|" ANAMAG_CODART);
fields.add("DSArticolo|" ANAMAG_DESCR);
fields.add("DSArticoloAgg|" ANAMAG_DESCRAGG "|1|70");
fields.add("CodUntMagazzino|49->UM||PZ");
fields.add("CodIva|" ANAMAG_CODIVA);
fields.add("CodLinea|" ANAMAG_GRMERC "|1|3");
fields.add("CodCategMerceologica|" ANAMAG_GRMERC);
fields.add("ArtGruppo|" ANAMAG_GRUPPOV);
fields.add("ArtConto|" ANAMAG_CONTOV);
fields.add("ArtSottoconto|" ANAMAG_SOTTOCV);
fields.add("Bloccato|" ANAMAG_SOSPESO);
TString query = build_query(LF_ANAMAG);
query << "\nJOIN " << LF_UMART << " INTO CODART==CODART";
TISAM_recordset art(query);
sync_table(art, "tieArticoli", fields);
// Sincronizzo le unit<69> di misura
{
query.cut(0) << "SELECT * from tieArticoli where Origine=" << their_origin() << " AND " << where_time_import() << ";";
//_log->log(0, query);
TODBC_recordset odbcunit(query);
odbcunit.connect(_dsn, _usr, _psw);
TProgress_monitor p(odbcunit.items(), "Aggiornamento unit<69> di misura");
for (bool go = odbcunit.move_first(); go; go = odbcunit.move_next())
{
if (!p.add_status())
break;
// Umart
TLocalisamfile umart(LF_UMART);
TRectype rumart(LF_UMART);
const TString& codpadre = odbcunit.get("CodPadre").as_string();
// Quel coglione mette codart blank e non <20> in grado di sistemarlo...
// E non so se ci sono solo spazi nel codice, quindi devo farlo a mano da codice
if (codpadre.blank())
continue;
rumart.put("CODART", codpadre);
rumart.put("NRIGA", 1);
rumart.put("UM", "PZ");
rumart.put("FC", UNO);
if (rumart.rewrite_write(umart) != NOERR)
{
// Eror!
bool tolla = true;
TString msg = "Errata importazione UM per l'articolo ";
msg << codpadre;
_log->log(1, msg);
}
}
}
{
// Controllo se esistono varianti e le aggiungo
query.cut(0) << "SELECT * FROM tieArtVarianti where origine=" << their_origin() << " AND " << where_time_import() << ";";
//_log->log(0, query);
TODBC_recordset odbc(query);
odbc.connect(_dsn, _usr, _psw);
// Apro codcorr per aggiungere i codici dei clienti
TLocalisamfile ccor(LF_CODCORR);
TRectype rccor(LF_CODCORR);
// Il primo giro svuoto CODCORR dagli articoli inseriti (sono stati importati tantissimi articoli con CODART == CODARTALT, cos<6F> facendo pulisco)
TProgress_monitor p(odbc.items(), "Pulizia Codici clienti");
for (bool go = odbc.move_first(); go; go = odbc.move_next())
{
if (!p.add_status())
break;
ccor.first(); // Useless??
rccor.zero();
const TString& codpadre = odbc.get("CodPadre").as_string();
rccor.put(CODCORR_CODART, codpadre);
rccor.put(CODCORR_NRIGA, 1);
if (codpadre.full() && ccor.read(rccor, _isequal) == NOERR)
{
while (rccor.get(CODCORR_CODART) == codpadre)
{
rccor.remove(ccor);
rccor.next(ccor);
}
}
}
for (bool go = odbc.move_first(); go; go = odbc.move_next())
{
// Lavoro sul file ISAM, pi<70> veloce
// Azzero
ccor.first(); // Useless??
rccor.zero();
bool add = true;
int riga = 1;
const TString& codpadre = odbc.get("CodPadre").as_string();
const TString& codarticolo = odbc.get("CodArticolo").as_string();
if (codpadre.blank() || codarticolo.blank())
continue;
rccor.put(CODCORR_CODART, codpadre);
rccor.put(CODCORR_NRIGA, riga);
// E quel coglione mette sempre codart == codartalt...
if (codpadre != codarticolo && ccor.read(rccor, _isequal) == NOERR)
{
while (add && rccor.get(CODCORR_CODART) == codpadre)
{
riga = rccor.get_int(CODCORR_NRIGA);
add = rccor.get(CODCORR_CODARTALT) != codarticolo;
rccor.next(ccor);
}
}
if (add)
{
rccor.zero();
rccor.put(CODCORR_CODART, codpadre);
rccor.put(CODCORR_NRIGA, riga++);
rccor.put(CODCORR_CODARTALT, codarticolo);
rccor.put(CODCORR_UM, ini_get_string(CONFIG_DITTA, "BS", "SKCodUmsDef"));
ccor.write(rccor);
}
}
}
// Conai
if (_hasConai)
{
// Apro anamag per aggiungere le informazioni sugli articoli
TLocalisamfile art(LF_ANAMAG);
TRectype rart(LF_ANAMAG);
query.cut(0) << "SELECT * FROM tieArtCONAI where origine=" << their_origin() << " AND " << where_time_import() << ";";
//_log->log(0, query);
TODBC_recordset odbc(query);
odbc.connect(_dsn, _usr, _psw);
TProgress_monitor p(odbc.items(), "Aggiornamento CONAI");
for (bool go = odbc.move_first(); go; go = odbc.move_next())
{
if (!p.add_status())
break;
art.first(); // Useless??
rart.zero();
rart.put(ANAMAG_CODART, odbc.get("Cod_PK").as_string());
if (odbc.get("Cod_PK").as_string().blank())
continue;
if (rart.read(art, _isequal) == NOERR)
{
static TString catCON;
// Metodo del cazzo, format crasha e non ho tempo, magari in un futuro sistemarlo (se non ho visto male funziona solo su linux)
TString a = odbc.get("CatAC").as_string().left(4); a.lpad(4);
TString b = odbc.get("CatAL").as_string().left(4); b.lpad(4);
TString c = odbc.get("CatCA").as_string().left(4); c.lpad(4);
TString d = odbc.get("CatLE").as_string().left(4); d.lpad(4);
TString e = odbc.get("CatPL").as_string().left(4); e.lpad(4);
TString f = odbc.get("CatVE").as_string().left(4); f.lpad(4);
catCON.cut(0) << a << b << c << d << e << f;
/*
catCON.format("%4 s%4 s%4 s%4 s%4 s%4 s",
odbc.get("CatAC").as_string().left(4), // Categoria Acciaio
odbc.get("CatAL").as_string().left(4), // Categoria Alluminio
odbc.get("CatCA").as_string().left(4), // Categoria Carta
odbc.get("CatLE").as_string().left(4), // Categoria Legno
odbc.get("CatPL").as_string().left(4), // Categoria Plastica
odbc.get("CatVE").as_string().left(4) // Categoria Vetro
);
*/
rart.put(ANAMAG_CONAISC, catCON);
rart.put(ANAMAG_CONACC, odbc.get("PesoAC").as_real()); // Peso Acciaio
rart.put(ANAMAG_CONALL, odbc.get("PesoAL").as_real()); // Peso Alluminio
rart.put(ANAMAG_CONCAR, odbc.get("PesoCA").as_real()); // Peso Carta
rart.put(ANAMAG_CONLEG, odbc.get("PesoLE").as_real()); // Peso Legno
rart.put(ANAMAG_CONPLA, odbc.get("PesoPL").as_real()); // Peso Plastica
rart.put(ANAMAG_CONVET, odbc.get("PesoVE").as_real()); // Peso Vetro
art.rewrite(rart);
}
else
// EROR! EROR!
{
bool tolla = true;
}
}
}
}
static bool ClifoEvaluator(const TISAM_recordset& rec, const char* fldname, const char* expr, TVariant& var)
{
const TAnagrafica& a = _anagr.anag(rec);
if (xvt_str_same(fldname, "Cod_PK"))
{
TLocalisamfile& cfv = rec.cursor()->file(LF_CFVEN);
TString80 codprcf = cfv.get(CFV_CODPRCF);
if (codprcf.blank() || codprcf[0] == 'C') // Anagrafica gestita da Campo
{
const char t = rec.get(CLI_TIPOCF).as_string()[0];
const long c = rec.get(CLI_CODCF).as_int();
TString8 cod_pk; cod_pk.format("C%06ld%c", c, t);
if (cod_pk != codprcf)
{
cfv.put(CFV_CODPRCF, codprcf = cod_pk);
cfv.rewrite();
}
}
var = codprcf;
return true;
}
if (xvt_str_same(fldname, "Cognome"))
{
if (a.fisica())
var = a.cognome();
return true;
}
if (xvt_str_same(fldname, "Nome"))
{
if (a.fisica())
var = a.nome();
return true;
}
if (xvt_str_same(fldname, "Indirizzo"))
{
TString ind;
ind = a.via_residenza();
if (ind.full())
{
const TString& civ = a.civico_residenza();
if (civ.full()) ind << ',' << civ;
}
const TString& loc = a.localita_residenza();
if (loc.full()) ind << ',' << loc;
ind.strip_double_spaces();
var = ind;
return true;
}
if (xvt_str_same(fldname, "Citta"))
{
var = a.comune_residenza();
return true;
}
if (xvt_str_same(fldname, "Provincia"))
{
var = a.provincia_residenza();
return true;
}
if (xvt_str_same(fldname, "ComuneNascita"))
{
var = a.comune_nascita();
return true;
}
if (xvt_str_same(fldname, "PVNascita"))
{
var = a.provincia_nascita();
return true;
}
if (xvt_str_same(fldname, "Telefono") || xvt_str_same(fldname, "Cellulare") || xvt_str_same(fldname, "CellulareSMS"))
{
const char* suff = (*fldname == 'C') ? (strlen(fldname)>9 ? "3" : "2") : "";
TString8 pref; pref << "PTEL" << suff;
TString80 tele; tele << "TEL" << suff;
TString80 str; rec.get(pref).as_string(str); str << ' ' << rec.get(tele).as_string();
str.strip_double_spaces();
char* s = str.get_buffer();
for (const char* f = s; *f; f++)
{
if (*f == ' ' || (*f >= '0' && *f <= '9'))
{
if (f > s) *s = *f;
s++;
}
}
*s = '\0';
}
if (xvt_str_same(fldname, "Tipo"))
{
var = a.fisica() ? 1 : 2;
return true;
}
if (xvt_str_same(fldname, "Cliente"))
{
const char tipocf = rec.get(CLI_TIPOCF).as_string()[0];
var = tipocf == 'C';
return true;
}
if (xvt_str_same(fldname, "Fornitore"))
{
const char tipocf = rec.get(CLI_TIPOCF).as_string()[0];
var = tipocf == 'F';
return true;
}
if (_strnicmp(fldname, "Cli_", 4) == 0)
{
const char tipocf = rec.get(CLI_TIPOCF).as_string()[0];
return tipocf != 'C';
}
if (_strnicmp(fldname, "For_", 4) == 0)
{
const char tipocf = rec.get(CLI_TIPOCF).as_string()[0];
return tipocf != 'F';
}
return false;
}
const TString& TSknet_sync::comune(const TRecordset& recset, const char* fld_cap, const char* fld_den) const
{
TString8 cap; if (fld_cap && *fld_cap) cap = recset.get(fld_cap).as_string().left(5);
TString80 den; if (fld_den && *fld_den) den = recset.get(fld_den).as_string();
return ::cap2comune(cap, den);
}
bool TSknet_sync::split_phone(const TRecordset& odbc, const char* number, TIsamfile& clifo, const char* pre, const char* num) const
{
TString pn = odbc.get(number).as_string();
if (pn.full())
{
pn.strip_double_spaces();
const int maxpref = clifo.curr().length(pre);
int split = -1;
for (int i = 0; pn[i] && i <= maxpref; i++)
{
if (!isdigit(pn[i]))
{
split = i;
break;
}
}
if (split > 1)
{
clifo.put(pre, pn.left(split));
clifo.put(num, pn.mid(split + 1));
}
else
{
clifo.put(pre, "");
clifo.put(num, pn);
}
}
return pn.full();
}
void TSknet_sync::load_clifo(const char tipocf)
{
TString str(255);
str << "SELECT * FROM tieAnagCFP WHERE [Origine]=" << their_origin() << " AND";
str << '[' << (tipocf == 'F' ? "Fornitore" : "Cliente") << "]=1 AND " << where_time_import() << ";";
TFast_isamfile clifo(LF_CLIFO);
//_log->log(0, str);
TODBC_recordset odbc(str);
odbc.connect(_dsn, _usr, _psw);
const TRecnotype n = odbc.items();
str.cut(0) << TR("Importazione ") << (tipocf == 'F' ? TR("Fornitori") : TR("Clienti"));
TProgress_monitor pi(n, str);
for (bool ok = odbc.move_first(); ok; ok = odbc.move_next())
{
if (odbc.get("Cod_PK").as_string().len() == 1)
continue;
long codcf = odbc.get(tipocf == 'F' ? "For_CodFor" : "Cli_CodCG").as_int();
if (codcf <= 0)
{
const TString& cod_pk = odbc.get("Cod_PK").as_string();
codcf = atol(cod_pk.mid(1));
}
TLocalisamfile cfv(LF_CFVEN);
if (codcf > 0)
{
clifo.put(CLI_TIPOCF, tipocf);
clifo.put(CLI_CODCF, codcf);
if (clifo.read(_isequal) != NOERR)
{
clifo.zero();
clifo.put(CLI_TIPOCF, tipocf);
clifo.put(CLI_CODCF, codcf);
}
}
else
{
// NON <20> POSSIBILE
TString err = "Attenzione <20> prensente un cliente con codice errato: "; err << odbc.get("Cod_PK").as_string() << " Non verr<72> importato.";
_log->log(2, err);
continue;
}
cfv.put(CFV_TIPOCF, tipocf);
cfv.put(CFV_CODCF, codcf);
if (cfv.read(_isequal) != NOERR)
{
cfv.zero();
cfv.put(CFV_TIPOCF, tipocf);
cfv.put(CFV_CODCF, codcf);
TString8 codprcf; codprcf.format("C%06ld%c", codcf, tipocf);
cfv.put(CFV_CODPRCF, codprcf);
}
clifo.put(CLI_RAGSOC, odbc.get("RagSoc").as_string());
clifo.put(CLI_PAIV, odbc.get("PartitaIva").as_string());
clifo.put(CLI_COFI, odbc.get("CodFiscale").as_string());
clifo.put(CLI_MAIL, odbc.get("EMail").as_string());
// Fatturazione Elettronica
clifo.put(CLI_PEC, odbc.get("PEC").as_string());
cfv.put(CFV_PADESTIN, odbc.get("CodDest").as_string());
const int tipo = odbc.get("Tipo").as_int(); // 1=Fisica; 2=Giuridica; 3=Altro
if (tipo == 1)
{
clifo.put(CLI_SESSO, odbc.get("Sesso").as_string());
clifo.put(CLI_DATANASC, odbc.get("DTNascita").as_date());
clifo.put(CLI_COMNASC, comune(odbc, "", "ComuneNascita"));
clifo.put(CLI_TIPOPERS, 'F');
}
else
clifo.put(CLI_TIPOPERS, 'G');
TToken_string indirizzo(odbc.get("Indirizzo").as_string(), ',');
TString ind = indirizzo.get(0);
TString civ = indirizzo.get();
TString loc = indirizzo.get();
if (civ.len() > 10)
{
if (loc.full())
ind << ' ' << civ;
else
loc = civ;
civ.cut(0);
}
clifo.put(CLI_INDCF, ind.left(50));
clifo.put(CLI_CIVCF, civ);
clifo.put(CLI_LOCCF, loc);
clifo.put(CLI_CAPCF, odbc.get("Cap").as_string());
// Stato
TString statoISO = odbc.get("CodStato").as_string(), stato = "";
if (statoISO.empty())
statoISO = "IT";
clifo.put(CLI_STATOPAIV, statoISO);
// Se lo stato no <20> Italia devo fare una ricerca scomoda e lenta in %STA
if (statoISO != "IT")
{
TRelation relCom(LF_TABCOM);
TRectype& partCom = relCom.curr();
partCom.zero();
partCom.put("COD", "STA");
TCursor cur(&relCom, "", 1, &partCom, &partCom);
for (cur = 0; cur.pos() < cur.items(); ++cur)
if (cur.curr().get("S10") == statoISO)
{
stato = cur.curr().get("CODTAB");
break;
}
}
clifo.put(CLI_STATOCF, stato);
// Comune
TString comune;
int errComuni;
TLocalisamfile isamComuni(LF_COMUNI);
comune = odbc.get("Citta").as_string();
isamComuni.put("STATO", stato);
isamComuni.put("COM", comune);
errComuni = isamComuni.read(_isequal);
// Se non lo trovo cambio la chiave e provo a cercarlo per Descrizione
if (errComuni != NOERR)
{
isamComuni.zero();
isamComuni.setkey(2);
isamComuni.put("DENCOM", comune.upper());
errComuni = isamComuni.read(_isequal);
comune = errComuni == NOERR ? isamComuni.get("COM") : "";
}
if(comune.blank())
clifo.put(CLI_LOCCF, odbc.get("Citta").as_string());
else
clifo.put(CLI_COMCF, comune);
split_phone(odbc, "Telefono", clifo, CLI_PTEL, CLI_TEL);
split_phone(odbc, "Cellulare", clifo, CLI_PTEL2, CLI_TEL2);
split_phone(odbc, "CellulareSMS", clifo, CLI_PTEL3, CLI_TEL3);
split_phone(odbc, "Fax", clifo, CLI_PFAX, CLI_FAX);
clifo.put(CLI_MAIL, odbc.get("EMail").as_string());
clifo.put(CLI_CODPAG, odbc.get(tipocf == 'F' ? "For_CodPagamento" : "Cli_CodPagamento").as_string());
if (_hasConai)
{
cfv.put(CFV_DATAECONAI, odbc.get("CNDataEs").as_date());
cfv.put(CFV_ESACC, odbc.get("CNEsac").as_string()); // Esenzione Acciaio
cfv.put(CFV_ESALL, odbc.get("CNEsal").as_string()); // Esenzione Alluminio
cfv.put(CFV_ESCAR, odbc.get("CNEsca").as_string()); // Esenzione Carta
cfv.put(CFV_ESPLA, odbc.get("CNEspl").as_string()); // Esenzione Plastica
cfv.put(CFV_ESLEG, odbc.get("CNEsle").as_string()); // Esenzione Legno
cfv.put(CFV_ESVET, odbc.get("CNEsve").as_string()); // Esenzione Vetro
// So bad is so good!
TString prodConai;
prodConai << (odbc.get("CNPac").as_int() == 1 ? "X" : " "); // Produttore Acciaio
prodConai << (odbc.get("CNPal").as_int() == 1 ? "X" : " "); // Produttore Alluminio
prodConai << (odbc.get("CNPca").as_int() == 1 ? "X" : " "); // Produttore Carta
prodConai << (odbc.get("CNPpl").as_int() == 1 ? "X" : " "); // Produttore Plastica
prodConai << (odbc.get("CNPle").as_int() == 1 ? "X" : " "); // Produttore Legno
prodConai << (odbc.get("CNPve").as_int() == 1 ? "X" : " "); // Produttore Vetro
cfv.put("PRODCONAI", prodConai);
cfv.put(CFV_ADDCONAI, prodConai.blank());
//cfv.put(CFV_CONAIASS, prodConai.blank()); Non c'<27> modo di sapere quando metterlo
}
cfv.put(CFV_RAGGDOC, !odbc.get("RaggDoc").as_string().blank());
TLocalisamfile cfb(LF_CFBAN);
cfb.put("TIPOCF", tipocf);
cfb.put("CODCF", codcf);
cfb.put("TIPOBAN", "V");
cfb.put("NRIGA", 1);
if (cfb.read(_isequal) != NOERR)
{
cfb.zero();
cfb.put("TIPOCF", tipocf);
cfb.put("CODCF", codcf);
cfb.put("TIPOBAN", "V");
cfb.put("NRIGA", 1);
}
TString cin, abi, cab, contcor, iban;
if (tipocf == 'C')
{
abi = odbc.get("Cli_Abi").as_string();
cab = odbc.get("Cli_Cab").as_string();
contcor = odbc.get("Cli_ContoCorr").as_string();
}
else
{
abi = odbc.get("For_Abi").as_string();
cab = odbc.get("For_Cab").as_string();
contcor = odbc.get("For_ContoCorr").as_string();
}
if (!abi.blank() && !cab.blank())
{
int err = 1;
// Calcolo il CIN
TString msg, bban;
bban << "#" << abi << cab << contcor;
for (char cin = 'A'; cin <= 'Z' && err == 1; cin++)
{
bban[0] = cin;
err = bban_check(bban, msg);
if (err == 0)
{
cin = bban[0];
break;
}
}
// Calcolo l'IBAN
if (err == NOERR)
{
err = 1;
iban.cut(0) << statoISO << "##" << bban;
for (int pp = 0; pp <= 99 && err == 1; pp++)
{
msg.format("%02d", pp);
iban.overwrite(msg, 2);
err = iban_check(iban, msg);
if (err == 0)
{
break;
}
}
}
// Abi e Cab sempre, posso anche avere solo il primo dei due
cfb.put("ABI", abi);
cfb.put("CAB", cab);
// Il conto corrente ovviamente solo se <20> giusto
if (err == NOERR)
{
cfb.put("NUMCC", contcor);
cfb.put("IBAN", iban);
}
else
{
TString msg; msg << "L'IBAN del contatto " << tipocf << " " << codcf << "non <20> corretto, verranno importati solo ABI e CAB";
cfb.put("NUMCC", "");
cfb.put("IBAN", "");
_log->log(1, msg);
}
cfb.write_rewrite();
}
// Always true
cfv.put(CFV_RAGGEFF, true);
cfv.put(CFV_ADDBOLLI, tipocf == 'C');
// Non ho capito se alla fine mi passa qua i dati o nel campo NOTE
cfv.put(CFV_ASSFIS, cache().get("%SKI", tipocf == 'C' ? odbc.get("Cli_CodIva").as_string() : odbc.get("For_CodIva").as_string(), "S6"));
// Parso il campo Note
TToken_string note(odbc.get("Note").as_string());
if (!note.blank() && note[note.len() - 1] == '|')
note.cut(note.len() - 1);
for (int i = 0; i < note.items(); i++)
{
int pipe = note.find('|');
TString token = note.get(i);
if (token.starts_with("PNE="))
{
TToken_string pne(token.mid(4), ',');
TString nonacc;
TString nonscd;
for (int k = 0; k < pne.items(); k++)
{
TToken_string pno(pne.get(k), '/');
// DA GIORNO DA MESE A GIORNO A MESE
nonacc << pno.get(0) << "-" << pno.get(1) << "," << pno.get(2) << "-" << pno.get(3) << ";";
// IL GIORNO IL MESE
nonscd << pno.get(4) << "-" << pno.get(5) << ";";
}
nonacc.cut(nonacc.len() - 1);
nonscd.cut(nonscd.len() - 1);
cfv.put(CFV_NONACCEFF, nonacc);
cfv.put(CFV_NONSCADEFF, nonscd);
}
else
if (token.starts_with("RE="))
{
// Disabled, always true by analysis
}
else
if (token.starts_with("NOTE="))
{
TString note = token.mid(5);
if (!note.blank())
cfv.put(CFV_CODNOTE, clifo_add_note(cfv, note));
}
else
if (token.starts_with("ENAMAIL="))
{
bool bymail = false;
TString email = "";
if (token.mid(8).full())
{
bymail = true;
email = odbc.get("EMail").as_string();
}
clifo.put(CLI_BYMAIL, bymail);
clifo.put(CLI_DOCMAIL, email);
}
else
if (token.starts_with("REF="))
{
clifo.put(CLI_REFERENTE, token.mid(4));
}
else
if (token.starts_with("EDOC="))
{
clifo.put(CLI_BYMAIL, true);
clifo.put(CLI_DOCMAIL, token.mid(5));
}
else
if (token.starts_with("SCONTO="))
{
cfv.put(CFV_SCONTO, token.mid(7));
}
else
if (token.starts_with("AGENT="))
{
cfv.put(CFV_CODAG, token.mid(6));
}
else
if (token.starts_with("ASSFIS="))
{
cfv.put(CFV_ASSFIS, cache().get("%SKI", token.mid(7), "S6"));
}
else
{
if (!token.blank())
{
// Han chiesto di disabilitarlo
//cfv.put(CFV_CODNOTE, clifo_add_note(cfv, token));
}
else
{
TString err = "Token non riconosciuto per il c/f ";
err << tipocf << codcf << ": ";
err << token.left(token.find('=')) << "\nQuesto dato non verr<72> importato";
_log->log(2, err);
}
}
}
TString user = ini_get_string(CONFIG_DITTA, "BS", "SKImportUser");
if (user.empty())
user = "BEESTORE";
clifo.put(CLI_UTENTE, user);
TDate dua = odbc.get(BS_DTULTAGG).as_date();
if (!dua.ok()) dua = TDate(TODAY);
clifo.put(CLI_DATAAGG, dua);
cfv.write_rewrite();
clifo.write_rewrite();
if (!pi.add_status())
break;
}
}
void TSknet_sync::sync_clifo(int cfmask)
{
if (cfmask & 1) load_clifo('C');
if (cfmask & 2) load_clifo('F');
}
void TSknet_sync::clean()
{
if (yesno_box("Vuoi svuotare il database?") == 1)
{
// Mi ricarico il tempo
set_time();
TString str;
TODBC_recordset voldemort(str);
voldemort.connect(_dsn, _usr, _psw);
// Clienti
if (ini_get_bool(CONFIG_DITTA, "BS", "SKSyncClienti"))
str << "DELETE FROM tieAnagCFP WHERE Origine=" << their_origin() << " AND Cliente=1 AND " << where_time_delete() << ";\n";
// Fornitori
if (ini_get_bool(CONFIG_DITTA, "BS", "SKSyncFornitori"))
str << "DELETE FROM tieAnagCFP WHERE Origine=" << their_origin() << " AND Fornitore=1 AND " << where_time_delete() << ";\n";
// Documenti
if (ini_get_bool(CONFIG_DITTA, "BS", "SKSyncDoc"))
{
str << "DELETE FROM tieTBolFat WHERE Origine=" << their_origin() << " AND " << where_time_delete() << ";\n";
str << "DELETE FROM tieDMovMag WHERE Origine=" << their_origin() << " AND " << where_time_delete() << ";\n";
str << "DELETE FROM tieDMovMagCONAI WHERE Origine=" << their_origin() << " AND " << where_time_delete() << ";\n";
}
// Articoli di Magazzino
if (ini_get_bool(CONFIG_DITTA, "BS", "SKSyncAnamag"))
{
str << "DELETE FROM tieArticoli WHERE Origine=" << their_origin() << " AND " << where_time_delete() << ";\n";
str << "DELETE FROM tieArtVarianti WHERE Origine=" << their_origin() << " AND " << where_time_delete() << ";\n";
str << "DELETE FROM tieArtCONAI WHERE Origine=" << their_origin() << " AND " << where_time_delete() << ";\n";
}
// Valute
if (ini_get_bool(CONFIG_DITTA, "BS", "SKSyncVAL"))
str << "DELETE FROM tieValute WHERE Origine=" << their_origin() << " AND " << where_time_delete() << ";\n";
// Codici IVA
if (ini_get_bool(CONFIG_DITTA, "BS", "SKSyncIVA"))
str << "DELETE FROM tieIVA WHERE Origine=" << their_origin() << " AND " << where_time_delete() << ";\n";
// UMS
if (ini_get_bool(CONFIG_DITTA, "BS", "SKSyncUMS"))
str << "DELETE FROM tieUntMisura WHERE Origine=" << their_origin() << " AND " << where_time_delete() << ";\n";
//_log->log(0, str);
voldemort.exec(str); // Elimina tutte le anagrafiche importate da BeeStore
voldemort.commit();
}
}
void TSknet_sync::set_time()
{
// Prelevo il tempo dell'ultima importazione
sprintf_s(_lastUpdate, sizeof(_lastUpdate), ini_get_string(CONFIG_DITTA, "BS", "LAST_IMPORT", "19900101 00:00:00.000"));
// Preparo il tempo attuale
time_t rt = time(NULL);
struct tm * now = localtime(&rt);
sprintf_s(_thisUpdate, sizeof(_thisUpdate),
"%d%02d%02d %02d:%02d:%02d.999",
now->tm_year + 1900,
now->tm_mon + 1,
now->tm_mday,
now->tm_hour,
now->tm_min,
now->tm_sec);
}
const TString TSknet_sync::where_time_import()
{
TString time_import;
time_import << "[DTUltAgg] > '" << _lastUpdate << "'";
return time_import;
}
const TString TSknet_sync::where_time_delete()
{
TString time_delete;
time_delete << "[DTUltAgg] <= '" << _lastUpdate << "'";
return time_delete;
}
const bool TSknet_sync::clifo_has_conai(const TString4& tipocf, const long codcf)
{
TString keyCli; keyCli << tipocf << "|" << codcf;
TRectype clifo = cache().get(LF_CFVEN, keyCli);
return clifo.get_bool("ADDCONAI") || !clifo.get("PRODCONAI").blank();
}
bool TSknet_sync::save_and_delete_movmag(TMov_mag*& doc) const
{
int err = 0;
if (doc != NULL)
{
if (doc->rows() > 0)
{
TLocalisamfile mm(LF_MOVMAG);
err = doc->write(mm);
if (err != NOERR)
{
TString msg;
msg.format(FR("Errore %d in registrazione scontrino %ld del %s"), err,
doc->get_long(MOVMAG_NUMREG), (const char*)doc->get(MOVMAG_DATAREG));
_log->log(2, msg);
msg << TR("\nSi desidera proseguire ugualmente?");
if (noyes_box(msg))
err = 0;
}
}
delete doc;
doc = NULL;
}
return err == 0;
}
bool TSknet_sync::save_and_delete_doc(TDocumento*& doc) const
{
int err = 0;
if (doc != NULL)
{
if (doc->rows() > 0)
{
err = doc->write();
if (err != NOERR)
{
TString msg;
msg.format(FR("Errore %d in registrazione dcoumento %s/%ld del %s"), err,
(const char *)doc->get(DOC_CODNUM), doc->get_long(DOC_NDOC), (const char*)doc->get(DOC_DATADOC));
_log->log(2, msg);
msg << TR("\nSi desidera proseguire ugualmente?");
if (noyes_box(msg))
err = 0;
}
}
delete doc;
doc = NULL;
}
return err == 0;
}
void TSknet_sync::sync_val()
{
TString_array fields;
fields.add("CodValuta|CODTAB");
fields.add("DSValuta|S0");
fields.add("Simbolo|CODTAB");
sync_table("%VAL", "tieValute", fields);
}
void TSknet_sync::sync_doc()
{
const TString8 codcausdef = ini_get_string(CONFIG_DITTA, "bs", MOVMAG_CODCAUS, "", 2);
/*
if (codcausdef.blank())
{
_log->log(2, "Configurare parametri per movimenti Bee Store");
return;
}
*/
TString str(255);
str << "SELECT tieDMovMag.*, tieTBolFat.*, tieTBolFat.Annullato AS DOCANNULLATO, tieDMovMagCONAI.*\n";
str << "FROM tieDMovMag\nRIGHT JOIN tieTBolFat ON tieDMovMag.CodTestata = tieTBolFat.Cod_PK\n";
if (_hasConai)
str << "LEFT JOIN tieDMovMagCONAI ON tieDMovMag.Cod_PK = tieDMovMagCONAI.Cod_PK\n";
str << "WHERE tieTBolFat.Origine = " << their_origin() << " AND tieTBolFat." << where_time_import();
//str << "WHERE tieDMovMag.Origine = " << their_origin() << " AND tieDMovMag.TipoTestata = 2"; // verificare
str << "\nORDER BY tieTBolFat.Cod_PK,tieDMovMag.NumRiga";
//_log->log(0, str);
TODBC_recordset docs(str);
docs.connect(_dsn, _usr, _psw);
TProgress_monitor pi(docs.items(), str);
long num_doc = -1, nd, codcf;
TString4 tipocf;
TDocumento* doc = NULL;
for (bool ok = docs.move_first(); ok; ok = docs.move_next())
{
//TToken_string test(docs.get("CodTestata").as_string(), '\\');
const TString keyDoc = docs.get("CodTestata").as_string();
nd = docs.get("NumRif").as_int();
TString wrk = docs.get("CodCliente").as_string();
while (wrk[0] >= 'A')
wrk.ltrim(1);
codcf = atol(wrk);
tipocf = docs.get("TipoIntestatario").as_string();
if ((tipocf != "C" && tipocf != "F") || codcf == 0)
{
TString msg; msg.format("Attenzione! Per il doc n.%d <20> presente il tipo C/F = '%s' con cod = %d \nIl documento verr<72> saltato.", nd, tipocf, codcf);
_log->log(1, msg);
continue;
}
if (nd != num_doc)
{
if (num_doc > 0 && !save_and_delete_doc(doc))
break;
num_doc = nd;
const TDate datadoc = docs.get("DataMov").as_date();
TString8 numdoc;
TString8 tipodoc;
char stato_doc = '\0';
// Controllo se ho ricevuto un codice Campo per il TipoDoc o devo prenderlo dalle impostazioni
if (docs.get("TipoDocCE").is_empty())
{
switch (docs.get("TipoDoc").as_int())
{
case 1: // Bolla
numdoc = ini_get_string(CONFIG_DITTA, "BS", "SKCODNUMBOL");
tipodoc = ini_get_string(CONFIG_DITTA, "BS", "SKTIPODOCBOL");
break;
case 2: // Fattura
numdoc = ini_get_string(CONFIG_DITTA, "BS", "SKCODNUMFAT");
tipodoc = ini_get_string(CONFIG_DITTA, "BS", "SKTIPODOCFAT");
break;
case 6: // NC
numdoc = ini_get_string(CONFIG_DITTA, "BS", "SKCODNUMNC");
tipodoc = ini_get_string(CONFIG_DITTA, "BS", "SKTIPODOCNC");
break;
case 7: // Richiesta Trasferimento da Altro Magazzino
numdoc = ini_get_string(CONFIG_DITTA, "BS", "SKCODNUMTAM");
tipodoc = ini_get_string(CONFIG_DITTA, "BS", "SKTIPODOCTAM");
break;
case 9: // Ordine Cliente
numdoc = ini_get_string(CONFIG_DITTA, "BS", "SKCODNUMORC");
tipodoc = ini_get_string(CONFIG_DITTA, "BS", "SKTIPODOCORC");
break;
default:
warning_box("Attenzione! Per il doc con codice: %s <20> presente un tipo documento non supportato.\nIl documento saltato", keyDoc);
}
}
else
{
numdoc = docs.get("TipoDocCE").as_string();
tipodoc = docs.get("TipoDocCE").as_string();
}
if (numdoc.blank() || tipodoc.blank())
{
_log->log(2, "Configurare parametri per movimenti Bee Store");
return;
}
TTipo_documento tipo(tipodoc);
const TString8 codcaus = tipo.caus_mov().blank() ? codcausdef : tipo.caus_mov();
// Controllo che il documento non esista gi<67>
static TDocumento existDoc;
if (existDoc.read('D', datadoc.year(), numdoc, nd) == NOERR) // Ha uno stato che considero bloccato
{
stato_doc = existDoc.stato();
if (existDoc.stato() >= '3')// && docs.get("DOCANNULLATO").as_int() == 1)
{
TString err; err << "Il documento " << datadoc.year() << " " << numdoc << " " << nd << " con chiave " << docs.get("Cod_PK").as_string() << " verr<72> sostituito ma <20> gi<67> stato fatturato.";
_log->log(2, err);
}
existDoc.remove();
}
/*
// Salto i documenti annullati
if (docs.get("tieTBolFat.Annullato").as_int() == 1)
continue;
*/
doc = new TDocumento();
doc->put(DOC_ANNO, datadoc.year());
doc->put(DOC_DATADOC, datadoc);
doc->put(DOC_NDOC, nd);
doc->put(DOC_PROVV, "D");
doc->put(DOC_CODNUM, numdoc);
doc->put(DOC_TIPODOC, tipodoc);
doc->put(DOC_TIPOCF, tipocf);
doc->put(DOC_CODCF, codcf);
doc->cli2doc();
if (stato_doc != '\0')
doc->put(DOC_STATO, stato_doc);
const TString8 codval = docs.get("CodValuta").as_string();
const real cambio = docs.get("CambioValuta").as_real();
const TString asp = docs.get("AspettoBeni").as_string();
const int ncolli = docs.get("NumeroColli").as_int();
doc->put(DOC_CODVAL, codval);
doc->put(DOC_CAMBIO, cambio);
doc->put(DOC_ASPBENI1, asp.sleft(50));
doc->put(DOC_ASPBENI2, asp.smid(50));
doc->put(DOC_NCOLLI, ncolli);
doc->put(DOC_CAUSMAG, codcaus);
const TString codAg = docs.get("CodAgente").as_string();
const TString codPag = docs.get("CodPagamento").as_string();
if (!codAg.blank())
doc->put(DOC_CODAG, codAg);
if (!codPag.blank())
doc->put(DOC_CODPAG, codPag);
}
const int tipoart = docs.get("TipoArticolo").as_int();
TString4 tiporiga;
// Se la riga <20> customizzata evito i controlli
if (tipoart >= 14)
{
tiporiga = docs.get("TipoArticolo").as_string();
}
else
{
// Facciamo un po' di speculazioni
switch (tipoart)
{
default:
case 0:
// Tiporiga 1 -> Merce
tiporiga = "01";
break;
case 1:
// Se la QTA <20> 0 sar<61> una spesa a spesa a valore
if (docs.get("Quantita").as_int() == 0)
{
tiporiga = "02";
}
else
{
tiporiga = "03";
}
break;
case 2:
// Se non ho QTA sar<61> una descrizione
if (docs.get("Quantita").as_int() == 0)
{
tiporiga = "05"; // Descrizione
}
else
// nel dubbio, Merce
tiporiga = "01";
}
}
const TString80 codart = docs.get("CodArticolo").as_string();
const TString descr = docs.get("DSRiga").as_string();
if (tiporiga == "01" && ini_get_bool(CONFIG_DITTA, "BS", "SKUseCustomRiga", false))
{
TLocalisamfile codcor(LF_CODCORR); codcor.setkey(2);
TRectype rcodcor(LF_CODCORR);
rcodcor.put(CODCORR_CODARTALT, codart);
if (codcor.read(rcodcor, _isequal) == NOERR)
tiporiga = ini_get_string(CONFIG_DITTA, "BS", "SKNumCustomRiga", "14");
}
TRectype& rdoc = doc->new_row(tiporiga);
if(codart.blank() && tiporiga == "03" && descr.starts_with("Bancal"))
rdoc.put(RDOC_CODART, "B1");
else
rdoc.put(RDOC_CODART, codart);
if (tipoart == 2)
{
if (cache().get("SPP", codart).not_empty())
rdoc.put(RDOC_CODARTMAG, codart);
}
else
{
if (cache().get(LF_ANAMAG, codart).not_empty())
rdoc.put(RDOC_CODARTMAG, codart);
}
rdoc.put(RDOC_CODARTMAG, codart);
// rdoc.check_row();
rdoc.put(RDOC_DESCR, descr.sleft(50));
if (descr.len() > 50)
{
rdoc.put(RDOC_DESCLUNGA, "X");
rdoc.put(RDOC_DESCEST, descr.smid(50));
}
rdoc.put(RDOC_CODMAG, docs.get("CodMagazzino").as_string().left(5));
rdoc.put(RDOC_CODMAGC, docs.get("CodMagazDest").as_string().left(5));
TString ums = docs.get("CodUntMis").as_string();
if (ums.blank() && cache().get("%TRI", tiporiga, "S7") == "M")
ums = ini_get_string(CONFIG_DITTA, "BS", "SKCodUmsDef");
rdoc.put(RDOC_UMQTA, ums);
rdoc.put(RDOC_QTA, docs.get("Quantita").as_real());
rdoc.put(RDOC_PREZZO, docs.get("PrzNettoSede").as_real()); // o PrzNettoValuta ??
real valsconto1(docs.get("Sconto1").as_real());
real valsconto2(docs.get("Sconto2").as_real());
real valsconto3(docs.get("Sconto3").as_real());
TString codiva = docs.get("CodIva").as_string();
if (codiva.blank() || codiva == "0")
{
codiva = ini_get_string(CONFIG_DITTA, "BS", "SKCodIvaDef");
}
else
{
codiva = cache().get("%SKI", codiva, "S6");
}
rdoc.put(RDOC_CODIVA, codiva);
TString80 sconto;
if (valsconto1 != ZERO)
sconto << valsconto1.stringa(6, 2);
if (valsconto2 != ZERO)
{
if (sconto.full())
sconto << "+";
sconto << valsconto2.stringa(6, 2);
}
if (valsconto3 != ZERO)
{
if (sconto.full())
sconto << "+";
sconto << valsconto3.stringa(6, 2);
}
rdoc.put(RDOC_SCONTO, sconto);
// Provvigione agenti
rdoc.put(RDOC_PERCPROV, docs.get("PercProvv").as_real());
// "CONSCACC", "CONSCALL", "CONSCCAR", "CONSCPLA", "CONSCLEG", "CONSCVET"
if (_hasConai && clifo_has_conai(tipocf, codcf))
{
// In base al conai che ha abilitato controllo
if (ini_get_bool(CONFIG_DITTA, "ve", "CONFACC")) // Acciaio
{
rdoc.put("CONSCACC", docs.get("CatAC").as_string());
rdoc.put("CONPUACC", docs.get("PesoAC").as_string());
}
if (ini_get_bool(CONFIG_DITTA, "ve", "CONFALL")) // Alluminio
{
rdoc.put("CONSCALL", docs.get("CatAL").as_string());
rdoc.put("CONPUALL", docs.get("PesoAL").as_string());
}
if (ini_get_bool(CONFIG_DITTA, "ve", "CONFCAR")) // Carta
{
rdoc.put("CONSCCAR", docs.get("CatCA").as_string());
rdoc.put("CONPUCAR", docs.get("PesoCA").as_string());
}
if (ini_get_bool(CONFIG_DITTA, "ve", "CONFLEG")) // Legno
{
rdoc.put("CONSCLEG", docs.get("CatLE").as_string());
rdoc.put("CONPULEG", docs.get("PesoLE").as_string());
}
if (ini_get_bool(CONFIG_DITTA, "ve", "CONFPLA")) // Plastica
{
rdoc.put("CONSCPLA", docs.get("CatPL").as_string());
rdoc.put("CONPUPLA", docs.get("PesoPL").as_string());
}
if (ini_get_bool(CONFIG_DITTA, "ve", "CONFVET")) // Vetro
{
rdoc.put("CONSCVET", docs.get("CatVE").as_string());
rdoc.put("CONPUVET", docs.get("PesoVE").as_string());
}
}
if (!pi.add_status())
break;
}
save_and_delete_doc(doc); // Salva ultimo documento in sospeso
}
bool TSknet_sync::create()
{
_dsn = ini_get_string(CONFIG_DITTA, "BS", "DSN", "BEESTORE");
_sqlog = ini_get_string(CONFIG_DITTA, "BS", "Log", "");
_usr = ini_get_string(CONFIG_DITTA, "BS", "USR", "BEESTORE");
_psw = decode(ini_get_string(CONFIG_DITTA, "BS", "PSW", "BEESTORE"));
_hasConai = ini_get_bool(CONFIG_DITTA, "BS", "SKEnabCONAI", false);
if (_dsn.full())
{
TProgress_monitor ti(1, TR("Connessione a SQL Server"), false);
TString query; query << "SELECT * FROM tieValute;";//"ODBC(" << _dsn << ")\nSELECT * FROM tieValute;";
TODBC_recordset recset(query);
recset.connect(_dsn, _usr, _psw); // Dovrebbe connettersi anche con solo _dsn valorizzato
recset.move_first();
if (_sqlog.full() && _sqlog.is_relative_path())
{
TFilename n; n.tempdir();
n.add(_sqlog.name());
_sqlog = n;
}
recset.set_log_file(_sqlog);
return TSkeleton_application::create();
}
return error_box(FR("Impossibile connettersi al DSN '%s'"), (const char*)_dsn);
}
void TSknet_sync::main_loop()
{
TSknet_mask mask;
while (mask.run() == K_ENTER)
{
mask.autosave(); // Rende definitivi tutti i paramentri in [bs]
_log = new TLog_report;
// Prendo la data attuale
set_time();
if (mask.get_bool("SKSyncUMS"))
sync_ums();
if (mask.get_bool("SKSyncIVA"))
sync_iva();
if (mask.get_bool("SKSyncAnamag"))
sync_anamag();
if (mask.get_bool("SKSyncVAL"))
sync_val();
int cfmask = 0;
if (mask.get_bool("SKSyncClienti")) cfmask |= 1;
if (mask.get_bool("SKSyncFornitori")) cfmask |= 2;
if (cfmask)
sync_clifo(cfmask);
if (mask.get_bool("SKSyncDoc"))
sync_doc();
_log->log(0, "Procedura terminata!");
_log->preview();
delete _log;
_log = NULL;
// Aggiorno l'ultimo uppidate
ini_set_string(CONFIG_DITTA, "BS", "LAST_IMPORT", _thisUpdate);
if (mask.get_bool("SKEmptyOnImp"))
clean();
}
}
TSknet_sync& bss()
{
static TSknet_sync* bss = new TSknet_sync();
return *bss;
}
int bs0300(int argc, char* argv[])
{
bss().run(argc, argv, TR("SKNT Importer"));
return 0;
}