/*
https://app-v2.focusnfe.com.br
see the suppliers liste
Authentique
support@bitcarvers.com
sdjkauAhT.11
//https://wifi1.impacthub.community/hotspot/?ap=fc:ec:da:fc:5b:d5&id=test:22:fb:27:d8:d8&t=1594985233&url=http://captive.apple.com%2fhotspot-detect.html&ssid=ImpactHub_2G
//http://46.28.110.128/hotspot/?ap=fc:ec:da:fc:5b:d5&id=test:22:fb:27:d8:d8&t=1594985233&url=http://captive.apple.com%2fhotspot-detect.html&ssid=ImpactHub_2G
*/
$DOMAIN["name"] = 'Floripa';
$DOMAIN["currency"] = 'R$';
$DOMAIN['invoiceName'] = "Invoice No. ";
$DOMAIN['invoice2Name'] = "Correction receipt Nr. ";
$DOMAIN["stornoService"] = 26;
$DOMAIN["changeService"] = 25;
$DOMAIN['manualAccounts'] = array();
$DOMAIN['manualSymbols'] = array();
$DOMAIN['swift'] = "GIBAATWMXXX";
$DOMAIN['iban'] = "BR302011129251651600";
// Invoicing details
define('DEBIT_ROUNDING_LIMIT', 5); // Minimal amount of account's debt to be allowed for direct debit
define('INVOICE_ROUNDING_LIMIT', 0.5); // Minimum unpaid invoice amount to indicate it as unpaid
define('DEFAULT_DUE_INTERVAL', 7); // Default invoice due to interval (adds to invoice's issued date)
define('MINIMUM_FIRST_NOTIFICATION_INTERVAL', 14); // Interval from invoice's issued date to notify account the invoice is not paid
define('INVOICE_NOTIFY_INTERVAL', 4); // Minimum interval between 2 unpaid invoice notifications
function locationToEntity($obj, $forceNew = false) {
$e = 1; // Default
if ($obj['location'] == 2) {
$e = 2;
} else if ($obj['location'] == 4) {
$e = 3;
} else if ($obj['service']['serviceEntity'] == 4 || $obj['location'] == 6) {
// bewiky
$e = 4;
} else if ($obj['service']['serviceEntity'] == 5 || $obj['location'] == 8) {
// trajano, centro
$e = 5;
} else if ($obj['service']['serviceEntity'] == 6 || $obj['location'] == 10) {
// Porto alegre
$e = 6;
} else if ($obj['service']['serviceEntity'] == 7 || $obj['location'] == 7) {
// sapiens -> primavera
//if ($forceNew || (isset($obj['account']['organisation']['newerInvoicingEntities']) && $obj['account']['organisation']['newerInvoicingEntities'])) {
$e = 7; // sapiens je pouzity pro kontrakty
//} else {
// $e = 1;
//}
} else if ($obj['location'] == 12) {
// seo-pejota -> primavera
$e = 1;
} else if (isset($obj['service']['taxCode']) && in_array($obj['service']['taxCode'], ['8440/8599604', '8718/7020400'])) {
// BRAVA
$e = 8;
}
return $e;
}
function floripaSetReceivedDate() {
// Set date received HUBLE-26575
SQL::query("UPDATE payment SET receivedWhen = paidWhen WHERE method NOT IN (".comma(PaymentMethod::CARD_ASAAS, PaymentMethod::BLIMBOO, PaymentMethod::BLIMBOO_DEBIT).") AND receivedWhen IS NULL AND paidWhen IS NOT NULL");
$mapping = [];
foreach (mysqlObjects("SELECT id, name FROM entity WHERE id != 4") as $entity) {
dbg("floripaSetReceivedDate for entity $entity[id]");
$asaasKeys = getAsaasKeysForEntity($entity['id']);
$offset = 0;
$pageLength = 100;
getAsaasnewPaymentsxxx:
$asaasKeys = getAsaasKeysForEntity($entity['id']);
if (startsWith($asaasKeys['token'], '?')) continue; // skip if it is with ?
$params = [
'creditDate[ge]' => rToday(ST(rToday().' - 60 DAY')),
'creditDate[le]' => rToday(),
'limit' => $pageLength,
'offset' => $offset
];
$result = asaasCall($asaasKeys, 'GET:v3/payments', $params);
if ($result['http_code'] == 200) {
//echoh2("Offset: $offset (page per $pageLength)");
$data = json_decode($result['content'], true);
foreach ($data['data'] as $did => $d) {
if (in_array($d['billingType'], ['CREDIT_CARD'])) {
if ($d['status'] == 'RECEIVED' && $d['value'] > 0) {
$mapping[$d['confirmedDate']] = $d['creditDate'];
//echo('
| '.$d['billingType'].' | '.$d['confirmedDate'].' | '.$d['paymentDate'].' | '.$d['creditDate'].' |
');
}
}
}
if ($data['hasMore']) {
$offset += $pageLength;
goto getAsaasnewPaymentsxxx;
}
}
}
foreach ($mapping as $paidWhen => $receivedWhen) {
echodiv("$paidWhen -> $receivedWhen");
SQL::update("payment", "method = ".PaymentMethod::CARD_ASAAS." AND receivedWhen IS NULL AND paidWhen = '".escape($paidWhen)."'", ['receivedWhen' => $receivedWhen]);
}
}
function filterCEP($cep) {
$cep = normalizeCEP($cep);
if (mb_strlen($cep) <= 7) {
return false;
}
if (sqlCount("organisation", "zip = '$cep' OR zip = '".escape(normalizeCEP($cep))."'") > 0) return true;
/*
rErrorReporting(false);
$content = file_get_contents("http://cep.republicavirtual.com.br/web_cep.php?formato=xml&cep=$cep");
rErrorReporting(true);
if (!$content) return true;
if (strpos($content, "cep completo") === false) {
return false;
}
*/
return true;
}
function normalizeCEP($cep) {
$cep = generateFriendly($cep, "0-9", "");
return $cep;
}
function filterCPF($cpf) {
$cpf = preg_replace('/\D/', '', $cpf);
if ( strlen( $cpf ) != 11 ) {
return false;
}
if( preg_match( '/^(\d{1})\1{10}$/', $cpf ) ) {
return false;
}
$sum = 0;
for( $i = 0; $i < 9; $i++ ) {
$sum += $cpf[$i] * (10-$i);
}
$mod = $sum % 11;
$digit = ($mod > 1) ? (11 - $mod) : 0;
if ($cpf[9] != $digit) {
return false;
}
$sum = 0;
for ($i = 0; $i < 10; $i++) {
$sum += $cpf[$i] * (11-$i);
}
$mod = $sum % 11;
$digit = ($mod > 1) ? (11 - $mod) : 0;
if ($cpf[10] != $digit){
return false;
}
return true;
}
function cardType($number) {
$number = str_replace("*", "0", $number);
$number=preg_replace('/[^\d]/','',$number);
if (preg_match('/^3[47][0-9]{13}$/',$number))
{
return 'amex'; //::AMEX;
}
elseif (preg_match('/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/',$number))
{
return 'diners'; //::DINERS;
}
elseif (preg_match('/^6(?:011|5[0-9][0-9])[0-9]{12}$/',$number))
{
return 'discover'; //::DISCOVER;
}
elseif (preg_match('/^(?:2131|1800|35\d{3})\d{11}$/',$number))
{
return 'jcb'; //::JCB;
}
elseif (preg_match('/^5[1-5][0-9]{14}$/',$number))
{
return 'mastercard'; //::MASTERCARD;
}
elseif (preg_match('/^4[0-9]{12}(?:[0-9]{3})?$/',$number))
{
return 'visa'; //PaymentMethod::VISA;
}
else
{
return 'visa'; // Other
exit;
}
}
function outNFF($num) {
return number_format($num, 2, '.', '');
}
function getIGPMForMonth($dateStart, $dateEnd) {
$fromCache = true;
if (strtotime($dateEnd) > strtotime(rToday())) {
$fromCache = false;
$dateEnd = rToday();
}
$dateStart = explode('-', $dateStart);
$dateEnd = explode('-', $dateEnd);
$cache = mysqlSimpleObjectCond("brazil_igpm_cache", "
year1 = $dateStart[0] AND month1 = $dateStart[1]
AND year2 = $dateEnd[0] AND month2 = $dateEnd[1]
");
if ($cache) return $cache['value'];
$result = rcurl_get_web_page("https://www3.bcb.gov.br/CALCIDADAO/publico/corrigirPorIndice.do?method=corrigirPorIndice", array(
'aba' => 1,
'selIndice' => '00189IGP-',
'dataInicial' => $dateStart[1].'/'.$dateStart[0],
'dataFinal' => $dateEnd[1].'/'.$dateEnd[0],
'valorCorrecao' => '100,00'
));
if ($result['http_code'] != 200) {
rSupportEmail("Problem calling https://www3.bcb.gov.br/CALCIDADAO/publico/corrigirPorIndice.do", $result);
return null;
}
$val = (float) str_replace(",", '.', mb_strbetween('">', " %", mb_strbetween("percentual", "%", $result['content'])));
$val = $val / 100;
mysqlUpdateObject("brazil_igpm_cache", null, array(
'year1' => $dateStart[0],
'month1' => $dateStart[1],
'year2' => $dateEnd[0],
'month2' => $dateEnd[1],
'value' => $val
));
return $val;
}
$NFECodesData = array();
$NFECodesData[] = array(
array('11689/8230001', uf_strict('SERVIÇOS DE ORGANIZAÇÃO DE FEIRAS, CONGRESSOS, EXPOSIÇÕES E FESTAS')),
array('8230001', ''),
2
);
$NFECodesData[] = array(
array('2511/8211300', 'Serviço de espaços para desenvolvimento organizacional'),
array('8211300', ''),
2
);
$NFECodesData[] = array(
array('8440/8599604', 'Treinamento em desenvolvimento profissional e gerencial'),
array('8599604', ''),
3
);
$NFECodesData[] = array(
array('8718/7020400', 'Atividades de Consultoria em gestão empresarial, exceto consultoria técnica especifíca'),
array('7020400', ''),
5
);
$NFECodesData[] = array(
array('9001901/9001901', 'Produção teatral'),
array('9001901', ''),
2
);
$NFECodesData[] = array(
array('9001902/9001902', 'Produção musical'),
array('9001902', ''),
2
);
$NFECodesData[] = array(
array('7311400/7311400', 'Agências de publicidade'),
array('7311400', ''),
2.5
);
// HUBLE-27878
$NFECodesData[] = array(
array('5819100/5819100', 'Edição de cadastros, listas e de outros produtos gráficos'),
array('5819100', ''),
5
);
$NFECodesData[] = array(
array('6319400/6319400', 'Portais, provedores de conteúdo e outros serviços de informação na internet'),
array('6319400', ''),
2
);
$NFECodesData[] = array(
array('5914600/5914600', 'Atividades de exibição cinematográfica'),
array('5914600', ''),
2
);
$NFECodesData[] = array(
array('9001999/9001999', 'Artes cênicas, espetáculos e atividades complementares não especificadas anteriormente'),
array('9001999', ''),
2
);
$NFECodesData[] = array(
array('6204000/6204000', 'Consultoria em tecnologia da informação'),
array('6204000', ''),
2
);
$NFECodesData[] = array(
array('7410299/7410299', 'Atividades de design não especificadas anteriormente'),
array('7410299', ''),
3
);
$NFECodesData[] = array(
array('7420001/7420001', 'Atividades de produção de fotografias, exceto aérea e submarina'),
array('7420001', ''),
5
);
$NFECodesData[] = array(
array('74900104/74900104', 'Atividades de intermediação e agenciamento de serviços e negócios em geral, exceto imobiliários'),
array('74900104', ''),
3
);
// retentionType
// 1 = ir/irrf
// 2 = csfr (not used, cumulative 3+4+5)
// 3 = pis
// 4 = cofins
// 5 = csll
// Default Retentions
// https://docs.google.com/spreadsheets/d/1OsZQ6cvTI5wtd73yLkPAybHf3k8aPXxq/edit?gid=1866940403#gid=1866940403
// HUBLE-27493
// https://docs.google.com/spreadsheets/d/1OsZQ6cvTI5wtd73yLkPAybHf3k8aPXxq/edit?gid=1866940403#gid=1866940403
// remove after accepting HUBLE-26278
// HUBLE-27878
// HUBLE-27493
$DomainRetentions['8718/7020400'] = [
// OK2
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
$DomainRetentions['8440/8599604'] = [
// OK2
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
$DomainRetentions['11689/8230001'] = [
// OK2
// No retentions - HUBLE-41411
// array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
// array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
// array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
// array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
$DomainRetentions['9001901/9001901'] = [
// OK2
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
$DomainRetentions['9001902/9001902'] = [
// OK2
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
$DomainRetentions['7311400/7311400'] = [
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
];
$DomainRetentions['6319400/6319400'] = [
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
$DomainRetentions['5914600/5914600'] = [
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
$DomainRetentions['9001999/9001999'] = [
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
$DomainRetentions['6204000/6204000'] = [
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
$DomainRetentions['7410299/7410299'] = [
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
/*
$DomainRetentions['7490104/7490104'] = [
array('retentionType' => 1, 'value' => 1.50, 'minval' => 10, 'minvalGroup' => null),
array('retentionType' => 3, 'value' => 0.65, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 4, 'value' => 3.00, 'minval' => 10, 'minvalGroup' => 1),
array('retentionType' => 5, 'value' => 1.00, 'minval' => 10, 'minvalGroup' => 1),
];
*/
$DomainRetentions['2511/8211300'] = [
// HUBLE-39184
// sem retentions
];
// HUBLE-38531
// https://docs.google.com/spreadsheets/d/11gWHYk_7uB_olgrSthDt4AVdCaUOlhbNM2GGWU3T7HE/edit?gid=1610623915#gid=1610623915
$CBSbyCNAE = [
//"11689/8230001" => ['codigo_nbs' => '1.1806.63.00', 'codigo_indicador_operacao' => '100301'],
"11689/8230001" => ['codigo_nbs' => '1.1806.63.00', 'codigo_indicador_operacao' => '040101'], // new indop, was 100301 and not worked (comment HUBLE-42854#response210691)
'9001902/9001902' => ['codigo_nbs' => '1.2502.10.00', 'codigo_indicador_operacao' => '040101'],
//"7054/5819100" => ['codigo_nbs' => '1.1805.31.00', 'codigo_indicador_operacao' => '100301'],
"7054/5819100" => ['codigo_nbs' => '1.1806.59.00', 'codigo_indicador_operacao' => '100301'],
//"5819100/5819100" => ['codigo_nbs' => '1.1805.31.00', 'codigo_indicador_operacao' => '100301'],
"5819100/5819100" => ['codigo_nbs' => '1.1806.59.00', 'codigo_indicador_operacao' => '100301'],
//"2511/8211300" => ['codigo_nbs' => '1.1806.40.00', 'codigo_indicador_operacao' => '100301'],
//"2511/8211300" => ['codigo_nbs' => '1.1806.59.00', 'codigo_indicador_operacao' => '100301'],
//"2511/8211300" => ['codigo_nbs' => '1.1805.31.00', 'codigo_indicador_operacao' => '020101'],
//"2511/8211300" => ['codigo_nbs' => '1.1806.40.00', 'codigo_indicador_operacao' => '100301'], // versao emissao platforma municipio
//"2511/8211300" => ['codigo_nbs' => '1.1806.40.00', 'codigo_indicador_operacao' => '020101'], // comentario de contabilidade
//"2511/8211300" => ['codigo_nbs' => '1.1806.40.00', 'codigo_indicador_operacao' => '100301'], // tentativa so para PB - ibs_cbs_codigo_municipio_incidencia = municipl. de tomador
// "2511/8211300" => ['codigo_nbs' => '1.1806.63.00', 'codigo_indicador_operacao' => '020101'], // Joao testo OK
"2511/8211300" => ['codigo_nbs' => '1.1806.63.00', 'codigo_indicador_operacao' => '100301'], // voltando codigo velho, 8.11.2026
//'7311400/7311400' => ['codigo_nbs' => '1.1406.20.00', 'codigo_indicador_operacao' => '100301'],
'7311400/7311400' => ['codigo_nbs' => '1.1406.19.00', 'codigo_indicador_operacao' => '100301'],
'8718/7020400' => ['codigo_nbs' => '1.1401.19.00', 'codigo_indicador_operacao' => '100301'],
'8440/8599604' => ['codigo_nbs' => '1.2205.19.00', 'codigo_indicador_operacao' => '030101'],
];
// HUBLE-38531
// https://docs.google.com/spreadsheets/d/11gWHYk_7uB_olgrSthDt4AVdCaUOlhbNM2GGWU3T7HE/edit?gid=1610623915#gid=1610623915
$TaxCodeToCNAE_nacional = [
//"9177/6204000" => "010101",
//"11744/6204000" => "010601",
//"9114/6319400" => "010801",
//"11794/8211300" => "030301",
//"11738/7410299" => "071101",
//"9058/6821802" => "100501",
//"9062/7311400" => "100801",
//"11130/7490104" => "100501",
//"9095/5914600" => "120201",
//"9015/5914600" => "121601",
//"9096/5914600" => "120201",
"11689/8230001" => "120801", // OK, aliquotas OK
//"9094/9001901" => "120101",
//"11699/9001901" => "121301",
//"11698/9001902" => "121301",
//"9093/9001999" => "120101",
//"9030/5914600" => "130301",
//"9024/7420001" => "130301",
//"9018/9001902" => "130201",
'6319400/6319400' => '010801', // backward compatibility, jiz nepouzivame
'9001902/9001902' => '121301', // Producao musical, backward compatibility, jiz nepouzivame
'9001901/9001901' => '121301', // SERVIÇOS DE PRODUÇÃO DE EVENTOS, backward compatibility, jiz nepouzivame
"7054/5819100" => "170201", // OK, aliquotas ok
"5819100/5819100" => "170201", // backward compatibility, jiz nepouzivame
//"8731/6204000" => "170101",
//"8727/7020400" => "170101",
//"8750/7311400" => "170601",
//"2511/8211300" => "170201", // OK
//"2511/8211300" => "030301", // OK
//"2511/8211300" => "170201", // versao emissao platforma municipio
"2511/8211300" => "030301", // Joao
'7311400/7311400' => '170601', // new alias, OK
//'7490104/7490104' => '100501', // new alias, OK - jiz nepouzivame od 3.12.2025
'8718/7020400' => '170101', // brava, OK
'8440/8599604' => '080201', // brava, OK
];
// HUBLE-38531
// HUBLE-42854#response211230
foreach ([1, 3, 4, 5, 7, 9001, 9002, 9003, 9004, 9005, 9007] as $i) {
$TaxCodeToCNAE_nacional_entity[$i] = [
//"2511/8211300" => "030301"
//"2511/8211300" => "170201" // versao emissao platforma municipio\
"2511/8211300" => "30301" // versao emissao platforma municipio
];
}unset($i);
$NFSECodeList = array();
$NFECodesMapping = array();
foreach ($NFECodesData as $_nfditem) {
$NFSECodeList[$_nfditem[0][0]] = $_nfditem[0][0].' '.$_nfditem[0][1];
$NFECodesMapping[$_nfditem[0][0]] = $_nfditem;
}
// Continente (Palhoça, Palhoca)
$NFECodesMappingEntity[2]['11689/8230001'] = array(
array(1208, 'Planejamento, organização e administração de feiras, exposições, congressos e congêneres.'),
array(1208, ''),
4);
$NFECodesMappingEntity[2]['8440/8599604'] = array(
array(802, 'Instrução, treinamento, orientação pedagógica e educacional, avaliação de conhecimentos de qualquer natureza.'),
array(802, ''),
2);
$NFECodesMappingEntity[2]['2511/8211300'] = array(
array(1702, 'Datilografia, digitação, estenografia, expediente, secretaria em geral, resposta audível, redação, edição, interpretação, revisão, tradução, apoio e infra-estrutura administrativa e congêneres.'),
array(1702, ''),
3);
$NFECodesMappingEntity[2]['8718/7020400'] = array(
array(1701, 'Assessoria ou consultoria de qualquer natureza, não contida em outros itens desta lista'),
array(1701, ''),
3);
// Porto alegre
// https://focusnfe.com.br/blog/nfse-porto-alegre/
$NFECodesMappingEntity[6]['11689/8230001'] = array(
array('12.08', 'Planejamento, organização e administração de feiras, exposições, congressos e congêneres.'),
array(null, ''),
2,
'120800100'
);
$NFECodesMappingEntity[6]['8440/8599604'] = array(
array('8.02', 'Instrução, treinamento, orientação pedagógica e educacional, avaliação de conhecimentos de qualquer natureza.'),
array(null, ''),
2,
'80200100');
$NFECodesMappingEntity[6]['2511/8211300'] = array(
array('17.02', 'Datilografia, digitação, estenografia, expediente, secretaria em geral, resposta audível, redação, edição, interpretação, revisão, tradução, apoio e infra-estrutura administrativa e congêneres.'),
array(null, ''),
2,
'170200100');
$NFECodesMappingEntity[6]['8718/7020400'] = array(
array('17.01', 'Assessoria ou consultoria de qualquer natureza, não contida em outros itens desta lista'),
array(null, ''),
2,
'170100100');
$EntityAlternatives = [];
foreach (SQL::objects('entity', "alternativeFor IS NOT NULL") as $e) {
$EntityAlternatives[$e['alternativeFor']] = $e[id];
}
foreach ($TaxCodeToCNAE_nacional_entity as $eid => $ef) {
if (isset($EntityAlternatives[$eid])) {
$TaxCodeToCNAE_nacional_entity[$EntityAlternatives[$eid]] = $ef;
}
}
foreach ($NFECodesMappingEntity as $entityId => $specialEntityData) {
if (isset($EntityAlternatives[$entityId])) {
$NFECodesMappingEntity[$EntityAlternatives[$entityId]] = $NFECodesMappingEntity[$entityId];
}
}
// ASAAS
function getAsaasKeysForEntity($invoiceEntity) {
//if (DEBUG_MODE) {
// $asaasKeys['token'] = '$aact_YTU5YTE0M2M2N2I4MTliNzk0YTI5N2U5MzdjNWZmNDQ6OjAwMDAwMDAwMDAwMDAwNjY3OTc6OiRhYWNoX2ZiYWNlZjY0LTdjNzgtNDEzZi1hOWZjLTY4ZGYyOWY5ZjY3YQ==';
// $asaasKeys['url'] = "https://sandbox.asaas.com/api/";
//}
$asaasKeystore = [
'novo-primavera' => '$aact_prod_000MzkwODA2MWY2OGM3MWRlMDU2NWM3MzJlNzZmNGZhZGY6OmJjNWYzYTUzLTRjNGEtNDZmNi04MDQ3LTcyMjQzODhmNmQzNzo6JGFhY2hfNTllMzBkNWEtNTI5Zi00ZGUwLTkyZTItOWViMjRlMjRlNjgz',
'novo-sapiens' => '$aact_prod_000MzkwODA2MWY2OGM3MWRlMDU2NWM3MzJlNzZmNGZhZGY6Ojk2MjgwNDA1LWE1NjYtNDlkMC1iNzdiLWJhNmUzZGQwZGY4YTo6JGFhY2hfNDI3MWQ4MzgtYzEyNi00YzFhLTkwMjctOWU1YjNiNGFkYjUy',
'novo-PedraBranca' => '$aact_prod_000MzkwODA2MWY2OGM3MWRlMDU2NWM3MzJlNzZmNGZhZGY6OjZhZTI0NjY4LWVlOTUtNDJmMC04NDFiLTlhNmZiOTJjNmIxNjo6JGFhY2hfNDRjYTA3NmQtN2M0ZS00MzExLTk5ZDctYWNiOGM4MjAzYzYy',
'novo-BeWiki' => '$aact_prod_000MzkwODA2MWY2OGM3MWRlMDU2NWM3MzJlNzZmNGZhZGY6OmJlOTI4YzlkLTM0NjYtNGMwNC1hMWRlLTIyN2EzZDFlOWYwMzo6JGFhY2hfMjJhMzdlYWUtMTJlOS00OGFkLTljN2MtYmE5ZTYwODc3M2Ni',
'novo-Centro' => '$aact_prod_000MzkwODA2MWY2OGM3MWRlMDU2NWM3MzJlNzZmNGZhZGY6OjJlZWZlYmU4LWE5ZDgtNGU0NC1hOGQzLTNhYTZjN2IyZjc1NDo6JGFhY2hfMzUxMDkyNWYtYWJlNC00OGZjLWE2YmYtNWM4NDBiZWM2MTUz',
];
$asaasKeystore['primavera'] = '$aact_YTU5YTE0M2M2N2I4MTliNzk0YTI5N2U5MzdjNWZmNDQ6OjAwMDAwMDAwMDAwMDAzNTQyNDU6OiRhYWNoXzdmYWJmYjc2LTZjZjEtNGRkZi05YmRmLWZiYTY2YTQ1Y2JhMA==';
$asaasKeystore['pedra-branca'] = '$aact_YTU5YTE0M2M2N2I4MTliNzk0YTI5N2U5MzdjNWZmNDQ6OjAwMDAwMDAwMDAwMDAzNTQyNDY6OiRhYWNoX2IwNTk2NmFiLTdiNTUtNDJhYS1iZGRjLTg5NzEwMDMwNGU5Mw==';
$asaasKeystore['beira-mar'] = '?'; //$aact_YTU5YTE0M2M2N2I4MTliNzk0YTI5N2U5MzdjNWZmNDQ6OjAwMDAwMDAwMDAwMDAzNTQyNDg6OiRhYWNoXzE1Y2Y4YmYwLTQ5ZjUtNGNlYi04MWE3LWQyNGFkNzRhMmIwMw==';
$asaasKeystore['centro'] = '$aact_MzkwODA2MWY2OGM3MWRlMDU2NWM3MzJlNzZmNGZhZGY6OmMzNjUwMmI3LTQ0YmQtNDMxNi1hZTdhLTlkYTRiZGY3ZDM5Mzo6JGFhY2hfZGQwOGM1MzktNjJlOS00OWY1LTk0NDEtMjIxNWI2MDRlOGIx==';
$asaasKeystore['porto-alegre'] = '$aact_prod_000MzkwODA2MWY2OGM3MWRlMDU2NWM3MzJlNzZmNGZhZGY6OmFlYzlkYWMzLWQxZmYtNDhkZi1iYmNkLWM3ZTAzZGU3NWQ4NDo6JGFhY2hfMzJhOGYwNTctMDUzOS00OTliLTkxMDctNThhMTIwMDE5MTE5'; // '?'; // HUBLE-42879,
$asaasKeystore['sapiens'] = '$aact_prod_000MzkwODA2MWY2OGM3MWRlMDU2NWM3MzJlNzZmNGZhZGY6OmU1M2Y2ZTYwLTgwY2MtNDI4Zi04ZGVkLWEwODUxMDFjNTQwZDo6JGFhY2hfZGRhOGYwYjktMDVhNi00ODExLThlOGYtMzBhMDRiZTA0YzFl';
$asaasKeystore['brava'] = '$aact_prod_000MzkwODA2MWY2OGM3MWRlMDU2NWM3MzJlNzZmNGZhZGY6OjIzYjdiZTcwLTNkYzgtNDExMy1hMTU0LTAzN2M2NzQ4OTRhNjo6JGFhY2hfZjg3NmU1OWUtNjM3YS00OWQ3LWI1NjEtYWVjMjA2NzQzZDcx'; // HUBLE-38833
$asaasKeys = [];
$asaasKeys['url'] = RenDataSources::getASAASService()['url'];
$asaasKeys['token'] = '?';
if ($invoiceEntity == 1) {
$asaasKeys['token'] = $asaasKeystore['primavera'];
} else if ($invoiceEntity == 2) {
$asaasKeys['token'] = $asaasKeystore['pedra-branca'];
} else if ($invoiceEntity == 3) {
$asaasKeys['token'] = $asaasKeystore['beira-mar'];
} else if ($invoiceEntity == 5) {
$asaasKeys['token'] = $asaasKeystore['centro'];
} else if ($invoiceEntity == 6) {
$asaasKeys['token'] = $asaasKeystore['porto-alegre'];
} else if ($invoiceEntity == 7) {
$asaasKeys['token'] = $asaasKeystore['sapiens'];
} else if ($invoiceEntity == 8) {
$asaasKeys['token'] = $asaasKeystore['brava'];
} else if ($invoiceEntity == 9007) { // sapiens parque novo
$asaasKeys['token'] = $asaasKeystore['novo-sapiens'];
} else if ($invoiceEntity == 9002) { // pedra branca
$asaasKeys['token'] = $asaasKeystore['novo-PedraBranca'];
} else if ($invoiceEntity == 9001) { // primavera
$asaasKeys['token'] = $asaasKeystore['novo-primavera'];
} else if ($invoiceEntity == 9006) { // BeWiki
$asaasKeys['token'] = $asaasKeystore['novo-BeWiki'];
} else if ($invoiceEntity == 9008) { // Centro
$asaasKeys['token'] = $asaasKeystore['novo-Centro'];
}
return $asaasKeys;
}
function process2paymentForFloripa($cond = '') {
global $asaasKeys;
$start = time();
if (DEBUG_MODE) {
echoreddiv("Cannot launch debit process on cards in debug mode.");
exit;
}
_dfv(HUBLE_DOMAIN_LASTDEBITLAUNCH, rNow());
// must be 5 minutes old at least
$list = mysqlObjects("SELECT * FROM payment WHERE method = ".PaymentMethod::CARD_ASAAS." AND createdWhen < '".rNow()."' - INTERVAL 5 MINUTE
AND status = ".PaymentStatus::ISSUED." $cond ");
foreach ($list as $p) {
if (time() - $start > 60) break; // one session max 60 s
$p = mysqlSimpleObject('payment', $p['id']);
if ($p['debitErrorNote']) {
echoyellowdiv("Skipping as error before ($p[debitErrorNote])");
continue;
}
$entities = [];
foreach (mysqlObjects("SELECT invoice.entity, invoice.account FROM payment_invoice INNER JOIN invoice ON invoice.id = invoice_id WHERE payment_id = $p[id]") as $pi) {
$entities[$pi['entity']] = $pi['entity'];
}
if (count($entities) > 1) {
mysqlUpdateObject("payment", $p['id'], array(
'debitErrorNote' => "More entities for payment id $p[id]?"
));
continue;
}
$asaasKeys = getAsaasKeysForEntity(array_key_first($entities));
if (!isset($asaasKeys['token'])) {
mysqlUpdateObject("payment", $p['id'], array(
'debitErrorNote' => "Entity not configured for ASAAS"
));
continue;
}
$organisation = rLoadTo($p['organisation'], Organisation);
echodiv("Org $organisation[id]");
$account = $organisation['defaultInvoiceContact'];
$cardDetails = mysqlSimpleObject('paymentdetails', $account['creditCardId']);
if (!$cardDetails) {
echoreddiv("Card not found.");
mysqlUpdateObject("payment", $p['id'], array(
'debitErrorNote' => "Card not found."
));
} else {
$cardDetailsData = json_decode($cardDetails['data'], true);
if (!$cardDetailsData) {
echoreddiv("Card not found.");
mysqlUpdateObject("payment", $p['id'], array(
'debitErrorNote' => "Card not found."
));
} else {
sleep(rand(5, 15));
$document_number = $organisation['taxId'] && $organisation['type'] == OrganisationType::COMPANY ? $organisation['taxId'] : ($account['enterpreneurId'] ? $account['enterpreneurId'] : $account['documentId']);
echodiv("Searching for customer ".implode(', ', [$organisation['country'], $account['email'], $document_number]));
$customerId = assasGetExistingCustomer($organisation['country'], $account['email'], $document_number);
if (!$customerId) {
echodiv("Adding new customer ad-hoc");
$customerId = asaasConstructCustomer(asaasCustomerPayloadByOrganisationAndAccount($organisation, $account), [
'organisation' => $organisation,
'account' => $account
], $account);
}
if (!$customerId) {
echoreddiv("Customer not found...");
rUrgentEmail("cannot register customer", asaasCustomerPayloadByOrganisationAndAccount($organisation, $account));
mysqlUpdateObject("payment", $p['id'], array(
'debitErrorNote' => "Customer cannot be registered."
));
continue;
}
echolimediv("Customer ID:".$customerId);
//echovar($cardDetailsData);
$expDate = strtotime(rToday().' + 2 DAY');
$params = [
'billingType' => 'CREDIT_CARD',
'customer' => $customerId,
'value' => $p['amount'],
'dueDate' => rToday($expDate),
'description' => $p['description'],
'externalReference' => 'D'.$p['id'],
];
$result = asaasCall($asaasKeys, 'POST:v3/payments', $params);
if ($result['http_code'] == 200) {
//echovar($result);
$data = json_decode($result['content'], true);
$cobrancaId = $data['id'];
echovar($data);
echohr();
// use card to pay
$result2 = asaasCall($asaasKeys, 'POST:v3/payments/'.$cobrancaId.'/payWithCreditCard', json_encode([
'creditCard' => [
'number' => $cardDetailsData['card_number'],
'holderName' => $cardDetailsData['name'],
'expiryMonth' => $cardDetailsData['card_expiration_month'],
'expiryYear' => $cardDetailsData['card_expiration_year'],
'ccv' => $cardDetailsData['card_cvv'],
],
'creditCardHolderInfo' => [
'name' => $cardDetailsData['name'],
'email' => $cardDetailsData['email'],
'cpfCnpj' => $cardDetailsData['cpf'],
'address' => $cardDetailsData['address'],
'addressNumber' => $cardDetailsData['addressNumber'],
'addressComplement' => $cardDetailsData['complement'],
'postalCode' => $cardDetailsData['postalCode'],
'phone' => $cardDetailsData['phone'],
]
]));
//echoh1("Payment result:");
//echovar($result2);
$paymentStatus = json_decode($result2['content'], true);
if ($result2['http_code'] == 200 && $paymentStatus['status'] == 'CONFIRMED') {
echovar($result2);
echohr();
echolimediv("Charged OK");
mysqlUpdateObject("payment", $p['id'], array(
'description' => 'ASAAS debit',
'paidWhen' => rToday(),
//'identification' => $paymentStatus['id'],
'status' => 16,
'netValue' => $paymentStatus['netValue'],
));
} else {
echoreddiv("Error2");
echovar($result2);
echohr();
$errors = '';
if ($paymentStatus) {
foreach ($paymentStatus['errors'] as $e) {
$errors .= $e['description']."
";
}
}
if (!$errors) $errors = '?';
mysqlUpdateObject("payment", $p['id'], array(
'debitErrorNote' => "Problem with output status occured ($errors)."
));
}
} else {
echoreddiv("Error1");
echovar($result);
echohr();
$errors = "The transaction was not able to be processed.";
mysqlUpdateObject("payment", $p['id'], array(
'debitErrorNote' => "Problem with output status occured ($errors)."
));
}
}
}
// end after 1
break;
}
}
function domainCron($force = false) {
global $CoworkAccountFacade;
global $MailFacade;
if (Timer::morning() && ST(_dfv(HUBLE_DOMAIN_LAST_DEBIT_PROCESSED)) < ST(rNow().' - 3 DAY - 8 HOUR')) { // try every 3 days
mysqlTxBegin();
$method = PaymentMethod::CARD_ASAAS;
$t = $CoworkAccountFacade()->getIssueDate();
_dfv(HUBLE_DOMAIN_LAST_DEBIT_PROCESSED, rNow());
$CoworkAccountFacade()->processPayments($t, $method);
_dfv(HUBLE_DOMAIN_TASKS_PENDING_DEBIT_PROCESS, 0);
mysqlTxCommit();
}
// launch randomly the debits
if (date('G', strtotime(rNow())) >= 7 || $force) {
if (date('G', strtotime(rNow())) <= 22 || $force) {
if (ST(_dfv(HUBLE_DOMAIN_LASTDEBITLAUNCH)) < ST(rNow()." - ".rand(1, 6)." MINUTE") || $force) {
// try 10 payments each iteration
for ($i = 0; $i <= 15; $i++) {
process2paymentForFloripa();
}
}
}
}
echoh1("Cancellation of debits...");
$hoursLimit = 6;
$payments = getDebitLongFails(true);
foreach ($payments as $payment) {
$tryAgain = false;
if ($payment['debitErrorNote']) {
// Cancel immediatellyss
echoreddiv($payment['id'].' of '.$payment['organisation'].' - errorous: '.$payment['debitErrorNote']);
$tryAgain = true;
} else if (ST($payment['createdWhen']) < ST(rNow().' - '.$hoursLimit.' HOUR')) {
echoreddiv($payment['id'].' of '.$payment['organisation'].' - late: '.$payment['createdWhen']);
$tryAgain = true;
}
if ($tryAgain) {
//Dev::tell("Trying again a debit of org. $payment[organisation]");
$invoices = mysqlObjects("SELECT invoice.* FROM invoice INNER JOIN payment_invoice ON payment_id = $payment[id] AND invoice.id = invoice_id");
foreach ($invoices as $invoice) {
mysqlUpdateObject("invoice", $invoice['id'], array(
'notifyLevel' => $invoice['notifyLevel'] + 1,
'notifiedWhen' => rNow()
));
}
$CoworkAccountFacade()->unasignPayment($payment['id']);
mysqlUpdateObject('payment', $payment['id'], array(
'status' => PaymentStatus::CANCELLED
));
}
}
echoh1('Automatic cancelling debit methods');
if (_dfv(HUBLE_DOMAIN_DEBIT_CANCEL_ALL_AUTOCHARGE_AUTOMATICLY)) {
$payments = getDebitLongFails();
foreach ($payments as $p) {
if ($p['method'] != PaymentMethod::CARD_ASAAS) continue;
Dev::tell("Cancelling debit of org. $p[organisation]");
cancelPaymentDebitAndEmail($p);
}
_dfv(HUBLE_DOMAIN_DEBIT_FAIL_COUNT, 0);
}
echoh1("Sending NFSe");
if (_dfv(HUBLE_DOMAIN_FOCUS_NFE_AUTO_SEND) && Timer::day() && Timer::workday()) {
foreach (mysqlSimpleObjects('nfse', "status = 10 AND createdWhen >= '".rNow()."' - INTERVAL 3 MONTH AND createdWhen < '".rNow()."' - INTERVAL 10 MINUTE", 'ORDER BY id DESC LIMIT 5') as $nfse) {
if (count(mysqlObjects("SELECT invoice.id FROM invoiceitem INNER JOIN invoice ON invoice.id = invoiceitem.invoice WHERE
invoiceitem.nfse = $nfse[id] AND invoice.sent > 0")) > 0 ) {
if ($MailFacade()->nfse($nfse)) {
mysqlUpdateObject('nfse', $nfse['id'], array('status' => 20));
}
}
}
}
}
function isSimpleNacional($organisation) {
$organisation = mysqlSimpleObject('organisation', $organisation['id']);
if (ST($organisation['fetchBillingDetailsRegisterLast']) < ST(rNow().' - 14 DAY')) {
return $organisation['brazil_simplesNactional'];
}
$out = false;
if (!$organisation['taxId']) {
$out = false;
} else {
$r = rcurl_get_web_page('https://server11.bitcarvers.com/cnpj', ['q' => $organisation['taxId']]);
if ($r['http_code'] == 200) {
echovar(json_decode($r['content'], true));
if (isset($r['content']['simples']) && $r['content']['simples'] == 'sim') {
$out = true;
}
} else {
$out = false; // not found
}
}
mysqlUpdateObject('organisation', $organisation['id'], [
'brazil_simplesNactional' => $out,
'fetchBillingDetailsRegisterLast' => rNow()
]);
return $out;
}
function getTokenForNfse($nfseId) {
global $EntityObjects;
$nfo = mysqlObject("SELECT entity FROM nfse WHERE id = $nfseId", false);
if (!$nfo) {
echoreddiv("Cannot fetch nfse #$nfseId");
exit;
}
return $EntityObjects[$nfo['entity']]['nfse_token'];
}
function getNFSe($nfseHubleRefId) {
$nfseHubleRefId = SQL::id($nfseHubleRefId);
$fnfeurl = _dfv(HUBLE_DOMAIN_FOCUS_HOMOLOGACAO) ? RenDataSources::getBrazilianNFSEEmissionService()['urlTesting'] : RenDataSources::getBrazilianNFSEEmissionService()['url'];
$url = $fnfeurl."/v2/nfsen/".$nfseHubleRefId."?token=".getTokenForNfse($nfseHubleRefId);
$r = rcurl_get_web_page($url, null, null, 10, null, true, 'Huble', DEBUG_MODE ? false : true);
if ($r['success']) {
return JSON::from($r['content']);
}
return null;
}
function deleteNFSe($nfseHubleRefId) {
$fnfeurl = _dfv(HUBLE_DOMAIN_FOCUS_HOMOLOGACAO) ? RenDataSources::getBrazilianNFSEEmissionService()['urlTesting'] : RenDataSources::getBrazilianNFSEEmissionService()['url'];
$r = CURL::delete($fnfeurl."/v2/nfsen/".$nfseHubleRefId."?token=".getTokenForNfse($nfseHubleRefId));
if ($r['success']) {
return $r;
}
return false;
}
function createNfse($nfseHubleRefId, $newData) {
$fnfeurl = _dfv(HUBLE_DOMAIN_FOCUS_HOMOLOGACAO) ? RenDataSources::getBrazilianNFSEEmissionService()['urlTesting'] : RenDataSources::getBrazilianNFSEEmissionService()['url'];
$newData = json_encode($newData);
$newDataX = str_replace("\/", "\u002f", $newData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fnfeurl."/v2/nfsen?token=".getTokenForNfse($nfseHubleRefId)."&ref=" . $nfseHubleRefId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $newDataX);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$body = curl_exec($ch);
$result = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($result == 202) {
return true;
}
echoh1('ERROR - '.$nfseHubleRefId);
echovar($newData);
echovar($body);
rSupportEmail("NFE generation problem", json_encode($newData, JSON_HEX_QUOT)."\n\n\nERROR: ref $nfseHubleRefId ".$body."\n\n");
return false;
}
Membros/clientes login