# Docs functions




use Docs;
use Fees;
use Customers;	

$Docs = Docs->new($db, $admin, \%conf);
my $Fees     = Fees->new($db, $admin, \%conf);
my $Payments = Payments->new($db, $admin, \%conf);
my $Customer = Customers->new($db, $admin, \%conf);
my $Company  = $Customer->company();

#Default 20% VAT
$conf{DOCS_VAT_INCLUDE}=20 if (! defined($conf{DOCS_VAT_INCLUDE}));

#**********************************************************
# docs_print
#**********************************************************
sub docs_contract {
  my ($attr) = @_;
	
	if ($FORM{UID}) {
		my $user_main_info = $users->info($FORM{UID}, { SHOW_PASSWORD => 1 });
		$Docs              = $users->pi({ UID => $FORM{UID} });

    $conf{DOCS_LANGUAGE} = $conf{default_language} if (! $conf{DOCS_LANGUAGE});
		require "../../language/$conf{DOCS_LANGUAGE}.pl";
		require "../../Abills/modules/Docs/lng_$conf{DOCS_LANGUAGE}.pl";

    my ($y, $m, $d)=split(/-/, (($users->{CONTRACT_DATE}) ? $users->{CONTRACT_DATE} : $DATE ) , 3);
    $Docs->{CONTRACT_DATE_LIT} = "$d ". $MONTHES_LIT[int($m)-1] ." $y $_YEAR";

		%{ $attr } = %{ Docs }, %{ $user_main_info };
		my $contract_tpl = 'contract';

		if ($Docs->{CONTRACT_SUFIX}) {
			if ($conf{DOCS_CONTRACT_TYPES}) {
    	  #PREFIX:SUFIX:NAME;

        $conf{DOCS_CONTRACT_TYPES} =~ s/\n//g;
        my (@contract_types_list)=split(/;/, $conf{DOCS_CONTRACT_TYPES});
        foreach my $line (@contract_types_list) {
        	my ($prefix, $sufix, $name, $tpl_name)=split(/:/, $line);
        	
        	if ($sufix eq $Docs->{CONTRACT_SUFIX}) {
        	  $contract_tpl = $tpl_name;
        	
        	  $Docs->{CONTRACT_ID} .= $Docs->{CONTRACT_SUFIX};
        	  last;
        	 }
         }
       }
		 }
		docs_print($contract_tpl, { %$admin, %$Docs, %$attr });
	 }
}



#**********************************************************
# docs_invoice_add
# Order array format
# NAME|UNIT|COUNT|PRICE
#**********************************************************
sub docs_invoice_add  {
	my ($attr) = @_;

  if ($attr->{create}) {
   if (defined($FORM{OP_SID}) and $FORM{OP_SID} eq $COOKIES{OP_SID}) {
 	   $html->message('err', $_ERROR, "$_INVOICE $_EXIST");
 	   return 0;
    }
   elsif(! $attr->{CUSTOMER}) {
     $html->message('err', "$_ERROR", "$_ORG_NAME");
    }
   elsif($FORM{PREVIEW}) {
     docs_preview('invoice', { %FORM });
     return 0;
    }
   else {
     $Docs->{FROM} = $attr->{FROM} if ($attr->{FROM});
     $Docs->docs_invoice_add({ %$attr });

     if(! $Docs->{errno}) {
       if ($conf{DOCS_PDF_PRINT}) {
  	     $html->message('info', "$_INVOICE $_ADDED", "$_INVOICE $_NUM: [$Docs->{DOC_ID}] $_DATE: $FORM{DATE} ". $html->button($_PRINT, "qindex=$index&print=$Docs->{DOC_ID}&UID=$LIST_PARAMS{UID}&pdf=1", { ex_params => 'target=_new', BUTTON => 1 }));
   	     return 0;
        }
       else {
         $html->message('info', "$_INVOICE $_ADDED", "$_INVOICE $_NUM: [$Docs->{DOC_ID}] $_DATE: $FORM{DATE} ". 
           $html->button($_PRINT, "qindex=$index&print=$Docs->{DOC_ID}&UID=$LIST_PARAMS{UID}", { ex_params => 'target=_new', BUTTON => 1 }) );
         $Docs->docs_invoice_info($Docs->{DOC_ID});
        }
      }
     elsif ($Docs->{errno} && $Docs->{errno} == 1) {
     	 $html->message('err', $_ERROR, "$ERR_NO_ORDERS");	
     	 return 0;
      }
     elsif ($Docs->{errno} ) {
       $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}} $Docs->{errstr}");	
       return 0;
      }
    }
  }

  $Docs->{TOTAL_SUM}=0.00;

  if ($Docs->{ORDERS}) {
		my $i = 1;
		my @ORDERS = @{ $Docs->{ORDERS} };
		$Docs->{ORDER}='';
		foreach my $line (@ORDERS) {
			my $sum = sprintf("%.2f", $line->[3] * $line->[4]);

		  $Docs->{ORDER}.="<tr><th align='right'>$i</th><td align='left'>$line->[1]</td><td align='center'>$units[$line->[2]]</td>
		  <td align='right'>$line->[3]</td><td align='right'>$line->[4]</td><td align='right'>$sum</td></tr>";

   	  $Docs->{'ORDER_NUM_'.$i}   = $i;
      $Docs->{'ORDER_NAME_'.$i}  = $line->[1];
      $Docs->{'ORDER_COUNT_'.$i} = $count;
      $Docs->{'ORDER_PRICE_'.$i} = $line->[4];
      $Docs->{'ORDER_SUM_'.$i}   = $sum;
      $Docs->{'ORDER_PRICE_WITHOUT_VAT_'.$i} = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $line->[4] - $line->[4] / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $line->[4]);
      $Docs->{'ORDER_SUM_WITHOUT_VAT_'.$i}   = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $sum - $sum / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $sum);
		  $i++;
		  $Docs->{TOTAL_SUM}+=$sum;
		 }
	 }

  if ($Docs->{PAYMENT_ID}) {
    my $list = $Docs->accounts_list({ PAYMENT_ID => $Docs->{PAYMENT_ID} });
    if ($Docs->{TOTAL} > 0) {
      $Docs->account_info($list->[0]->[9]);	
     }
    $Docs->{ACCOUNT_ID}=$Docs->{ACCT_ID};
    
    push @PAYMENT_METHODS, @EX_PAYMENT_METHODS if (@EX_PAYMENT_METHODS);

    for(my $i=0; $i<=$#PAYMENT_METHODS; $i++) {
	    $PAYMENTS_METHODS{"$i"}="$PAYMENT_METHODS[$i]";
     }

    my %PAYSYS_PAYMENT_METHODS = %{ cfg2hash($conf{PAYSYS_PAYMENTS_METHODS}) };

    while(my($k, $v) = each %PAYSYS_PAYMENT_METHODS ) {
	    $PAYMENTS_METHODS{$k}=$v;
     }

    my $method = 0;


    $list = $Payments->list({ ID => $Docs->{PAYMENT_ID} });
    if ($Payments->{TOTAL} > 0) {
    	$method=$list->[0]->[6];

    	if ($conf{DOCS_PAYMENT_METHODS}) {
    		my %methods_hash = %{ cfg2hash($conf{DOCS_PAYMENT_METHODS}) };

        if ($methods_hash{$method}) {
          $Docs->{PAYMENT_METHOD}=$methods_hash{$method};
         }
        else {
        	$Docs->{PAYMENT_METHOD}=$methods_hash{0};
         }
    	 }
    	else {
        $Docs->{PAYMENT_METHOD} = $PAYMENT_METHODS[$method];
       }
     }
   }
 
  $Docs->{TOTAL_SUM} = sprintf("%.2f", $Docs->{TOTAL_SUM});

  $Docs->{'TOTAL_SUM_WITHOUT_VAT'}= sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $Docs->{TOTAL_SUM} - ($Docs->{TOTAL_SUM}) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $Docs->{TOTAL_SUM} );
  $Docs->{'TOTAL_SUM_VAT'}        = sprintf("%.2f", $Docs->{TOTAL_SUM}-$Docs->{'TOTAL_SUM_WITHOUT_VAT'});




  docs_print('invoice', $Docs) if (! $FORM{QUICK});
}



#**********************************************************
# docs_invoice_list
#**********************************************************
sub docs_invoice {
  my ($attr) = @_;

  if ($FORM{create}) {
    docs_invoice_add({ %FORM }); 
    return 0;
   }
  elsif (! $FORM{print}) {
    $Docs->{SEL_ORDER} .= $html->form_select('ORDER', 
                                    { 
 	                                   SELECTED    => $FORM{ORDER},
 	                                   SEL_ARRAY   => ($conf{DOCS_ORDERS})? $conf{DOCS_ORDERS} : [$_DV],
                                     NO_ID       => 1
 	                                  });

    #$Docs->{COMPANY_VAT}=$user->{COMPANY_VAT}.' %';
    $users->pi({ $users->{UID} });
    $Docs->{OP_SID}  = mk_unique_value(16);
    $Docs->{CUSTOMER}= $users->{FIO} || '-';
    $Docs->{CAPTION} = $_INVOICE;

    $html->tpl_show(_include('docs_account_add', 'Docs'), { %$Docs, %$users }) if (! $FORM{pdf});
   }


  docs_invoice_list();
}

#**********************************************************
# docs_invoice_list
#**********************************************************
sub docs_invoice_list {

push @PAYMENT_METHODS, @EX_PAYMENT_METHODS if (@EX_PAYMENT_METHODS);

for(my $i=0; $i<=$#PAYMENT_METHODS; $i++) {
  $PAYMENTS_METHODS{$i}=$PAYMENT_METHODS[$i];
 }

my %PAYSYS_PAYMENT_METHODS = %{ cfg2hash($conf{PAYSYS_PAYMENTS_METHODS}) };
while(my($k, $v) = each %PAYSYS_PAYMENT_METHODS ) {
  $PAYMENTS_METHODS{$k}=$v;
 }


if($FORM{del} && $FORM{is_js_confirmed}) {
  $Docs->docs_invoice_del($FORM{del});
  if(! $Docs->{errno}) {
    $html->message('info', "$_INFO", "$_DELETED N: [$FORM{del}]");
   }
  elsif ($Docs->{errno}) {
    $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}}");	
    return 0;
   }
 }
