batch/scripts/clients/SfrIndicateur.php

403 lines
9.3 KiB
PHP

<?php
error_reporting(E_ALL ^ E_STRICT ^ E_NOTICE ^ E_WARNING);
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
try {
$opts = new Zend_Console_Getopt(
//Options
array(
'help|?' => "Displays usage information.",
'manual=s' => "Provide manualy the file without save in database",
'debug' => "Send a mail for debug",
)
);
$opts->parse();
} catch (Zend_Console_Getopt_Exception $e) {
echo $e->getUsageMessage();
exit;
}
//Usage
if( isset($opts->help) || count($opts->getOptions())==0 )
{
echo "Place files in right directory for sending to the customer.\n";
echo $opts->getUsageMessage();
exit;
}
require_once APPLICATION_PATH.'/configs/config.php';
require_once 'framework/fwk.php';
require_once 'framework/common/chiffres.php';
require_once 'framework/common/dates.php';
require_once 'framework/mail/sendMail.php';
require_once 'framework/common/mysql.php';
require_once 'Metier/insee/classMInsee.php';
require_once 'Metier/scores/classMSolvabilite.php';
require_once 'Metier/partenaires/classMLiens.php';
$c = new Zend_Config($application->getOptions());
$db = Zend_Db::factory($c->profil->db->metier);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
//Configuration
$fileOptionsIn = array(
'type' => 'csv',
'delimiter' => ';',
'enclosure' => '"',
'header' => array('idDemande', 'SSAEmetteur'),
'columns' => array('siren', 'nbLignes', 'dateContrat', 'nbContrats', 'ir'),
);
$fileOkOptionsOut = array(
'type' => 'csv',
'delimiter' => ';',
'enclosure' => '"',
'header' => array('idDemande', 'SSAEmetteur'),
'columns' => array('siren', 'idVOR', 'PO', 'commentaire'),
'name' => 'FICH_RCE_RETOUR_',
);
$fileErrorOptionsOut = array(
'type' => 'csv',
'delimiter' => ';',
'enclosure' => '"',
'header' => array('idDemande', 'SSAEmetteur'),
'columns' => array('siren', 'code'),
'name' => 'FICH_RCE_ERREUR_',
);
$client = 'SFR';
$typeDepot = 'SFTP';
$prestation = 'FICH_RCE';
// => Manual Mode
if ( $opts->manual ) {
$filepath = $opts->manual;
$pathOut = dirname($filepath);
$dateBegin = date('YmdHis');
//Read file
$result = execFileIn($filepath, $fileOptionsIn, array('ok'=>$fileOkOptionsOut, 'error'=>$fileErrorOptionsOut), true);
foreach($result as $code => $file) {
$filename = $file['name'] . $dateBegin . '.csv';
execFileOut($pathOut . DIRECTORY_SEPARATOR . $filename, $file);
}
}
// => Automatic mode
else {
//Lire les fichiers à traiter dans la table
$c = new Zend_Config($application->getOptions());
$db = Zend_Db::factory($c->profil->metier);
Zend_Db_Table::setDefaultAdapter($db);
//client, name, typeDepot, dateDepot, fileDepot, nblignes, dateInsert, dateExecute
$fluxinM = new Application_Model_JoFluxFileIn();
$sql = $fluxinM->select()
->where('client=?',$client)
->where('name=?', $prestation)
->where('typeDepot=?',$typeDepot)
->where('dateExecute=?','0000-00-00 00:00:00')
->order('dateInsert DESC');
$pitems = $fluxinM->fetchAll($sql);
if ( $pitems->count()==0 ) {
//Send a mail
} else {
//Create output file from result
$pathOut = $c->profil->path->storage .
DIRECTORY_SEPARATOR . 'clients' .
DIRECTORY_SEPARATOR . 'recv';
foreach ($pitems as $p) {
$filepath = $pathOut . DIRECTORY_SEPARATOR . $p->fileDepot;
break;
}
//Read file
$result = execFileIn($filepath, $fileOptionsIn, array('ok'=>$fileOkOptionsOut, 'error'=>$fileErrorOptionsOut));
$fluxoutM = new Application_Model_JoFluxFileOut();
$rows = 0;
foreach($result as $code => $file) {
$dateBegin = date('YmdHis');
$filename = $file['name'] . $dateBegin . '.csv';
$rows = execFileOut($pathOut . DIRECTORY_SEPARATOR . $filename, $file);
$dateEnd = date('YmdHis');
$fluxoutM->insert(array(
'client' => $client,
'name' => $prestation,
'nbLines' => $rows,
'dateBegin' => $dateBegin,
'dateEnd' => $dateEnd,
'fileOut' => $filename,
'typeDepot' => $typeDepot,
'dateDepot' => '0000-00-00 00:00:00',
));
}
//Ecrire la date d'execution dans flux_filein
$fluxinM->update(array(
'dateExecute' => $dateEnd,
), 'id='.$p->id);
}
}
/**
*
* @param array $values
* @param array $row
* @param string $debug
* @return multitype:number multitype: Ambigous <string, multitype:, number, mixed, NULL>
*/
function execInternal($values, $row, $debug = false)
{
$error = 0;
$siren = $values['siren'];
echo "$siren";
$classInsee = new MInsee();
//Siren valide - 1010
if ( !$classInsee->valideSiren($siren) ) {
$error = 1;
$values['code'] = '1010';
echo " - Erreur 1010.";
}
//Siren existant - 1020
else if ( !$classInsee->sirenExiste($siren) ) {
$error = 1;
$values['code'] = '1020';
echo " - Erreur 1020.";
}
if ( $error == 0 ) {
//Calculate data
require_once 'Metier/Sfr/Sfr.php';
$sfrM = new Metier_Sfr();
//Set Values
$sfrM->setVal('ValContratDate', $values['dateContrat']);
$sfrM->setVal('ValIR', $values['ir']);
//Evaluate
$sfrM->evaluate($siren);
$values['idVOR'] = $sfrM->getIndicateur();
$values['commentaire'] = $sfrM->getComment();
$values['PO'] = $sfrM->getPo();
$valuesDebug = $sfrM->getValDebug();
if ($debug) {
$values = array_merge($values, $valuesDebug);
}
echo " - VOR=".$values['idVOR']." , commentaire=".$values['commentaire']." , PO=".$values['PO'];
}
echo PHP_EOL;
if ( !$debug ) {
$sfrDataM = new Application_Model_JoSfrData();
$sfrDataM->insert(array(
'NumSeq',
'siren',
'NbLignes',
'NbContrats',
'DateContrat',
'IR',
'IdVOR',
'comment',
'PO',
'debug',
'error',
));
}
return array(
'values' => $values,
'error' => $error,
);
}
/**
*
* @param unknown $filepath
* @param array $fileOptionsIn
* @param array $filesOptionsOut
* @param boolean $debug
* @return Ambigous <multitype:, unknown, number, unknown, string, mixed, NULL>
*/
function execFileIn($filepath, $fileOptionsIn, $filesOptionsOut = array(), $debug = false)
{
//Read file
if ( file_exists($filepath) ) {
$output = $filesOptionsOut;
if (($handle = fopen($filepath, 'r')) !== false) {
$row = 0;
while (($data = fgetcsv($handle, 0, $fileOptionsIn['delimiter'], $fileOptionsIn['enclosure'])) !== false)
{
$row++;
echo "Ligne $row : ";
//Header
if (count($fileOptionsIn['header']) > 0 && $row == 1) {
foreach ( $fileOptionsIn['header'] as $i => $column ) {
$header[$column] = $data[$i];
}
echo "Detection HEADER.".PHP_EOL;
if ($debug) {
$output['error']['header'] = array();
$output['ok']['header'] = array();
} else {
$output['error']['header'] = $header;
$output['ok']['header'] = $header;
}
}
//Content
else {
//Set values from file
$values = array();
foreach ( $fileOptionsIn['columns'] as $i => $column ) {
$values[$column] = $data[$i];
}
//Exec the process
$valuesClient = execInternal($values, $row, true);
//Format output
if ( $valuesClient['error'] == 1 ) {
$output['error']['line'][] = $valuesClient['values'];
if ($debug) {
$output['error']['columns'] = array_keys($valuesClient['values']);
}
} else {
$output['ok']['line'][] = $valuesClient['values'];
if ($debug) {
$output['ok']['columns'] = array_keys($valuesClient['values']);
}
}
}
}
}
fclose($handle);
return $output;
}
}
/**
*
* @param string $file
* @param array $options
*/
function execFileOut($file, $options)
{
$fp = fopen($file, 'w');
//=> Header
$line = array();
//Dynamic Header
if ( count($options['header'])>0 ) {
foreach ( $options['header'] as $i => $column ) {
$line[] = $column;
}
}
//Static Header
else {
foreach ( $options['columns'] as $i => $column ) {
$line[] = $column;
}
}
fputcsv($fp, $line, $options['delimiter'], $options['enclosure']);
//=> Content
if ( count($options['line'])>0 ) {
foreach ($options['line'] as $c ) {
$line = array();
foreach ( $options['columns'] as $i => $column ) {
$line[] = $c[$column];
}
fputcsv($fp, $line, $options['delimiter'], $options['enclosure']);
}
}
fclose($fp);
return count($options['line']);
}
//Lire ligne à ligne pour intégration
//Eviter les lignes vide
//=> Siren Ok alors calcul puis dans bdd et dans fichier ok
//=> Siren Non Ok dans fichier erreur avec son code
//Siren invalide, siren inexistant, calcul impossible
//Ligne d'entête (colonne 1 RCE<NumSeq>)
//SIREN => VARCHAR(9)
//Nombre de lignes actives => INT
//Date d'entrée en relation => VARCHAR()
//Nombre de contrats actifs => INT
//Indicateur de recouvrement => FLOAT
//Elements de sortie
//SIREN
//Indicateur VOR
//PO
//Commentaire
//Paramètres supplémentaires
//NumSeq
//Elements de calcul
//date
//Historisation
// INSERT [LOW_PRIORITY] [IGNORE] [INTO] nom_de_la_table [(liste des colonnes)] SELECT ...