#include "770100a.h"
#include "770101.h"
#include "770102.h"
#include <tabutil.h>       
//
// Lista modifiche
//
// 27.5.96	work_tipoluogo() disabilita il campo PROGRBANCA e lo abilita
//			solo se e' un versamento in banca
//
//  5.6.96	Calcolo contributo INPS
// 22.7.96	Esegue controllo ritenuta solo se diversa da ZERO
//					Tolti tutti i trunc() per lasciare i decimali nei conti
// 24.7.96  Non considera piu' la perc. come 100 se lasciata vuota
// 					

HIDDEN TString80 	tmp1, tmp2;
HIDDEN real			__impo  = ZERO;
HIDDEN real			__compe = ZERO;
HIDDEN real			__percra = ZERO;
HIDDEN TString80	__rite;
HIDDEN bool __bRicalcolaRigaPag = FALSE;
HIDDEN real	__rCompensoCg = ZERO;
void CalcolaInps(const real& rPercCassaPrev,const real& rCompenso, const real &rPercContrInps,
                 const real& rPercAssContrInps,const real &rQuotaCommitContrInps, 
                 real& rInpsPerc,real &rInpsComplex);

void TSchedaPercipienti::init_mask(TMask& m)
{
  update_lasts(m);
  __bRicalcolaRigaPag = FALSE;       
  __rCompensoCg = ZERO;
  if (tipo_coll() != nessuno)
  {
    const bool variazione = coll_variazione();
    if (!variazione) compila_testata(m);
    switch (tipo_coll())
    {
      case pagamento:
      case occasionale:
// Compilo riga di pagamento SOLO SE NON ce ne sono gia'..
        if ( (tipo_coll() == pagamento && _rel->pag_items() == 0) 
              ||
              tipo_coll() == occasionale )          
        {
          const real totrit(m.get(F_TOTRIT));
          const real totdoc(m.get(F_TOTDOC));
          const real compenso(m.get(F_COMPENS));
          const real spese(m.get(F_SPESE));
                    
          if ( (tipo_coll() == pagamento && (_coll._compenso + totrit == totdoc) )
               ||
               (tipo_coll() == occasionale) )
          {
            TSheet_field& pags = (TSheet_field&)m.field(F_PAGAMENTI);            
            TRectype rpag(_rel->pag(0));
            rpag.zero();
            real& imponibile = _coll._compenso;
            rpag.put("DATAPAG",    _coll._datadoc);
            rpag.put("COMPENSO",   compenso);
            rpag.put("SPESA",      spese);  
// forza il ricalcolo della riga pag. (da check_causale)
            __bRicalcolaRigaPag = TRUE;
            __rCompensoCg = compenso;
// Update spreadsheet
            rec2row(pags.row(0), rpag, 0);
            pags.force_update();
          }
        }
//        break;
      default:               
// per evitare di riscrivere tutto dopo registra      
        _coll._tipo_coll = nessuno;
        break;
    }
  }             
  fill_sheet(m);
}

// Utilizzato in collegamento da cg
real TSchedaPercipienti::calcola_ritenuta(const real& imponibile, TString& sPercRa,
          real&  rPercCassaPrev,real& rPercContrInps,real& rPercAssContrInps,
                real& rQuotaCommitContrInps, bool& bContrInps)
{
  TTable cau("%ca7");
  TString codcau(curr_mask().get(F_CODCAUS));
  cau.zero();
  cau.put("CODTAB", codcau);
  cau.read();
  real rQuotaRaCaus = cau.get_real("R0");  
  sPercRa = cau.get("R0");
  bContrInps=cau.get_bool("B4");
  if (bContrInps)
  {
	  rPercCassaPrev=cau.get_real("R5");
	  rPercContrInps=cau.get_real("R1");
	  rPercAssContrInps=cau.get_real("R2");
	  rQuotaCommitContrInps=cau.get_real("R3");
  }
  else
  {
	  rPercCassaPrev=ZERO;
	  rPercContrInps=ZERO;
	  rPercAssContrInps=ZERO;
	  rQuotaCommitContrInps=ZERO;
  }
  real rite = ZERO;
  rite  =  (imponibile * rQuotaRaCaus)/100.00;
  return rite;
}

// Utilizzato in collegamento da cg  Forse ora da togliere..
real TSchedaPercipienti::calcola_imponibile(const real& compenso)
{                                            
  TTable cau("%ca7");
  TString codcau(curr_mask().get(F_CODCAUS));
  cau.zero();
  cau.put("CODTAB", codcau);
  if (cau.read() != NOERR)
    return ZERO;
  real        quota_imp   = cau.get_int("R4");
  TString16   cod_qua(cau.get("S1"));
  real        imponibile_calcolato = ZERO;
// Calcola imponibile                       
  if (compenso != ZERO) 
    imponibile_calcolato = (compenso * quota_imp) / 100.00;            
  return imponibile_calcolato;
}