elsif($FORM{print}) {
  $Docs->docs_invoice_info($FORM{print}, { UID => $LIST_PARAMS{UID} });
  ($Docs->{SUM_MAIN}, $Docs->{SUM_SUB})=split(/\./, $Docs->{TOTAL_SUM});
  $Docs->{TOTAL_SUM}=0.00;
  
 
  if ($Docs->{ORDERS}) {
		my $i = 1;
		my @ORDERS = @{ $Docs->{ORDERS} };
		$Docs->{ORDER}='';
		foreach my $line (@ORDERS) {
			
			my $sum = sprintf("%.2f", $line->[3] * $line->[4]);
      $Docs->{ORDER}.="<tr><th align='right'>$i</th><td align='left'>$line->[1]</td><td align='center'>$units[$line->[2]]</td>
		      <td align='right'>$line->[3]</td><td align='right'>$line->[4]</td><td align='right'>$sum</td></tr>";
		  
   	  $Docs->{'ORDER_NUM_'.$i}   = $i;
      $Docs->{'ORDER_NAME_'.$i}  = $line->[1];
      $Docs->{'ORDER_COUNT_'.$i} = $line->[2];
      $Docs->{'ORDER_PRICE_'.$i} = $line->[4];
      $Docs->{'ORDER_SUM_'.$i}   = $sum;
       
      $Docs->{'ORDER_PRICE_WITHOUT_VAT_'.$i} = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $line->[4] - $line->[4] / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $line->[4]);
      $Docs->{'ORDER_SUM_WITHOUT_VAT_'.$i}   = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $sum - $sum / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $sum);
		  $Docs->{TOTAL_SUM}+=$sum;
		  $i++;
   	 }
	 }

  $Docs->{TOTAL_SUM} = sprintf("%.2f", $Docs->{TOTAL_SUM});

  if ($Docs->{PAYMENT_ID}) {
    my $list = $Docs->accounts_list({ PAYMENT_ID => $Docs->{PAYMENT_ID} });
    if ($Docs->{TOTAL} > 0) {
      $Docs->account_info($list->[0]->[10]);	
     }
    $Docs->{ACCOUNT_ID}=$Docs->{ACCT_ID};

    push @PAYMENT_METHODS, @EX_PAYMENT_METHODS if (@EX_PAYMENT_METHODS);

    for(my $i=0; $i<=$#PAYMENT_METHODS; $i++) {
	    $PAYMENTS_METHODS{"$i"}="$PAYMENT_METHODS[$i]";
     }

    my %PAYSYS_PAYMENT_METHODS = %{ cfg2hash($conf{PAYSYS_PAYMENTS_METHODS}) };

    while(my($k, $v) = each %PAYSYS_PAYMENT_METHODS ) {
	    $PAYMENTS_METHODS{$k}=$v;
     }

    my $method = 0;

    $list = $Payments->list({ ID => $Docs->{PAYMENT_ID} });
    if ($Payments->{TOTAL} > 0) {
    	$method=$list->[0]->[6];
    	
    	if ($conf{DOCS_PAYMENT_METHODS}) {
        my %methods_hash = %{ cfg2hash($conf{DOCS_PAYMENT_METHODS}) };        

        if ($methods_hash{$method}) {
          $Docs->{PAYMENT_METHOD}=$methods_hash{$method};
         }
        else {
        	$Docs->{PAYMENT_METHOD}=$methods_hash{0};
         }
    	 }
    	else {
        $Docs->{PAYMENT_METHOD} = $PAYMENT_METHODS[$method];
       }

     }
   }
  
  if ($conf{DOCS_VAT_INCLUDE}) {
   	 $Docs->{ORDER_TOTAL_SUM_VAT}  = sprintf("%.2f", $Docs->{TOTAL_SUM} / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}));
   	 $Docs->{TOTAL_SUM_WITHOUT_VAT}= sprintf("%.2f",$Docs->{TOTAL_SUM} - $Docs->{ORDER_TOTAL_SUM_VAT});
   	 $Docs->{VAT}                  = sprintf("%.2f", $conf{DOCS_VAT_INCLUDE});
   }
 
  docs_print('invoice', $Docs);
  return 0;
 }
elsif (! $LIST_PARAMS{UID}) {
  $info{PAYMENT_METHOD_SEL} = $html->form_select('PAYMENT_METHOD', 
                                { SELECTED     => (defined($FORM{PAYMENT_METHOD}) && $FORM{PAYMENT_METHOD} ne '') ? $FORM{METHOD} : '',
 	                                SEL_HASH     => { '' => $_ALL, %PAYMENTS_METHODS },
 	                                NO_ID        => 1,
 	                                SORT_KEY     => 1
 	                               });

  form_search({ SEARCH_FORM => ($FORM{pdf}) ? '' : $html->tpl_show(_include('docs_invoice_search', 'Docs'), 
  	                                  { %info, %FORM }, 
  	                                  { notprint => 1 })  
	            });
}

if (! $FORM{sort}) {
  $LIST_PARAMS{SORT}='2 DESC,1 DESC';
  #$LIST_PARAMS{DESC}='DESC';
}

if ($FORM{print_list}) {
	my $list = $Docs->docs_invoice_list( { %FORM, %LIST_PARAMS, 
                                         FULL_INFO  => 1 } );
  my @MULTI_ARR = ();
  my $doc_num   = 0;
  
  foreach my $line (@$list) {
    my %D = ();
    $D{INVOICE_ID}   = $line->[0];
    $D{DATE}         = $line->[1];
    my ($y, $m, $d)=split(/-/, $line->[1], 3);
    $D{FROM_DATE_LIT} = "$d ". $MONTHES_LIT[int($m)-1] ." $y $_YEAR";
    $D{DATE_EURO_STANDART} = "$d.$m.$y";
    $D{FIO}           = $line->[2];
    $D{LOGIN}         = $line->[15];
    $D{ACCOUNT_ID}    = $line->[8];
    $D{FIO}           = $line->[2];
    $D{ADDRESS_FULL}  = "$line->[10], $line->[11], $line->[12]";
    $D{TOTAL_SUM}     = sprintf("%.2f", $line->[3]);
    $D{CONTRACT_ID}   = $line->[13] || '';
    $D{CONTRACT_DATE} = "$line->[14]" || '0000-00-00';
    
     	my $method=$line->[7];
    	
    	if ($conf{DOCS_PAYMENT_METHODS}) {
        my %methods_hash = %{ cfg2hash($conf{DOCS_PAYMENT_METHODS}) };        

        if ($methods_hash{$method}) {
          $D{PAYMENT_METHOD}=$methods_hash{$method};
         }
        else {
        	$D{PAYMENT_METHOD}=$methods_hash{0};
         }
    	 }
    	else {
        $D{PAYMENT_METHOD} = $PAYMENT_METHODS[$method];
       }
    $D{TOTAL_SUM}     = $line->[3];

    if ($conf{DOCS_VAT_INCLUDE}) {
   	   $D{ORDER_TOTAL_SUM_VAT}  = sprintf("%.2f", $D{TOTAL_SUM} / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}));
   	   $D{TOTAL_SUM_WITHOUT_VAT}= sprintf("%.2f", $D{TOTAL_SUM} - $D{ORDER_TOTAL_SUM_VAT});
   	   $D{TOTAL_SUM_VAT}        = sprintf("%.2f", $D{TOTAL_SUM} - $D{TOTAL_SUM_WITHOUT_VAT});
     }
    $D{ORDER_PRICE_WITHOUT_VAT_1}=$D{TOTAL_SUM_WITHOUT_VAT} || 0,00;
    $D{ORDER_TOTAL_SUM_VAT}=$D{TOTAL_SUM_VAT} || 0,00;

#   if ($Docs->{TOTAL} > 0) {
#   	 ($Docs->{SUM_MAIN}, $Docs->{SUM_SUB})=split(/\./, $D{TOTAL_SUM});
#      $Docs->{FROM_DATE_LIT}='';
#
#     my $list = $Docs->{ORDERS};
#     my $i=0;
#     foreach my $line (@$list) {
#   	   $i++;
#   	   $Docs->{ORDER} .= sprintf("<tr><td align=right>%d</td><td>%s</td><td align=right>%d</td><td align=right>%d</td><td align=right>%.2f</td><td align=right>%.2f</td></tr>\n", 
#   	     $i, $line->[1], $line->[2], $line->[3], $line->[4], ($line->[2]*$line->[4])) if (! $conf{DOCS_PDF_PRINT});
#   	   
#   	   my $count = $line->[2] || 1;
#   	   my $sum   = sprintf("%.2f", $count*$line->[4]);
#   	   
#   	   $D{'ORDER_NUM_'.$i}   = $i;
#       $D{'ORDER_NAME_'.$i}  = $line->[1];
#       $D{'ORDER_COUNT_'.$i} = $count;
#       $D{'ORDER_PRICE_'.$i} = $line->[4];
#       $D{'ORDER_SUM_'.$i}   = $sum;
#       
#       $D{'ORDER_PRICE_WITHOUT_VAT_'.$i} = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $line->[4] - $line->[4] / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $line->[3]);
#       $D{'ORDER_SUM_WITHOUT_VAT_'.$i}   = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $sum - ($sum) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $sum );
#      }
#
#     $D{'TOTAL_SUM_WITHOUT_VAT'}= sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $D{TOTAL_SUM} - ($Docs->{TOTAL_SUM}) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $D{TOTAL_SUM} );
#     $Docs->{'TOTAL_SUM_VAT'}   = sprintf("%.2f", $D{TOTAL_SUM}-$Docs->{'TOTAL_SUM_WITHOUT_VAT'});
#     
#      my $i=0; 
#      foreach my $field_id ( @{ $Company->{INFO_FIELDS_ARR} } ) {
#         my($position, $type, $name)=split(/:/, $Company->{INFO_FIELDS_HASH}->{$field_id});
#         $Company->{$field_id}=$Company->{INFO_FIELDS_VAL}->[$i];
#         $i++;
#       }
#    }
#-----------------------
    push @MULTI_ARR, { %D, 
                       DOC_NUMBER => sprintf("%.6d",  $doc_num),
    	                };
    $doc_num++;
    print "UID: LOGIN: $line->[0] FIO: $line->[1] SUM: $line->[2]\n" if ($debug > 2);
	 }

  #print "Content-Type: text/html\n\n";
  print $html->header() if ($FORM{qindex});  
  my $single_tpl = $html->tpl_show(_include('docs_invoice', 'Docs', { pdf => $FORM{pdf} }), undef, 
                                           { MULTI_DOCS   => \@MULTI_ARR, 
  	                                         #SAVE_AS      => $save_filename,
  	                                         #DOCS_IN_FILE => $docs_in_file,
  	                                         debug        => $debug
  	                                       }); 
	return 0;
}

