// 771230.cpp - Quadri C, D, D1, E, E1, E2
#include <relapp.h>
#include <config.h>
#include <msksheet.h>
#include <sort.h>
#include <tabutil.h>
#include <progind.h>
#include "caus77.h"
#include "77lib.h"
#include "scperc.h"
#include "rpag.h"
#include "perc.h"
#include "prospe1.h"
#include "defmask.h"
#include "771230a.h" 
#include "774200.h"

class TQuadroC_E2 : public TRelation_application
{
  private:                                             
    TString			_quadro;	// Codice del quadro in gestione        
    bool  			_registra;  // Se TRUE fa i riporti
    
    struct righe_pag
    {
     char tipoa;
     char codan[6];
     char codcau[3];
     char perc[7]; //3 + 2decimali + la virgola
     real somme;
     real impo;
     real rite;
     real comp;
     bool acim;
     bool bInps;
     real inps;                                 
    };
    righe_pag*       _rig;
    TRelation*       _rel;
    TMask*           _msk[2];
    TSort*           _sort;
    long             _codanagr;
    char             _tipoa, _tipoq;
    int              _nproga;
    int              _mode;
    int              _anno_dic;  // anno dichiarazione
    TLocalisamfile*  _per, *_scper, *_rpag, *_qd;
    TTable*          _ca7; 
    TRiporti         _rip;
    
    int   			_file;

  private:               
    static bool nprog_handler   (TMask_field& f, KEY key);
    static bool codanagr_handler(TMask_field& f, KEY key);
    static bool genera_handler  (TMask_field& f, KEY key);
    static bool codditta_hnd    (TMask_field& f, KEY key);    
    static bool setta_nprog     (TMask_field& f);
    static bool imponibile_hnd  (TMask_field& f, KEY key);

    bool QuadroC()  const { return _tipoq == 'C'; }  
    bool QuadroD()  const { return _tipoq == 'D'; }  
    bool QuadroD1() const { return _tipoq == '1'; }  
    bool QuadroE()  const { return _tipoq == 'E'; }  
    bool QuadroE1() const { return _tipoq == '2'; }  
    bool QuadroE2() const { return _tipoq == '3'; }  
                    
  protected:
    virtual bool user_create();
    virtual bool user_destroy();
    virtual int  rewrite(const TMask& m);
    virtual int  write  (const TMask& m);  
    virtual bool remove();
    virtual TRelation* get_relation() const { return _rel; }
    virtual TMask* get_mask(int mode);
    virtual bool changing_mask(int mode);  
    virtual void init_query_mode (TMask&);
    virtual void init_query_insert_mode (TMask&);    
    virtual void on_config_change();    
    
    TMask* load_mask(int n);
    bool generazione(); 
    bool azzera_quadro();
    void riempi_record(char,long,int,const real&,const real&,
                       const real&,const real&,const real&,bool,
                       const real& inps_perc, bool bCinps=FALSE);
    void init_sort(); 
    void leggi_sort(TProgind&);
    TRectype& look_causali(int c);
    int anno_dic() const { return _anno_dic; }
    bool scrivi_dati_per(TRectype& rec);
    void genera_prospetto(int,real&,real&,real&);
        
  public:                    
    TQuadroC_E2(char tipo);
    virtual ~TQuadroC_E2() {};
};                    

inline TQuadroC_E2& app() { return (TQuadroC_E2&) main_app(); }

TQuadroC_E2::TQuadroC_E2(char tipo): _rel(NULL), _mode(0), _tipoq(tipo)
{  
  memset(_msk, 0, sizeof(_msk));  
}

bool TQuadroC_E2::changing_mask(int mode)
{
  if (mode == MODE_QUERY)
    return _mode != MODE_QUERY;
  else
    return TRUE;
}
        
TMask* TQuadroC_E2::get_mask(int mode)
{
  const int m = (mode == MODE_QUERY) ? 0 : 1;
  _mode = mode;
  return load_mask(m);
}

