data-raw/terms_mix_bayer_brasil.R

## code to prepare `terms_mix_bayer_brasil` dataset goes here

devtools::load_all()

filtered_docs <- tipo_documento_bayer_brasil %>%
  filter(tipo_de_doc_2 %in% c(
    "Venda",
    "Venda Barter",
    "Complemento de Preço",
    "Venda ES",
    "Complemento de Preço ES"
  )) %>%
  select(tipo_doc_faturamento, tipo_de_doc_2, tipo_doc)

df_doc <- nflists_bayer_brasil %>%
  inner_join(filtered_docs, by = c("tipo_doc_fat" = "tipo_doc_faturamento"))

df_doc_camp <- df_doc %>%
  inner_join(campanhas_bayer_brasil %>% mutate(id = id %>% as.character()), by = c("id_campanha" = "id"))

df_to_model <- df_doc_camp %>%
  select(
    cliente, nome_do_cliente, cidade, regiao,
    data_de_emissao, data_de_vencto, modalidade, montante_encargo_imposto, org_vendas, tipo_de_doc_2, escritorio_de_vendas, grp_vend, id_campanha
  )


terms_mix_bayer_brasil1 <- df_to_model %>%
  mutate(
    aging = as.numeric(lubridate::as_date(data_de_vencto) - lubridate::as_date(data_de_emissao)),
    terms_mix = case_when(
      modalidade %>% str_detect("Barter") ~ "Barter",
      modalidade %>% str_detect("CRA") ~ "CRA",
      modalidade %>% str_detect("Rural") ~ "Rural Credit",
      aging <= 0 ~ "Cash",
      aging <= 30 ~ "Short-Term",
      aging > 30 ~ "Traditional"
    ),
    modalidade = case_when(
      terms_mix == "Barter" ~ "Covered Terms",
      terms_mix == "CRA" ~ "Open Terms",
      terms_mix == "Rural Credit" ~ "Open Terms",
      terms_mix == "Cash" ~ "Cash",
      terms_mix == "Short-Term" ~ "Open Terms",
      terms_mix == "Traditional" ~ "Open Terms"
    ),
    anomes = str_c(lubridate::year(data_de_emissao), stringr::str_pad(lubridate::month(data_de_emissao), width = 2, pad = "0")),
    setor_atividade = "Quimico Bayer",
    negocio = "Crop Protection Bayer",
    marca = "Quimico Bayer",
    safra = "Quimico Bayer",
    uneg = escritorio_de_vendas,
    reg = grp_vend,
    legacy = "Bayer"
  ) %>%
  filter(terms_mix %>% is.not.na()) # sometimes there are fiscal notes with no end date


terms_mix_bayer_brasil2 <- terms_mix_bayer_brasil1 %>%
  left_join(clients_bayer %>% mutate(parceiro_negocios_bayer = parceiro_negocios_bayer %>% as.character()), by = c("cliente" = "parceiro_negocios_bayer")) %>%
  filter(classe_de_risco %>% is.na()) # Either na or Intercompany this excludes intercompany


terms_mix_bayer_brasil <- terms_mix_bayer_brasil2 %>%
  rename(
    consultor = consultor_interno,
    data_de_vencimento = data_de_vencto,
    cond_pgto = id_campanha
  ) %>%
  group_by(cliente, nome_grupo_agregado_monsanto_bayer, setor_atividade, negocio, marca, safra, uneg, reg, consultor, anomes, data_de_vencimento, aging, cond_pgto, terms_mix, modalidade, legacy) %>%
  summarise(valor_brl = sum(montante_encargo_imposto)) %>%
  ungroup()

usethis::use_data(terms_mix_bayer_brasil, compress = "xz", overwrite = TRUE)
brunocarlin/nflistBayer documentation built on April 26, 2020, 10:38 p.m.