#include "calib01.h"
#include "calib02.h"
#include "camask.h"

#include <rdoc.h>
#include <pconti.h>

#include "movana.h"
#include "pconana.h"
#include "rmovana.h"
#include "rrip.h"
#include "saldana.h"

///////////////////////////////////////////////////////////
// TSaldanal
///////////////////////////////////////////////////////////

void TSaldanal::copy(const TSaldanal& sa)
{
  _ini = sa._ini;
  _dare = sa._dare;
  _avere = sa._avere;
  _fin = sa._fin;
  _movimentato = sa._movimentato;
}

///////////////////////////////////////////////////////////
// TPconana_recordset
///////////////////////////////////////////////////////////

const TVariant& TPconana_recordset::get(const char* field) const
{
  const TFixed_string column_name(field);
  if (column_name[0] == '#')
  {
    if (column_name == "#CMSCDC")
    {
      const TMultilevel_code_info& info = ca_multilevel_code_info(LF_FASI);
      switch (info.parent())
      {
      case LF_CDC     : return get_tmp_var() = _bill.costo();
      case LF_COMMESSE: return get_tmp_var() = _bill.commessa();
      default         : return NULL_VARIANT; 
      }
    }
    if (column_name == "#COSTO")
      return get_tmp_var() = _bill.costo();
    if (column_name == "#COMMESSA")
      return get_tmp_var() = _bill.commessa();
    if (column_name == "#FASE")
      return get_tmp_var() = _bill.fase();
    if (column_name == "#DATA_INIZIALE")
      return get_tmp_var() = _dal;
    if (column_name == "#DATA_FINALE")
      return get_tmp_var() = _al;
  }
  else
  {
    const TRectype& curr = relation()->curr();
    if (column_name.starts_with(PCONANA_CODCONTO))
    {
      TString80 str;
      if (_tipo == 'C')
      {
        const TBill b(curr);
        str = b.string(0x8);
      }
      else
        str = curr.get(PCONANA_CODCONTO);

      if (column_name[8] == ':')
      {
        const TMultilevel_code_info& info = ca_multilevel_code_info(_tipo == 'C' ? LF_PCON : LF_PCONANA);
        const int level = column_name[9] - '1';
        str.cut(info.total_len(level));
      }
      return get_tmp_var() = str;
    }
    if (column_name.starts_with(PCONANA_DESCR))
    {
      TString80 str;
      if (_tipo == 'C')
      {
        TBill b(curr);
        if (column_name[5] == ':')
        {
          if (column_name[6] == '1')
            b.set(b.gruppo(), 0, 0); else
          if (column_name[6] == '2')
            b.set(b.gruppo(), b.conto(), 0);
        }
        str = b.descrizione();
      }
      else
      {
        if (column_name[5] == ':')
        {
          const TMultilevel_code_info& info = ca_multilevel_code_info(LF_PCONANA);
          const int level = column_name[6] - '1';
          str = curr.get(PCONANA_CODCONTO);
          str.cut(info.total_len(level));
          str = cache().get(LF_PCONANA, str, PCONANA_DESCR);
        }
        else
          str = curr.get(PCONANA_DESCR);
      }
      return get_tmp_var() = str;
    }
    if (column_name == PCONANA_INDBIL)
    {
      long ib = curr.get_int(PCONANA_INDBIL);
      if (ib == 0)
      {
        if (_tipo == 'C')
        {
          TBill b(curr);
          ib = b.indicatore_bilancio(); 
        }
        else
        {
          const TCodice_con conto = curr.get(PCONANA_CODCONTO);
          const TMultilevel_code_info& info = ca_multilevel_code_info(LF_PCONANA);
          for (int i = info.levels()-2; i >= 0 && ib <= 0; i--)
          {
            const TString& k = conto.left(info.total_len(i));
            const TRectype& pca = cache().get(LF_PCONANA, conto);
            ib = pca.get_long(PCONANA_INDBIL);
          }
        }
      }
      return get_tmp_var() = ib;
    }

    if (column_name.starts_with("SALDO:"))
    {
      TString16 sub_field = column_name.mid(6);
      const char last = sub_field.right(1)[0];
      int tipimov = 0;
      switch (last)
      {
      case 'C': tipimov = _saldanal_consuntivo; sub_field.rtrim(1); break; // Consuntivo
      case 'P': 
      case 'V': tipimov = _saldanal_preventivi; sub_field.rtrim(1); break; // Preventivo o variazione preventivo
      default : tipimov = _tipimov; break;
      }

      ((TAnal_bill&)_bill).set_conto(get(PCONANA_CODCONTO).as_string());
      const TSaldanal& s = ca_saldo(_bill, _dal, _al, tipimov);

      TVariant& var = get_tmp_var();
      if (sub_field == "INI_DARE")
      {
        var = s._ini.sezione() == 'D' ? s._ini.valore() : ZERO; 
      } else
      if (sub_field == "INI_AVERE")
      {
        var = s._ini.sezione() == 'A' ? s._ini.valore() : ZERO; 
      } else
      if (sub_field == "MOV_DARE")
      {
        var = s._dare.valore(); 
      } else
      if (sub_field == "MOV_AVERE")
      {
        var = s._avere.valore(); 
      } else
      if (sub_field == "FIN_DARE")
      {
        var = s._fin.sezione() == 'D' ? s._fin.valore() : ZERO;     
      } else
      if (sub_field == "FIN_AVERE")
      {
        var = s._fin.sezione() == 'A' ? s._fin.valore() : ZERO;     
      } else
      if (sub_field == "INI_DARE_IND")
      {
        var = s._ini.sezione() == 'D' ? s._iniind.valore() : ZERO; 
      } else
      if (sub_field == "INI_AVERE_IND")
      {
        var = s._ini.sezione() == 'A' ? s._iniind.valore() : ZERO; 
      } else
      if (sub_field == "MOV_DARE_IND")
      {
        var = s._dareind.valore(); 
      } else
      if (sub_field == "MOV_AVERE_IND")
      {
        var = s._avereind.valore(); 
      } else
      if (sub_field == "FIN_DARE_IND")
      {
        var = s._fin.sezione() == 'D' ? s._finind.valore() : ZERO;     
      } else
      if (sub_field == "FIN_AVERE_IND")
      {
        var = s._fin.sezione() == 'A' ? s._finind.valore() : ZERO;     
      }
      return var;
    }
  }
  return TISAM_recordset::get(column_name);
}

