---
title: "Invoice"
geometry: "left=3cm,right=2cm,top=2cm,bottom=2cm"
fontsize: 11pt
papersize: a4
params: 
  lang: 1
  app_path: 'app'
header-includes:
 - \usepackage{lastpage}
 - \usepackage{fancyhdr}
 - \usepackage{titlesec}
 - \usepackage{ifthen}
 - \titlespacing{\title}{0pt}{\parskip}{-\parskip}
output:
  pdf_document
---

<!-- logic chunk start -->
```{r setup_chunk, message = F,echo=F,warning=F}
box::use(
  lubridate[...],
  readr[...],
  dplyr[filter, bind_rows],
  purrr[keep, discard],
  magrittr[`%>%`],
  rjson[rjson_fromJSON = fromJSON]
)

lan_idx <- as.numeric(params$lang)

#
#   READING FILES
#

# main files
fields_names_list <- rjson_fromJSON(file = file.path(params$app_path, "json/field_names.json"))
final_currency_list <- rjson_fromJSON(file = file.path(params$app_path, "json/invoice_and_final_currency.json"))

#
# bank and businesses
#
business_to_bill_list <- rjson_fromJSON(file = file.path(params$app_path, "json/business_to_bill.json"))
consultant_account_list <- rjson_fromJSON(file = file.path(params$app_path, "json/consultant_account.json"))
consultant_business_list <- rjson_fromJSON(file = file.path(params$app_path, "json/consultant_business.json"))

#
# special multiline - salary - days
#
salary_list <- rjson_fromJSON(file = file.path(params$app_path, "json/salary.json"))

#
# oneliner costs
#
oneliners_list <- rjson_fromJSON(file = file.path(params$app_path, "json/oneliner_costs.json"))
oneliners_list <- oneliners_list %>% discard(names(.) %in% "file_identifier")

#
# grouped costs
#
grouped_list <- rjson_fromJSON(file = file.path(params$app_path, "json/grouped_costs.json"))
grouped_list <- grouped_list %>% discard(names(.) %in% "file_identifier")

#
#  account field check
#

if (is.null(consultant_account_list$show)) {
  consultant_account_list$show <- TRUE
}

#
#   READING DATES
#

# dates
sm <- month(salary_list$dates$start, label = TRUE)

em <- month(salary_list$dates$end, label = TRUE)

single_month <- month(salary_list$single$date, label = TRUE, abbr = FALSE)
single_year <- year(salary_list$single$date)
single_day <- day(salary_list$single$date)

sdt <- day(salary_list$dates$start)
edt <- day(salary_list$dates$end)
sy <- year(salary_list$dates$start)
ey <- year(salary_list$dates$end)

inv_dt <- day(final_currency_list$invoiceDate)
inv_m <- month(final_currency_list$invoiceDate, label = TRUE)
inv_y <- year(final_currency_list$invoiceDate)

#
#   currencies VARIABLES
#

final_currency <- toupper(final_currency_list$final_currency)
salary_currency <- toupper(salary_list$main$currency)
salary_currency_text <- toupper(salary_currency)
grouped_currency <- toupper(grouped_list$currency)

#
#   SALARY LOGIC
#

# currency exchanges comparisons
final_to_salary_exchange_condition <- final_currency == salary_currency

if (final_to_salary_exchange_condition) {
  salary_currency_text <- ""
}

use_dates <- salary_list$dates$use
use_salary_and_related <- salary_list$main$use_salary_and_related
use_single_date <- salary_list$single$use
use_period <- salary_list$period$use
use_modified <- salary_list$modified_days$use
use_nwd <- salary_list$non_working_days$use

use_month <- salary_list$single$`show_month/year_only`
single_string <- paste(single_month, single_year)

if (use_single_date && !use_month) {
  single_string <- paste(single_day, single_month, single_year)
}

total_days <- salary_list$main$total_days

salary_periods <- salary_list$period$number

periods_string <- ifelse((salary_periods == 0 || salary_periods == "") || !use_period, "",
  paste0(salary_periods, " ", salary_list$period$name)
)

day_pay <- salary_list$main$salary / total_days

modified_days <- ifelse(use_modified, salary_list$modified_days$days, 0)

non_working_days <- ifelse(use_nwd, salary_list$non_working_days$days, 0)

modified_pay <- modified_days * day_pay * (salary_list$modified_days$percentage / 100)

common_payable_days <- total_days - modified_days - non_working_days

common_payable_salary_days_pay <- common_payable_days * day_pay

common_plus_modified_pay <- common_payable_salary_days_pay + modified_pay
common_plus_modified_pay_rounded <- round(common_plus_modified_pay, 1)
common_payable_salary_days_pay_rounded <- round(common_payable_salary_days_pay, 1)

exchange_salary_text <- ifelse(final_to_salary_exchange_condition,
  "|",
  paste(
    common_plus_modified_pay_rounded, "|",
    "/", salary_list$main$currency_exchange_to_Final_Currency,
    "="
  )
)

salary_days_pay_final <- ifelse(final_to_salary_exchange_condition,
  common_plus_modified_pay,
  round(common_plus_modified_pay / salary_list$main$currency_exchange_to_Final_Currency)
)

modified_pay_rounded <- round(modified_pay, 1)

salary_days_pay_final <- ifelse(use_salary_and_related, salary_days_pay_final, 0)

#
#   ONELINER COSTS LOGIC
#

oneliners_filtered_list <- oneliners_list |> keep(~ .$use)
oneliners_final <- 0

if (length(oneliners_filtered_list) > 0) {
  oneliners_filtered_df <- bind_rows(oneliners_filtered_list, .id = "name")

  if ("currency" %in% colnames(oneliners_filtered_df)) {
    oneliners_filtered_df$currency <- toupper(oneliners_filtered_df$currency)
  }

  oneliners_filtered_df$needs_exchange <- ifelse(oneliners_filtered_df$currency != final_currency, TRUE, FALSE)

  oneliners_filtered_df_not_exchanged <- oneliners_filtered_df |> filter(!needs_exchange)

  oneliners_filtered_df_not_exchanged$formatted_value <- format(round(oneliners_filtered_df_not_exchanged$value),
    scientific = FALSE
  )

  oneliners_filtered_df_exchanged <- oneliners_filtered_df |> filter(needs_exchange)
  oneliners_filtered_df_exchanged$exchanged_value <- round(
    oneliners_filtered_df_exchanged$value / oneliners_filtered_df_exchanged$currency_exchange_to_Final_Currency
  )

  oneliners_filtered_df_exchanged$exchanged_value_formatted <- format(oneliners_filtered_df_exchanged$exchanged_value,
    scientific = FALSE
  )

  oneliners_exchange_text <- paste(
    format(oneliners_filtered_df_exchanged$value, scientific = FALSE), "|", "/",
    oneliners_filtered_df_exchanged$currency_exchange_to_Final_Currency, "="
  )

  oneliners_final <- sum(oneliners_filtered_df_not_exchanged$value,
    oneliners_filtered_df_exchanged$exchanged_value,
    na.rm = TRUE
  )
}

#
#   GROUPED COSTS LOGIC
#

# currency exchanges comparisons
final_to_grouped_exchange_condition <- final_currency == grouped_currency

grouped_currency_text <- grouped_currency

if (final_to_grouped_exchange_condition) {
  grouped_currency_text <- ""
}

exchange_grouped_text <- "|"

total_grouped_finals <- 0

use_grouped <- grouped_list$use

if (use_grouped) {
  grouped_list_root <- grouped_list %>% keep(names(.) %in% c(
    "currency_exchange_to_Final_Currency", "use",
    "GeneralName", "currency"
  ))
  grouped_sublists <- grouped_list %>% discard(names(.) %in% c(
    "currency_exchange_to_Final_Currency", "use",
    "GeneralName", "currency"
  ))

  sublists_df <- bind_rows(grouped_sublists, .id = "json_name")
  grouped_root_df <- grouped_list_root |> bind_rows()

  if ("currency" %in% colnames(grouped_root_df)) {
    grouped_root_df$currency <- toupper(grouped_root_df$currency)
  }

  grouped_df <- cbind(grouped_root_df, sublists_df)

  grouped_df$value_formatted <- format(grouped_df$value, scientific = FALSE)
  total_grouped_finals_original <- total_grouped_finals <- sum(grouped_df$value)
  if (final_to_grouped_exchange_condition) {
    total_grouped_finals <- sum(grouped_df$value)
  } else {
    grouped_df$exchanged_value <- grouped_df$value / grouped_df$currency_exchange_to_Final_Currency
    total_grouped_finals <- sum(grouped_df$exchanged_value)
  }

  if (!final_to_grouped_exchange_condition) {
    exchange_grouped_text <- paste(
      format(total_grouped_finals_original, scientific = FALSE), "|",
      "/", grouped_list_root$currency_exchange_to_Final_Currency,
      "="
    )
  }
}

grouped_final_formatted <- format(round(total_grouped_finals), scientific = FALSE)

#
#   TOTALS
#

total_sum <- sum(salary_days_pay_final, oneliners_final, total_grouped_finals, na.rm = TRUE)

total_pay_rounded <- round(total_sum)
total_pay_formatted_rounded <- format(total_pay_rounded, scientific = FALSE)

salary_days_pay_final_rounded <- round(salary_days_pay_final)
salary_days_pay_final_rounded_formatted <- format(salary_days_pay_final_rounded, scientific = FALSE)
```
<!-- logic chunk end -->