my $list = $Docs->docs_invoice_list( { %LIST_PARAMS } );

my $table = $html->table( { width      => '100%',
                            caption    => "$_INVOICE",
                            border     => 1,
                            title      => ['#', $_DATE, $_CUSTOMER, $_SUM, $_USER, $_ADMIN, $_TIME, $_PAYMENT_METHOD, '-', '-'],
                            cols_align => ['right', 'right', 'left', 'right', 'left', 'left', 'right', 'center'],
                            qs         => $pages_qs,
                            pages      => $Docs->{TOTAL},
                            ID         => 'DOCS_INVOCE'
                          });

if ($conf{DOCS_PDF_PRINT}) {
	$pages_qs .= "&pdf=1";
}

foreach my $line (@$list) {
  my $delete = ($permissions{1}{2}) ?  $html->button($_DEL, "index=$index&del=$line->[9]&UID=$line->[8]", { MESSAGE => "$_DEL ?", BUTTON => 1 }) : ''; 

  $table->addrow("$line->[0]", 
   "$line->[1]",
   "$line->[2]", 
   "$line->[3]", 
   $html->button($line->[4], "index=11&UID=$line->[8]"),
   "$line->[5]", 
   "$line->[6]", 
   $PAYMENTS_METHODS{"$line->[7]"}, 
   $html->button($_PRINT, "qindex=$index&print=$line->[9]&UID=$line->[8]$pages_qs", { ex_params => 'target=_new', BUTTON => 1 }) ,
   $delete);
}
print $table->show();

$table = $html->table( { width      => '100%',
                         cols_align => ['right', 'right'],
                         rows       => [ [ $html->button("$_PRINT $_LIST", "qindex=$index&print_list=1$pages_qs". (($conf{DOCS_PDF_PRINT}) ? '&pdf=1' : ''), { BUTTON => 1, ex_params => 'target=new'  }), "$_TOTAL:", $html->b($Docs->{TOTAL})
                          ] ]
                      } );

print $table->show();
}

#**********************************************************
# docs_accounts_list
#**********************************************************
sub docs_accounts_list {

my @payments_status = ("$_UNPAID", "$_PAID", "$_PARTLY_PAID");
push @PAYMENT_METHODS, @EX_PAYMENT_METHODS if (@EX_PAYMENT_METHODS);

for(my $i=0; $i<=$#PAYMENT_METHODS; $i++) {
  $PAYMENTS_METHODS{$i}=$PAYMENT_METHODS[$i];
 }

if ($conf{PAYSYS_PAYMENTS_METHODS}) {
  my %PAYSYS_PAYMENT_METHODS = %{ cfg2hash($conf{PAYSYS_PAYMENTS_METHODS}) };
  while(my($k, $v) = each %PAYSYS_PAYMENT_METHODS ) {
    $PAYMENTS_METHODS{$k}=$v;
   }
}

if ($LIST_PARAMS{UID} || $FORM{UID}) {
	docs_account();
	return 0 if ($FORM{'print'});
 }
elsif(defined($FORM{del}) && $FORM{is_js_confirmed} ) {
  $Docs->account_del($FORM{del});
  
  if(! $Docs->{errno}) {
    $html->message('info', "$_INFO", "$_DELETED N: [$FORM{del}]");
   }
  elsif ($Docs->{errno}) {
    $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}}");	
    return 0;
   }
 }
else {
	$info{PAID_STATUS_SEL} = $html->form_select('PAID_STATUS', 
                                    { 
 	                                   SELECTED     => $FORM{PAID_STATUS},
 	                                   ARRAY_NUM_ID => 1,
 	                                   SEL_ARRAY    => [ $_ALL, $_PAID, $_UNPAID ],
                                     NO_ID        => 1
 	                                  });

  $info{PAYMENT_METHOD_SEL} = $html->form_select('PAYMENT_METHOD', 
                                { SELECTED     => (defined($FORM{PAYMENT_METHOD}) && $FORM{PAYMENT_METHOD} ne '') ? $FORM{METHOD} : '',
 	                                SEL_HASH     => { '' => $_ALL, %PAYMENTS_METHODS },
 	                                NO_ID        => 1,
 	                                SORT_KEY     => 1
 	                               });


  form_search({ SEARCH_FORM => ($FORM{pdf}) ? '' : $html->tpl_show(_include('docs_account_search', 'Docs'), 
  	                                  { %info, %FORM }, 
  	                                  { notprint => 1 })  
	            });
}

if (! $FORM{sort}) {
  $LIST_PARAMS{SORT}='2 DESC, 1 DESC';
  #$LIST_PARAMS{DESC}='DESC';
}

if ($FORM{print_list}) {
	my $list = $Docs->accounts_list( { %FORM, %LIST_PARAMS, 
                                     FULL_INFO  => 1 } );

  my @MULTI_ARR = ();
  my $doc_num   = 0;
  
  foreach my $line (@$list) {
    my %D = ();
    $D{NUMBER}     = $line->[0];
    $D{DATE}       = $line->[1];
    my ($y, $m, $d)=split(/-/, $line->[1], 3);
    $D{FROM_DATE_LIT} = "$d ". $MONTHES_LIT[int($m)-1] ." $y $_YEAR";
    $D{DATE_EURO_STANDART} = "$d.$m.$y";
    $D{FIO}           = $line->[2];
    $D{ADDRESS_FULL}  = "$line->[11], $line->[12], $line->[13]";
    $D{TOTAL_SUM}     = sprintf("%.2f", $line->[3]);
    $D{CONTRACT_ID}   = $line->[15];
    $D{CONTRACT_DATE} = "$line->[16]";
    $D{BILL_ID}       = $line->[17];
    $D{UID}           = $line->[9];
    
    if ($conf{DOCS_VAT_INCLUDE}) {
   	   $D{ORDER_TOTAL_SUM_VAT}  = sprintf("%.2f", $D{TOTAL_SUM} / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}));
   	   $D{TOTAL_SUM_WITHOUT_VAT}= sprintf("%.2f", $D{TOTAL_SUM} - $Docs->{ORDER_TOTAL_SUM_VAT});
   	   $D{TOTAL_SUM_VAT}        = sprintf("%.2f", $conf{DOCS_VAT_INCLUDE});
     }

   if ($Docs->{TOTAL} > 0) {
   	 ($Docs->{SUM_MAIN}, $Docs->{SUM_SUB})=split(/\./, $D{TOTAL_SUM});
      $Docs->{FROM_DATE_LIT}='';

     my $list = $Docs->{ORDERS};
     my $i=0;
     foreach my $line (@$list) {
   	   $i++;
   	   $Docs->{ORDER} .= sprintf("<tr><td align=right>%d</td><td>%s</td><td align=right>%d</td><td align=right>%d</td><td align=right>%.2f</td><td align=right>%.2f</td></tr>\n", 
   	     $i, $line->[1], $line->[2], $line->[3], $line->[4], ($line->[2]*$line->[4])) if (! $conf{DOCS_PDF_PRINT});
   	   
   	   my $count = $line->[2] || 1;
   	   my $sum   = sprintf("%.2f", $count*$line->[4]);
   	   
   	   $D{'ORDER_NUM_'.$i}   = $i;
       $D{'ORDER_NAME_'.$i}  = $line->[1];
       $D{'ORDER_COUNT_'.$i} = $count;
       $D{'ORDER_PRICE_'.$i} = $line->[4];
       $D{'ORDER_SUM_'.$i}   = $sum;
       
       $D{'ORDER_PRICE_WITHOUT_VAT_'.$i} = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $line->[4] - $line->[4] / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $line->[3]);
       $D{'ORDER_SUM_WITHOUT_VAT_'.$i}   = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $sum - ($sum) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $sum );
      }

     

     $D{'TOTAL_SUM_WITHOUT_VAT'}= sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $D{TOTAL_SUM} - ($Docs->{TOTAL_SUM}) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $D{TOTAL_SUM} );
     $Docs->{'TOTAL_SUM_VAT'}   = sprintf("%.2f", $D{TOTAL_SUM}-$Docs->{'TOTAL_SUM_WITHOUT_VAT'});
     
      my $i=0; 
      foreach my $field_id ( @{ $Company->{INFO_FIELDS_ARR} } ) {
         my($position, $type, $name)=split(/:/, $Company->{INFO_FIELDS_HASH}->{$field_id});
         $Company->{$field_id}=$Company->{INFO_FIELDS_VAL}->[$i];
         $i++;
       }
    }
#-----------------------
    push @MULTI_ARR, { %D, 
                       DOC_NUMBER => sprintf("%.6d",  $doc_num),
    	                };
    $doc_num++;
    print "UID: LOGIN: $line->[0] FIO: $line->[1] SUM: $line->[2]\n" if ($debug > 2);
	 }

  print $html->header() if ($FORM{qindex});  
  my $single_tpl = $html->tpl_show(_include('docs_account', 'Docs', { pdf => $FORM{pdf} }), undef, 
                                           { MULTI_DOCS   => \@MULTI_ARR, 
  	                                         #SAVE_AS      => $save_filename,
  	                                         #DOCS_IN_FILE => $docs_in_file,
  	                                         debug        => $debug
  	                                       }); 
	return 0;
}

my @CAPTION = ('#', $_DATE, $_CUSTOMER, $_SUM, $_STATUS, $_USER, $_ADMIN, $_TIME, "$_PAYMENT_METHOD", '-', '-');
if ( $user->{UID} ) {
	@CAPTION = ('#', $_DATE, $_CUSTOMER, $_SUM, $_STATUS);
}

my $list = $Docs->accounts_list( { %LIST_PARAMS } );
my $table = $html->table( { width      => '100%',
                            border     => 1,
                            caption    => "$_ACCOUNTS",
                            title      => \@CAPTION,
                            cols_align => ['right', 'right', 'left', 'right', 'left', 'left', 'right', 'center:noprint', 'center:noprint'],
                            qs         => $pages_qs,
                            pages      => $Docs->{TOTAL},
                            ID         => 'DOCS_ACCOUNTS_LIST'
                          });