bool TSchedaPercipienti::vers_notify(TSheet_field& s, int r, KEY k)
{
  switch(k)
  {                               
// Pulisco descrizioni luogo e tipo versamento (solo se non gia' indicati!)
    case K_SPACE: 
    {
      TSheet_field& vers = app().vers();   
      TMask& mp = vers.sheet_mask();          
      TString16 tipo(mp.get(F_TIPOVERS));
      TString16 luo (mp.get(F_LUOVERS));
      if (tipo.empty())
        mp.reset(70);  
      if (luo.empty())
        mp.reset(71);        
      break;
    }
    case K_INS:                   
    {   
// Aggiorna NUMVERS nella riga aggiunta  
/*      TSheet_field& vers = app().vers();
      TToken_string& riga = vers.row(r);
      riga.add(++(app()._lastvers), 7);
      break;*/
    }
    default:
      break;
  }
  return TRUE;
}

bool TSchedaPercipienti::pags_notify(TSheet_field& s, int r, KEY k)
{
  switch(k)
  {
// Pulisco i buffer di confronto  
    case K_ENTER:               
      __impo 	= ZERO;
      __compe	= ZERO;
      __percra	= ZERO;
      __rite = "";
      break;
    case K_INS:                   
    {   
// Aggiorna NUMVERS e NUMPAG nella riga aggiunta  
/*
      TSheet_field& pags = app().pags();
      TToken_string& riga = pags.row(r);
      riga.add(-1, 7);  
      riga.add(++(app()._lastpag), 8);
      break;         */
    }
    case K_SPACE:
    {
      app()._azzerato_pag = FALSE;
// Se c'e' competenza => diventa obbligatoria DATAPAG
      TSheet_field& pags = app().pags();   
      TMask& m = app().curr_mask();
// Salvo imponibile e compenso precedenti alla modifica.
// v. imponibile_handler e compenso_handler
      TToken_string& row = pags.row(r);
      __compe = row.get(1);
      __impo  = row.get(3);
      __percra = atof(row.get(4));
      __rite   = row.get(7);
      if (__percra == 0.0)
        __percra  = atof(s.mask().get(F_PERRIT));
      const long annoc = m.get_long(F_ANNOCOMP);
      const long mesec = m.get_long(F_MESECOMP);       
#define F_DATAPAG 101      
      TMask& mp = pags.sheet_mask();              
      TEdit_field& fld = mp.efield(F_DATAPAG);
      
      if (annoc != 0L || mesec != 0L)
        fld.check_type(CHECK_REQUIRED);
      else
        fld.check_type(CHECK_NONE);
      break;                        
    }
    default:
      break;
  }
  return TRUE;
}

TSheet_field& TSchedaPercipienti::pags() const
{
  TSheet_field& s = (TSheet_field&)curr_mask().field(F_PAGAMENTI);
  return s;
}

TSheet_field& TSchedaPercipienti::vers() const
{
  TSheet_field& s = (TSheet_field&)curr_mask().field(F_VERSAMENTI);
  return s;
}
              
bool TSchedaPercipienti::my_empty_items(TToken_string& r, bool vers)
{      
  TString rr;     
  
  if (vers)
   for (int i=0; i < COLONNE_SIGNIFICATIVE_SPREADSHEET_VERSAMENTI; i++)
   {
     rr = r.get(i);
     rr.trim();     
     switch (i) {
       case 0: // 1015
        if (rr.not_empty()) 
          return FALSE;
        break;       
       case 1:        
        if (rr.not_empty()) 
          return FALSE;
        break;       
       case 2:   // lugo e tipo vers.
       case 3:
        if (rr.not_empty())
          if (rr != "N") 
            return FALSE;
        break;
       case 4:
       case 5:
        if (rr.not_empty()) 
          return FALSE;      
        break;
       case 6:
         if (rr.not_empty()) {
           real   rrr(real::ita2eng(rr));
           if (rrr != ZERO) 
             return FALSE;
         }
         break;
       default:
         break;
    }
  }        
  else
    for (int i=0; i < COLONNE_SIGNIFICATIVE_SPREADSHEET_PAGAMENTI; i++)
    {
      rr = r.get(i);   
      rr.trim();
      switch (i) {
        case 0: // Data
          if (rr.not_empty()) 
            return FALSE;
          break;       
        case 1:   // Compenso  
          if (rr.not_empty()) {
            real rrr(real::ita2eng(rr)); 
            if (rrr != ZERO) 
              return FALSE;
          }
          break; 
        case 2:   // Spese e Imponibile
        case 3:  
          if (rr.not_empty()) {
            real rrr(real::ita2eng(rr)); 
            if (rrr != ZERO) 
              return FALSE;
          }
          break; 
        case 4:   // r.a. che faccio ?
          break;
        case 5:
        case 6:  
          if (rr.not_empty()) {    
            real rrr(real::ita2eng(rr)); 
            if (rrr != ZERO) 
              return FALSE;
          }
          break; 
        default:
          break;
      }
    }        
  return TRUE;
}

void TSchedaPercipienti::pag_pack()
{
  TString_array& rows = pags().rows_array();

  const int max = rows.items();
  for (int i = 0; i < max; i++)
  {
    TToken_string& r = (TToken_string&)rows[i];
    if (my_empty_items(r, FALSE))             // Remove all empty strings
      rows.destroy(i, FALSE);
  }

  rows.pack();
//  rows.sort(compare_rows);           // Pack and sort array
}
  