TMask* TQuadroC_E2::load_mask(int n)
{
  if (_msk[n] != NULL) 
    return _msk[n]; 
    
  TFilename name("771230"); 
  
  if (n == 0) 
  { 
    switch (_tipoq) 
    {
    case 'C':
      name << 'd';
      break;
    case 'D':
      name << 'a';
      break;
    case '1':
      name << 'e';
      break;
    case 'E' :
      name << 'g';
      break;
    case '2' :
      name << 'i';
      break;       
    case '3':
      name = "77qe2a";
      break;
    default:
      break;
    }
  }
  else 
  {
    switch (_tipoq)
    {
    case 'C':
      name << 'f';
      break;
    case 'D':
      name << 'b';
      break;
    case '1':
      name << 'c';
      break;      
    case 'E':
      name << 'h';
      break;
    case '2' :
      name << 'l';
      break;        
    case '3':
      name = "77qe2b";
      break;
    default:
      break;
    }
  }  
  
  TMask* m = new TMask(name);

  switch (n)
  {                                   
    case 0:
      if (m)
      {        
       m->set_handler(F_CODDITTA, codditta_hnd);
       m->set_handler(F_NPROG, nprog_handler);
       m->set_handler(F_CODANAGRCOM, codanagr_handler);
       m->set_handler(F_CODANAGRPERC, codanagr_handler);
       if (_quadro != "E2")
         m->set_handler(F_GENERA, genera_handler);    
      }
      break;
    case 1:                                 
      if (m)
      {
        m->set_handler(F_IMPONIBILE, imponibile_hnd);
        m->set_handler(F_PERC,       imponibile_hnd);
      }
      break;
    default:
      break;  
  }        
  m->disable(DLG_FINDREC);
  
  return _msk[n] = m;
}

// Ricerca e output dell'ultimo nprog del percipiente scelto
bool TQuadroC_E2::setta_nprog(TMask_field& f)
{
  long  nprog = 0L;
  const char tipoa    = f.mask().get(F_TIPOA)[0];
  const long codanagr = atol(f.get());
  const long codditta = get_firm_770();
  
  TLocalisamfile quad(app()._file);
    
  quad.zero();
  quad.put("CODDITTA", codditta);
  quad.put("TIPOA",    tipoa);
  quad.put("CODANAGR", codanagr);
    
  TRectype rec(quad.curr());
    
  quad.read();
    
  if (quad.curr() > rec) 
  {
    f.mask().set(F_NPROG, nprog+1);
    return TRUE;
  }
      
  for ( ; !quad.eof(); quad.next())   
  {
    if (quad.curr() > rec) break;
    nprog = quad.get_long("NPROG");
  }

  //app()._last_scheda = nprog;

  f.mask().set(F_NPROG, nprog+1);
  return TRUE;
}

bool TQuadroC_E2::codditta_hnd(TMask_field& f, KEY k)
{         
  if (k == K_TAB && !f.mask().is_running())
  {
    TString16 codditta; codditta << get_firm_770();
    if (codditta != "0")        
    {
      f.set(codditta);
      f.check();
    }
  }   
  return TRUE;                                           
}

bool TQuadroC_E2::imponibile_hnd(TMask_field& f, KEY k)
{         
  if (k == K_TAB)
  {
    if (f.dlg() == F_PERC)
    {
      real perc (f.get());
      if (perc == ZERO)
      {                              
        int causale = f.mask().get_int(F_CODCAUS);
        TRectype& cau = app().look_causali(causale);
        real aliquota = cau.get_real(rPERC_RAC);
        f.mask().set(F_PERC, aliquota.string());
      }
    }

    real imponibile (f.mask().get(F_IMPONIBILE));
    real aliquota   (f.mask().get(F_PERC));
    
    real importo = ZERO;
    
    importo = imponibile * (aliquota/100);

    f.mask().set(app()._tipoq == 'C' ? F_RITENUTE : F_IMPORTO, importo.string());
  }   
  return TRUE;                                           
}

void TQuadroC_E2::init_sort()
{
  _rig  = new righe_pag;
  _sort = new TSort(sizeof(righe_pag));

  _sort->addsortkey ((char*)&(_rig->tipoa)  - (char*)&(_rig->tipoa), 1);
  _sort->addsortkey ((char*)&(_rig->codan)  - (char*)&(_rig->tipoa), 5);
  _sort->addsortkey ((char*)&(_rig->codcau) - (char*)&(_rig->tipoa), 2);
  _sort->addsortkey ((char*)&(_rig->perc)   - (char*)&(_rig->tipoa), 6);
  _sort->init();
}