bool TPconana_recordset::valid_record(const TRelation& rel) const
{
  TCodice_con conto;
  const TRectype& curr = rel.curr();
  if (curr.num() == LF_PCON)
  {
    const TBill b(curr);

    int level = 0;
    if (b.conto() != 0)
      level++;
    if (b.sottoconto() != 0)
      level++;

    (bool&)(_is_anal[level]) = curr.get_bool(PCN_ANALITICA);

		if (level < 2)  // Ignora gruppi e conti 
      return false;

    // Ignora i sottoconti non analitici nemmeno a livello di conto o gruppo
    if (!(_is_anal[2] || _is_anal[1] || _is_anal[0]))
      return false;

    conto = b.string(0x8);
  }
  else
  {
    conto = curr.get(PCONANA_CODCONTO);
    if (conto.len() <= _conto_minlen)
      return false;
  }

  if (_movimentati || _nonnulli)
  {
    ((TAnal_bill&)_bill).set_conto(conto);
    const TSaldanal& s = ca_saldo(_bill, _dal, _al, _tipimov);
    if (_movimentati && !s._movimentato)
      return false;
    if (_nonnulli && s._fin.is_zero())
      return false;
  }
  return true;
}
  
static const TPconana_recordset* _current_recset = NULL;

bool TPconana_recordset::pianoconti_filter(const TRelation* rel)
{ return _current_recset->valid_record(*rel); }

void TPconana_recordset::set_custom_filter(TCursor& cursor) const 
{
  const int logic = cursor.curr().num();
  TRectype darec(logic), arec(logic);
  if (logic == LF_PCON)
  {
    if (_da_conto.full())
    {
		  darec.put(PCN_GRUPPO,     _da_conto.mid(0,3));
		  darec.put(PCN_CONTO,      _da_conto.mid(3,3));
		  darec.put(PCN_SOTTOCONTO, _da_conto.mid(6,6));
    }
    if (_a_conto.full())
    {
  		arec.put(PCN_GRUPPO,      _a_conto.mid(0,3));
	  	arec.put(PCN_CONTO,       _a_conto.mid(3,3));
		  arec.put(PCN_SOTTOCONTO,  _a_conto.mid(6,6));
    }
    memset((void*)_is_anal, 0, sizeof(_is_anal)); // Azzera flags di conti analitici
  }
  else
  {
    darec.put(PCONANA_CODCONTO, _da_conto);
    arec.put(PCONANA_CODCONTO, _a_conto);
  }
  cursor.setregion(darec, arec);

  _current_recset = this;
  cursor.set_filterfunction(pianoconti_filter);
}

void TPconana_recordset::set_tipo(char tipo)
{
  if (tipo != 'A' && tipo != 'C')
  {
  	TConfig& cfg = ca_config();
    tipo = cfg.get_bool("UsePdcc") ? 'C' : 'A';
  }
  _tipo = tipo;

  if (_tipo == 'A')
  {
    set("USE PCONANA");
    const TMultilevel_code_info& info = ca_multilevel_code_info(LF_PCONANA);
    _conto_minlen = info.total_len(-1);  // Lunghezza fino al penultimo livello
  }
  else
  {
    set("USE PCON");
    _conto_minlen = 6;  // Gruppo(3)+Conto(3)
  }
}

void TPconana_recordset::set_filter(char tipo, const char* da_conto, const char* a_conto,
                                    const char* costo, const char* commessa, const char* fase,
                                    const TDate& dal, const TDate& al,
                                    word tipimov, bool movimentati, bool nonnulli)
{
  set_tipo(tipo);

  _da_conto = da_conto;
  _a_conto = a_conto;
    
  _dal = dal;
  _al = al;

  _tipimov= tipimov;
  _movimentati = movimentati;
  _nonnulli = nonnulli;

  _bill.reset();
  _bill.set_costo(costo);
  _bill.set_commessa(commessa);
  _bill.set_fase(fase);
}