void TSchedaPercipienti::ver_pack()
{
  TString_array& rows = vers().rows_array();

  const int max = rows.items();
  for (int i = 0; i < max; i++)
  {
    TToken_string& r = (TToken_string&)rows[i];
    if (my_empty_items(r, TRUE))             // Remove all empty strings
      rows.destroy(i, FALSE);
  }
  rows.pack();
//  rows.sort(compare_rows);           // Pack and sort array
}


//
// LOAD_PAG_SHEET
//
// Inizializza array sheet dei pagamenti
// 
void TSchedaPercipienti::load_pag_sheet(const long numvers)
{
  real  comp, spese, imp, ritpag;
  int   i, iNumRigaAS;
  
  TSheet_field& pag = pags();
  _pags->destroy();

  iNumRigaAS = 0; 	// numero di riga dell'array-sheet. Viene incrementato
  					// solo quando si trovano pagamenti 'giusti' (cioe' solo
  					// quando si aggiungono elementi all'array-sheet)
  for ( i = 0; i < pag.items(); i++)
  {
    TToken_string* d    = new TToken_string(64);
    TToken_string& riga = pag.row(i);

// Scarto le righe non significative 
    if (my_empty_items(riga, FALSE)) continue;

    const long nvers = riga.get_long(9);
    
// "Se il pagamento e' gia' stato selezionato DA UN ALTRO versamento
//  NON si deve vedere! "    
    if (nvers > 0  &&  nvers != numvers) 
      continue; 

    const long npag = i;    
    
    const int LARGHEZZA_COL = 15;
    d->add(" ");                    // 0 spazio per la 'X' di selezione
    TString dep(riga.get(0));
    d->add(dep);                    // 1 data pagamento
    comp    = riga.get(1); 
    dep     = comp.string(".");
    dep.right_just(LARGHEZZA_COL);
    d->add(dep);       				// 2 compenso
    spese   = riga.get(2);      
    dep     = spese.string(".");
    dep.right_just(LARGHEZZA_COL);    
    d->add(dep);      				// 3 spese

// NB 
// se cambia posizione nriga o ritpag nella tokenstring cambia 
// anche in pag_select()!
    ritpag  =   riga.get(SS_POS_RITPAG);
    dep     = ritpag.string(".");     
    dep.right_just(LARGHEZZA_COL);        
    d->add(dep);
    
    d->add(i, SS_POS_NRIGA);
// Metto nell'array-sheet anche NUMVERS
    d->add(nvers, SS_POS_NVER);   
    
    _pags->add(*d);   // aggiungo la riga nell'array_sheet
// Setto il bit alla posizione numpag e metto la X
    if (nvers == numvers)
    {
      _selected.set(npag);    
      _pags->check(iNumRigaAS, TRUE);
    }                        
    iNumRigaAS++; // ignoro in questo contatore i pagamenti che NON 
                  // si vedono (se il pagamento e' scartato prima di qui
                  // non ci passa)
  }
}  

void TSchedaPercipienti::attach_pag_vers (int pag, long numvers)
{
  TSheet_field&  pag_s = pags();
  TToken_string& riga  = pag_s.row(pag);

// setta NUMVERS nello sheet
  riga.destroy(9);
  riga.add(numvers, 9);

// setta NUMVERS nel record
  _rel->pag(pag).put("NUMVERS", numvers);  
}

void TSchedaPercipienti::detach_pag_vers (int pag)
{
  TSheet_field& pag_s = pags();
  TToken_string& riga = pag_s.row(pag);

  riga.destroy(9);
  riga.add(-1L, 9);   

// setta NUMVERS nel record
  _rel->pag(pag).put("NUMVERS", -1L);    
}
                                                         
//
// VERS_ATTACHED ( numvers )
//
// Determina se c'e' ALMENO UN pagamento collegato al versamento NUMVERS
//                                                         
bool TSchedaPercipienti::vers_attached(const long numvers)
{
  long numv = 0L;

// Aggiorna lo sheet dei pagamenti per questo versamento
  app().load_pag_sheet(numvers);                        

  for (int j = 0; j < _pags->items(); j++)
  {
// Leggo NUMVERS
    TToken_string& riga  = _pags->row(j);
    numv = riga.get_long(SS_POS_NVER);

    if (numv > 0L)
      if (numv == numvers) 
        return TRUE;
  }
  return FALSE;
}

// 
// CHECK_PAGAMENTI
// Questo serve solo a impedire di uscire senza aver collegato almeno
// un pagamento
//                 
bool TSchedaPercipienti::check_pagamenti(TMask_field& f, KEY k)
{
  const long  numvers = get_numvers(f);
  return app().vers_attached(numvers);
} 

void TSchedaPercipienti::setta_ritvers(TMask_field& f, const real& ritenuta) 
{
  TString80 rit_str(ritenuta.string());
  f.mask().set(F_RITVERS, rit_str);     
  f.mask().field(F_RITVERS).set_dirty(); // Forza on_hit()    
}