my @rows = ();

foreach my $line (@$list) {
  my $delete = ($permissions{1}{2}) ?  $html->button($_DEL, "index=$index&del=$line->[10]&UID=$line->[9]", { MESSAGE => "$_DEL ID $line->[10] ?", BUTTON => 1 }) : ''; 

  @rows = ( "$line->[0]", 
   $html->button("$line->[1]", "qindex=$index&print=$line->[10]&UID=$line->[9]$pages_qs". ( ($conf{DOCS_PDF_PRINT}) ? '&pdf=1' : '' ), {  ex_params => 'target=_new' }), 
   "$line->[2]", 
   "$line->[3]", 
   ($line->[4]) ? (($user->{UID}) ? $payments_status[1] : $html->button($payments_status[1], "index=2&UID=$line->[9]&ID=$line->[4]") ) :  $html->color_mark($payments_status[0], $_COLORS[6]) 
   );  

  if ( ! $user->{UID}  ) {
    push @rows, $html->button($line->[5], "index=11&UID=$line->[9]"),
    "$line->[6]", 
    "$line->[7]", 
    ($PAYMENTS_METHODS{$line->[8]}) ? $PAYMENTS_METHODS{$line->[8]} : $line->[8], 
    $html->button($_PRINT, "qindex=$index&print=$line->[10]&UID=$line->[9]". ( ($conf{DOCS_PDF_PRINT}) ? '&pdf=1' : '' ), {  ex_params => 'target=_new', BUTTON => 1 }), 
    $delete;
   }

  $table->addrow( @rows );
}

print $table->show();

$table = $html->table( { width      => '100%',
                         cols_align => ['right', 'right'],
                         rows       => [ [ (($user->{UID}) ? '' : $html->button("$_PRINT $_LIST", "qindex=$index&print_list=1$pages_qs". (($conf{DOCS_PDF_PRINT}) ? '&pdf=1' : ''), { BUTTON => 1, ex_params => 'target=new'  }) ), 
                         "$_TOTAL:", $html->b($Docs->{TOTAL}) ] ]
                      } );


print $table->show();

return 0;
}



#**********************************************************
# docs_tax_invoice_list
#**********************************************************
sub docs_tax_invoice_list {
	my ($attr) = @_;


if (! $attr->{COMPANY} ) {
  if ($LIST_PARAMS{COMPANY_ID} || $FORM{COMPANY_ID}) {
	  docs_tax_invoice();
	  return 0 if ($FORM{'print'});
   }
  elsif(defined($FORM{del}) && $FORM{is_js_confirmed} ) {
    $Docs->tax_invoice_del($FORM{del});
    if(! $Docs->{errno}) {
      $html->message('info', "$_INFO", "$_DELETED N: [$FORM{del}]");
     }
    elsif ($Docs->{errno}) {
      $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}}");	
      return 0;
     }
   }
  elsif($FORM{print}) {
	  docs_tax_invoice();
	
	  return 0;
   }
 }
else {
  $index=$FORM{index};
 }


  form_search({ SEARCH_FORM => ($conf{DOCS_PDF_PRINT}) ? '' : $html->tpl_show(_include('docs_search', 'Docs'), 
  	                                  { %info, %FORM }, 
  	                                  { notprint => 1 })
	            });

if (! $FORM{sort}) {
  $LIST_PARAMS{SORT}='2 DESC,1 DESC';
  #$LIST_PARAMS{DESC}='DESC';
}
 

if ($FORM{print_list}) {
	my $list = $Docs->tax_invoice_list( { %LIST_PARAMS, 
		                                    COMPANY_ID => $FORM{COMPANY_ID},
		                                    FULL_INFO  => 1 } );

  my @MULTI_ARR = ();
  my $doc_num   = 0;
  
  foreach my $line (@$list) {

    my %D = ();
    $D{NUMBER}=        $line->[0];
    $D{DATE}  =        $line->[1];
    $D{COMPANY_NAME} = $line->[2];
    $D{ADDRESS}      = "$line->[11], $line->[12], $line->[13]";
    $D{TOTAL_SUM}    = sprintf("%.2f", $line->[3]);

    if ($conf{DOCS_VAT_INCLUDE}) {
   	   $D{ORDER_TOTAL_SUM_VAT}  = sprintf("%.2f", $D{TOTAL_SUM} / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}));
   	   $D{TOTAL_SUM_WITHOUT_VAT}= sprintf("%.2f", $D{TOTAL_SUM} - $Docs->{ORDER_TOTAL_SUM_VAT});
   	   $D{TOTAL_SUM_VAT}        = sprintf("%.2f", $conf{DOCS_VAT_INCLUDE});
     }




   if ($Docs->{TOTAL} > 0) {
   	 ($Docs->{SUM_MAIN}, $Docs->{SUM_SUB})=split(/\./, $D{TOTAL_SUM});
      $Docs->{FROM_DATE_LIT}='';

     my $list = $Docs->{ORDERS};
     my $i=0;
     foreach my $line (@$list) {
   	   $i++;
   	   $Docs->{ORDER} .= sprintf("<tr><td align=right>%d</td><td>%s</td><td align=right>%d</td><td align=right>%d</td><td align=right>%.2f</td><td align=right>%.2f</td></tr>\n", 
   	     $i, $line->[1], $line->[2], $line->[3], $line->[4], ($line->[2]*$line->[4])) if (! $conf{DOCS_PDF_PRINT});
   	   
   	   my $count = $line->[2] || 1;
   	   my $sum   = sprintf("%.2f", $count*$line->[4]);
   	   
   	   $D{'ORDER_NUM_'.$i}   = $i;
       $D{'ORDER_NAME_'.$i}  = $line->[1];
       $D{'ORDER_COUNT_'.$i} = $count;
       $D{'ORDER_PRICE_'.$i} = $line->[4];
       $D{'ORDER_SUM_'.$i}   = $sum;
       
       $D{'ORDER_PRICE_WITHOUT_VAT_'.$i} = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $line->[4] - $line->[4] / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $line->[3]);
       $D{'ORDER_SUM_WITHOUT_VAT_'.$i}   = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $sum - ($sum) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $sum );
      }

     

     $D{'TOTAL_SUM_WITHOUT_VAT'}= sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $D{TOTAL_SUM} - ($Docs->{TOTAL_SUM}) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $D{TOTAL_SUM} );
     $Docs->{'TOTAL_SUM_VAT'}   = sprintf("%.2f", $D{TOTAL_SUM}-$Docs->{'TOTAL_SUM_WITHOUT_VAT'});
     
      my $i=0; 
      foreach my $field_id ( @{ $Company->{INFO_FIELDS_ARR} } ) {
         my($position, $type, $name)=split(/:/, $Company->{INFO_FIELDS_HASH}->{$field_id});
         $Company->{$field_id}=$Company->{INFO_FIELDS_VAL}->[$i];
         $i++;
       }
    }
#-----------------------

    
    push @MULTI_ARR, { %D, 
                       DOC_NUMBER => sprintf("%.6d",  $doc_num),
    	                };
    $doc_num++;
    print "UID: LOGIN: $line->[0] FIO: $line->[1] SUM: $line->[2]\n" if ($debug > 2);
	 }

  #print "Content-Type: text/html\n\n";
  print $html->header() if ($FORM{qindex});  
  my $single_tpl = $html->tpl_show(_include('docs_tax_invoice', 'Docs', { pdf => $FORM{pdf} }), undef, 
                                           { MULTI_DOCS   => \@MULTI_ARR, 
  	                                         #SAVE_AS      => $save_filename,
  	                                         #DOCS_IN_FILE => $docs_in_file,
  	                                         debug        => $debug
  	                                       }); 


	return 0;
}

my $list = $Docs->tax_invoice_list( { %LIST_PARAMS, COMPANY_ID => $FORM{COMPANY_ID} } );
my $table = $html->table( { width      => '100%',
                            border     => 1,
                            caption    => "$_TAX_INVOICE",
                            title      => ['#', $_DATE, $_CUSTOMER, $_SUM, $_ADMIN, $_TIME, '-', '-'],
                            cols_align => ['right', 'right', 'left', 'right', 'left', 'left', 'right', 'center:noprint', 'center:noprint'],
                            qs         => $pages_qs,
                            pages      => $Docs->{TOTAL},
                            ID         => 'DOCS_TAX_INVOICE'
                          });


foreach my $line (@$list) {
  my $delete = ($permissions{1}{2}) ?  $html->button($_DEL, "index=$index&del=$line->[8]&COMPANY_ID=$line->[7]", { MESSAGE => "$_DEL ID '$line->[8]' ?", BUTTON => 1 }) : ''; 

  $table->addrow("$line->[0]", 
   "$line->[1]",
   $html->button("$line->[2]", "index=13&COMPANY_ID=$line->[7]"),, 
   "$line->[3]", 
   $html->button($line->[4], "index=11&UID=$line->[7]"),
   "$line->[5]", 
   $html->button($_PRINT, "qindex=$index&print=$line->[8]&UID=$line->[8]$pages_qs". ( ($conf{DOCS_PDF_PRINT}) ? '&pdf=1' : '' ), {  ex_params => 'target=_new', BUTTON => 1 }), 
   $delete);
}
print $table->show();

$table = $html->table( { width      => '100%',
                         cols_align => ['right', 'right'],
                         rows       => [ [ $html->button("$_PRINT $_LIST", "qindex=$index&print_list=1$pages_qs". (($conf{DOCS_PDF_PRINT}) ? '&pdf=1' : ''), { BUTTON => 1, ex_params => 'target=new'  }), "$_TOTAL:", $html->b($Docs->{TOTAL}), "$_SUM:", $html->b($Docs->{SUM}),  ] ]
                      } );

print $table->show();
return 0;
}