<!-- pagination setup -->

\pagestyle{fancy}
\setlength{\headsep}{0cm}

\newcommand{\mypagestyle}%
    {\ifthenelse{\pageref{LastPage}>1}%
        {\thispagestyle{fancy}}%
        {\thispagestyle{empty}}%
    }
\mypagestyle

\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
\cfoot{\thepage\ `r fields_names_list$of[lan_idx]` \pageref{LastPage}}

<!-- pdf part 1: left up: invoice number -->

\vspace{-12truemm}
\raggedright `r fields_names_list$invoiceNumber[lan_idx]`: `r final_currency_list$invoice_number` \par

<!-- part 2: right up: consultant business -->

\raggedleft `r fields_names_list$consultantBusiness[lan_idx]`: `r consultant_business_list$name`    
\raggedleft `r fields_names_list$consultantBusinessId[lan_idx]`: `r consultant_business_list$id`    
\raggedleft `r consultant_business_list$address1`  
\raggedleft `r consultant_business_list$address2`   
\raggedleft `r consultant_business_list$address3`   
\raggedleft `r fields_names_list$consultantPhone[lan_idx]` :  `r consultant_business_list$phone` 

<!-- part 3: left: bill to business -->

\raggedright `r fields_names_list$billTo[lan_idx]` \par  
 
