%% file: Standard Multipage.tex
%% Purpose: Multipage bill template for e-Bills
%%
%% Created by Mark Asplen-Taylor
%% Asplen Management Ltd
%% www.asplen.co.uk
%%
%% Modified for Freeside by Kristian Hoffman
%%
%% Changes
%% 	0.1	4/12/00	Created
%%	0.2	18/10/01	More fields added
%%	1.0	16/11/01	RELEASED
%%	1.2	16/10/02	Invoice number added
%%	1.3	2/12/02	Logo graphic added
%%	1.4	7/2/03	Multipage headers/footers added
%%      n/a     forked for Freeside; checked into CVS
%%      12/04/18  added support for coupon placement, top or bottom of page

\documentclass[letterpaper]{article}

\usepackage{fancyhdr,lastpage,ifthen,array,longtable,afterpage,caption,multirow,bigstrut}
\usepackage[breakwords]{truncate} % to avoid overflowing boxes
\usepackage{graphicx}			% required for logo graphic
\usepackage[utf8]{inputenc}             % multilanguage support
\usepackage[T1]{fontenc}
[@-- if ( length($watermark) ) {
  $OUT .= '
\usepackage{background}
\backgroundsetup{
  placement=center,
  opacity=0.25,
  color=black,
  angle=0,
  contents=' . $watermark . '
}';
}
'';
--@]