#**********************************************************
# docs_tax_invoice
#**********************************************************
sub docs_tax_invoice {
	my ($attr) = @_;

 if (! $attr->{COMPANY} && ! $FORM{qindex}) {
   $FORM{subf}=$FORM{index};
   $index=13;
   $index2=$FORM{index};
   form_companies();
   return 0;
  }
 elsif($FORM{qindex}) {
   $Company->info($FORM{COMPANY_ID});
  }
 else {
  	$Company = $attr->{COMPANY};
  }
 $Docs->{DATE}     =$DATE;
 $Docs->{DONE_DATE}=$DATE;
 $Docs->{FROM_DATE}=$DATE;

 if ($FORM{create}) {
   my $list = $Fees->reports({ MONTH      => $FORM{MONTH},
   	                           BILL_ID    => $Company->{BILL_ID},
   	                           TYPE       => 'METHOD'
   	                        });

   if ($Fees->{TOTAL} < 1) {
     $html->message('info', $_INFO, "$_FEES $_NOT_EXIST");
    }
  
   my @FEES_METHODS = ($_ONE_TIME, $_ABON, $_FINE, $_ACTIVATE);
   push @FEES_METHODS, @EX_FEES_METHODS if (@EX_FEES_METHODS);


   my $i = 1;
   foreach my $line (@$list) {
      $FORM{SUM}       +=$Fees->{SUM};    
      $FORM{'IDS'}     .= "$i, ";
      $FORM{'ORDER_'. $i}= $FEES_METHODS[$line->[0]];
      $FORM{'COUNTS_'.$i}= '1';
      $FORM{'UNIT_'.$i}  = '1';
      $FORM{'SUM_'.$i}   = $line->[3];
      $i++;
    }

  my ($y, $m)=split(/-/, $FORM{PERIOD});

  my $days_in_month=($m!=2?(($m%2)^($m>7))+30:(!($y%400)||!($y%4)&&($y%25)?29:28));

   if (defined($FORM{OP_SID}) and $FORM{OP_SID} eq $COOKIES{OP_SID}) {
 	   $html->message('err', $_ERROR, "$_EXIST");
    }
   elsif (! $FORM{SUM_1} && $FORM{SUM} < 0.01) {
     $html->message('err', "$_ERROR", $_WRONG_SUM);
    }
   elsif($FORM{PREVIEW}) {
     docs_preview('tax_invoice', { %FORM });
     return 0;
    }
   else {
     $FORM{COMPANY_ID}=$LIST_PARAMS{COMPANY_ID} if (! $FORM{COMPANY_ID});
     
     $Docs->tax_invoice_add({ %FORM, DATE => "$FORM{MONTH}-01" });

     if(! $Docs->{errno}) {
       $html->message('info', "$_ADDED", "$_NUM: [$Docs->{DOC_ID}] $_DATE: $FORM{DATE}");
       $Docs->tax_invoice_info($Docs->{DOC_ID}, { COMPANY_ID => $LIST_PARAMS{COMPANY_ID} });
       ($Docs->{SUM_MAIN}, $Docs->{SUM_SUB})=split(/\./, $Docs->{TOTAL_SUM});
       $Docs->{NUMBER}=$Docs->{DOC_ID};
       my $list = $Docs->{ORDERS};
       my $i=0;

       foreach my $line (@$list) {
   	     $i++;
   	     $Docs->{ORDER} .= sprintf("<tr><td align='right'>%d</td><td>%s</td><td align='right'>%d</td><td align='right'>%d</td><td align='right'>%.2f</td><td align='right'>%.2f</td></tr>\n", 
   	       $i, $line->[1], $line->[2], $line->[3], $line->[4], ($line->[3]*$line->[4]));
  
        }

       if ($conf{DOCS_PDF_PRINT}) {
       	 $html->message('info', $_ADDED, "$_TAX_INVOICE $_ADDED. ". $html->button($_PRINT, "qindex=$index&print=$Docs->{DOC_ID}&UID=$LIST_PARAMS{UID}&COMPANY_ID=$FORM{COMPANY_ID}&pdf=1", { ex_params => 'target=_new', BUTTON => 1 }));
       	 return 0;
        }
      
       #print $html->header() if ($FORM{qindex});
       if( $user->{UID} ) {
         $FORM{qindex}    = $index;
         $html->{NO_PRINT}= undef;

         docs_print('tax_invoice', { %$Docs, %$Company,  A_FIO => $admin->{A_FIO} });
         exit;
        }
       else {
         docs_print('tax_invoice', { %$Docs, %$Company, A_FIO => $admin->{A_FIO} });
        }

       $FORM{'print'}=1;
       return 0;
      }
     elsif ($Docs->{errno} == 7) {
     	 $html->message('err', $_ERROR, "$_EXIST");	
      }
     else {
     	 $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}}");	
      }
    }
  }
 elsif($FORM{print}) {
   $Docs->tax_invoice_info($FORM{print}, { UID => $LIST_PARAMS{UID} });
   
   if ($conf{DOCS_VAT_INCLUDE}) {
   	 $Docs->{ORDER_TOTAL_SUM_VAT}  = sprintf("%.2f", $Docs->{TOTAL_SUM} / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}));
   	 $Docs->{TOTAL_SUM_WITHOUT_VAT}= sprintf("%.2f", $Docs->{TOTAL_SUM} - $Docs->{ORDER_TOTAL_SUM_VAT});
   	 $Docs->{TOTAL_SUM_VAT}        = sprintf("%.2f", $conf{DOCS_VAT_INCLUDE});
    }

   $Docs->{NUMBER}=$Docs->{DOC_ID};

   if ($Docs->{TOTAL} > 0) {
   	 ($Docs->{SUM_MAIN}, $Docs->{SUM_SUB})=split(/\./, $Docs->{TOTAL_SUM});
      $Docs->{FROM_DATE_LIT}='';

     my $list = $Docs->{ORDERS};
     my $i=0;
     foreach my $line (@$list) {
   	   $i++;
   	   $Docs->{ORDER} .= sprintf("<tr><td align=right>%d</td><td>%s</td><td align=right>%d</td><td align=right>%d</td><td align=right>%.2f</td><td align=right>%.2f</td></tr>\n", 
   	     $i, $line->[1], $line->[2], $line->[3], $line->[4], ($line->[2]*$line->[4]));
   	   
   	   my $count = $line->[2] || 1;
   	   my $sum   = sprintf("%.2f", $count*$line->[4]);
   	   
   	   $Docs->{'ORDER_NUM_'.$i}   = $i;
       $Docs->{'ORDER_NAME_'.$i}  = $line->[1];
       $Docs->{'ORDER_COUNT_'.$i} = $count;
       $Docs->{'ORDER_PRICE_'.$i} = $line->[4];
       $Docs->{'ORDER_SUM_'.$i}   = $sum;
       
       $Docs->{'ORDER_PRICE_WITHOUT_VAT_'.$i} = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $line->[4] - $line->[4] / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $line->[3]);
       $Docs->{'ORDER_SUM_WITHOUT_VAT_'.$i}   = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $sum - ($sum) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $sum );
      }

     

     $Docs->{'TOTAL_SUM'}            = sprintf("%.2f", $Docs->{TOTAL_SUM});
     $Docs->{'TOTAL_SUM_WITHOUT_VAT'}= sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $Docs->{TOTAL_SUM} - ($Docs->{TOTAL_SUM}) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $Docs->{TOTAL_SUM} );
     $Docs->{'TOTAL_SUM_VAT'}        = sprintf("%.2f", $Docs->{TOTAL_SUM}-$Docs->{'TOTAL_SUM_WITHOUT_VAT'});
     
     my $i=0; 
     foreach my $field_id ( @{ $Company->{INFO_FIELDS_ARR} } ) {
       my($position, $type, $name)=split(/:/, $Company->{INFO_FIELDS_HASH}->{$field_id});
       $Company->{$field_id}=$Company->{INFO_FIELDS_VAL}->[$i];
       
       #print "";
       $i++;
     }
     
#     $Company->{_ipn_u}='123456790';
#     exit;
     docs_print('tax_invoice', { %$Docs, %$Company, A_FIO => $admin->{A_FIO} });
    }
   else {

     $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}}");	
    }
   return 0;
  }
 elsif(defined($FORM{change})) {
   $Docs->tax_invoice_change({ %FORM });
   if(! $Docs->{errno}) {
     $html->message('info', "$_INFO", "$_CHANGED N: [$FORM{DOC_ID}]");
    }
  }
 elsif(defined($FORM{chg})) {
   $Docs->tax_invoice_info($FORM{chg});
   if(! $Docs->{errno}) {
     $html->message('info', "$_INFO", "$_CHANGING N: [$FORM{chg}]");
    }
  }
 elsif(defined($FORM{del}) && $FORM{is_js_confirmed}) {
   $Docs->tax_invoice_del($FORM{del});
   if(! $Docs->{errno}) {
     $html->message('info', "$_INFO", "$_DELETED N: [$FORM{del}]");
    }
  }
	
	if(! $user->{UID}  ) {
  	$Docs->{FORM_ACCT_ID} = "<tr><td>$_TAX_INVOICE $_NUM:</td><td><input type='text' name='ACCT_ID' value='%ACCT_ID%'></td></tr>\n";
   }

  $Docs->{SEL_ORDER} .= $html->form_select('ORDER', 
                                    { 
 	                                   SELECTED    => $FORM{ORDER},
 	                                   SEL_ARRAY   => ($conf{DOCS_ORDERS})? $conf{DOCS_ORDERS} : [$_DV],
                                     NO_ID       => 1
 	                                  });

  #$Docs->{COMPANY_VAT}=$user->{COMPANY_VAT}.' %';
  $Docs->{OP_SID}  = mk_unique_value(16);
  $users->pi({  $users->{UID} });

  $Docs->{CUSTOMER}=  $users->{FIO} || '-';
  $Docs->{CAPTION} =  $_ACCOUNT;

  my ($Y, $M, $D)=split(/-/, $DATE, 3);  
  my @MONTH_ARR = ('');
  for(my $i=1; $i<13; $i++) {
	  my $m = sprintf("%.2d", $i);
	  push @MONTH_ARR, "$Y-$m";
   }
  $FORM{MONTH}="$Y-$M" if (! $FORM{MONTH});

  my $table = $html->table( { width       => '100%',
  	                          caption     => "$_TAX_INVOICE",
	                            rowcolor    => $_COLORS[0],
                              rows        => [[ 
                                                #"$_USER: ", $users_list,
                                                "$_PERIOD: ", $html->form_select('MONTH', 
                                                           { SELECTED   => $FORM{MONTH},
 	                                                           SEL_ARRAY  => \@MONTH_ARR,
 	                                                           NO_ID      => 1
                                                          } ),
                                                 "$_DATE: ", $html->form_input('DATE', "$Y-$M-01"),
                                          $html->form_input('show', $_CREATE, { TYPE => "SUBMIT" })
                                         ]],                                   
                      });

  print $html->form_main({ CONTENT => $table->show({ OUTPUT2RETURN => 1 }),
	                         HIDDEN  => { COMPANY_ID => "$FORM{COMPANY_ID}",
	                         	            index      => $index,
	                         	            subf       => $FORM{subf},
	                                      create     => "1"
	                                     }
	                       });

  #$html->tpl_show(_include('docs_tax_invoice_add', 'Docs'), { %$Docs, %$users });
  
  docs_tax_invoice_list($attr);
}