`r business_to_bill_list$billTo1`  
`r business_to_bill_list$billTo2`  
`r business_to_bill_list$billTo3`  
`r business_to_bill_list$billTo4`  
`r business_to_bill_list$billTo5`  

<!-- part 4: right: date -->

\begin{flushright} 
`r fields_names_list$date[lan_idx]`:  `r inv_dt` `r inv_m` `r inv_y`  
\end{flushright} 

<!-- part 5: table -->

| `r fields_names_list$Services[lan_idx]`| |  |   |  | `r fields_names_list$amount[lan_idx]` |
|--------|-------:|----|----:|----|-----------:|
``` {r table, results="asis", echo=F, eval=T}
cat( # nolint
  if (use_dates || use_single_date || use_period || use_salary_and_related) {
    paste0("| ", salary_list$main$section_title, " | | | | | |\n")
  },
  if (use_dates) {
    paste0(
      "|\\hspace{2mm}", "", sdt, " ", sm, " ", sy, " ",
      salary_list$dates$date_connector, " ", edt, " ", em, " ", ey, "| | |  |   |   |\n"
    )
  },
  if (use_single_date) {
    paste0("|\\hspace{2mm}", salary_list$single$text, " ", single_string, "| | |  |   |   |\n")
  },
  if (use_modified && use_salary_and_related) {
    paste0(
      "|\\hspace{8mm}", salary_list$modified_days$text, ": |", modified_days, "/", total_days, "|",
      "|", modified_pay_rounded, "|", salary_currency_text, "|  |", "\n"
    )
  },
  if ((use_modified | use_nwd) && use_salary_and_related) {
    paste0(
      "|\\hspace{8mm}", salary_list$main$common_days_text, "|", common_payable_days, "/", total_days, "|",
      "|", common_payable_salary_days_pay_rounded, "|", salary_currency_text, "|  |", "\n"
    )
  },
  if (use_period && !use_salary_and_related) {
    paste0("|\\hspace{2mm}", periods_string, " | | | | | |\n")
  },
  if (use_salary_and_related) {
    paste0(
      "|\\hspace{2mm}", periods_string,
      "| |", salary_currency_text, "|", exchange_salary_text, "|", salary_days_pay_final_rounded_formatted, " ",
      final_currency, "|", "\n"
    )
  },
  if (length(oneliners_filtered_list)) {
    oneliners_strings <- paste0("| | | | |  \n")
    for (idx in seq_len(nrow(oneliners_filtered_df_not_exchanged))) {
      oneliners_strings <- c(
        oneliners_strings,
        paste0(
          "|", oneliners_filtered_df_not_exchanged[idx, "text"],
          "| |", "|", "|", " ", "|",
          oneliners_filtered_df_not_exchanged[idx, "formatted_value"], " ",
          final_currency, "|", "\n"
        )
      )
    }

    for (idx in seq_len(nrow(oneliners_filtered_df_exchanged))) {
      oneliners_strings <- c(
        oneliners_strings,
        paste0(
          "|", oneliners_filtered_df_exchanged[idx, "text"], "| |",
          oneliners_filtered_df_exchanged[idx, "currency"], "|",
          oneliners_exchange_text[idx],
          "|", " ", " ", oneliners_filtered_df_exchanged[idx, "exchanged_value_formatted"], " ",
          final_currency, "|", "\n"
        )
      )
    }
    oneliners_strings
  },
  if (use_grouped) {
    grouped_strings <- character()
    for (grouped_idx in seq_len(nrow(grouped_df))) {
      grouped_strings <- c(
        grouped_strings,
        paste0(
          "|\\hspace{2mm}", grouped_df[grouped_idx, "name"], "| |", "|",
          " ", grouped_df[grouped_idx, "value_formatted"], "|", grouped_df[grouped_idx, "currency"], " ", "| |", "\n"
        )
      )
    }
    grouped_strings <- c(
      paste0("| | | | | \n"),
      grouped_strings,
      paste0(
        "|", grouped_list$GeneralName, "| |", grouped_currency_text, "|", exchange_grouped_text, "|",
        grouped_final_formatted, " ",
        final_currency, "|", "\n"
      )
    )
    grouped_strings
  },
  paste0("| | | | | \n"),
  paste0("| **TOTAL**  |   |   |   |   |**", total_pay_formatted_rounded, "** ", final_currency, "|"),
  sep = ""
)
```