TPconana_recordset::TPconana_recordset(char tipo) : TISAM_recordset("USE PCONANA")
{ 
  set_tipo(tipo);
}

///////////////////////////////////////////////////////////
// TAnal_report
///////////////////////////////////////////////////////////

size_t TAnal_report::get_usr_words(TString_array& words) const
{
  TReport::get_usr_words(words);
  
  const char* const name[] = 
  { 
    "CA_FORMAT_COSTO", 
    "CA_FORMAT_COMMESSA", 
    "CA_FORMAT_FASE", 
    "CA_FORMAT_CONTO",
    "CA_FORMAT_CMSCDC",
    "CA_FORMAT_CONTO_DESCR",
    NULL
  };

  ((TAnal_report*)this)->_first_msg = words.items(); // Calcola il primo numero disponibile
  size_t i; 
  for (i = 0; name[i] != NULL; i++)
    words.add(name[i]);
  
  return words.items();
}

void TAnal_report::msg_format(int logicnum, TVariant_stack& stack)
{
  const TString& str_in = curr_field()->get().as_string();
  if (str_in.full())
  {
    TString8 separator = " ";
    if (stack.items() > 0)
      separator = stack.pop().as_string();
    if (separator.not_empty())
    {
      const TMultilevel_code_info& mci = ca_multilevel_code_info(logicnum);
      TString80 str_out = str_in;
      for (int i = mci.levels()-2; i >= 0; i--)
        str_out.insert(separator, mci.total_len(i));
      curr_field()->set(str_out);
    }
  }
}

void TAnal_report::msg_format_costo(TVariant_stack& stack)
{ msg_format(LF_CDC, stack); }

void TAnal_report::msg_format_commessa(TVariant_stack& stack)
{ msg_format(LF_COMMESSE, stack); }

void TAnal_report::msg_format_fase(TVariant_stack& stack)
{ msg_format(LF_FASI, stack); }

char TAnal_report::determina_tipo_pdc(TVariant_stack& stack) const
{
  // Cerca di determinare se si usa il piano contabile o analitico
  char tipo = ' ';
  switch (stack.items())
  {
  case  0: break;
  case  1:
    {
      const char t = stack.peek(0).as_string()[0];
      if (t == 'A' || t == 'C')
      {
        tipo = t;
        stack.drop();
      }
    }
    break;
  default:
    {
      const char t = stack.peek(1).as_string()[0];
      if (t == 'A' || t == 'C')
      {
        tipo = t;
        stack.roll(1);
        stack.drop();
      }
    }
    break;
  }

  if (tipo != 'A' && tipo != 'C')
  {
    const TString& conto = curr_field()->get().as_string();
    const int contolen = conto.len();
    if ((contolen == 3 || contolen == 6 || contolen == 12) && real::is_natural(conto))
      tipo = 'C';
    else
      tipo = 'A';
  }

  return tipo;
}

void TAnal_report::msg_format_conto(TVariant_stack& stack)
{ 
  if (determina_tipo_pdc(stack) == 'C')
    msg_format(LF_PCON, stack); 
  else
    msg_format(LF_PCONANA, stack); 
}

void TAnal_report::msg_format_conto_descr(TVariant_stack& stack)
{
  // Cerca di determinare se si usa il piano contabile o analitico
  const TString& conto = curr_field()->get().as_string();

  if (determina_tipo_pdc(stack) == 'C')
  {
    TToken_string chiave;
    chiave.add(conto.mid(0,3));
    chiave.add(conto.mid(3,3));
    chiave.add(conto.mid(6,6));
    const TString& conto_descr = cache().get(LF_PCON, chiave, PCN_DESCR);
    curr_field()->set(conto_descr);
  }
  else
  {
    const TString& conto_descr = cache().get(LF_PCONANA, conto, PCONANA_DESCR);
    curr_field()->set(conto_descr);
  }
}

void TAnal_report::msg_format_commessa_costo(TVariant_stack& stack)
{
  const TMultilevel_code_info& fas_info = ca_multilevel_code_info(LF_FASI);
  const int pa = fas_info.parent();
  if (pa > 0)
	  msg_format(pa, stack);
}

bool TAnal_report::execute_usr_word(unsigned int opcode, TVariant_stack& stack)
{
  bool ok = true;
  if (opcode >= _first_msg)
  {
    opcode -= _first_msg;
    switch (opcode)
    {
    case 0 : msg_format_costo(stack);          break;
    case 1 : msg_format_commessa(stack);       break;
    case 2 : msg_format_fase(stack);           break;
    case 3 : msg_format_conto(stack);          break;
    case 4 : msg_format_commessa_costo(stack); break;
    case 5 : msg_format_conto_descr(stack);    break;
    default: ok = false; break;
    }
  }
  else 
    ok = TReport::execute_usr_word(opcode, stack);
  return ok;
}

///////////////////////////////////////////////////////////
// TAnal_bill
///////////////////////////////////////////////////////////