#**********************************************************
# docs_account
#**********************************************************
sub docs_reports {
	my ($attr) = @_;
	
}


#**********************************************************
# docs_account
#**********************************************************
sub docs_account {
 my ($attr) = @_;

 $Docs->account_defaults();		
 $Docs->{DATE}=$DATE;

 

 if ($FORM{create}) {
   if ($FORM{OP_SID} and $FORM{OP_SID} eq $COOKIES{OP_SID}) {
 	   $html->message('err', $_ERROR, "$_EXIST");
    }
   elsif (! $FORM{SUM_1} && $FORM{SUM} < 0.01) {
     $html->message('err', "$_ERROR", "$_WRONG_SUM");
    }
   elsif(! $LIST_PARAMS{UID}) {
     $html->message('err', "$_ERROR", "$_SELECT_USER");
    }
   elsif(! $FORM{CUSTOMER}) {
     $html->message('err', "$_ERROR", "$_ORG_NAME");
    }
   elsif($FORM{PREVIEW}) {
     docs_preview('account', { %FORM });
     return 0;
    }
   else {
     $FORM{UID}=$LIST_PARAMS{UID} if (! $FORM{UID});
     $Docs->account_add({ %FORM });
     if(! $Docs->{errno}) {
       $FORM{ACCOUNT_ID}=$Docs->{DOC_ID};
       $Docs->account_info($Docs->{DOC_ID}, { UID => $LIST_PARAMS{UID} });

       ($Docs->{SUM_MAIN}, $Docs->{SUM_SUB})=split(/\./, $Docs->{TOTAL_SUM});

       my $list = $Docs->{ORDERS};
       my $i=0;


       foreach my $line (@$list) {
   	     $i++;
   	     $Docs->{ORDER} .= $html->tpl_show(_include('docs_account_order_row', 'Docs'), 
   	        { NUMBER => $i,
   	        	NAME   => $line->[1],
   	        	COUNT  => $line->[3],
   	        	UNIT   => $line->[2],
   	        	PRICE  => $line->[4],
   	        	SUM    => sprintf("%.2f", $line->[3]*$line->[4])
   	        	}, 
   	         { OUTPUT2RETURN => 1 });
   	     
        }

       if ($conf{DOCS_PDF_PRINT}) {
       	 $html->message('info', "$_ACCOUNT $_ADDED", "$_ACCOUNT $_ADDED. ". $html->button($_PRINT, "qindex=$index&ACCOUNT_ID=$Docs->{DOC_ID}&print=$Docs->{DOC_ID}&UID=$LIST_PARAMS{UID}&pdf=1", { ex_params => 'target=_new', BUTTON => 1 }));
       	 return 0;
        }
       else {
         $html->message('info', "$_ACCOUNT $_ADDED", "$_ACCOUNT $_NUM: [$Docs->{ACCT_ID}] $_DATE: $FORM{DATE} ".
          $html->button($_PRINT, "qindex=$index&ACCOUNT_ID=$Docs->{DOC_ID}&print=$Docs->{DOC_ID}&UID=$LIST_PARAMS{UID}", { ex_params => 'target=_new', BUTTON => 1 }) );
          #return 0;
        }
       	

      
       #print $html->header() if ($FORM{qindex});
       if( $user->{UID} ) {
         $FORM{qindex}    = $index;
         $html->{NO_PRINT}= undef;

         if ($Docs->{COMPANY_ID}) {
         	 $Company->info($Docs->{COMPANY_ID});
         	 docs_print('account_company', { %$Docs, %$Company });
          }
         else {
           docs_print('account', $Docs);
          }

         exit;
        }
       else {
         if ($Docs->{COMPANY_ID}) {
         	 $Company->info($Docs->{COMPANY_ID});
         	 docs_print('account_company', { %$Docs, %$Company });
          }
         else {
           docs_print('account', $Docs) if (! $FORM{QUICK});;
          }
        }

       $FORM{'print'}=1;
       return 0;
      }
    }
  }
 elsif($FORM{print}){
   $Docs->account_info($FORM{print}, { UID => $LIST_PARAMS{UID} });
   
   if ($conf{DOCS_VAT_INCLUDE}) {
   	 $Docs->{ORDER_TOTAL_SUM_VAT}  = sprintf("%.2f", $Docs->{TOTAL_SUM} / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}));
   	 $Docs->{TOTAL_SUM_WITHOUT_VAT}= sprintf("%.2f",$Docs->{TOTAL_SUM} - $Docs->{ORDER_TOTAL_SUM_VAT});
   	 $Docs->{VAT}                  = sprintf("%.2f", $conf{DOCS_VAT_INCLUDE});
    }

   if ($Docs->{TOTAL} > 0) {
   	 ($Docs->{SUM_MAIN}, $Docs->{SUM_SUB})=split(/\./, $Docs->{TOTAL_SUM});
      $Docs->{FROM_DATE_LIT}='';

     my $list = $Docs->{ORDERS};
     my $i=0;
     foreach my $line (@$list) {
   	   $i++;
 	     $Docs->{ORDER} .= $html->tpl_show(_include('docs_account_order_row', 'Docs'), 
   	        { NUMBER => $i,
   	        	NAME   => $line->[1],
   	        	COUNT  => $line->[3],
   	        	UNIT   => $line->[2],
   	        	PRICE  => $line->[4],
   	        	SUM    => sprintf("%.2f", $line->[3]*$line->[4])
   	        	}, 
   	         { OUTPUT2RETURN => 1 }) if (! $FORM{pdf});

   	   #$Docs->{ORDER} .= sprintf("<tr><td align=right>%d</td><td>%s</td><td align=right>%d</td><td align=right>%d</td><td align=right>%.2f</td><td align=right>%.2f</td></tr>\n", 
   	   #  $i, $line->[1], $line->[2], $line->[3], $line->[4], ($line->[2]*$line->[4]));
   	   
   	   my $count = $line->[2] || 1;
   	   my $sum   = sprintf("%.2f", $count*$line->[4]);
   	   
   	   $Docs->{'ORDER_NUM_'.$i}   = $i;
       $Docs->{'ORDER_NAME_'.$i}  = $line->[1];
       $Docs->{'ORDER_COUNT_'.$i} = $count;
       $Docs->{'ORDER_PRICE_'.$i} = $line->[4];
       $Docs->{'ORDER_SUM_'.$i}   = $sum;
       
       $Docs->{'ORDER_PRICE_WITHOUT_VAT_'.$i} = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $line->[4] - $line->[4] / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $line->[3]);
       $Docs->{'ORDER_SUM_WITHOUT_VAT_'.$i}   = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $sum - ($sum) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $sum );
      }

     
     $Docs->{TOTAL_SUM} = sprintf("%.2f", $Docs->{TOTAL_SUM});
     
     if ($Docs->{COMPANY_ID}) {
       $Company->info($Docs->{COMPANY_ID});
       docs_print('account_company', { %$Docs, %$Company });
      }
     else {
       docs_print('account', $Docs);
      }
    }
   else {
     $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}}");	
    }
   return 0;
  }
 elsif(defined($FORM{change})) {
   $Docs->account_change({ %FORM });
   if(! $Docs->{errno}) {
     $html->message('info', "$_INFO", "$_CHANGED N: [$FORM{DOC_ID}]");
    }
  }
 elsif(defined($FORM{chg})) {
   $Docs->account_info($FORM{chg});
   if(! $Docs->{errno}) {
     $html->message('info', "$_INFO", "$_CHANGING N: [$FORM{chg}]");
    }
  }
 elsif(defined($FORM{del}) && $FORM{is_js_confirmed}) {
   $Docs->account_del($FORM{del});
   if(! $Docs->{errno}) {
     $html->message('info', "$_INFO", "$_DELETED N: [$FORM{del}]");
    }
  }
	
	if(! $user->{UID}  ) {
  	$Docs->{FORM_ACCT_ID} = "<tr><td>$_ACCOUNT $_NUM:</td><td><input type='text' name='ACCT_ID' value='%ACCT_ID%'></td></tr>\n";
    $Docs->{DATE_FIELD}="- <input type=text name=DATE value='%DATE%'>";
    
   }
  else {
  	$Docs->{DATE_FIELD}="$DATE";
  	$users = $user;
   }
  $Docs->{SEL_ORDER} .= $html->form_select('ORDER', 
                                    { 
 	                                   SELECTED    => $FORM{ORDER},
 	                                   SEL_ARRAY   => ($conf{DOCS_ORDERS})? $conf{DOCS_ORDERS} : [$_DV],
                                     NO_ID       => 1
 	                                  });

  $Docs->{OP_SID}  = mk_unique_value(16);
  $users->pi({  $users->{UID} });

  $Docs->{CUSTOMER}= $users->{FIO} || '-';
  $Docs->{CAPTION} = $_ACCOUNT;
  
  
  
  $html->tpl_show(_include('docs_account_add', 'Docs'), { %$Docs, %$users }) if (! $FORM{pdf});
}




#**********************************************************
# docs_preview
#**********************************************************
sub docs_preview {
	my ($type, $ATTR)=@_;
	
	$html->tpl_show(_include("docs_$template.tpl", 'Docs'), $ATTR);
}