void TQuadroC_E2::riempi_record(char t,long ca,int cc,const real& p, 
                             const real& so,const real& im,
                             const real& ri,const real& co,bool acim,
                             const real& inps, bool bInps)
{
  _rig->tipoa = t;
  sprintf(_rig->codan, "%5ld", ca);
  sprintf(_rig->codcau, "%02d", cc);
// 22.5.96 Cambiato il formato @@@,@@ con @.@@@,@@
// Ci vuole anche il punto delle migliaia se real::string() sbaglia 
// a calcolare il numero di decimali.
//  TString16 pp(p.string("@.@@@,@@"));
  double ppd = atof(p.string());
  sprintf(_rig->perc, "%.2f", ppd);
  _rig->somme = so;
  _rig->impo  = im;
  _rig->rite  = ri;
  _rig->comp  = co;
  _rig->acim  = acim;                        
  _rig->inps  = inps;                                    
  _rig->bInps = bInps;
  _sort->sort((const char*)_rig);
}    

bool TQuadroC_E2::genera_handler(TMask_field& f , KEY k)
{
  if (k == K_SPACE)  
  {
    app().generazione();
    app()._registra = TRUE; // Genera i riporti alla fine
  }
  return TRUE;
}

TRectype& TQuadroC_E2::look_causali(int codc)
{                            
  TString16 dep;
  _ca7->zero();
  dep.format("%02d", codc);
  _ca7->put("CODTAB", dep);
  _ca7->read();      
  if (_ca7->bad())
     _ca7->zero();
  return _ca7->curr();
}

bool TQuadroC_E2::generazione()
{ 
  if (!yesno_box("Conferma la generazione ?"))
    return FALSE;

  init_sort();
  
  TToken_string exp;
  exp.add("CODDITTA=CODDITTA");
  exp.add("TIPOA=TIPOA");
  exp.add("CODANAGR=CODANAGR");
  exp.add("NPROG=NPROG");
  
  TRelation rel (LF_SCPERC);
  rel.add(LF_RPAG, exp, 1);
  TString16 filt; filt.format("CODDITTA=%ld", get_firm_770());
  
  TCursor cur (&rel,filt,1);              
  
  azzera_quadro();
  
  TLocalisamfile& scperc = rel.lfile();
  TLocalisamfile& rpag   = rel.lfile(LF_RPAG);  
  cur = 0L;
  const long nitems = cur.items();  
  
  TProgind p(nitems ? nitems : 1, "Generazione in corso...", FALSE, TRUE, 70);
  long codan, codditta;
  char tipoa;
  int codcaus, nprog;
  TString16 qua;
  TDate datapag; 
  real perc=ZERO,somme=ZERO,impo=ZERO,rite=ZERO,comp=ZERO,inps=ZERO;
  
  for (; cur.pos() < nitems; ++cur)
  { 
    p.addstatus(1);
    
    codditta = scperc.get_long(SPR_CODDITTA);
    tipoa    = scperc.get(SPR_TIPOA)[0];
    codan    = scperc.get_long(SPR_CODANAGR);
    codcaus  = scperc.get_int(SPR_CODCAUS);
    nprog    = scperc.get_int(SPR_NPROG);
    
    TRectype  cau        = look_causali(codcaus);
    TString16 qua        = cau.get(bCODICE_QUADRO);
    bool      acc_imp    = cau.get_bool(bSOMME_ASSOG_RAC);
    bool	  bContrInps = cau.get_bool(bCONTRIBUTO_INPS);
                         
    if (_tipoq == 'D' && qua != "D")  continue;
    if (_tipoq == 'C' && qua != "C")  continue;  
    if (_tipoq == '1' && qua != "D1") continue;
    if (_tipoq == 'E' && qua != "E")  continue;
    if (_tipoq == '2' && qua != "E1") continue;
    
    if (cur.is_first_match(LF_RPAG))
    {
      TRecnotype nrec = rpag.recno();
      rpag.zero();
      rpag.setkey(1);
      rpag.put(PAG_CODDITTA, (long)codditta);      
      rpag.put(PAG_TIPOA, tipoa);
      rpag.put(PAG_CODANAGR, (long)codan);
      rpag.put(PAG_NPROG, nprog);
      TRectype recc (rpag.curr());
      for (rpag.read(_isgteq); !rpag.eof() ;rpag.next())
      {
        TRectype rec (rpag.curr());
        if (rec > recc) break;
        datapag = rpag.get(PAG_DATAPAG);
        if (datapag.year() != _anno_dic)
          continue;  
        //codtrib = cau.get_int("I0");
        perc  = rpag.get_real(PAG_PERC);
        somme = rpag.get_real(PAG_SPESA);
        rite  = rpag.get_real(PAG_RITENUTA);
        impo  = rpag.get_real(PAG_IMPONIBILE);
        comp  = rpag.get_real(PAG_COMPENSO);    
        inps  = rpag.get_real(PAG_INPSPERC);
        
        if (perc==ZERO && comp==ZERO && rite==ZERO && impo==ZERO 
            && somme==ZERO) 
          continue;
        riempi_record(tipoa,codan,codcaus,perc,somme,impo,rite,comp,acc_imp,inps,bContrInps);  
      } 
      rpag.readat(nrec);
    }
  }
  _sort->endsort();      
  
  leggi_sort(p);
  
  delete _rig;
  delete _sort;
  return TRUE;
}                

