UPDATE **main_table** AS servi
INNER JOIN (
    SELECT s.serie, IFNULL(MAX(doc.numero),0) AS numero
    FROM **DB**.f_serie AS s
    INNER JOIN **DB**.f_causali AS cau ON (s.id=cau.idserie AND s.annocontabile=cau.annocontabile)
    LEFT JOIN **DB**.f_documenti AS doc ON (cau.id=doc.idcausale AND cau.annocontabile=doc.annocontabile)
    WHERE s.annocontabile=@annocontabile
    GROUP BY s.serie
    ORDER BY s.serie
) AS serie ON (servi.infe_serie=serie.serie)
SET servi.infe_numero=serie.numero
;
SET @num:=0
;
SET @serie:='.'
;
DROP TEMPORARY TABLE IF EXISTS **renum_table**
;
CREATE TEMPORARY TABLE IF NOT EXISTS **renum_table**
SELECT renum.idkey, renum.numero, renum.reset_serie AS serie
FROM (
    SELECT renum.idkey
    , @num:=IF(renum.serie!=@serie,renum.numero,@num) AS store_num
    , (@num:=@num+1) AS numero
    , @serie:=renum.serie AS reset_serie
    FROM
    (
        SELECT DISTINCT servi.idautista AS idkey, servi.infe_serie AS serie, servi.infe_numero AS numero
        FROM **main_table** AS servi
        WHERE servi.idautista IS NOT NULL AND servi.infe_importo!=0.00
        ORDER BY servi.data, idkey, serie
    ) AS renum
) AS renum
;
UPDATE **main_table** AS servi
INNER JOIN **renum_table** AS renum ON (servi.idautista=renum.idkey AND servi.infe_serie=renum.serie)
SET servi.infe_numero=renum.numero
;


INSERT INTO **DB**.f_documenti
(annocontabile,idcausale,numero,data,idpersona,no_bollo,last_modify,note,tommy_serv_fatt_type)
SELECT @annocontabile
, servi.infe_idcau
, servi.infe_numero
, IF(@data_fattura!='NONE',@data_fattura,servi.data)
, servi.infe_idpersona
, 0 AS no_bollo
, CAST(servi.idautista AS CHAR)
, servi.infe_serie
, 'S'
FROM (
    SELECT DISTINCT servi.infe_numero, servi.infe_idpersona, servi.idautista, MAX(servi.data) AS data, servi.infe_serie, servi.infe_idcau
    FROM **main_table** AS servi
    WHERE servi.idautista IS NOT NULL AND servi.infe_importo!=0.00
    GROUP BY servi.idautista, servi.infe_serie
) AS servi
;
UPDATE **main_table** AS servi
INNER JOIN **DB**.f_documenti AS doc ON (servi.idautista=CAST(doc.last_modify AS DECIMAL(10,0)) AND servi.infe_serie=doc.note)
SET servi.infe_iddocumento=doc.id
;


INSERT INTO **DB**.f_documenti_dettagli
(annocontabile,iddocumento,idvocedocumento,prezzo,quantita,um,importo,idiva,note,tommy_serv_fatt_type,sys_save_field)
SELECT @annocontabile
, servi.infe_iddocumento
, servi.infe_idvoce
, CAST( (servi.infe_importo*100/(100+servi.infe_iva_valore)) AS DECIMAL(12,2))
, 1
, servi.infe_um
, CAST( (servi.infe_importo*100/(100+servi.infe_iva_valore)) AS DECIMAL(12,2))
, servi.infe_idiva
, CONCAT('Data: ',InvData(servi.data),' - Num. servizio: ',IFNULL(servi.numero_servizio,''),' - Assistiti: ',IFNULL(servi.assistiti,'')) AS note
, servi.idautista
, servi.id
FROM **main_table** AS servi
WHERE servi.idautista IS NOT NULL AND servi.infe_importo!=0.00