int TAnal_bill::compare(const TSortable& s) const
{
  const TAnal_bill& b = (const TAnal_bill&)s;
  int cmp = _conto.compare(b._conto);
  if (cmp == 0)
  {
    cmp = _costo.compare(b._costo);
    if (cmp == 0)
    {
      cmp = _commessa.compare(b._commessa);
      if (cmp == 0)
        cmp = _fase.compare(b._fase);    
    }
  }
  return cmp;
}
  
bool TAnal_bill::match(const TAnal_bill& b) const
{
  if (b._conto.full() && _conto != b._conto)
    return false;
  if (b._costo.full() && _costo != b._costo)
    return false;
  if (b._commessa.full() && _commessa != b._commessa)
    return false;
  if (b._fase.full() && _fase != b._fase)
    return false;
  return true;
}

void TAnal_bill::set_conto(const char* c)
{ _conto = c; _conto.trim(); }

void TAnal_bill::set_costo(const char* c)
{ _costo = c; _costo.trim(); }

void TAnal_bill::set_commessa(const char* c)
{ _commessa = c; _commessa.trim(); }

void TAnal_bill::set_fase(const char* c)
{ _fase = c; _fase.trim(); }

const TString&  TAnal_bill::conto() const
{ return _conto; }

const TString& TAnal_bill::costo() const
{ return _costo; }

const TString& TAnal_bill::commessa() const
{ return _commessa; }

const TString& TAnal_bill::fase() const
{ return _fase; }

void TAnal_bill::reset()
{
  _conto = _costo = _commessa = _fase = "";
}

TIndbil TAnal_bill::indicatore_bilancio() const
{
	TIndbil indbil = ib_null;
	const TMultilevel_code_info& info = ca_multilevel_code_info(LF_PCONANA);

  TCodice_con conto = _conto; // Codice conto da affettare in sottolivelli
	for (int i = info.levels() - 1; i >= 0 && indbil == ib_null; i--)
	{
		conto.cut(info.total_len(i));
    const TRectype& pconana = cache().get(LF_PCONANA, conto);
		indbil = TIndbil(pconana.get_int(PCONANA_INDBIL));
	}
  //non ha trovato l'indicatore;potrebbe essere il caso di un conto contabile usato in analitica
  if (indbil == ib_null && _conto.len() == 12 && real::is_natural(_conto))
  {
    const int gr = atoi(_conto.mid(0,3));
    const int co = atoi(_conto.mid(3,3));
    const long so = atol(_conto.mid(6,6));
    const TBill zio_cg(gr, co, so);
    indbil = TIndbil(zio_cg.indicatore_bilancio());
  }

	return indbil;
}

const TString& TAnal_bill::testata() const
{
	const TRectype& rec = cache().get(LF_PCONANA, _conto);
	const TString& testata = rec.get(PCONANA_TESTATA);
	if (testata.full())
		return testata;
	else	//metodo fichissimo per evitare parole troncate!
	{
		const TString& descr = rec.get(PCONANA_DESCR);
		//se la descrizione e' abbastanza corta da stare nel campo testata la usa direttamente..
		if (descr.len() <= 15)
			return descr;
		//..in caso contrario fa in modo da adattarla senza troncamenti
		TParagraph_string str(descr, 15);
		TString& tmp = get_tmp_string();
		tmp = str.get(0);
		tmp << '\n' << str.get(1);

		return tmp;
	}
}

bool TAnal_bill::get(const TRectype& rec)
{
  bool ok = true;
  reset();
  switch(rec.num())
  {
  case LF_RMOVANA: 
    set_conto(rec.get(RMOVANA_CODCONTO));
    set_costo(rec.get(RMOVANA_CODCCOSTO));
    set_commessa(rec.get(RMOVANA_CODCMS));
    set_fase(rec.get(RMOVANA_CODFASE));
    break;
  case LF_RIGHEDOC:
    set_commessa(RDOC_CODCMS);
    set_fase(RDOC_FASCMS);
    break;
  case LF_SALDANA:
    set_conto(rec.get(SALDANA_CONTO));
    set_costo(rec.get(SALDANA_COSTO));
    set_commessa(rec.get(SALDANA_COMMESSA));
    set_fase(rec.get(SALDANA_FASE));
    break;
  case LF_RRIP:
    set_costo(rec.get(RRIP_CODCOSTO));
    set_commessa(rec.get(RRIP_CODCMS));
    set_fase(rec.get(RRIP_CODFASE));
    set_conto(rec.get(RRIP_CODCONTO));
    break;
  default: 
    ok = false;
    break;
  }
  return ok;
}

void TAnal_bill::copy(const TAnal_bill& b)
{
  set_conto(b.conto());
  set_costo(b.costo());
  set_commessa(b.commessa());
  set_fase(b.fase());
}

const TAnal_bill& TAnal_bill::operator=(const TAnal_bill& b)
{ 
  copy(b); 
  return *this;
}

TAnal_bill::TAnal_bill()
{ }

TAnal_bill::TAnal_bill(const TAnal_bill& b)
{ copy(b); }

TAnal_bill::TAnal_bill(const char* conto, const char* costo, const char* commessa, const char* fase)
{
  set_conto(conto);
  set_costo(costo);
  set_commessa(commessa);
  set_fase(fase);
}