bool TQuadroC_E2::azzera_quadro()
{ 
  const char* title;
  
  if (_tipoq == 'C')
    title = "Azzeramento quadro C";
  else
    if (_tipoq == 'D')
      title = "Azzeramento quadro D";
    else    
      if (_tipoq == '1')
        title = "Azzeramento quadro D1";
      else 
        if (_tipoq == 'E')
          title = "Azzeramento quadro E";
        else
          title = "Azzeramento quadro E1";
                 

// Tutto cio' solo per contare gli items e far andare correttamente
// il "termometro" (sic..)
  TRelation rel (_file);
  TString16 filt; filt.format("CODDITTA=%ld", get_firm_770());
  TCursor cur (&rel,filt,1);           
//  TLocalisamfile& quadro = rel.lfile();   
  TLocalisamfile quadro(_file);                    
  cur = 0L;
  const long nitems = cur.items();  
  
  TProgind prog(nitems, title, FALSE, TRUE);

  quadro.zero();
  quadro.put("CODDITTA", (long)get_firm_770());
  TRectype dep(quadro.curr());
    
  for (quadro.read(); !quadro.eof(); quadro.next())
  { 
    prog.addstatus(1);
    if (quadro.curr() > dep) break;
    quadro.read(_isequal, _lock);
    quadro.remove();
  }   
  
  if (_tipoq == '2')
  {            
    TLocalisamfile quadro(LF_PROSPE1);                    
  
    TProgind prog(quadro.items(), "Azzeramento prospetto del quadro E1", FALSE, TRUE);
  
    quadro.zero();
    quadro.put("CODDITTA", (long)get_firm_770());
    TRectype dep(quadro.curr());
    
    for (quadro.read(); !quadro.eof(); quadro.next())
    { 
      prog.addstatus(1);
      if (quadro.curr() > dep) break;
      quadro.read(_isequal, _lock);
      quadro.remove();
    }   
  }
  return TRUE;
}     

void TQuadroC_E2::genera_prospetto(int cau, real& comp, real& impo, real& rite)
{
  TLocalisamfile pr (LF_PROSPE1);
  
  pr.setkey(1);
  pr.zero();
  pr.put(PRE_CODDITTA, (long)get_firm_770());
  pr.put(PRE_CODCAUS,  cau);
  if (pr.read() == NOERR)
  {
    comp += pr.get_real(PRE_COMPENSO);
    impo += pr.get_real(PRE_IMPONIBILE);
    rite += pr.get_real(PRE_RITENUTA);

    pr.put(PRE_COMPENSO,   comp);
    pr.put(PRE_IMPONIBILE, impo);
    pr.put(PRE_RITENUTA,   rite);
    pr.rewrite();    
  }
  else
  {
    pr.put(PRE_CODDITTA,   (long)get_firm_770());
    pr.put(PRE_CODCAUS,    cau);
    pr.put(PRE_COMPENSO,   comp);
    pr.put(PRE_IMPONIBILE, impo);
    pr.put(PRE_RITENUTA,   rite);
    pr.write();
  }
}

