batch/bin/clientRrgSurv.php
Michael RICOIS ff65eaf3de PHP-CS-Fixer
2016-11-29 17:02:54 +01:00

383 lines
13 KiB
PHP

<?php
//error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);
// --- Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(__DIR__ . '/../application'));
// --- Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// --- Composer autoload
require_once realpath(__DIR__ . '/../vendor/autoload.php');
// Create application, bootstrap, and run
$application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
// --- Options
$displayUsage = false;
try {
$opts = new Zend_Console_Getopt(array(
'help|?' => "Displays usage information.",
'since=s' => "Depuis une date (format AAAAMMJJ) ou depuis le dernier flux (flux)",
'from=s' => "depuis surveillance (surv) ou logs (log:default)",
'debug' => "Génére uniquement un fichier sans télétransmission",
'cron' => "Mandatory option for launch the cli in cron",
));
$opts->parse();
} catch (Zend_Console_Getopt_Exception $e) {
$displayUsage = true;
}
// --- Aide / Options
if (count($opts->getOptions())==0 || isset($opts->help)) {
$displayUsage = true;
}
// --- Usage
if ($displayUsage) {
echo "Prestation RRG Surveillance.\n";
echo $opts->getUsageMessage();
exit;
}
$c = new Zend_Config($application->getOptions());
Zend_Registry::set('config', $c);
// Database
$config = new \Doctrine\DBAL\Configuration();
$connectionParams = array(
'dbname' => $c->profil->db->metier->params->dbname,
'user' => $c->profil->db->metier->params->username,
'password' => $c->profil->db->metier->params->password,
'host' => $c->profil->db->metier->params->host,
'charset' => 'utf8',
'driver' => 'pdo_mysql',
);
try {
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
Zend_Registry::set('doctrine', $conn);
} catch (\Doctrine\DBAL\DBALException $e) {
echo "Connection Database impossible.\n";
exit;
}
$login = 'rrgws';
$client = 'rrg';
$typeDepot = 'FTP';
$prestation = 'HEXAVIA';
//Output path
$pathOut = $c->profil->path->shared . '/clients/' . $client . '/recv';
$fileOptionsOut = array(
'dir' => $pathOut,
'type' => 'csv',
'delimiter' => '$',
/*'enclosure' => '"',*/
/*'header' => array(
'ID_S&D',
'SIRET',
'DATE_CREATION',
'CA',
'ANNEE_CA',
'CODE_PAIEMENT',
'LIBELLE_CODE_PAIE',
'INDISCORE20',
'ENCOURS'
),*/
'columns' => array(
'SourceID',
'Siret',
'DateCreaEn',
'BilanCA',
'BilanDateCloture',
'PaiementCS',
'PaiementInfo',
'Indiscore',
'Encours',
),
'name' => 'surv_',
//'encoding' => 'ISO-8859-15',
);
require_once APPLICATION_PATH.'/configs/config.php';
require_once 'Metier/Scores/MScores.php';
$db = Zend_Db::factory($c->profil->db->metier);
$db->setFetchMode(Zend_Db::FETCH_OBJ);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
$execRef = new Scores_Exec_Ref('RRGSURV');
$execId = $execRef->start();
$dateStart = new DateTime();
$dateEnd = new DateTime();
if ($opts->since == 'flux') {
try {
$sql = "SELECT * FROM sdv1.flux_fileout WHERE client=:client
AND name=:prestation AND fileOut LIKE :file AND depotDate!='0000-00-00 00:00:00'
ORDER BY depotDate DESC LIMIT 0,1";
$stmt = $conn->prepare($sql);
$stmt->bindValue('client', 'rrg');
$stmt->bindValue('prestation', 'HEXAVIA');
$stmt->bindValue('file', 'surv_%');
$stmt->execute();
$resultDate = $stmt->fetch(\PDO::FETCH_OBJ);
} catch (\Doctrine\DBAL\DBALException $e) {
echo "Erreur";
exit;
}
$dateStart = DateTime::createFromFormat('Y-m-d H:i:s', $resultDate->dateEnd);
} elseif ($opts->since) {
$dateStart = DateTime::createFromFormat('Ymd', $opts->since);
} else {
if ($dateStart->getWeekday() == 1) {
$dateStart->sub(new DateInterval('P3D'));
} else {
$dateStart->sub(new DateInterval('P3D'));
}
}
$dateSql1 = $dateStart->format('Y-m-d');
$dateSql2 = $dateEnd->format('Y-m-d');
// --- Entités consultées via webservice (dateAjout) + Entités avec scores modifiés ou ajoutés (indiScoreDate)
if ($opts->from == 'surv') {
echo date('Y-m-d H:i:s')." - Selection dans le portefeuille entre le $dateSql1 et $dateSql2\n";
$sql = "SELECT LPAD(surv.siren,9,0) AS siren, surv.dateAjout, score.indiScore20, score.indiScoreDate, score.encours, score.cs, score.dateBilan
FROM jo.surveillances_site AS surv LEFT JOIN jo.scores_surveillance AS score ON surv.siren = score.siren
WHERE surv.source='score' AND surv.login='".$login."' AND
( (surv.dateAjout BETWEEN '".$dateSql1." 00:00:00' AND '".$dateSql2." 23:59:59')
OR (score.indiScoreDate BETWEEN '".$dateSql1." 00:00:00' AND '".$dateSql2." 23:59:59') )
GROUP BY siren ORDER BY siren, dateAjout DESC";
}
// --- Entités consultées via webservice depuis les logs (dateHeure) + Entités avec scores modifiés ou ajoutés (indiScoreDate)
elseif ($opts->from == 'log') {
echo date('Y-m-d H:i:s')." - Selection dans les logs entre le $dateSql1 et $dateSql2\n";
$sql = "SELECT LPAD(surv.siren,9,0) AS siren, surv.dateHeure AS dateAjout, score.indiScore20, score.indiScoreDate, score.encours, score.cs, score.dateBilan
FROM sdv1.logs AS surv LEFT JOIN jo.scores_surveillance AS score ON surv.siren = score.siren
WHERE surv.login='".$login."' AND page='identite' AND
( (surv.dateHeure BETWEEN '".$dateSql1." 00:00:00' AND '".$dateSql2." 23:59:59')
OR (score.indiScoreDate BETWEEN '".$dateSql1." 00:00:00' AND '".$dateSql2." 23:59:59') )
GROUP BY siren ORDER BY siren, dateAjout DESC";
}
try {
$itemStmt = $conn->executeQuery($sql);
} catch (\Doctrine\DBAL\DBALException $e) {
echo $e->getMessage();
echo "\n";
}
$nb = $itemStmt->rowCount();
if ($nb == 0) {
echo date('Y-m-d H:i:s')." - Aucun élément.\n";
} else {
$dateBegin = date('YmdHis');
echo date('Y-m-d H:i:s')." - NbLignes=".$nb."\n";
if ($execId !== null) {
$execRef->total($execId, $nb);
}
// --- Ecriture du fichier
$file = $fileOptionsOut['dir'] . '/' .$fileOptionsOut['name'] . substr($dateBegin, 0, 8) . '.' . $fileOptionsOut['type'];
// --- Ouverture fichier
$fp = fopen($file, 'w');
if ($fp === false) {
echo date('Y-m-d H:i:s')." - ERREUR Impossible de créer le fichier ".$file."\n";
exit;
}
// --- Header
if (count($fileOptionsOut['header']) > 0) {
fputcsv($fp, $fileOptionsOut['header'], $fileOptionsOut['delimiter'], $fileOptionsOut['enclosure']);
}
$iDb = new Metier_Util_Db();
$row = 0;
// --- Content
while ($item = $itemStmt->fetch(\PDO::FETCH_OBJ)) {
if (intval($item->siren) == 0) {
continue;
}
$row++;
if ($opts->debug) {
echo date('Y-m-d H:i:s')." - Ligne ".$row;
}
if ($execId !== null) {
$execRef->increment($execId, $row);
}
// --- Data
$sql = "SELECT LPAD(source_id,10,0) AS source_id, LPAD(siren,9,0) AS siren, LPAD(nic,5,0) AS nic
FROM jo.etablissements WHERE siege=1 AND siren=:siren ORDER BY actif DESC LIMIT 0,1";
$etabStmt = $conn->prepare($sql);
$etabStmt->bindValue('siren', $siren);
$etabStmt->execute();
$etablissement = $etabStmt->fetch(\PDO::FETCH_OBJ);
$DateCreaEn = '';
$BilanCA = '';
$BilanDateCloture = '';
$Indiscore = '';
$Encours = '';
// --- Calcul du score ou lecture depuis la table de sauvegarde des scores
if ($item->indiScoreDate === null) {
if ($opts->debug) {
echo " - Calcul du score";
}
require_once 'Metier/Scores/MScores.php';
$evaluation = calculIndiScore($item->siren, 0, false, 0, false, 'scores', $iDb);
$PaiementCS = $evaluation['cs'];
$Indiscore = $evaluation['Indiscore20'];
$Encours = round($evaluation['encours']/1000) * 1000;
} else {
if ($opts->debug) {
echo " - Données en cache";
}
$PaiementCS = $item->cs;
$Indiscore = $item->indiScore20;
$Encours = round($item->encours/1000) * 1000;
}
// --- Informations identitaire
$iInsee = new Metier_Insee_MInsee($iDb);
$tabIdentite = $iInsee->getIdentiteEntreprise($item->siren, 0, 0, false, false);
$DateCreaEn = $tabIdentite['DateCreaEn'];
if ($tabIdentite['DateCreaEt'] > 0 && $tabIdentite['DateCreaEt'] < $tabIdentite['DateCreaEn']) {
$DateCreaEn = $tabIdentite['DateCreaEt'];
} elseif ($tabIdentite['DateCreaEn'] > 0) {
$DateCreaEn = $tabIdentite['DateCreaEn'];
}
// --- Correction pour l'envoi des dates
if (!empty($DateCreaEn)) {
if (strlen($DateCreaEn)<8) {
$DateCreaEn = str_pad($DateCreaEn, 8, '0', STR_PAD_RIGHT);
}
if (substr($DateCreaEn, -2) * 1 == 0) {
$DateCreaEn = substr($DateCreaEn, 0, 6).'01';
}
}
// --- Gestion des bilans
$today = new DateTime();
if (!empty($tabIdentite['bilanDate'])) {
$compare = DateTime::createFromFormat('Ymd', $tabIdentite['bilanDate']);
$interval = $today->diff($compare, true);
$diffMonth = $interval->format('%y') * 12 + $interval->format('%m');
if ($diffMonth < 37) {
$BilanDateCloture = substr($tabIdentite['bilanDate'], 6, 2).
substr($tabIdentite['bilanDate'], 4, 2).substr($tabIdentite['bilanDate'], 0, 4);
$BilanCA = $tabIdentite['bilanFL'];
}
}
// --- Estimation du CA bilan
if (empty($BilanCA) && !empty($tabIdentite['bilanAnnee'])) {
// --- Condition RRG
if ($tabIdentite['Eff'] > 0
|| substr($tabIdentite['FJ'], 0, 1) == 1 && $tabIdentite['Eff'] < 1
|| !empty($tabIdentite['NafEnt']) && strlen($tabIdentite['NafEnt']) == 5 && $tabIdentite['NafEnt'] != '0000Z') {
$dateClotureEstime = new DateTime();
$dateClotureEstime->modify('first day of this month');
$dateCreaRecente = clone $dateClotureEstime;
$dateCreaRecente->sub(new DateInterval('P2Y1M'));
$dateCompare = DateTime::createFromFormat('Ymd', $DateCreaEn);
// --- Création récente ( now - 2 ans < Date de création )
if ($dateCreaRecente < $dateCompare) {
$BilanDateCloture = '3112'.date('Y');
$BilanCA = $tabIdentite['bilanFLestime'];
}
// --- Date cloture estimée < Date de création
elseif ($dateClotureEstime < $dateCompare) {
$BilanDateCloture = '3112'.$tabIdentite['bilanAnnee'];
$BilanCA = $tabIdentite['bilanFLestime'];
}
}
}
// Récupération du libellé d'information de paiement
$PaiementInfo = '';
if (in_array($PaiementCS, array('0', 'I', 'P', 'D'))) {
$iFacto = new Metier_Partenaires_MFacto($iDb);
$info = $iFacto->getLibInfoCS($PaiementCS);
$PaiementInfo = $info['LibCS'];
}
$values = array(
'SourceID' => $etablissement->source_id,
'Siret' => $etablissement->siren.$etablissement->nic,
'DateCreaEn' => $DateCreaEn,
'BilanCA' => $BilanCA,
'BilanDateCloture' => $BilanDateCloture,
'PaiementCS' => $PaiementCS,
'PaiementInfo' => $PaiementInfo,
'Indiscore' => $Indiscore,
'Encours' => $Encours,
);
// --- Trier données
$line = array();
foreach ($fileOptionsOut['columns'] as $i => $column) {
$line[] = $values[$column];
}
// --- Ecrire ligne
if ($opts->debug) {
echo " - Ecriture ligne";
}
if (empty($fileOptionsOut['enclosure'])) {
fwrite($fp, join($fileOptionsOut['delimiter'], $line)."\n");
} else {
fputcsv($fp, $line, $fileOptionsOut['delimiter'], $fileOptionsOut['enclosure']);
}
if ($opts->debug) {
echo "\n";
}
}
// --- Fermeture fichier
fclose($fp);
// --- Encoding
if (array_key_exists('encoding', $fileOptionsOut)) {
if ($fileOptionsOut['encoding'] == 'ISO-8859-15') {
passthru("iconv -f UTF-8 -t ISO-8859-15 ".$file." -o ".$file.".enc");
passthru("cp -fv ".$file.".enc ".$file);
}
}
$nbLines = $row;
echo date('Y-m-d H:i:s')." - Nb Lignes Traitées : ".$nbLines."\n";
if ($opts->cron) {
$dateEnd = date('YmdHis');
$conn->insert('sdv1.flux_fileout', array(
'client' => $client,
'name' => $prestation,
'nbLines' => $nbLines,
'dateBegin' => $dateBegin,
'dateEnd' => $dateEnd,
'fileOut' => basename($file),
'depotType' => $typeDepot,
'depotDate' => '0000-00-00 00:00:00',
));
}
}
if ($execId !== null) {
$execRef->end($execId);
}
echo date('Y-m-d H:i:s')." - Fin.\n";