\catcode`\{=1
\catcode`\}=2
\special{ps:%
  SDict begin [
    /Title (Invoice \#[@-- $invnum --@])
    /DOCINFO pdfmark
  end
}
\end

\newcommand{\extracouponspace}{[@-- defined($extracouponspace) ? $extracouponspace : '2.7in' --@]}

\addtolength{\voffset}{-0.0cm}		% top margin to top of header
\addtolength{\hoffset}{-0.6cm}		% left margin on page
\addtolength{\topmargin}{[@-- defined($topmargin) ? $topmargin : '-1.00cm' --@]}
\setlength{\headheight}{2.0cm} 		% height of header
[@-- if ($coupon && $couponlocation eq "top") { '\addtolength{\headheight}{\extracouponspace}'; } --@] % add coupon space to header
\setlength{\headsep}{[@-- defined($headsep) ? $headsep : '1.0cm' --@]}
\setlength{\footskip}{1.0cm}		% bottom of footer from bottom of text

%\addtolength{\textwidth}{2.1in}    	% width of text
\setlength{\textwidth}{19.5cm}
\setlength{\textheight}{[@-- defined($textheight) ? $textheight : '19.5cm' --@]}
\setlength{\oddsidemargin}{-0.9cm} 	% odd page left margin
\setlength{\evensidemargin}{-0.9cm} 	% even page left margin

\LTchunksize=40


\begin{document}


\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{1pt}

\renewcommand{\footrule}{
[@--
  $coupon ? '\ifthenelse{\equal{\thepage}{1}}' : '';
--@]
  {
  }
  {
    \vbox to 0pt{\rule{\headwidth}{\footrulewidth}\vss}
  }
}

% Adjust the inset of the mailing address
\newcommand{\addressinset}[1][]{\hspace{1.0cm}}

% Adjust the inset of the return address and logo
\newcommand{\returninset}[1][]{\hspace{-0.25cm}}

% New command for address lines i.e. skip them if blank
\newcommand{\addressline}[1]{\ifthenelse{\equal{#1}{}}{}{#1\\}}

% Inserts dollar symbol
\newcommand{\dollar}[1][]{\symbol{36}}

% Remove plain style header/footer
\fancypagestyle{plain}{
  \fancyhead{}
}
\fancyhf{}

% Define fancy header/footer for first and subsequent pages
\fancyfoot[C]{
\ifpageone{\global\setlength\headheight{2cm}}
  \ifthenelse{\equal{\thepage}{1}}
  { % First page
[@--
  if ($coupon && $couponlocation eq "bottom") {
    $OUT .= '\vspace{-\extracouponspace}';
    $OUT .= '\rule[0.5em]{\textwidth}{\footrulewidth}\\\\';
    $OUT .= $coupon;
    $OUT .= '\vspace{'.
      (defined($couponfootsep) ? $couponfootsep : '0.2in') .
      '}';
  }
  elsif ($coupon && $couponlocation eq "top") {
    $OUT .= '\vspace{-\extracouponspace}';
  }
  '';
--@] [@-- $smallerfooter ? '\scriptsize{' : '\small{' --@]
[@-- $footer --@]
    }[@-- ($coupon && $couponlocation eq "bottom") ? '\vspace{\extracouponspace}' : '' --@]
  }
  { % ... pages
    [@-- $smallerfooter ? '\scriptsize{' : '\small{' --@]
[@-- $smallfooter --@]
    }
  }
}

\fancyfoot[R]{
  \ifthenelse{\equal{\thepage}{1}}
  { % First page
  }
  { % ... pages
    \small{\thepage~[@-- emt('of') --@]~\pageref{LastPage}}
  }
}

\fancyhead[L]{
  \ifthenelse{\equal{\thepage}{1}}
  { % First page
[@--
  if ($coupon && $couponlocation eq "top") {
    $OUT .= '\vspace{-\extracouponspace}';
    $OUT .= $coupon;
    $OUT .= '\rule[0.5em]{\textwidth}{\footrulewidth}\\\\';
    $OUT .= '\vspace{'.
      (defined($couponfootsep) ? $couponfootsep : '0.2in') .
      '}';
  }
--@]\returninset
    \makebox{
      \begin{tabular}{ll}
        \begin{minipage}[b]{5.5cm}
[@-- $returnaddress --@]
        \end{minipage} &
        \includegraphics{[@-- $logo_file --@]}\\
      \end{tabular}
    }
  }
  { % ... pages
    %\includegraphics{[@-- $logo_file --@]}	% Uncomment if you want the logo on all pages.
  }
}

\fancyhead[R]{
  \ifthenelse{\equal{\thepage}{1}}
  { % First page
    \begin{tabular}{ccc}
    [@-- join(' & ', ( $no_date   ? '' : emt('Invoice date') ),
                     ( $no_number ? '' : emt('Invoice #')    ),
                     emt('Customer #')
             )
    --@]\\
    \vspace{0.2cm}
    \textbf{[@-- $date --@]} & \textbf{[@-- $invnum --@]} & \textbf{[@-- $custnum --@]} \\\hline
    \rule{0pt}{5ex} &~~ \huge{\textsc{[@-- emt($notice_name) --@]}} & \\
    \vspace{-0.2cm}
     & & \\\hline
    \end{tabular}
  }
  { % ... pages
    \small{
      \begin{tabular}{lll}
      [@-- join(' & ', emt('Invoice date'), emt('Invoice #'), emt('Customer #') ) --@]\\
      \textbf{[@-- $date --@]} & \textbf{[@-- $invnum --@]} & \textbf{[@-- $custnum --@]}\\
      \end{tabular}
    }
  }
}

\pagestyle{fancy}


%% Font options are:
%%	bch	Bitsream Charter
%% 	put	Utopia
%%	phv	Adobe Helvetica
%%	pnc	New Century Schoolbook
%%	ptm	Times
%%	pcr	Courier

\renewcommand{\familydefault}{phv}


% Commands for freeside table header...

\newcommand{\FSdescriptionlength} { [@-- $unitprices ? '8.2cm' : '12.8cm' --@] }
\newcommand{\FSdescriptioncolumncount} { [@-- $unitprices ? '4' : '6' --@] }
\newcommand{\FSunitcolumns}{ [@--
  $unitprices
  ? '\makebox[2.5cm][r]{\textbf{~~' . emt('Unit Price') . '}} &' .
    '\makebox[1.4cm]{\textbf{~' . emt('Quantity') . '}} & '
  : '' --@] }

\newcommand{\FShead}{
  \hline
  \rule{0pt}{2.5ex}
  \makebox[1.4cm]{} &
  \multicolumn{\FSdescriptioncolumncount}{l}{
    \truncate{\FSdescriptionlength}{\textbf{[@-- emt('Description') --@]}}
  } &
  \FSunitcolumns
  \makebox[1.6cm][r]{\textbf{[@-- emt('Amount') --@]}} \\
  \hline
}

\newcommand{\FSusagehead}{
  \hline
  \rule{0pt}{2.5ex}
  \makebox[1.4cm]{} &
  \multicolumn{4}{l}{
    \truncate{\FSdescriptionlength}{\textbf{[@-- emt('Description') --@]}}
  } &
  \textbf{~~[@-- emt('Calls') --@]} &
  \textbf{~~[@-- emt('Duration') --@]} &
  \textbf{~~[@-- emt('Amount') --@]} \\
  \hline
}

% ...description...
\newcommand{\FSdesc}[5]{
  \multicolumn{1}{c}{\rule{0pt}{2.5ex}\textbf{#1}} &
  \multicolumn{[@-- $unitprices ? '4' : '6' --@]}{l}{
    \truncate{\FSdescriptionlength}{\textbf{#2}}
  } &
[@-- $unitprices ? '  \multicolumn{1}{r}{\textbf{#3}} &'."\n".
                   '  \multicolumn{1}{r}{\textbf{#4}} &'."\n"
                 : ''
--@]
  \multicolumn{1}{r}{\textbf{#5}}\\
}
% ...extended description...
\newcommand{\FSextdesc}[1]{
  \multicolumn{1}{l}{\rule{0pt}{1.0ex}} &
  \multicolumn{6}{l}{
    \truncate{12.8cm}{\small{~~~#1}}
  } \\
}
% ...call detail (multiple columns already)...
\newcommand{\FScalldetail}[1]{
  \multicolumn{1}{l}{\rule{0pt}{1.0ex}} &
  ~~~#1
  \\
}
}
% ...and total line items (which use the full 12.8cm length, ignoring
% unitprice/quantity
\newcommand{\FStotaldesc}[2]{
  & \multicolumn{6}{l}{
    \truncate{12.8cm}{#1}
  } & #2\\
}

% ...usage class summary
\newcommand{\FSusagedesc}[4]{
  \multicolumn{1}{c}{\rule{0pt}{2.5ex}} &
  \multicolumn{4}{l}{\textbf{#1}} &
  \multicolumn{1}{r}{\textbf{#2}} &
  \multicolumn{1}{r}{\textbf{#3}} &
  \multicolumn{1}{r}{\textbf{#4}}
  \\
}

%	Headers and footers defined for the first page
\addressinset \rule{0.5cm}{0cm}
\makebox{
\begin{minipage}[t]{7.0cm}
\vspace{[@-- defined($addresssep) ? $addresssep : '0.25cm' --@]}
\textbf{[@-- $payname --@]}\\
\addressline{[@-- $company --@]}
\addressline{[@-- $address1 --@]}
\addressline{[@-- $address2 --@]}
\addressline{[@-- $city --@], [@-- $state --@]~~[@-- $zip --@]}
\addressline{[@-- $country --@]}
\end{minipage}}
\hfill
\makebox{
\begin{minipage}[t]{6.4cm}
[@--
  if ($ship_enable) {
    $OUT .= '\textbf{' . emt('Service Address') . '}\\\\';
    $OUT .= "\\addressline{$ship_company}";
    $OUT .= "\\addressline{$ship_address1}";
    $OUT .= "\\addressline{$ship_address2}";
    $OUT .= "\\addressline{$ship_city, $ship_state~~$ship_zip}";
    $OUT .= "\\addressline{$ship_country}";
    $OUT .= '~\\\\';
  }else{
    $OUT .= '';
  }
--@]
\begin{flushright}
[@-- $terms ? emt('Terms') . ': ' . emt($terms) : '' --@]\\
[@-- $po_line --@]\\
\end{flushright}
\end{minipage}}
\vspace{1.5cm}
%
[@-- $summary --@]
%
\section*{}
[@--
  foreach my $section ( grep { !$summary || $_->{description} ne $finance_section } @sections ) {
    if ($section->{'pretotal'} && !$summary) {
      $OUT .= '\begin{flushright}';
      $OUT .= '\large\textsc{'. $section->{'pretotal'}. '}\\\\';
      $OUT .= '\\end{flushright}';
    }
    $OUT .= '\pagebreak' if $section->{'post_total'};
    unless ($section->{'summarized'} ) {
      $OUT .= '\captionsetup{singlelinecheck=false,justification=raggedright,font={Large,sc,bf}}';
      $OUT .= '\ifthenelse{\equal{\thepage}{1}}{\setlength{\LTextracouponspace}{\extracouponspace}}{\setlength{\LTextracouponspace}{0pt}}'
        if $coupon;
      $OUT .= '\begin{longtable}{cllllllr}';
      $OUT .= '\caption*{ ';
      if ($section->{'location'}) {
        $OUT .= $section->{'location'}{'label_prefix'}. ': '
          if length($section->{'location'}{'label_prefix'});
        $OUT .= $section->{'location'}{'address1'};
        $OUT .= ', ' . $section->{'location'}{'address2'}
          if length($section->{'location'}{'address2'});
        $OUT .= ', ' .
                $section->{'location'}{'city'} . ', ' .
                $section->{'location'}{'state'} . '~' .
                $section->{'location'}{'zip'};
      } elsif ( $section->{'description'} ) {
        $OUT .= ($section->{'description'});
      } else {
        $OUT .= emt('Charges');
      }
      $OUT .= '}\\\\';
      if ($section->{header_generator}) {
        $OUT .= &{$section->{header_generator}}();
      } elsif ( $section->{usage_section} ) {
        $OUT .= '\FSusagehead';
      } else {
        $OUT .= '\FShead';
      }
      $OUT .= '\endfirsthead';
      $OUT .= '\multicolumn{7}{r}{\rule{0pt}{2.5ex}'.emt('Continued from previous page').'}\\\\';
      if ($section->{header_generator}) {
        $OUT .= &{$section->{header_generator}}();
      } elsif ( $section->{usage_section} ) {
        $OUT .= '\FSusagehead';
      } else {
        $OUT .= '\FShead';
      }
      $OUT .= '\endhead';
      $OUT .= '\multicolumn{7}{r}{\rule{0pt}{2.5ex}'.emt('Continued on next page...').'}\\\\';
      $OUT .= '\endfoot';
      $OUT .= '\hline';

      if (scalar(@sections) > 1 and !$section->{no_subtotal}) {
        if ($section->{total_generator}) {
          $OUT .= &{$section->{total_generator}}($section);
        } else {
          $OUT .= '\FStotaldesc{' . $section->{'description'} . ' Total}' .
                  '{' . $section->{'subtotal'} . '}' . "\n";
        }
      }

      #if ($section == $sections[$#sections]) {
        foreach my $line (grep {$_->{section}->{description} eq $section->{description}} @total_items) {
          if ($section->{total_line_generator}) {
            $OUT .= &{$section->{total_line_generator}}($line);
          } else {
            $OUT .= '\FStotaldesc{' . $line->{'total_item'} . '}' .
                    '{' . $line->{'total_amount'} . '}' . "\n";
          }
        }
      #}

      $OUT .= '\hline';
      $OUT .= '\endlastfoot';

      my $lastref = 0;
      foreach my $line (
        grep { ( scalar( @sections ) > 1
               ? $section->{'description'} eq $_->{'section'}->{'description'}
               : 1
             ) }
        @detail_items )
      {
        my $ext_description = $line->{'ext_description'};

        # Don't break-up small packages.
        my $rowbreak = @$ext_description < 5 ? '*' : '';

        $OUT .= "\\hline\n" if (($line->{'ref'} || 0) ne $lastref);
        if ($section->{description_generator}) {
          $OUT .= &{$section->{description_generator}}($line);
        } elsif ($section->{usage_section}) {
          my $minutes = sprintf('%d', $line->{'duration'} / 60);
          my $seconds = $line->{'duration'} % 60;
          $OUT .= '\FSusagedesc
            {' . $line->{'description'} . '}
            {' . $line->{'quantity'} . '}
            {' . $minutes . 'm ' . $seconds . 's' . '}
            {' . $line->{'amount'} . '}';
        } else {
          $OUT .= '\FSdesc'.
                  '{}'.
                  '{' . $line->{'description'} . '}' ;
          if ( $unitprices and length($line->{'unit_amount'}) ) {
            # then show the unit amount and quantity
            $OUT .=
                '{\\dollar' . $line->{'unit_amount'} . '}'.
                '{'         . $line->{'quantity'}    . '}';
          } else {
            # leave those columns blank
            $OUT .= '{}{}';
          }
          $OUT .= '{\\dollar' . $line->{'amount'} . "}${rowbreak}\n";
        }
        $lastref = $line->{'ref'} || 0;

        foreach my $ext_desc (@$ext_description) {
          if ($section->{extended_description_generator}) {
            $OUT .= &{$section->{extended_description_generator}}($ext_desc);
          } elsif ( $ext_desc !~ /[^\\]&/ ) {
            $OUT .= '\FSextdesc{' . $ext_desc . "}$rowbreak\n";
          } else { # call detail
            $OUT .= '\FScalldetail{' . $ext_desc . "}$rowbreak\n";
          }
        }

      }

      $OUT .= '\end{longtable}';
    }
    if ($section->{'posttotal'}) {
      $OUT .= '\begin{flushright}';
      $OUT .= '\normalfont\large\bfseries\textsc{'. $section->{'posttotal'}. '}\\\\';
      $OUT .= '\\end{flushright}';
    }
  }

--@]
[@--

  my @location_summary_sections =
    grep {
      ref $_->{location}
      && $_->{locationnum}
      && $_->{description}
      && $_->{description} ne $finance_section
    } @sections;
  if ( $multisection eq 'location' && scalar(@location_summary_sections) > 1 ) {

$OUT .= '
      \hline
      \section*{}
      \captionsetup{singlelinecheck=false,justification=raggedright,font={Large,sc,bf}}
      \ifthenelse{\equal{\thepage}{1}}{\setlength{\LTextracouponspace}{\extracouponspace}}{\setlength{\LTextracouponspace}{0pt}}

      \begin{longtable}{cllllllr}
      \caption*{ '. emt('Summary of New Charges by Location') .' }
      \\\\

      \hline
      \rule{0pt}{2.5ex}
      \makebox[1.4cm]{} &
      \multicolumn{6}{l}{
        \truncate{13.0cm}{\textbf{'. emt('Location') .'}}
      } &
      \makebox[1.6cm][r]{\textbf{'. emt('Amount') .'}} \\\\
      \hline

      \endfirsthead
      \multicolumn{7}{r}{\rule{0pt}{2.5ex}'. emt('Continued from previous page') .'}
      \\
      \FShead
      \endhead
      \multicolumn{7}{r}{\rule{0pt}{2.5ex}'. emt('Continued on next page...') .'}
      \\
      \endfoot
      \hline
      \endlastfoot
      \hline
    ';

    for my $section (@location_summary_sections) {
      $OUT.= '
        \rule{0pt}{2.5ex}
        \makebox[1.4cm]{} &
        \multicolumn{6}{l}{
          \truncate{12.0cm}{\textbf{'. $section->{description} .'}}
        } &
        \makebox[1.6cm][r]{\textbf{'. $section->{subtotal} .'}} \\\\
      ';
    }

    $OUT .= '\end{longtable}';
  }
--@]

\vfill
\begin{minipage}[t]{\textwidth}
  [@-- length($summary)
         ? ''
        : ( $smallernotes
              ? '\scriptsize{ '.$notes.' }'
              : $notes
          )
  --@]
  [@-- $coupon ? '\ifthenelse{\equal{\thepage}{1}}{\rule{0pt}{\extracouponspace}}{}' : '' --@]
\end{minipage}
\end{document}