#**********************************************************
# docs_print
#**********************************************************
sub docs_print {
	my ($type, $ATTR)=@_;

  $conf{DOCS_LANGUAGE} = $conf{default_language} if (! $conf{DOCS_LANGUAGE});

  if (-f "../Abills/modules/Docs/lng_$conf{DOCS_LANGUAGE}.pl") {
    require "../language/$conf{DOCS_LANGUAGE}.pl";
    require "../Abills/modules/Docs/lng_$conf{DOCS_LANGUAGE}.pl";
   }
  else {
    require "../../language/$conf{DOCS_LANGUAGE}.pl";
    require "../../Abills/modules/Docs/lng_$conf{DOCS_LANGUAGE}.pl";
   }

	if (defined(@MONTHES_LIT) && $ATTR->{DATE}) {
    my ($y, $m, $d)=split(/-/, $ATTR->{DATE}, 3);
    $ATTR->{FROM_DATE_LIT} = "$d ". $MONTHES_LIT[int($m)-1] ." $y $_YEAR";
    
    $ATTR->{DAY}=$d;
    $ATTR->{MONTH_LIT}=$MONTHES_LIT[int($m)-1];
    $ATTR->{YEAR}=$y;
    $ATTR->{DATE_EURO_STANDART}="$d.$m.$y";
   }


  $ATTR->{SUM_LIT} = int2ml("$ATTR->{TOTAL_SUM}", { 
  	 ONES             => \@ones,
     TWOS             => \@twos,
     FIFTH            => \@fifth,
     ONE              => \@one,
     ONEST            => \@onest,
     TEN              => \@ten,
     TENS             => \@tens,
     HUNDRED          => \@hundred,
     MONEY_UNIT_NAMES => $conf{MONEY_UNIT_NAMES} || \@money_unit_names,
     LOCALE           => $conf{LOCALE}
  	  });

	my $template = $type;
  print $html->header() if ($FORM{qindex});

  if ($LIST_PARAMS{COMPANY_ID}) {

   }
  else {
    $users = $user if ($user->{UID});
   }

  my $tpl_sufix = '';
  if ($Docs->{UID}) {
    $users->info($Docs->{UID}) if (! $users->{BILL_ID});
    $users->pi({  UID => $Docs->{UID} }) ;
    $users->{ADDRESS_FULL}="$users->{ADDRESS_STREET}, $users->{ADDRESS_BUILD}, $users->{ADDRESS_FLAT}"; 
    
    if ($users->{GID}) {
       $users->group_info($users->{GID});
       if ($users->{SEPARATE_DOCS}) {
       	 $tpl_sufix = "_$users->{GID}"; 
        }
     }
    print "Content-Type: text/html\n\n";
    print $tpl_sufix;
   }

	$html->tpl_show(_include("docs_$template$tpl_sufix", 'Docs', 
	    { pdf => $FORM{pdf} }), { %$users, %$ATTR });
}


#**********************************************************
# Make multiuser documents
#**********************************************************
sub docs_summary {

	
	my $list = $users->list({ DEPOSIT    => '<0',
		                        DISABLE    => 0,
		                        PAGE_ROWS  => 1000000   });
	my @MULTI_ARR = ();

	foreach my $line (@$list) {
    #print "-$line->[0], $line->[1], $line->[3], $line->[4]<br>";
    
    push @MULTI_ARR, { FIO     => $line->[1], 
    	                 DEPOSIT => $line->[2],
    	                 CREDIT  => $line->[3],
    	                 SUM     => $line->[2],
    	                 SUM_VAT => ($conf{DOCS_VAT_INCLUDE}) ? sprintf("%.2f", $line->[2] / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE})) : 0.00
    	                };
	 }

  $html->tpl_show(_include("docs_multi_invoice", 'Docs', 
                                     { pdf         => $FORM{pdf} }), 
                                     { MULTI_PRINT => \@MULTI_ARR });
}


















































#**********************************************************
# docs_tax_invoice_list
#**********************************************************
sub docs_acts_list {
  my ($attr) = @_;


if (! $attr->{COMPANY} ) {
  if ($LIST_PARAMS{COMPANY_ID} || $FORM{COMPANY_ID}) {
	  docs_acts();
	  return 0 if ($FORM{'print'});
   }
  elsif(defined($FORM{del}) && $FORM{is_js_confirmed} ) {
    $Docs->act_del($FORM{del});
    if(! $Docs->{errno}) {
      $html->message('info', "$_INFO", "$_DELETED N: [$FORM{del}]");
     }
    elsif ($Docs->{errno}) {
      $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}}");	
      return 0;
     }
   }
  elsif($FORM{print}) {
	  docs_acts();
	
	  return 0;
   }
 }
else {
  $index=$FORM{index};
 }

  form_search({ SEARCH_FORM   => ($FORM{pdf}) ? '' : $html->tpl_show(_include('docs_search', 'Docs'),
  	                                  { %info, %FORM }, 
  	                                  { notprint => 1 }),
  	            HIDDEN_FIELDS => { COMPANY_ID => $FORM{COMPANY_ID} || undef }
	            });



#  Date  Customer  Sum  User  Administrators  Time  

if (! defined($FORM{sort})) {
  $LIST_PARAMS{SORT}=1;
  $LIST_PARAMS{DESC}='DESC';
}

my $list = $Docs->acts_list( { %LIST_PARAMS, 
	                             COMPANY_ID   => $FORM{COMPANY_ID} 
	                             } );

my $table = $html->table( { width      => '100%',
                            border     => 1,
                            caption    => "$_ACTS",
                            title      => ['#', $_DATE, $_CUSTOMER, $_SUM, $_ADMIN, $_TIME, '-', '-'],
                            cols_align => ['right', 'right', 'left', 'right', 'left', 'left', 'right', 'center:noprint', 'center:noprint'],
                            qs         => $pages_qs,
                            pages      => $Docs->{TOTAL},
                            ID         => 'DOCS_TAX_INVOICE'
                          });

$pages_qs = '';

foreach my $line (@$list) {
  my $delete = ($permissions{1}{2}) ?  $html->button($_DEL, "index=$FORM{index}&del=$line->[8]&COMPANY_ID=$line->[7]", { MESSAGE => "$_DEL ID '$line->[8]' ?", BUTTON => 1 }) : ''; 

  $table->addrow("$line->[0]", 
   "$line->[1]",
   $html->button("$line->[2]", "index=13&COMPANY_ID=$line->[7]"),, 
   "$line->[3]", 
   $html->button($line->[4], "index=11&UID=$line->[7]"),
   "$line->[5]", 
   $html->button($_PRINT, "qindex=$FORM{index}&print=$line->[8]&COMPANY_ID=$line->[7]". (($conf{DOCS_PDF_PRINT}) ? '&pdf=1' : ''). (($pages_qs) ? $pages_qs : ""  ) , { ex_params => 'target=_new', BUTTON => 1 }), 
   $delete);
}
print $table->show();

$table = $html->table( { width      => '100%',
                         cols_align => ['right', 'right'],
                         rows       => [ [ $html->button("$_PRINT $_LIST", "qindex=$index&print_list=1$pages_qs". (($conf{DOCS_PDF_PRINT}) ? '&pdf=1' : ''), { BUTTON => 1, ex_params => 'target=new'  }), "$_TOTAL:", $html->b($Docs->{TOTAL}), "$_SUM:", $html->b($Docs->{SUM}),  ] ]
                      } );


print $table->show();

return 0;
}