// Guardo se ho compilato la data OPP. il flag 1015
// Leggo la maschera o la riga dello ss
bool TSchedaPercipienti::compilato_vers(TMask_field& f)
{
  TString16 datav;
  char v1015;
  
  if (f.mask().is_running())
  {
    datav = f.mask().get(F_DATAVERS);
    v1015 = f.mask().get(F_VERS_1015)[0];
  }
  else             
  {
    TSheet_field& ver    = app().vers();   
    const int riga_corr  = ver.selected();
    TToken_string& riga  = ver.row(riga_corr);
    v1015                = riga.get(0)[0];
    datav                = riga.get(1);
    datav.trim();
  }
  return datav.not_empty() || v1015 == 'X';
}     

  
//
// GET_NUMVERS
//
// Determina il numero di versamento corrente, prendendolo :
//
//      dalla maschera, se e' running SENNO'
//      dalla riga corrente dello spreadsheet
//                                     
long TSchedaPercipienti::get_numvers(TMask_field& f)
{
  long numvers = 0L;
  
// Prendo il numvers da campo nascosto nella maschera
  if (f.mask().is_running())
    numvers = f.mask().get_long(VERF_NUMVERS);
  else             
  {
    TSheet_field& ver    = app().vers();   
    const int riga_corr  = ver.selected();
    TToken_string& riga  = ver.row(riga_corr);
    numvers = riga_corr + 1;
//    numvers              = riga.get_long(SS_POS_NUMVERS);
  }
  return numvers;
}     

bool TSchedaPercipienti::pag_azzera (TMask_field& f, KEY k)
{     
  if (k == K_SPACE)
    app()._azzerato_pag = TRUE;  // Messo a FALSE in pag_notify
                       // Serve per NON far riscrivere la % di ritenuta
  return TRUE;
}

bool TSchedaPercipienti::ver_azzera (TMask_field& f, KEY k)
{     
  long        numvers = get_numvers(f);
  int         nriga   = 0;      
  TNikArray_sheet& pags = *app()._pags;
  
  if (k == K_SPACE)
  {    
    app().load_pag_sheet(numvers);       

    for (int j = 0; j < pags.items(); j++)
    {
      TToken_string& riga  = pags.row(j);
      long numv = riga.get_long(SS_POS_NVER);

      if (numv > 0L)
        if (numv == numvers) 
        {
          nriga =  pags.row(j).get_int(SS_POS_NRIGA);      
          pags.row(j).add(-1L, SS_POS_NVER);            
          app().detach_pag_vers(nriga);
        }
    }
  }
  return TRUE;
}

//
// PAG_SELECT
//
// Collegamento tra versamenti e pagamenti
//
// Calcolo ritenuta = SUM(ritpag) {dei pagamenti collegati} 
//
// Usa: load_pag_sheet() attach_pag_vers() e detach_pag_vers()
//
bool TSchedaPercipienti::pag_select (TMask_field& f, KEY k)
{
  if (k == K_SPACE)
  {                           
    if (!app().compilato_vers(f)) 
      return f.warning_box("Inserire prima la data del versamento");

    long        numvers = get_numvers(f);
    long        numpag  = 0L;
    int         nriga   = 0;      
// 13.7.95 Ricalcola la ritenuta, azzerando contenuto precedente
    real		ritenuta = ZERO;
    TBit_array& selected = app()._selected; 
    
    selected.reset();

// Costruisce array_sheet dei pagamenti     
    app().load_pag_sheet(numvers);       
    
    TNikArray_sheet& ASpags = *app()._pags;
/*
    const int iPagsASheetItems = ASpags.items();
// Metto la 'X' per quelli gia' collegati (se e' acceso il bit[NUMPAG])
    for (int j = 0; j < iPagsASheetItems; j++)
      ASpags.check(j, selected[j]);*/
                                                   
// seleziona e aggiungi alle gia' selezionate 
    if (ASpags.run() == K_ENTER)
    {
      for (int j = 0; j < ASpags.items(); j++)
      {
        // get effettivo numero riga pag.
        nriga =  ASpags.row(j).get_int(AS_POS_NRIGA);
                              
        int mesec = -1;
        int annoc = -1; // competenza
                                      
        if (ASpags.checked(j)) 
        {
// Scrive nello spread-sheet e nella relazione
          app().attach_pag_vers(nriga, numvers); 

 // Scrive nell'array_sheet (e' da qui che leggo dopo)
          ASpags.row(j).add((long)numvers, AS_POS_NVER);
          
          TDate datapag(ASpags.row(j).get(1));
          if (mesec < 0)
          {
            mesec = datapag.month();
            annoc = datapag.year();
          }
          else
          {
            if (mesec != datapag.month() || annoc != datapag.year())
// TBI inserire un'altra riga di versamento (?)
            ;
          }
          selected.set(numpag);

          real dep(real::ita2eng(ASpags.row(j).get(AS_POS_RITPAG)));
          ritenuta    +=  dep;
        }
        else       // pags.checked()
        {
// resetta se era stato settato prima        
          if (selected[numpag])  
          {
            selected.reset(numpag);
            ASpags.row(j).add(-1L, AS_POS_NVER);
            app().detach_pag_vers(nriga);
          }
        }
      }
      setta_ritvers(f, ritenuta);
    }  // if k==K_ENTER
  }
  return TRUE;
}       

#define F_SER_VERS        209
#define F_ABI_VERS        210
#define F_NUM_VERS        211
#define F_CAB_VERS        212
#define F_QUIETANZA_VERS  213