void TQuadroC_E2::leggi_sort(TProgind& p)
{
  TLocalisamfile qd(_file);
  const char* buf;
  TString16 keyp, key, perc, perc_p; 
  char tipoa, tipoa_p;
  long codanag, codanag_p;
  int codcaus_p, codcaus, nprog;
  real tot_somme=ZERO,tot_impo=ZERO,tot_rite=ZERO,tot_comp=ZERO, rQCInps=ZERO;
  real rTotQCInps    = ZERO;
  bool esiste_record = FALSE, acc_imp = FALSE;
  struct righe_pag* rp;

  keyp = key = ""; 
  nprog = 1;
  tot_somme = tot_impo = tot_rite = tot_comp = ZERO;
  
  while ((buf = _sort->retrieve()) != NULL)
  {
    p.addstatus(1);
    esiste_record = TRUE;
    rp = (struct righe_pag*)buf;
    tipoa   = rp->tipoa;           
    codanag = atol(rp->codan);
    codcaus = atoi(rp->codcau);
    perc    = rp->perc;                                                      
    acc_imp = rp->acim;
// non frega un tubo    bInps   = rp->bInps;  // se la riga aveva il contributo inps nella caus.
    rQCInps =  rp->inps;    

    if (QuadroE1() && !acc_imp) 
    {
      genera_prospetto(codcaus,rp->comp,rp->impo,rp->rite);
      esiste_record = FALSE;
    }
    else
    {
      key.format("%c%5ld%2d%s", tipoa, codanag, codcaus, (const char*)perc);
      if ( (key != keyp) && (keyp != "") ) 
      {
        qd.zero();
        qd.put("CODDITTA", (long)get_firm_770());
        qd.put("TIPOA",    tipoa_p);
        qd.put("CODANAGR", (long)codanag_p);
        qd.put("CODCAUS",  codcaus_p);                
        qd.put("NPROG",    nprog++);

// 12.6.96 aggiunto contributo inps        
        if (QuadroC())
          qd.put("CONTSSN", rTotQCInps);
          
        if (QuadroD() || QuadroC())
          qd.put("SOMME", tot_somme + tot_comp - tot_impo);
        else
          if (QuadroD1())
          {
            qd.put("QUOTAPRO", tot_comp - tot_impo);
            qd.put("SPESEANT", tot_somme);
          }
          else
            if (QuadroE())
              qd.put("SOMME",   tot_somme); 
            else
              if (QuadroE1())
                qd.put("SOMME", tot_comp);
        
        if (QuadroE1())
          qd.put("AMMONTARE",  tot_impo);
        else
          qd.put("IMPONIBILE", tot_impo);
        
        if (QuadroC())
          qd.put("RITENUTE", tot_rite);
        else
          qd.put("IMPORTO",  tot_rite);
    
        qd.put("PERC", perc_p);
      
//        if (_tipoq != 'E' && _tipoq != '2')
        if (!QuadroE() && !QuadroE1())
          qd.put("TOTALE", tot_comp + tot_somme);
        
//        if (_tipoq == '2')
        if (QuadroE1())
          qd.put("NETTO", tot_comp - tot_rite);
        else
          qd.put("NETTO", tot_impo - tot_rite); 
        qd.write();     
        rTotQCInps = tot_impo = tot_somme = tot_rite = tot_comp = ZERO;
      }                  
      
      tot_somme += rp->somme;
      tot_rite  += rp->rite;
      tot_impo  += rp->impo; 
      tot_comp  += rp->comp;
      rTotQCInps += rQCInps;
    
      if (tipoa_p != tipoa || codanag != codanag_p)
        nprog = 1;
      
      tipoa_p   = tipoa;        
      codanag_p = codanag;
      codcaus_p = codcaus;
      perc_p    = perc;
    
      keyp.format("%c%5ld%2d%s", tipoa_p, codanag_p, codcaus_p, (const char*)perc_p);
    } 
  }    // while (retrieve() != NULL)

  if (esiste_record)
  {
    qd.zero();
    qd.put("CODDITTA", (long)get_firm_770());
    qd.put("TIPOA",    tipoa_p);
    qd.put("CODANAGR", (long)codanag_p);
    qd.put("CODCAUS",  codcaus_p);                
    qd.put("NPROG",    nprog++);

//    if (_tipoq == 'D' || _tipoq == 'C')
    if (QuadroD() || QuadroC())
      qd.put("SOMME", tot_somme + tot_comp - tot_impo);
    else
//      if (_tipoq == '1')
      if (QuadroD1())
      {
        qd.put("QUOTAPRO", tot_comp - tot_impo);
        qd.put("SPESEANT", tot_somme);      
      }
      else                              
//        if (_tipoq == 'E')
        if (QuadroE())
          qd.put("SOMME",   tot_somme);
        else
//          if (_tipoq == '2')
          if (QuadroE1())
            qd.put("SOMME", tot_comp);
  
//    if (_tipoq == '2')
    if (QuadroE1())
      qd.put("AMMONTARE",  tot_impo);
    else
      qd.put("IMPONIBILE", tot_impo);
    
//    if (_tipoq == 'C')
    if (QuadroC())
      qd.put("RITENUTE", tot_rite);
    else
      qd.put("IMPORTO",  tot_rite);
      
    qd.put("PERC", perc_p);

// 12.6.96 aggiunto contributo inps
    if (QuadroC())
      qd.put("CONTSSN", rTotQCInps);
          
   
//    if (_tipoq != 'E' && _tipoq != '2')
    if (!QuadroE() && !QuadroE1())
      qd.put("TOTALE", tot_comp + tot_somme);

//    if (_tipoq == '2')
    if (QuadroE1())
      qd.put("NETTO", tot_comp - tot_rite);
    else
      qd.put("NETTO", tot_impo - tot_rite); 
    qd.write();     
  }  
}