<!-- part 6: right: signature -->

&nbsp;  
&nbsp;  
\begin{flushright} 
`r fields_names_list$Signature[lan_idx]`
\end{flushright}

<!-- part 7: left: bank Account and swift -->

``` {r account_header, results="asis", echo=F, eval=consultant_account_list$show} 
cat(paste0(
  "\\large \\textbf{", fields_names_list$WireInstructions[lan_idx], "} /",
  "\\normalsize ", fields_names_list$BankAccountInformation[lan_idx], ""))
```

``` {r intermediary, results="asis", echo=F, eval=all(consultant_account_list$use_intermediary, consultant_account_list$show) } 
cat(paste0(
  "\\large \\textbf{", fields_names_list$Intermediary[lan_idx], "} /",
  fields_names_list$CorrespondentBank[lan_idx], "\\textbf{ (Field 56):}  \n  "
))
cat(paste0("\\hspace{5mm}\\normalsize SWIFT: **", consultant_account_list$intermediary_bank_swift, "**  \n"))
cat(paste0(
  "\\hspace{5mm}", fields_names_list$Name[lan_idx], ": ", consultant_account_list$intermediary_bank_name, ", ",
  consultant_account_list$intermediary_bank_country, "  \n"
))
```

``` {r bank_details, results="asis", echo=F, eval=consultant_account_list$show} 
cat(paste0(
  "\\large ", fields_names_list$Beneficiary[lan_idx], " \\textbf{", fields_names_list$Bank[lan_idx], ":}  \n",
  "\\normalsize \\hspace{5mm}SWIFT: \\textbf{", consultant_account_list$final_bank_swift, "}  \n"
))
```
``` {r bank, results="asis", echo=F, eval=consultant_account_list$show} 
if (consultant_account_list$use_intermediary) {
  cat(paste0(
    "\\hspace{5mm}",
    "**",
    paste0(c(
      consultant_account_list$final_bank_short_name,
      " ",
      fields_names_list$Account[lan_idx]
    )[fields_names_list$order[[lan_idx]]], collapse = " "),
    " **", 
    fields_names_list$with[lan_idx], " ",
    consultant_account_list$intermediary_bank_name,
    ": ",
    "**", consultant_account_list$final_bank_account, "**  \n"
  ))
} else {
  cat("<!-- avoid line break -->")
}
```
``` {r account_details, results="asis", echo=F, eval=consultant_account_list$show} 
cat(paste0(
  "\\hspace{5mm}", fields_names_list$Name[lan_idx], ": \\textbf{", consultant_account_list$final_bank_name, "}  \n",
  "\\hspace{5mm}", fields_names_list$Address[lan_idx], ": ", consultant_account_list$final_bank_address, ", ",
  consultant_account_list$final_bank_country, "  \n"
))
```

``` {r account_details2, results="asis", echo=F, eval=consultant_account_list$show} 
cat(paste0(
  "\\large\\textbf{", fields_names_list$consultantBusiness[lan_idx], "} / ", fields_names_list$BeneficiaryCustomer[lan_idx],
  "  \n",
  "\\hspace{5mm}\\normalsize ", fields_names_list$Name[lan_idx], ": ", consultant_business_list$name, "  \n",
  "\\hspace{5mm}IBAN: **", consultant_account_list$IBAN, "**  \n"
))
```
<!-- part 8: optional -->

<!-- \large `r fields_names_list$RemittanceInformation[lan_idx]` \textbf{(Field 70)}:   -->
<!-- \hspace{5mm} \normalsize `r fields_names_list$Includealso[lan_idx]` **invoice number**, **contract number** -->