TAnal_bill::TAnal_bill(const TRectype& rec)
{
  get(rec);
}

////////////////////////////////////////////////////////
// TRiclassify_cache
////////////////////////////////////////////////////////

class TRiclassify_cache : public TCache
{
  int _conto_min;

protected:
  virtual TObject* key2obj(const char* key);
  void extract(const TString& conto, TString_array& conti) const;

public:
  const TString_array& conti(const TString& conto);
  TRiclassify_cache();
};

void TRiclassify_cache::extract(const TString& conto, TString_array& conti) const
{
  TRecord_array table(conto, LF_PANAPDC);
  for (int r = table.last_row(); r > 0; r = table.pred_row(r))
  {
    const TRectype& row = table.row(r);
    const TBill b(row);
    conti.add(b.string(0x8));
  }
}

TObject* TRiclassify_cache::key2obj(const char* key)
{
  TString_array* k = new TString_array;
  if (key && int(strlen(key)) > _conto_min)
  {
    extract(key, *k);
  }
  else
  {
    TString query = "USE PCONANA";
    if (key && *key)
    {
      query << "\nFROM CODCONTO=" << key;
      query << "\nTO CODCONTO=" << key;
    }
    TISAM_recordset pconana(query);
    for (TRecnotype i = 0; pconana.move_to(i); i++)
    {
      const TString& conto = pconana.get(PCONANA_CODCONTO).as_string();
      extract(conto, *k);
    }
  }
  return k;
}

const TString_array& TRiclassify_cache::conti(const TString& conto)
{
  return *(const TString_array*)objptr(conto);
}

TRiclassify_cache::TRiclassify_cache() : TCache(7) 
{ 
  const TMultilevel_code_info& info = ca_multilevel_code_info(LF_PCONANA);
  _conto_min = info.total_len(-1);  // Lunghezza conti fino al penultimo livello
}

////////////////////////////////////////////////////////
// TSaldi_cache
////////////////////////////////////////////////////////

class TSaldi_cache : private TCache
{
  TEsercizi_contabili _esc;
  TRiclassify_cache _riclass;

protected:
  virtual TObject* key2obj(const char* key);

  bool int_saldo_annuale(const TAnal_bill& bill, int annoini, int annofin, word tipo, TImporto& dare, TImporto& avere) const;
  bool int_saldo_movimenti(const TAnal_bill& bill, const TDate& dal, const TDate& al, word tipo, TSaldanal& s) const;

protected:
  bool saldo_annuale(const TAnal_bill& bill, int annoini, int annofin, word tipo, TImporto& dare, TImporto& avere);
  bool saldo_movimenti(const TAnal_bill& bill, const TDate& dal, const TDate& al, word tipo, TSaldanal& s);
  bool saldi(const TAnal_bill& bill, const TDate& dal, const TDate& al, word tipo, TSaldanal& s);

public:
  const TSaldanal& saldo(const TAnal_bill& bill, const TDate& dal, const TDate& al, word tipi = 0x1);
  TSaldi_cache();
};

TImporto ca_get_imp(const TRecordset& rs, const char* sez, const char* imp)
{
  const char sezione = rs.get(sez).as_string()[0];
  const real importo = rs.get(imp).as_real();
  return TImporto(sezione, importo);
}

// Calcolo saldo annuale di un conto reale NON riclassificato
bool TSaldi_cache::int_saldo_annuale(const TAnal_bill& b, int da_anno, int ad_anno, word tipo, 
                                     TImporto& dare, TImporto& avere) const
{
  bool movim = false;
  TString query, select;

  if (b.costo().full())
    select << "(COSTO=='" << b.costo() << "')";
  if (b.commessa().full())
  {
    if (select.full()) select << "&&";
    select << "(COMMESSA=='" << b.commessa() << "')";
  }
  if (b.fase().full())
  {
    if (select.full()) select << "&&";
    select << "(FASE=='" << b.fase() << "')";
  }
  if (da_anno > 0)
  {
    if (select.full()) select << "&&";
    select << "(ANNO>=" << da_anno << ")";
  }
  if (ad_anno > 0)
  {
    if (select.full()) select << "&&";
    select << "(ANNO<=" << ad_anno << ")";
  }

  query << "USE SALDANA KEY 2";
  if (select.full())
    query << " SELECT " << select;

  if (b.conto().full())
  {
    query << "\nFROM CONTO=" << b.conto();
    if (da_anno > 0)
      query << " ANNO=" << da_anno;
    query << "\nTO CONTO=" << b.conto();
    if (ad_anno > 0)
      query << " ANNO=" << ad_anno;
    query << '\n';
  }
  
  TISAM_recordset saldini(query);

  for (TRecnotype i = 0; saldini.move_to(i); i++)
  {
    TImporto imp;
    if (tipo & _saldanal_consuntivo)
    {
      imp += ca_get_imp(saldini, SALDANA_SEZIONE, SALDANA_SALDO);
    }
    if (tipo & _saldanal_preventivo)
    {
      imp += ca_get_imp(saldini, SALDANA_SEZIONEP, SALDANA_SALDOP);
    }
    if (tipo & _saldanal_variazione)
    {
      imp += ca_get_imp(saldini, SALDANA_SEZIONEV, SALDANA_SALDOV);
    }
    if (tipo & _saldanal_consuntivo_indiretto)
    {
      imp += ca_get_imp(saldini, SALDANA_SEZIONEI, SALDANA_SALDOI);
    }
    if (tipo & _saldanal_preventivo_indiretto)
    {
      imp += ca_get_imp(saldini, SALDANA_SEZIONEIP, SALDANA_SALDOIP);
    }
    if (tipo & _saldanal_variazione_indiretto)
    {
      imp += ca_get_imp(saldini, SALDANA_SEZIONEIV, SALDANA_SALDOIV);
    }
    if (!imp.is_zero())
    {
      if (imp.sezione() == 'D')
        dare += imp;
      else
        avere += imp;

      movim = true;
    }
  }

  return movim;
}