bool TQuadroC_E2::codanagr_handler(TMask_field& f, KEY k)
{
  if (k == K_TAB && f.focusdirty())
  {                      
    TMask& m = f.mask();
    const long codanagr = atol(f.get()); 
    const char tipoa    = m.get(F_TIPOA)[0];
// 12.6.96 Non lascia andare avanti se il perc. non esiste
    if (!esiste_perc(tipoa, codanagr))
      return f.warning_box("Percipiente inesistente");
    if (app()._quadro != "E2")
      f.mask().disable(F_GENERA);
    TString16 dummy(f.get());
    if (dummy.not_empty())   
      setta_nprog(f);
  }
  return TRUE;
}

// Passa al modo inserimento/modifica.
bool TQuadroC_E2::nprog_handler(TMask_field& f, KEY key)
{
  if (!f.mask().is_running()) return TRUE;
  
  if (key == K_TAB)   
  {
    const int nprog = atoi(f.get());
    if (nprog==0) return TRUE;
    f.mask().stop_run(K_AUTO_ENTER); // entra in modo modifica (se il record che ha chiave specificata esiste gia') oppure
                                     // inserimento (se trova che non esiste)
  }                                   
  return TRUE;
}

bool TQuadroC_E2::scrivi_dati_per(TRectype& rec)
{
  TLocalisamfile dati_per(LF_PERC);
  const long codditta = rec.get_long("CODDITTA");
  char       tipoa    = rec.get_char("TIPOA");
  const long codanagr = rec.get_long("CODANAGR");
  
  dati_per.zero();
  dati_per.put("CODDITTA", codditta);    
  dati_per.put("TIPOA", tipoa);    
  dati_per.put("CODANAGR", codanagr);   
  
  const bool preesistente = (dati_per.read() == NOERR);
  
  if (!preesistente)
  {
    dati_per.zero();
    dati_per.put("CODDITTA", codditta);    
    dati_per.put("TIPOA", tipoa);    
    dati_per.put("CODANAGR", codanagr);   
  
    dati_per.write();   
  }
    
  return preesistente;
}