void TSchedaPercipienti::work_tipoluogo(TMask_field& f)
{
  TMask&  m       = f.mask();
  char    tipo    = m.get(F_TIPOVERS)[0];
  char    luogo   = m.get(F_LUOVERS)[0];
  TSheet_field& ss = app().vers();
  const int  row   = ss.selected();
                        
  m.hide (-2);            // nasconde tutto                    
//  ss.enable_cell(row,4);    

  if (tipo == 'B')                     
  {
    m.show (-6);    // ABI e CAB
    m.enable(SM_PROGRBANCA); // abilita progressivo vers.banca
    ss.enable_cell(row,6);
  }
  else
  {
    m.disable(SM_PROGRBANCA);
    ss.disable_cell(row,6);    

    if (tipo == 'D')
    {
      if (luogo == 'T') 
      {
        m.show(-3);     // SOLO quietanza
        ss.disable_cell(row,4);
      }
      else 
      {
        m.show(-4);     // serie e numero
        ss.enable_cell(row,4);    
      }
    }
//    else        
    if (tipo == 'C')
    {
      m.show (-5);  // SOLO numero versamento
      ss.disable_cell(row,4); 
    } 
  }
}

bool TSchedaPercipienti::luo_hndl(TMask_field& f, KEY k)
{
  if (k == K_TAB)
    work_tipoluogo(f);
    
  if (k == K_ENTER)
  {
    work_tipoluogo(f);
    TMask&  m       = f.mask();
    char    tipo    = m.get(F_TIPOVERS)[0];
    char    luogo   = m.get(F_LUOVERS)[0];

// Se ho indicato il luogo => devo indicare anche il TIPO
    if (isalpha(luogo)) 
      return tipo == ' ' || tipo == '\0' ? 
        f.warning_box("Indicare il tipo del versamento") : TRUE;
  }
  return TRUE;
                               
}

bool TSchedaPercipienti::abicab_hndl(TMask_field& f, KEY k)
{
  if (f.to_check(k))
  {
    TString16 park(f.get());
    TMask&  m       = f.mask();
    char    tipo    = m.get(F_TIPOVERS)[0];

// ABI/CAB solo se tipo e' B
    if (tipo != 'B')
      return TRUE;
          
    for (int i=0; i<park.len(); i++)
      if (!isdigit(park[i]))
        return f.warning_box("Il codice ABI/CAB deve essere numerico");
  }
  return TRUE;
}

bool TSchedaPercipienti::tipo_hndl(TMask_field& f, KEY k)
{
  if (k == K_TAB)
    work_tipoluogo(f);

  if (k == K_ENTER || k == K_TAB)
  {
    TMask&  m       = f.mask();
    char    tipo    = m.get(F_TIPOVERS)[0];
    char    luogo   = m.get(F_LUOVERS)[0];
    
// Se ho indicato il tipo => devo indicare anche il LUOGO
    if (isalpha(tipo)) 
      return luogo == ' ' || luogo == '\0' ? 
        f.warning_box("Indicare il luogo del versamento") : TRUE;
  }
  return TRUE;
}
                             
//
// VERS1015_HANDLER
//                             
bool TSchedaPercipienti::vers1015_handler(TMask_field& f, KEY k)
{
  if (k == K_ENTER)
  {
    TString16 datas      = f.mask().get(F_DATAVERS);
    const bool v1015     = f.mask().get_bool(F_VERS_1015);
    const bool attaccati = check_pagamenti(f,k);

    if (attaccati)
      if (!v1015 && datas.empty())
        return f.warning_box("Manca la data del versamento");
        
// Non considerare versamenti non significativi    
    if (v1015 || datas.not_empty())
      return attaccati ? TRUE : f.warning_box("Nessun pagamento collegato");

    const real rite (f.mask().get(F_RITVERS));
// Pero' se c'e' la ritenuta non lo far passare
    if (rite != ZERO)
      return f.warning_box("Manca la data oppure il flag di versamento 1015");
              
    return TRUE;
  }
          
  if (k == K_SPACE || k == K_F2)
  {
    TSheet_field& ss = app().vers();
    const bool v1015 = (f.get() == "X");
    const int  row   = ss.selected();
    int i;

// Disabilito tutto MA NON ritenuta        
    if (v1015) 
    {
// Se son gia' disabilitati non fare nulla
      if (ss.cell_disabled(row, 1)) 
        return TRUE;

      f.mask().reset(102);
      f.mask().reset(103);
      f.mask().reset(104);
      f.mask().reset(105);
      f.mask().reset(106);  
      
      f.mask().disable(102);
      f.mask().disable(103);            
      f.mask().disable(104);
      f.mask().disable(105);
      f.mask().disable(106);
                  
      for (i=1; i<6; i++)          
        ss.disable_cell(row,i);
    }
    else
    { 
      f.mask().enable(102);
      f.mask().enable(103);      
      f.mask().enable(104);
      f.mask().enable(105);
      f.mask().enable(106);
    
      for (i=1; i<6; i++)
        ss.enable_cell(row,i);    
    }
  }
  return TRUE;
}

