\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{kiviletter}[2020/04/24 Letter Layouts for Kivitendo]

\newif\if@kivi@infobox
\DeclareOption{reffields}{\@kivi@infoboxfalse}
\DeclareOption{infobox}{\@kivi@infoboxtrue}
\@kivi@infoboxtrue

\ProcessOptions\relax


\RequirePackage{expl3}
\RequirePackage{iftex}
\KOMAoptions{fontsize=12pt}
% Schriftart, Eingabelayout der Tastatur
\ifPDFTeX
\RequirePackage[utf8]{inputenc}% Nur notwendig, wenn Basis älter als TL2018
\RequirePackage[T1]{fontenc}
\RequirePackage{lmodern}
\else
\RequirePackage{fontspec}
\fi

%\RequirePackage{xltabular}
\RequirePackage{tabularx}
\RequirePackage{longtable}
\RequirePackage{booktabs}
\PassOptionsToPackage{table}{xcolor}

\RequirePackage{xcolor}
\RequirePackage{graphicx}

\ifPDFTeX
\RequirePackage{eurosym}
\DeclareUnicodeCharacter{20AC}{\euro}
\fi

\RequirePackage[fromlogo,fromalign=right,
  firstfoot=false,%Für einheitliche Randeinstellungen
  refline=nodate,
	]{scrletter}
\LoadLetterOption{DIN}

\newkomavar{transaction}
\newkomavar[\lieferschein{}~\nr]{delivery}
\newkomavar[\angebot{}~\nr]{quote}
\newkomavar{orderID}
\newkomavar{projectID}

\usepackage{geometry}

\ExplSyntaxOn
\dim_new:N \g_kivi_margin_dim
\dim_gset:Nn \g_kivi_margin_dim {\useplength{toaddrhpos}}
\geometry{a4paper,margin=\g_kivi_margin_dim,heightrounded}
\savegeometry{kivi.letter@default}
%Scratch variables
\int_new:N \l_kivi_tmp_int
\bool_new:N \l_kivi_tmp_bool
\bool_new:N  \g_kivi_TableFoot_bool
\dim_new:N \g_kivi_orig@textheight_dim
\ExplSyntaxOff

\newsavebox{\shippingAddressBox}


\DeclareNewLayer[
foreground,
hoffset=\useplength{toaddrhpos},
voffset=\dimexpr\useplength{toaddrvpos}+\useplength{toaddrheight}+4\baselineskip,%sep to shippingaddressbox
contents={\usebox\shippingAddressBox}
]{kivitendo.shippingaddress}


\ExplSyntaxOn
\AtBeginLetter{\dim_gset:Nn \g_kivi_orig@textheight_dim {\textheight}}
\ExplSyntaxOff

\newpairofpagestyles{kivitendo.letter}{}
\renewcommand*{\letterpagestyle}{kivitendo.letter}

\DeclareNewPageStyleByLayers{kivitendo.letter.PricingTable}{
	kivitendo.TableHead,
	kivitendo.TableFoot
	kivitendo.letter.head.odd,kivitendo.letter.head.even,kivitendo.letter.head.oneside,%
	kivitendo.letter.foot.odd,kivitendo.letter.foot.even,kivitendo.letter.foot.oneside,%
}
\DeclareNewPageStyleByLayers{kivitendo.letter.first}{
	kivitendo.shippingaddress,
	kivitendo.TableFoot,
	kivitendo.letter.head.odd,kivitendo.letter.head.even,kivitendo.letter.head.oneside,%
	kivitendo.letter.foot.odd,kivitendo.letter.foot.even,kivitendo.letter.foot.oneside,%
}

\setkomavar{backaddress}{\firma\ $\cdot$ \strasse\ $\cdot$ \ort}

\setkomavar{firsthead}{
	\if@logo
	\rlap{\usekomavar{fromlogo}}%
	\fi
}

\@setplength{locwidth}{6cm}

\ExplSyntaxOn
\dim_new:N \l_kivi_tab_desc_dim
\bool_new:N \l_kivi_col_desc_bool
\bool_set_true:N \l_kivi_col_desc_bool 