#**********************************************************
# docs_tax_invoice
#**********************************************************
sub docs_acts {
	my ($attr) = @_;

  if (! $attr->{COMPANY} && ! $FORM{qindex}) {
    $FORM{subf}=$FORM{index};
    $index=13;
    $index2=$FORM{index};
    form_companies();
    return 0;
   }
  elsif($FORM{qindex}) {
    $Company->info($FORM{COMPANY_ID});
   }
  else {
  	$Company = $attr->{COMPANY};
   }


use Dv_Sessions;
my $Sessions = Dv_Sessions->new($db, $admin, \%conf);


  #$LIST_PARAMS{COMPANY_ID}=$FORM{COMPANY_ID};

  $Docs->{DATE}     = $FORM{DATE} || $DATE;
  $Docs->{DONE_DATE}= $DATE;
  $Docs->{FROM_DATE}= $DATE;

  my ($y, $m)=split(/-/, $FORM{MONTH});
  my $days_in_month=($m!=2?(($m%2)^($m>7))+30:(!($y%400)||!($y%4)&&($y%25)?29:28));


 if ($FORM{create}) {
   my $list = $Fees->reports({ MONTH      => $FORM{MONTH},
   	                           BILL_ID    => $Company->{BILL_ID},
   	                           TYPE       => 'METHOD'
   	                        });

   if ($Fees->{TOTAL} < 1) {
     $html->message('info', $_INFO, "$_FEES $_NOT_EXIST");
    }
  
   my @FEES_METHODS = ($_ONE_TIME, $_ABON, $_FINE, $_ACTIVATE);
   push @FEES_METHODS, @EX_FEES_METHODS if (@EX_FEES_METHODS);

   $FORM{SUM}     =$Fees->{SUM};    

#   my $i = 1;
#   foreach my $line (@$list) {
#      
#      $FORM{'IDS'}      .= "$i, ";
#      $FORM{'ORDER_'. $i}= $FEES_METHODS[$line->[0]];
#      $FORM{'COUNTS_'.$i}= '1';
#      $FORM{'UNIT_'.$i}  = '1';
#      $FORM{'SUM_'.$i}   = $line->[3];
#      $i++;
#    }

   #Get internet using
   my $report_list = $Sessions->reports({ 
                     INTERVAL   => $interval,
                     TP_ID      => $TP_ID,
                     COMPANY_ID => $FORM{COMPANY_ID}
	   	              });

  

   if (defined($FORM{OP_SID}) and $FORM{OP_SID} eq $COOKIES{OP_SID}) {
 	   $html->message('err', $_ERROR, "$_EXIST");
    }
   elsif (! $FORM{SUM_1} && $FORM{SUM} < 0.01) {
     $html->message('err', "$_ERROR", $_WRONG_SUM);
    }
   elsif($FORM{PREVIEW}) {
     docs_preview('tax_invoice', { %FORM });
     return 0;
    }
   else {
     $FORM{COMPANY_ID}=$LIST_PARAMS{COMPANY_ID} if (! $FORM{COMPANY_ID});
     
     $Docs->act_add({ %FORM, DATE => "$FORM{MONTH}-01" });


     if ($Docs->{errno} == 7) {
     	 $html->message('err', $_ERROR, "$_EXIST");	
      }
     elsif($Docs->{errno}) {
     	 $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}}");	
      }
    }
  }
 elsif($FORM{print}){
   $Docs->act_info($FORM{print}, { UID => $LIST_PARAMS{UID} });
  
   $Docs->{NUMBER}=$Docs->{DOC_ID};

   if ($Docs->{TOTAL} > 0) {
   	 ($Docs->{SUM_MAIN}, $Docs->{SUM_SUB})=split(/\./, $Docs->{TOTAL_SUM});
      $Docs->{FROM_DATE_LIT}='';
     

     $Docs->{'TOTAL_SUM'}             = sprintf("%.2f", $Docs->{TOTAL_SUM});
     $Docs->{'TOTAL_SUM_WITHOUT_VAT'} = sprintf("%.2f", ($conf{DOCS_VAT_INCLUDE}) ? $Docs->{TOTAL_SUM} - ($Docs->{TOTAL_SUM}) / ((100 + $conf{DOCS_VAT_INCLUDE} ) / $conf{DOCS_VAT_INCLUDE}) : $Docs->{TOTAL_SUM} );
     $Docs->{'TOTAL_SUM_VAT'}         = sprintf("%.2f", $Docs->{TOTAL_SUM}-$Docs->{'TOTAL_SUM_WITHOUT_VAT'});
     
     my $i=0; 
     foreach my $field_id ( @{ $Company->{INFO_FIELDS_ARR} } ) {
       my($position, $type, $name)=split(/:/, $Company->{INFO_FIELDS_HASH}->{$field_id});
       $Company->{$field_id}=$Company->{INFO_FIELDS_VAL}->[$i];
       $i++;
     }

     docs_print('act', { %$Docs, %$Company, A_FIO => $admin->{A_FIO} });
    }
   else {

     $html->message('err', $_ERROR, "[$Docs->{errno}] $err_strs{$Docs->{errno}}");	
    }
   return 0;
  }
 elsif($FORM{change}) {
   $Docs->act_change({ %FORM });

   if(! $Docs->{errno}) {
     $html->message('info', "$_INFO", "$_CHANGED N: [$FORM{DOC_ID}]");
    }
  }
 elsif($FORM{chg}) {
   $Docs->act_info($FORM{chg});

   if(! $Docs->{errno}) {
     $html->message('info', "$_INFO", "$_CHANGING N: [$FORM{chg}]");
    }
  }
 elsif($FORM{del} && $FORM{is_js_confirmed}) {
   $Docs->act_del($FORM{del});
   if(! $Docs->{errno}) {
     $html->message('info', "$_INFO", "$_DELETED N: [$FORM{del}]");
    }
  }
	
	if(! $user->{UID}  ) {
  	$Docs->{FORM_ACCT_ID} = "<tr><td>$_TAX_INVOICE $_NUM:</td><td><input type='text' name='ACCT_ID' value='%ACCT_ID%'></td></tr>\n";
   }

  #$Docs->{COMPANY_VAT}=$user->{COMPANY_VAT}.' %';
  $Docs->{OP_SID}  = mk_unique_value(16);
  $users->pi({  $users->{UID} });

  $Docs->{CUSTOMER}=  $users->{FIO} || '-';
  $Docs->{CAPTION} =  $_ACCOUNT;

  my ($Y, $M, $D)=split(/-/, $DATE, 3);  
  my @MONTH_ARR = ('');
  for(my $i=1; $i<13; $i++) {
	  push @MONTH_ARR, sprintf("%d-%.2d", $Y,$i);
   }

  $FORM{MONTH}="$Y-$M" if (! $FORM{MONTH});
  

  my $table = $html->table( { width       => '100%',
  	                          caption     => "$_ACTS",
	                            rowcolor    => $_COLORS[0],
                              rows        => [[ 
                                                #"$_USER: ", $users_list,
                                                "$_PERIOD: ", $html->form_select('MONTH', 
                                                           { SELECTED   => $FORM{MONTH},
 	                                                           SEL_ARRAY  => \@MONTH_ARR,
 	                                                           NO_ID      => 1
                                                          } ),
                                                 "$_DATE: ", $html->form_input('DATE', "$Y-$M-$D"),
                                          $html->form_input('show', $_CREATE, { TYPE => "SUBMIT" })
                                         ]],                                   
                      });

  print $html->form_main({ CONTENT => $table->show({ OUTPUT2RETURN => 1 }),
	                         HIDDEN  => { COMPANY_ID => "$FORM{COMPANY_ID}",
	                         	            subf       => $FORM{subf},
	                         	            index      => $index2,
	                                      create     => "1"
	                                     }
	                       });

  docs_acts_list($attr);
}


#**********************************************************
#
#**********************************************************
sub docs_tax_exports {

if ($FORM{d}) {
my ($y, $m, $d)=split(/-/, ($FORM{MONTH}) ? $FORM{MONTH}.'-01' : $DATE);

my $file_prefix = "26590025388695J1201503100000";
my $filename    = $file_prefix. "01$m$y".'.xml';

my ($fill_y, $fill_m, $fill_d)=split(/-/, ($FORM{DATE}) ? $FORM{DATE} : $DATE);
$Docs->{FILL_DATE}   = "$fill_d$fill_m$fill_y";
$Docs->{YEAR}=$y;
$Docs->{MONTH}=$m;

my $doc = $html->tpl_show(_include('docs_tax_export', 'Docs'), { %$Docs }, { OUTPUT2RETURN => 1 });

$LIST_PARAMS{PAGE_ROWS}=1000000;
$LIST_PARAMS{MONTH} = $FORM{MONTH} || "$y-$m";
my $list = $Docs->tax_invoice_reports({ %LIST_PARAMS });
my %invoice_hash = ();

my $num = 1;
foreach my $line ( @$list ) {
  push @{ $invoice_hash{T2RXXXXG2D}  }, $line->[1];
  push @{ $invoice_hash{T2RXXXXG3S}  }, $line->[2];
  push @{ $invoice_hash{T2RXXXXG4S}  }, 'ΟΝ';
  push @{ $invoice_hash{T2RXXXXG5S}  }, $line->[3];
  push @{ $invoice_hash{T2RXXXXG6S}   }, ''; # | $line->[3];
  push @{ $invoice_hash{T2RXXXXG7}   }, sprintf("%.2f", $line->[5]);
  push @{ $invoice_hash{T2RXXXXG8}   }, sprintf("%.2f", $line->[6]);
  push @{ $invoice_hash{T2RXXXXG9}   }, sprintf("%.2f", $line->[7]);

  $invoice_hash{T2R01G7} += $line->[5];
  $invoice_hash{T2R01G8} += $line->[6];
  $invoice_hash{T2R01G9} += $line->[7];
  $num++;
}


my @arr = (
  'T2RXXXXG2D', 
  'T2RXXXXG3S',
  'T2RXXXXG4S',
  'T2RXXXXG5S',
  'T2RXXXXG6S',
  'T2RXXXXG7',
  'T2RXXXXG8',
  'T2RXXXXG9',
  'T2RXXXXG10',
  'T2RXXXXG11',
  'T1RXXXXG12',
  'T1RXXXXG13',
  'T1RXXXXG14',
  'T1RXXXXG15',
  'T1RXXXXG16',

  );

foreach my $key (@arr) {
	my $i=1;
	foreach my $value ( @{ $invoice_hash{$key} } ) {
		$doc .= ($value) ? "<$key ROWNUM=\"$i\">$value</$key>\n" :  "<$key xsi:nil=\"true\" ROWNUM=\"$i\" />\n" ;
		$i++;
	}
}

$doc .= "
<T2R01G7>". sprintf("%.2f", $invoice_hash{T2R01G7}). "</T2R01G7>
<T2R01G8>". sprintf("%.2f", $invoice_hash{T2R01G8}). "</T2R01G8>
<T2R01G9>". sprintf("%.2f", $invoice_hash{T2R01G9}). "</T2R01G9>
<T2R01G10 xsi:nil=\"true\" />
<T2R01G11 xsi:nil=\"true\" />
<T2R01G12 xsi:nil=\"true\" />
<T2R02G7 xsi:nil=\"true\" />
<T2R02G8 xsi:nil=\"true\" />
<T2R02G9 xsi:nil=\"true\" />
<T2R02G10 xsi:nil=\"true\" />
<T2R02G11 xsi:nil=\"true\" />
<T2R02G12 xsi:nil=\"true\" /> 

	</DECLARBODY>
</DECLAR>";


my $filesize = length($doc);
print "Content-Type: text/plain; filename=\"$filename\"\n".
      "Content-Disposition: attachment; filename=\"$filename\" size=$filesize;".
      "\n\n";

print  $doc;

return 0;
}

my @MONTH_ARR = ('');
my ($Y, $M, $D)=split(/-/, $DATE, 3);
for (my $year=2009; $year<=$Y; $year++) {
  for(my $i=1; $i<13; $i++) {
	  my $m = sprintf("%.2d", $i);
	  push @MONTH_ARR, "$year-$m";
	  
   }
}


  $FORM{MONTH}="$Y-$M" if (! $FORM{MONTH});

  my $table = $html->table( { width       => '500',
  	                          caption     => "$_EXPORT - $_TAX_INVOICE",
	                            rowcolor    => $_COLORS[0],
                              rows        => [[ 
                                                "$_PERIOD: ", $html->form_select('MONTH', 
                                                           { SELECTED   => $FORM{MONTH},
 	                                                           SEL_ARRAY  => \@MONTH_ARR,
 	                                                           NO_ID      => 1
                                                          } ),
                                                 "$_CREATED: ",$html->date_fld2('DATE', { MONTHES => \@MONTHES, FORM_NAME => 'TAX_EXPORT', WEEK_DAYS => \@WEEKDAYS, DATE => "$Y-$M-01" }),
                                          $html->form_input('show', $_CREATE, { TYPE => "SUBMIT" })
                                         ]],                                   
                      });

  print $html->form_main({ CONTENT => $table->show({ OUTPUT2RETURN => 1 }),
	                         HIDDEN  => { 
	                         	            qindex      => $index,
	                         	            subf       => $FORM{subf},
	                                      create     => "1",
	                                      d          => 1
	                                     },
	                         NAME    => 'TAX_EXPORT'
	                       });
}



1