//
// Quadro C e E1:   immissione per le sole persone fisiche
//
bool TSchedaPercipienti::check_causale(TMask_field& f, KEY k)
{
  TMask& m = f.mask();
  
  if (k == K_TAB && m.is_running())
//  if (f.to_check(k))
  {
    TFixed_string cod_caus(f.get(),3);
        
    if (cod_caus.empty())
    {
      KEY ke = m.last_key();
      if (ke != K_QUIT && ke != K_ESC)
        return f.warning_box("Manca la causale");
    }
    else
    {
      TString16   cod_qua  (m.get(F_CODQUA));
      char        tipo    = m.get(F_TIPOA)[0];

      if (cod_qua == "C" || cod_qua == "E1")
        if (tipo == 'G')
          return f.warning_box("Con il quadro C o E1 e' possibile l'immissione"
                               " per le sole persone fisiche");
      if (__bRicalcolaRigaPag)
      {                               
        real rInpsComplex, rInpsPerc;
        TSheet_field& pags = app().pags();      
        TMask& ssMask = pags.sheet_mask();       
        real rPercCassaPrev        = ZERO;
	      real rPercContrInps        = ZERO;
	      real rPercAssContrInps     = ZERO;
	      real rQuotaCommitContrInps = ZERO;
	      bool bContrInps=FALSE;

// aggiorna la riga ( collegamenti con 6(occas.) e 3(pag.) )        
        TString sPercRa(6);
        real rImpoCg = app().calcola_imponibile(__rCompensoCg);
        real rRiteCg = app().calcola_ritenuta(rImpoCg,sPercRa,rPercCassaPrev,
          rPercContrInps,rPercAssContrInps,rQuotaCommitContrInps,bContrInps); 
        TToken_string& tsRiga = pags.row(0);
        tsRiga.add(rImpoCg.string(), 3);
        tsRiga.add(sPercRa, 4);
        tsRiga.add(rRiteCg.string(), 5);                                   
// Calcola anche contributo INPS
        if (bContrInps)
        {
	        real rScorporaComp, rImpInps;
	        CalcolaInps(rPercCassaPrev,__rCompensoCg,rPercContrInps,rPercAssContrInps,
	                    rQuotaCommitContrInps,rInpsComplex,rInpsPerc);
	         
	        TString sInpsComp(rInpsComplex.string());
	        TString sInpsPerc(rInpsPerc.string());      
          tsRiga.add(sInpsPerc,6);
          tsRiga.add(sInpsComp,7);
        }                                        
// Calcola il netto                                     
        real rSpesa(tsRiga.get(2));
        real rNetto = __rCompensoCg-rRiteCg+rSpesa-rInpsPerc;
        tsRiga.add(rNetto.string(),8);
        pags.force_update(0);
// Per evitare che i valori vengano azzerati:
        __compe = __rCompensoCg;
        __impo  = rImpoCg;
        __percra = atof(sPercRa);
        __rite = rRiteCg.string();
      }
    }                            
  }
  return TRUE;
}

///////////////////////////////////////////////////////////////////////////
//
//  RIGA PAGAMENTI
//
///////////////////////////////////////////////////////////////////////////
//
// SPESA_HANDLER
//
// Forza il ricalcolo del netto se cambia la spesa
//
bool TSchedaPercipienti::spesa_handler(TMask_field& f, KEY k)
{
  if (k == K_TAB)
    f.mask().send_key(K_TAB, MPAG_NETTO);  // forza il ricalcolo del netto
  return TRUE;
}

// CHECK_RITENUTA
// o Controlla se la ritenuta e' corretta (SOLO SE != ZERO 22.7.96)
// o Ricalcola la ritenuta se e' stata vuotata
bool TSchedaPercipienti::check_ritenuta(TMask_field& f, KEY k)
{
  if (k == K_TAB)
  {
    TString rit(f.get());
    const bool changed_rit = __rite.not_empty() ? __rite != rit : FALSE;
    const real imponibile(f.mask().get(MPAG_IMPONIBILE));

    if (rit.empty())       
      calcola_ritenuta(f,imponibile);
    else
      if (changed_rit)
        f.mask().send_key(K_TAB, MPAG_NETTO);  // forza il ricalcolo del netto
  }

// Controlla solo se RITENUTA != ZERO
  if (k == K_ENTER)
  {                                
    TMask& m = f.mask();
    const bool forzatura = app().curr_mask().get_bool(F_FORCED);  
    real  perc_ra = (m.get_real(MPAG_PERCRA) );
    if (perc_ra == ZERO)
      perc_ra = 100.00;
    const real imponibile (m.get(MPAG_IMPONIBILE));
    real ritenuta (m.get(MPAG_RITPAG));

    if (ritenuta == ZERO)
      return TRUE;
      
    real rite = ZERO;
// Se non indico la percentuale => considero come 100%    
    if (perc_ra != ZERO)    
      rite  =  (imponibile * perc_ra) / 100.00;
    else
      rite = imponibile;

    rite.trunc();
    ritenuta.trunc();
    rite.round(0);
    ritenuta.round(0);              
    
#ifdef DBG
    TString rites(rite.string());
    TString riten(ritenuta.string());
#endif

// Segnala solo se la ritenuta calcolata non e' compresa in quella 
// letta piu' o meno 1    
    if ( (rite < ritenuta-1)  || (rite > ritenuta+1) )
    {
#ifdef DBG    
      f.warning_box("Ritenuta errata calcolo: %s trovo: %s", (const char*) rites, (const char*) riten);
#else
      f.warning_box("Ritenuta errata");  
#endif      
      return forzatura;
    }
  }
  return TRUE;
}