bool TSaldi_cache::saldo_annuale(const TAnal_bill& b, int da_anno, int ad_anno, word tipo, 
                                 TImporto& dare, TImporto& avere)
{
  bool movim = false;
  if (ad_anno >= 0)
  {
    if (tipo & _saldanal_riclassify)
    {
      // Legge tabella di riclassificazione
      const TString_array& table = _riclass.conti(b.conto());
      if (!table.empty())
      {
        TAnal_bill c(b); // Conto riclassificato
        FOR_EACH_ARRAY_ROW(table, i, row)
        {
          c.set_conto(*row);
          movim |= int_saldo_annuale(c, da_anno, ad_anno, tipo, dare, avere);
        }
      }
    }
    else
      movim = int_saldo_annuale(b, da_anno, ad_anno, tipo, dare, avere);
  }
  return movim;
}

bool TSaldi_cache::int_saldo_movimenti(const TAnal_bill& b, 
                                       const TDate& dal, const TDate& al, 
                                       word tipo, TSaldanal& s) const
{
  TDate dataini;  //data da cui iniziare la scansione dei movimenti analitici (!=dal) 
  if (dal.ok())
  {
    const int annoprec = _esc.date2prevesc(dal);
    if (annoprec > 0)
      dataini = _esc[annoprec].fine()+1L;
    else
    {
      const int curr_eser = _esc.date2esc(dal);
      if (curr_eser > 0)
        dataini = _esc[curr_eser].inizio();
      else
        dataini = TDate(1,1,dal.year());
    }
  }

  TString query, select;

  if (b.costo().full())
  {
    if (select.full())
      select << "&&";
    select << "(CODCCOSTO==\"" << b.costo() << "\")";
  }
  if (b.commessa().full())
  {
    if (select.full())
      select << "&&";
    select << "(CODCMS==\"" << b.commessa() << "\")";
  }
  if (b.fase().full())
  {
    if (select.full())
      select << "&&";
    select << "(CODFASE==\"" << b.fase() << "\")";
  }
  //se il conto dovesse essere vuoto (dio ce ne scampi, ma qualche utonto lo ha fatto nelle tabelle di ripartizione!)..
  //..l'eventuale filtro sulle date va fatto nella SELECT
  if (b.conto().blank())
  {
    if (dataini.ok() || al.ok())
    {
      if (select.full())
        select << "&&";
      select << "(BETWEEN(DATACOMP," << dataini.date2ansi() << "," << al.date2ansi() << "))";
    }
  }


  query << "USE RMOVANA KEY 2\n";
  if (select.full())
    query << "SELECT " << select << "\n";

  // Faccio la join solo se mi serve il tipo movimento in testata
  const bool filtra_tipo = (tipo & _saldanal_qualsiasi) != 0 && 
                           (tipo & _saldanal_qualsiasi) != _saldanal_qualsiasi;
  if (filtra_tipo)
    query << "JOIN MOVANA INTO NUMREG==NUMREG\n";

  //se il conto � buono, anzich� passare per la SELECT usa la chiave 2 con il FROM/TO
  if (b.conto().full())
  {
    query << "FROM CODCONTO=\"" << b.conto() << '"';
    if (dataini.ok())
      query << " DATACOMP=" << dataini;
    query << "\n";

    query << "TO CODCONTO=\"" << b.conto() << '"';
    if (al.ok())
      query << " DATACOMP=" << al;
    query << "\n";
  }
  TISAM_recordset rmovana(query);

  for (TRecnotype i = 0; rmovana.move_to(i); i++)
  {
    // Controllo il tipo movimento solo se necessario
    if (filtra_tipo)
    {
      const char tipomov = rmovana.get("107.TIPOMOV").as_string()[0];
      int ntipomov = 0;
      if (tipomov == 'P')
        ntipomov = _saldanal_preventivo; else
      if (tipomov == 'V')
        ntipomov = _saldanal_variazione; 
      else
        ntipomov = _saldanal_consuntivo; 
      if ((ntipomov & tipo) == 0)
        continue;
    }

    const TDate data = rmovana.get(RMOVANA_DATACOMP).as_date();
    const TImporto imp(rmovana.get(RMOVANA_SEZIONE).as_string()[0], 
                       rmovana.get(RMOVANA_IMPORTO).as_real());
    if (data >= dal)
    {
      if (imp.sezione() == 'D')
        s._dare += imp;
      else
        s._avere += imp;
      s._movimentato = true;
			if (ca_ori_present(rmovana))
			{
				if (imp.sezione() == 'D')
					s._dareind += imp;
				else
					s._avereind += imp;
			}
    }
    else
    {
      s._ini += imp;
			if (ca_ori_present(rmovana))
	      s._iniind += imp;
    }
  }
  return s._movimentato;
}