\clist_map_inline:nn {pos, id, amount, price, pricetotal} {
	\bool_new:c {l_kivi_col_#1_bool}
	\dim_new:c {l_kivi_tab_#1_dim}
	\keys_define:nn {kivi/PricingTable} {
		#1 .choice:,
		#1 / true .code:n = \bool_set_true:c {l_kivi_col_#1_bool},
		#1 / false .code:n = \bool_set_false:c {l_kivi_col_#1_bool},
		#1  /unknown .code:n = {\bool_set_true:c {l_kivi_col_#1_bool}\dim_set:cn {g_kivi_tab_#1_dim} {##1}},
		#1 .default:n = true,
		#1 .initial:n = true,
	}
}

% set default values for colwidth
\dim_set:Nn \l_kivi_tab_pos_dim {3.5ex}
\dim_set:Nn \l_kivi_tab_id_dim {4em}
\dim_set:Nn \l_kivi_tab_amount_dim {5em}
\dim_set:Nn \l_kivi_tab_price_dim {7em}
\dim_set:Nn \l_kivi_tab_pricetotal_dim {7em}

\dim_new:N \g_kivi_tabcolsep_dim
\dim_gset:Nn \g_kivi_tabcolsep_dim {.5\tabcolsep}

\cs_new:Nn \__kivi_calc_desc_column: {
	\dim_gset:Nn \l_kivi_tab_desc_dim {
		\textwidth
		\bool_if:NT \l_kivi_col_pos_bool {-\l_kivi_tab_pos_dim -2\g_kivi_tabcolsep_dim}
		\bool_if:NT \l_kivi_col_id_bool {-\l_kivi_tab_id_dim -2\g_kivi_tabcolsep_dim}
		\bool_if:NT \l_kivi_col_amount_bool {-\l_kivi_tab_amount_dim -2\g_kivi_tabcolsep_dim}
		\bool_if:NT \l_kivi_col_pricetotal_bool  {-\l_kivi_tab_pricetotal_dim -2\g_kivi_tabcolsep_dim}
		\bool_if:NT \l_kivi_col_price_bool  {-\l_kivi_tab_price_dim -2\g_kivi_tabcolsep_dim}
	}
}

\newcolumntype{P}{>{\raggedleft\arraybackslash}p{\l_kivi_tab_price_dim}<{\,\currency}}

\RequirePackage{tcolorbox}
\tcbuselibrary{breakable, skins}

\tcb@new@skin{kivi@LT}{base@unbroken,%
	frame~engine=empty,interior~titled~engine=empty,interior~engine=empty,segmentation~engine=empty,title~engine=empty,%
	skin~first=kivi@LT@first,skin~middle=kivi@LT@middle,skin~last=kivi@LT@last,
	underlay~first~and~middle={
		\node[anchor=north]  at (interior.north)  {\csname box_use:c\endcsname  {g_kivi_LT@head_box}};
		\node[anchor=south]  at (interior.south)  {\csname box_use:c\endcsname  {g_kivi_LT@foot_box}};
	},
	underlay~unbroken~and~last={
	\node[anchor=north]  at (interior.north)  {\csname box_use:c\endcsname  {g_kivi_LT@head_box}};
	},
	boxsep=0pt,
	boxrule=0pt,
	left=0pt,
	right=0pt,
	bottom=\box_ht:N  \g_kivi_LT@foot_box+\box_dp:N  \g_kivi_LT@foot_box,
	top=\box_ht:N  \g_kivi_LT@head_box+\box_dp:N  \g_kivi_LT@head_box,
	parbox=false,
}

\tcb@new@skin{kivi@LT@first}{base@first,%
	frame~engine=empty,interior~titled~engine=empty,interior~engine=empty,segmentation~engine=empty,title~engine=empty,%
	skin~first=kivi@LT@first,skin~middle=kivi@LT@middle,skin~last=kivi@LT@middle,
}

\tcb@new@skin{kivi@LT@middle}{base@middle,%
	frame~engine=empty,interior~titled~engine=empty,interior~engine=empty,segmentation~engine=empty,title~engine=empty,%
	skin~first=kivi@LT@middle,skin~middle=kivi@LT@middle,skin~last=kivi@LT@middle,
}

\tcb@new@skin{kivi@LT@last}{base@last,%
	frame~engine=empty,interior~titled~engine=empty,interior~engine=empty,segmentation~engine=empty,title~engine=empty,%
	skin~first=kivi@LT@middle,skin~middle=kivi@LT@middle,skin~last=kivi@LT@last,
}

\tcbset{kivi@LT/.style={skin=kivi@LT}}%



\seq_new:N \l_kivi_PricingTable_seq
\seq_new:N \l_kivi_columns_seq
\seq_new:N \g_kivi_extraDescription_seq
\newcommand{\FakeTable}[1]{
	\par
	\seq_set_split:Nnn \l_kivi_PricingTable_seq {\tabularnewline} {#1}
	\begingroup
	\setlength{\tabcolsep}{\g_kivi_tabcolsep_dim}
	\seq_map_inline:Nn \l_kivi_PricingTable_seq {
		\seq_set_split:Nnn  \l_kivi_columns_seq {&} {##1}
	\seq_gclear:N \g_kivi_extraDescription_seq
	\exp_args:Nnx \use:n {\tabular[t]}\g_kivi_Pricing_colspec_tl
		\seq_pop_left:NN \__l_FakeTable_columns_seq \l_tmpa_tl
		\seq_item:Nn \l_kivi_columns_seq {\l_tmpa_tl}
		\seq_map_inline:Nn \__l_FakeTable_columns_seq {
			&\seq_item:Nn \l_kivi_columns_seq {####1}
		}
	\endtabular
	\seq_if_empty:NTF \g_kivi_extraDescription_seq
	{\par\nointerlineskip}
	{\par\nointerlineskip
	\begin{tcolorbox}[
		empty,
		left=\dim_eval:n {\l_kivi_tab_pos_dim+ \l_kivi_tab_id_dim +4\g_kivi_tabcolsep_dim},
		right=\dim_eval:n {\l_kivi_tab_num_dim+ 2\l_kivi_tab_price_dim +6\g_kivi_tabcolsep_dim},top=0pt,bottom=0pt,
		boxsep=0pt,
		breakable,
		lines~before~break=1,
	]
	\seq_use:Nn \g_kivi_extraDescription_seq {\\}
	\end{tcolorbox}
	\nointerlineskip
	}
	}
	\endgroup
}


\seq_new:N  \__l_FakeTable_columns_seq
\cs_new:Nn \__kivi_setup_FakeTable: {
	\seq_clear:N \__l_FakeTable_columns_seq
	\bool_if:NT \l_kivi_col_pos_bool {\seq_put_right:Nn \__l_FakeTable_columns_seq {1}}
	\bool_if:NT \l_kivi_col_id_bool  {\seq_put_right:Nn \__l_FakeTable_columns_seq {2}}
	\bool_if:NT \l_kivi_col_desc_bool  {\seq_put_right:Nn \__l_FakeTable_columns_seq {3}}
	\bool_if:NT \l_kivi_col_amount_bool {\seq_put_right:Nn \__l_FakeTable_columns_seq {4}}
	\bool_if:NT \l_kivi_col_pricetotal_bool   {\seq_put_right:Nn \__l_FakeTable_columns_seq {5}}
	\bool_if:NT \l_kivi_col_price_bool   {\seq_put_right:Nn \__l_FakeTable_columns_seq {6}}
}

\tl_new:N \g_kivi_Pricing_colspec_tl
\tl_gset:Nn \g_kivi_Pricing_colspec_tl {
	@{}
	\bool_if:NT \l_kivi_col_pos_bool {p{\l_kivi_tab_pos_dim}}
	\bool_if:NT \l_kivi_col_id_bool {p{\l_kivi_tab_id_dim}}
	p{\l_kivi_tab_desc_dim}
	\bool_if:NT \l_kivi_col_amount_bool {\exp_not:n {>{\raggedleft\arraybackslash}p{\l_kivi_tab_amount_dim}}}
	\bool_if:NT \l_kivi_col_price_bool {>{\raggedleft\arraybackslash}p{\l_kivi_tab_price_dim}<{\,\currency}}
	\bool_if:NT \l_kivi_col_pricetotal_bool {>{\raggedleft\arraybackslash}p{\l_kivi_tab_pricetotal_dim}<{\,\currency}}
	@{}
}


\clist_map_inline:nn {head, foot, firsthead, lastfoot} {%TODO reduce
	\box_new:c {g_kivi_LT@#1_box}
}

\cs_new:Nn \__kivi_setup_LT_boxes: {
	\__kivi_calc_desc_column:
	\hbox_gset:Nn \g_kivi_LT@head_box {
		\setlength{\tabcolsep}{\g_kivi_tabcolsep_dim}
		\exp_args:Nnx \use:n {\tabular[b]}\g_kivi_Pricing_colspec_tl
		\toprule
		\bool_if:NT \l_kivi_col_pos_bool {\bfseries\position &}
		\bool_if:NT \l_kivi_col_id_bool {\bfseries\artikelnummer &}
		\bfseries\bezeichnung
		\bool_if:NT \l_kivi_col_amount_bool {&\bfseries\menge}
		\bool_if:NT \l_kivi_col_price_bool { &\multicolumn{1}{>{\raggedleft}p{\l_kivi_tab_price_dim}}{\bfseries\einzelpreis}}
		\bool_if:NT \l_kivi_col_pricetotal_bool {&\multicolumn{1}{>{\raggedleft}p{\l_kivi_tab_pricetotal_dim}@{}}{\bfseries\gesamtpreis}}\\
		\\
		\midrule\\[-\dp\strutbox]
		\endtabular
	}
	\hbox_gset:Nn \g_kivi_LT@foot_box {
		\raisebox{\depth}{
			\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}}r@{}}
				\midrule
				\strut\weiteraufnaechsterseite
			\end{tabular*}
		}
	}
}


%Macht es sinn hier eine Variante zu machen, in der alle Spalten Belegbar sind?
\newenvironment{PricingTotal}{
	\tabular[t]{@{}p{\dim_eval:n {\linewidth-\l_kivi_tab_price_dim-2\tabcolsep}}P@{}}
	\midrule
}{
	\bottomrule\endtabular
}

\newcommand{\ExtraDescription}[1]{\seq_gput_right:Nn \g_kivi_extraDescription_seq {#1}}

\newenvironment{PricingTabular}[1][]{
	\begingroup
	\setlength{\tabcolsep}{\g_kivi_tabcolsep_dim}
	\__kivi_calc_desc_column:
	\exp_args:Nx \longtable \g_kivi_Pricing_colspec_tl
	% Tabellenkopf
	\toprule
	\bfseries\position & \bfseries\artikelnummer & \bfseries\bezeichnung & \bfseries\menge &\multicolumn{1}{P}{\bfseries\einzelpreis}&\multicolumn{1}{P@{}}{\bfseries\gesamtpreis}\\
	\midrule
	\endhead
	\midrule
	\multicolumn{6}{@{}r@{}}{\weiteraufnaechsterseite}\\
	\endfoot
}{
	\endlongtable
	\endgroup
}

\RequirePackage{xltabular}


\newenvironment{SimpleTabular}[1][\bfseries\position & \bfseries\menge & \bfseries\bezeichnung]
{
	\setlength{\tabcolsep}{\g_kivi_tabcolsep_dim}
	\xltabular{\linewidth}{@{}rrX@{}}
	\toprule
	#1\\
	\midrule\\\endhead
	\midrule
	\multicolumn{3}{@{}>{\raggedright}p{\linewidth}@{}}{\weiteraufnaechsterseite}\\
	\endfoot
	\bottomrule
	\endlastfoot
	\ignorespaces
}{
	\def\@currenvir{tabularx}
	\endxltabular
}

\newenvironment{PricingTabular*}[1][]{
	\bool_gset_true:N \g_kivi_inTable_bool
	\tl_if_empty:nF {#1} {\keys_set:nn {kivi/PricingTable} {#1}}
	\__kivi_setup_LT_boxes:
	\__kivi_setup_FakeTable:
	\PricingTabularBox\ignorespaces
}{\endPricingTabularBox}

\newtcolorbox{PricingTabularBox}{breakable,skin=kivi@LT}



\if@kivi@infobox
\setkomavar{location}{
	\ifkomavarempty{transaction}{}{
	\bfseries
	\usekomavar{transaction}
	}
	\par
	\medskip
	\begin{tabularx}{\useplength{locwidth}}{@{}l<{:}>{\raggedleft\arraybackslash}X@{}}
		\usekomavar*{date}&\usekomavar{date}\\
		\ifkomavarempty{myref}{}{
			\usekomavar*{myref}&\usekomavar{myref}\\
		}
		\kundennummer&\usekomavar{customer}\\
		\ifkomavarempty{yourref}{}{
			\usekomavar*{yourref}&\usekomavar{yourref}\\
		}
		\ifkomavarempty{delivery}{}{
			\usekomavar*{delivery}&\usekomavar{delivery}\\
		}
		\ifkomavarempty{quote}{}{
			\usekomavar*{quote}&\usekomavar{quote}\\
		}
		\ifkomavarempty{orderID}{}{\auftragsnummer&\usekomavar{orderID}\\}
		\ifkomavarempty{projectID}{}{\projektnummer&\usekomavar{projectID}\\}
		\ansprechpartner&\usekomavar{fromname}
		\ifkomavarempty{fromphone}{}{\\\textTelefon&\usekomavar{fromphone}}
		\ifkomavarempty{fromemail}{}{\\\textEmail&\usekomavar{fromemail}}
	\end{tabularx}
}
\removereffields
\AtBeginLetter{
	\ifdim\ht\shippingAddressBox>\z@
	\addtoplength{refvpos}{\dimexpr\ht\shippingAddressBox+\dp\shippingAddressBox}
	\addtoplength{refvpos}{4\baselineskip}%sep between address boxes
	\fi
}
\ExplSyntaxOff
\fi



\renewcommand*{\raggedsignature}{\raggedright}

\endinput