//
// CALCOLA_IMPONIBILE
//
// Chiamato dall'handler del COMPENSO
// Calcola l'imponibile SE il compenso e' diverso da ZERO
// e lo setta nella maschera
//                 
real TSchedaPercipienti::calcola_imponibile(TMask_field& f, const real& compenso, 
                                            const bool force)
{
  TMask& mm = app().curr_mask();
  TMask& lm = f.mask();
  real       quota_imp   = mm.get_real(F_QUOTAIMP);
  TString16   cod_qua    = mm.get(F_CODQUA);
  real        imponibile_calcolato = ZERO;
  const bool bContributoInps = mm.get_bool(F_FLAG_INPS);  
  const real imp_prec(lm.get(MPAG_IMPONIBILE));

// Ricalcolo sempre. NO! modifica del 4/10/95. Su richiesta di Omero
    if (imp_prec != ZERO && !force) 
      return imp_prec;

// Calcola imponibile                       
  if (compenso != ZERO) 
  {                       
    imponibile_calcolato = (compenso * quota_imp) / 100.00;
// 13.6.96 toglie il contributo inps
    if (bContributoInps)
    {
      real rPercCassaPrev=ZERO;
      rPercCassaPrev = mm.get_real(F_CASSA_PREV);
      imponibile_calcolato = (imponibile_calcolato / (100.00 + rPercCassaPrev)) * 100.00;
    }
    TString impost(imponibile_calcolato.string());
    lm.set(MPAG_IMPONIBILE, impost);
  }   
  return imponibile_calcolato;
}

bool TSchedaPercipienti::imponibile_handler(TMask_field& f, KEY k)
{                                  
  if (k == K_TAB)
  {
    const real imponibile(f.mask().get(MPAG_IMPONIBILE));
    const bool forza_ricalcolo = __impo != ZERO ? imponibile != __impo : FALSE;
    if (__impo != imponibile) 
      __impo = imponibile;
    if (forza_ricalcolo)
      calcola_ritenuta(f, imponibile, forza_ricalcolo);  
  }
  return TRUE;
}

void CalcolaInps(const real& rPercCassaPrev,const real& rCompenso, 
  const real& rPercContrInps,const real &rPercAssContrInps,
  const real& rQuotaCommitContrInps, real& rInpsPerc,real& rInpsComplex)
{
  real rScorporaComp, rImpInps;
  rScorporaComp = (rCompenso / (100.00 + rPercCassaPrev)) * 100.00;
  rImpInps      = (rScorporaComp / 100.00) * rPercAssContrInps;
  rImpInps.round(0);
  rInpsComplex  = (rImpInps / 100.00 ) * rPercContrInps;
// Se zero si considera 2/3
  if (rQuotaCommitContrInps == ZERO)
    rInpsPerc     = rInpsComplex - ((rInpsComplex * 2)/3);
  else
    rInpsPerc     = rInpsComplex - ((rInpsComplex * rQuotaCommitContrInps)/100.00);
}        

//  
// Handler del COMPENSO
//
// "Calcola ritenuta quando inserisci il compenso"    
// chiama calcola_imponibile se compenso e' cambiato
//
bool TSchedaPercipienti::compenso_handler(TMask_field& f, KEY k)
{
  TMask& mm = app().curr_mask();  	// main mask
  TMask& lm = f.mask();				// local mask
  const bool forzatura = mm.get_bool(F_FORCED);  
  real  compenso (lm.get(MPAG_COMPENSO));        
  real        imponibile = ZERO;
  TString16 cod_qua(mm.get(F_CODQUA));  
  const bool bContributoInps = mm.get_bool(F_FLAG_INPS);  
  bool bCambiatoCompenso = FALSE;

  if (k == K_TAB)
  {
    if (__compe != ZERO && compenso == ZERO)
      app()._azzerato_pag = FALSE;

    if (compenso == ZERO) 
      return TRUE;

    bCambiatoCompenso = __compe != ZERO ? __compe != compenso : FALSE;
    if (__compe != compenso) 
      __compe = compenso; // per evitare di perdere l'imponibile

    imponibile = calcola_imponibile(f, compenso, bCambiatoCompenso);
    
#ifdef DBG
    tmp1 = imponibile.string();
    tmp2 = compenso.string();
    if (cod_qua != "E1")    
      if (imponibile > compenso)
        warning_box("Imponibile = %s - Compenso = %s", (const char*)tmp1,(const char*)tmp2 );
#endif

    calcola_ritenuta(f, imponibile, bCambiatoCompenso);

// "Solo per il quadro E1 l'imponibile puo' essere maggiore del compenso"
    if (cod_qua != "E1")
      if (imponibile > compenso)
      {
        f.warning_box("L'imponibile non puo' essere" 
                      " maggiore del compenso");
        return forzatura;
      }

// Calcolo contributo INPS
    if (bContributoInps)
    {
      real rInpsPercPrima = lm.get_real(MPAG_INPSPERC);
      real rInpsCompPrima = lm.get_real(MPAG_INPSCOMP); 
      real rScorporaComp, rImpInps, rInpsComplex, rInpsPerc;
      real rPercCassaPrev        = mm.get_real(F_CASSA_PREV);
      real rPercContrInps        = mm.get_real(F_PERC_INPS);
      real rPercAssContrInps     = mm.get_real(F_PERC_ASS_INPS);      
      real rQuotaCommitContrInps = mm.get_real(F_PERC_COMMIT_INPS);
      CalcolaInps(rPercCassaPrev,compenso,rPercContrInps,rPercAssContrInps,
        rQuotaCommitContrInps,rInpsComplex,rInpsPerc);
         
      TString sInpsComp(rInpsComplex.string());
      TString sInpsPerc(rInpsPerc.string());      
// Setto i compensi INPS solo se prima erano vuoti
      if (rInpsPercPrima == ZERO || bCambiatoCompenso)
        lm.set(MPAG_INPSPERC, sInpsPerc);
      if (rInpsCompPrima == ZERO || bCambiatoCompenso)        
        lm.set(MPAG_INPSCOMP, sInpsComp); 
    }
    lm.send_key(K_TAB, MPAG_NETTO);  // forza il ricalcolo del netto
  }             
  
  if (k == K_ENTER)
  {
    // "Solo per il quadro E1 l'imponibile puo' essere maggiore del compenso"
    if (cod_qua != "E1")
      if (imponibile > compenso)
      {
        f.warning_box("L'imponibile non puo' essere" 
                      " maggiore del compenso");
        return forzatura;
      }
  }
  return TRUE;
}