int TQuadroC_E2::rewrite(const TMask& m)
{
  m.autosave(_rel);
  const int err = _rel->rewrite();
  scrivi_dati_per(_rel->curr());         
  _registra = TRUE;
  return err;
}

int TQuadroC_E2::write(const TMask& m)
{
  m.autosave(_rel);
  const int err = _rel->write();
  scrivi_dati_per(_rel->curr());         
  
  _registra = TRUE;
  
  return err;
}

bool TQuadroC_E2::remove()
{
  _registra = TRUE;
  return TRelation_application::remove();
}

bool TQuadroC_E2::user_create()
{                      
  switch (_tipoq)
  {
  case 'C':
    _file   = LF_QUAC;
    _quadro = "C";
    break;
  case 'D':
    _file   = LF_QUAD;
    _quadro = "D";
    break;
  case '1':
    _file   = LF_QUAD1;
    _quadro = "D1";
    break;           
  case 'E':
    _file   = LF_QUAE;
    _quadro = "E";
    break;
  case '2':
    _file   = LF_QUAE1;
    _quadro = "E1";
    break;    
  case '3':
    _file   = LF_QUAE2;
    _quadro = "E2";
    break;    
  default:
    break;
  }
     
  _qd       = new TLocalisamfile(_file);
  _rel      = new TRelation(_file);
  _rpag     = new TLocalisamfile(LF_RPAG);
  _ca7      = new TTable ("%CA7");

  set_search_field(F_CODANAGRPERC);
  
  _registra = FALSE;
  
  load_mask(0);                                   

  return TRUE;
}

bool TQuadroC_E2::user_destroy()
{ 
  if (_msk[1] != NULL) delete _msk[1];
  if (_msk[0] != NULL) delete _msk[0];

  TString16 quadro = "";
  
  switch (_tipoq)
  {
  case 'C':
    quadro << "C";
    break;
  case 'D':
    quadro << "D";
    break;
  case '1':
    quadro << "D1";
    break;         
  case 'E':
    quadro << "E";
    break;
  case '2':
    quadro << "E1";
    break;    
  case '3':
    quadro << "E2";
    break;    
  default:
    break;
  }
  
  if (_registra)
    _rip.set(quadro);

  delete _rel; 
  delete _qd;
  delete _rpag;
  delete _ca7;
  
  return TRUE;
}

void TQuadroC_E2::on_config_change()
{                                
  TConfig conf(CONFIG_STUDIO);
  _anno_dic = (int)conf.get_long(ANNO_SEL, NULL); 
}

void TQuadroC_E2::init_query_mode(TMask& m)
{ 
  m.set(F_ANNODIC, _anno_dic); 
  if (_quadro != "E2")
    m.enable(F_GENERA); 
    
// forza il ricalcolo dell'ultimo numero disponibile
  TString16 dummy(m.get(F_NPROG));
  if (dummy.not_empty())
    setta_nprog(m.field(F_NPROG));

  m.send_key(K_SHIFT+K_CTRL+'h', -1);  // nasconde (hide) group 1 - Scelta ANAGR
  m.send_key(K_SHIFT+K_CTRL+'s', -2);  // abilita (show) group 2 - Ricerca su DATI PERC
}

void TQuadroC_E2::init_query_insert_mode(TMask& m)
{ 
  m.set(F_ANNODIC, _anno_dic);

  m.send_key(K_SHIFT+K_CTRL+'h', -2);  // group 3 Nasconde ricerca su PERC
  m.send_key(K_SHIFT+K_CTRL+'s', -1);  // group 1 Ricerca su ANAGR
}

int quadriC_E2(int argc, char* argv[])
{
  const char tipo = toupper(*argv[2]); 
  const char* title = "Quadro D";
  TQuadroC_E2 a(tipo);
  switch (tipo)
  {
    case '1':
      title = "Quadro D1";
      break;
    case 'C':
      title = "Quadro C";
      break;      
    case 'E':
      title = "Quadro E";
      break;
    case '2':
      title = "Quadro E1";
      break;
    case '3':
      title = "Quadro E2";
      break;
    default:
      break;    
  }
  a.run(argc, argv, title);
  return TRUE;
}