bool TSaldi_cache::saldo_movimenti(const TAnal_bill& b, 
                                   const TDate& dal, const TDate& al, 
                                   word tipo, TSaldanal& s)
{
  bool movim = false;
  if (tipo & _saldanal_riclassify)
  {
    // Legge tabella di riclassificazione
    const TString_array& table = _riclass.conti(b.conto());
    if (!table.empty())
    {
      TAnal_bill c(b); // Conto riclassificato
      FOR_EACH_ARRAY_ROW(table, i, row)
      {
        c.set_conto(*row);
        movim |= int_saldo_movimenti(c, dal, al, tipo, s);
      }
    }
  }
  else
    movim = int_saldo_movimenti(b, dal, al, tipo, s);
  return movim;
}

bool TSaldi_cache::saldi(const TAnal_bill& bill, const TDate& dal, const TDate& al, 
                         word tipo, TSaldanal& s)
{
  if (dal.ok() || al.ok())
  {
    // Calcolo i saldi fino all'anno scorso.
    // In assemza di data iniziale mi torna 0
    const int anno_prec = _esc.date2prevesc(dal);
    if (anno_prec > 0 && bill.conto().full())
    {
      // Calcolo il saldo precedente solo per attivita' e passivita'
      const TIndbil indbil = bill.indicatore_bilancio();
      if (indbil == ib_attivita || indbil == ib_passivita)
      {
        TImporto dare, avere;
        saldo_annuale(bill, 0, anno_prec, tipo, dare, avere);
        s._ini = dare;
        s._ini += avere;
      }
    }

    if ((tipo & _saldanal_ultima_imm) != 0)
    {
      // Calcolo i saldi di quest'anno
      // In assemza di data iniziale somma tutti gli anni (fino al 9999)
      const int anno_ini = _esc.date2esc(dal);
      const int anno_fin = anno_ini > 0 ? anno_ini : 0;
      s._movimentato = saldo_annuale(bill, anno_ini, anno_fin, tipo, s._dare, s._avere);
    }
    else
    {
      saldo_movimenti(bill, dal, al, tipo, s);
    }
  }
  else
  {
    // Se non viene specificata nessuna data voglio il saldo all'ultima immissione
    s._movimentato = saldo_annuale(bill, 0, 0, tipo, s._dare, s._avere);
  }

  s._ini.normalize();
  s._fin = s._ini; 
  s._fin += s._dare; 
  s._fin += s._avere;
  s._finind = s._iniind; 
  s._finind += s._dareind; 
  s._finind += s._avereind;
  s._finind.normalize();

  return s._movimentato;
}

TObject* TSaldi_cache::key2obj(const char* key)
{
  TSaldanal* s = new TSaldanal;

  TToken_string tok(key);
  const TAnal_bill bill(tok.get(0), tok.get(1), tok.get(2), tok.get(3));
  const TDate dal = tok.get(4); // Le get precedenti avvengono in ordine inverso!
  const TDate al = tok.get();
  const int tipo = tok.get_int();
  saldi(bill, dal, al, tipo, *s);                    
  return s;
}

const TSaldanal& TSaldi_cache::saldo(const TAnal_bill& bill, const TDate& dal, const TDate& al, word tipi)
{
  TToken_string key;
  key.add(bill.conto(), 0);
  key.add(bill.costo(), 1);
  key.add(bill.commessa(), 2);
  key.add(bill.fase(), 3);
  key.add(dal, 4);
  key.add(al, 5);
  key.add(tipi, 6);
  return *(const TSaldanal*)objptr(key);
}


TSaldi_cache::TSaldi_cache() : TCache(3881)  // Numero primo
{ }

const TSaldanal& ca_saldo(const TAnal_bill& bill, const TDate& dal, const TDate& al, word tipi)
{
  static TSaldi_cache* cache = NULL;
  if (tipi == 0 && cache != NULL)
  {
    delete cache;
    cache = NULL;
  }
  if (cache == NULL)
    cache = new TSaldi_cache;
  return cache->saldo(bill, dal, al, tipi);
}


////////////////////////////////////////////////////////
// TAnal_report_mask
////////////////////////////////////////////////////////

bool TAnal_report_mask::on_field_event(TOperable_field& , TField_event , long )
{
	return true;
}