//
// CALCOLA_RITENUTA
//
// Calcola la ritenuta in base alla % r.a. indicata ( o, se vuota, a quella 
// della causale ) e setta il campo della maschera
//  
//  --[ NB ]--
//              Ricalcola solo se VUOTA            
//
bool TSchedaPercipienti::calcola_ritenuta(TMask_field& f, const real& imponibile, const bool forza, const real percent)
{
  TMask& m=f.mask();
  real rPercRaRiga  = m.get_real(MPAG_PERCRA);
  real rPercRaCaus  = app().curr_mask().get_real(F_PERRIT);
  const bool   azzerato = app()._azzerato_pag;
  const real rit_prec(m.get(MPAG_RITPAG));

  if (rit_prec != ZERO && !forza) 
    return FALSE;

  real rPerc = ZERO;
// Uso la percentuale della causale SE NON indicata qui E
// SE NON viene passata come parametro (in percra_handler quando si cambia
// l'aliquota)
  if (percent == ZERO)
    rPerc = rPercRaRiga != ZERO ? rPercRaRiga : rPercRaCaus;      
  else
    rPerc = percent;
//
// Faccio vedere % R.A. presa dalla causale se non l'ho indicata
// e se non ho premuto Azzera (1.12.95)
// Pero' se uno fa azzera e poi riscrive il compenso deve riapparire...
//          
//  const bool prendi_ra_da_causale = forza ? TRUE : perc_ra == ZERO && !azzerato;
  const bool prendi_ra_da_causale = rPercRaRiga == ZERO && !azzerato;  
  if (prendi_ra_da_causale)
  {
    TString quota_rast(rPercRaCaus.string());
    m.set(MPAG_PERCRA, quota_rast);
  }
    
// Calcolo ritenuta ...
  real rite = (imponibile * rPerc) / 100.00;
    
// .. riempie il campo corrispondente 
  TString ritest(rite.string());
  m.set(MPAG_RITPAG, ritest);  
  m.send_key(K_TAB, MPAG_NETTO);  // forza il ricalcolo del netto  
  return TRUE;
}

// 
// Handler della percentuale di r.a.
// ricalcolo la ritenuta quando cambia
//
bool TSchedaPercipienti::percra_handler(TMask_field& f, KEY k)
{
  if (k == K_TAB)
  {
    const real  compenso (f.mask().get(MPAG_COMPENSO));    
    const real  imponibile (f.mask().get(MPAG_IMPONIBILE));    
    real percra(f.get());
    const bool forza_ricalcolo = __percra != percra;
    if (__percra != percra) 
      __percra = percra;

    if (compenso != ZERO) 
    {
      if (forza_ricalcolo)
        calcola_ritenuta  (f, imponibile, forza_ricalcolo);    
    }
  }
  return TRUE;
}

bool TSchedaPercipienti::netto_handler(TMask_field& f, KEY k)
{
  if (k == K_TAB)
    calcola_netto(f);
  return TRUE;
}

// 
// Calcola e setta il NETTO
//                 
// Il netto e' ricalcolato e settato sempre visto che non e' gestibile
//
real TSchedaPercipienti::calcola_netto(TMask_field& f)
{
  real netto = ZERO;
  TMask& m = f.mask();    
  const real ritenuta (m.get(MPAG_RITPAG));
  const real compenso (m.get(MPAG_COMPENSO));
  const real spesa    (m.get(MPAG_SPESA));
  const real inpsperc (m.get(MPAG_INPSPERC));
      
  netto = compenso - ritenuta + spesa - inpsperc;
//  netto.trunc();      
  f.mask().set(MPAG_NETTO, netto.string());
  
  return netto;
}