int TAnal_report_mask::create_sheet_fields(short sheet_id, int lf, int& y, short& dlg)
{
	TSheet_field& sf = sfield(sheet_id);
  TMask& sm = sf.sheet_mask();

  const int h = ca_create_fields(sm, 0, lf, 1, y, dlg, short(dlg+50));

  for (int i = 0; i < h; i++)
  {
    TEdit_field& fld = sm.efield(short(dlg+i));
    int logic = lf;
    if (logic == LF_FASI)
    {
      const TMultilevel_code_info& fasinfo = ca_multilevel_code_info(LF_FASI);
      if (fasinfo.parent() != 0)
      {
        const TMultilevel_code_info& parinfo = ca_multilevel_code_info(fasinfo.parent());
        if (i < parinfo.levels())
          logic = fasinfo.parent();
      }
    }

    const char* fieldname = NULL;
    switch(logic)
    {
    case LF_CDC     : fieldname = RMOVANA_CODCCOSTO; break;
    case LF_COMMESSE: fieldname = RMOVANA_CODCMS;   break;
    case LF_FASI    : fieldname = RMOVANA_CODFASE;  break;
    default         : fieldname = RMOVANA_CODCONTO; break;
    }
    TFieldref* f = (TFieldref*)fld.field();
    f->set_name(fieldname);
    
    fld.check_type(CHECK_SEARCH);	//search e non normal perch� nelle..
		//..stampe non si vuole la fase legata alla commessa/cdc

    TEdit_field& dfld = sm.efield(short(dlg+50+i));
    dfld.set_field(EMPTY_STRING); // Toglie campi che fan saltare gli output!
  }

  y += h+1;
  dlg = short(dlg+h);

  return h;
}

void TAnal_report_mask::create_sheet(short sheet_id)
{
	TSheet_field& sf = sfield(sheet_id);
  TMask& sm = sf.sheet_mask();
  sm.hide(-1);

  const TMultilevel_code_info& fasinfo = ca_multilevel_code_info(LF_FASI);

	TConfig& ini = ca_config();

  int y = 1;
  short dlg = S_CDC1 + 100; // id del primo campo da generare

  for (int i = 0; i < 2; i++)
  {
    const TString& level = ini.get("Level", NULL, i+1);  // Legge il livello 1 o 2
    if (level == "CDC")                                  // Crea centro di costo 
    {
      if (fasinfo.parent() == LF_CDC)
        create_sheet_fields(sheet_id, LF_FASI, y, dlg);
      else
        create_sheet_fields(sheet_id, LF_CDC, y, dlg);

    } else
    if (level == "CMS")                                   // Crea commessa
    {
      if (fasinfo.parent() == LF_COMMESSE)
        create_sheet_fields(sheet_id, LF_FASI, y, dlg);
      else
        create_sheet_fields(sheet_id, LF_COMMESSE, y, dlg);
    }
  }

  if (fasinfo.levels() > 0 && fasinfo.parent() <= 0)
    create_sheet_fields(sheet_id, LF_FASI, y, dlg);

	for (short id = S_CDC12+100; id >= S_CDC1+100; id--)
  {
    const int pos = sm.id2pos(id);
    if (pos >= 0)
    {
      TMask_field& f = sm.fld(pos);
      const int size = f.size();
      const TString& prompt = f.prompt();
      sf.set_column_header(id, prompt);
      sf.set_column_justify(id, f.is_kind_of(CLASS_REAL_FIELD));
      sf.set_column_width(id, (max(3+size, prompt.len()+1)) * CHARX);
    }
    else
      sf.delete_column(id);
	}
}

int TAnal_report_mask::get_row_bill(TSheet_field& sf, int r, TAnal_bill& bill)
{
  int flag = 0;
  if (r >= 0 && r < sf.items())
  {
    int idx = sf.cid2index(S_CDC1);
    TToken_string& row = sf.row(r);
    for (int level = 0; level <= 2; level++)
    {
      const TMultilevel_code_info* info = ca_multilevel_code_info_by_index(level);
      if (info == NULL)
        break;
      TString20 code;
      for (int i = 0; i < info->levels(); i++)
        code << row.get(idx++);
      switch (info->logic())
      {
      case LF_CDC     : bill.set_costo(code);    flag |= 1; break;
      case LF_COMMESSE: bill.set_commessa(code); flag |= 2; break;
      case LF_FASI    : bill.set_fase(code);     flag |= 4; break;
      default: break;
      }
    }
  }
  return flag;
}

int TAnal_report_mask::set_row_bill(TSheet_field& sf, int r, const TAnal_bill& bill)
{
  int flag = 0;
  int idx = sf.cid2index(S_CDC1);
  TToken_string& row = sf.row(r);
  for (int level = 0; level <= 2; level++)
  {
    const TMultilevel_code_info* info = ca_multilevel_code_info_by_index(level);
    if (info == NULL)
      break;
    TToken_string code;
    switch (info->logic())
    {
    case LF_CDC     : code = bill.costo();    flag |= 1; break;
    case LF_COMMESSE: code = bill.commessa(); flag |= 2; break;
    case LF_FASI    : code = bill.fase();     flag |= 4; break;
    default: break;
    }
    info->unpack(code);
    FOR_EACH_TOKEN(code, tok)
      row.add(tok, idx++);
  }
  
  return flag;
}

bool TAnal_report_mask::esistono_riclassificazioni() const
{
  TLocalisamfile ric(LF_PANAPDC);
  return ric.first() == NOERR;
}