batch/scripts/clients/SfrIndicateur.php
2013-08-28 15:07:16 +00:00

391 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.",
'cron' => "Mandatory option for launch the cli in cron",
'manual=s' => "Provide manualy the file path to get result and debug values",
'file' => "Specify the file name to execute or regenerate output file",
'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';
// => Debug Mode - Create file with debug values
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
if ($opts->cron || $opts->file ) {
//Output path
$pathOut = $c->profil->path->storage .
DIRECTORY_SEPARATOR . 'clients' .
DIRECTORY_SEPARATOR . strtolower($client) .
DIRECTORY_SEPARATOR . 'recv';
if ( $opts->cron ) {
//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_Sdv1FluxFileIn();
$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 ) {
//@todo : Send a mail
exit;
}
foreach ($pitems as $p) {
$filepath = $pathOut . DIRECTORY_SEPARATOR . $p->fileDepot;
break;
}
}
if ($opts->file) {
$filepath = $pathOut . DIRECTORY_SEPARATOR . $opts->file;
}
if ( !file_exists($filepath) ) {
echo "Fichier inexistant ! ".PHP_EOL;
exit;
}
//Read file
$result = execFileIn($filepath, $fileOptionsIn, array('ok'=>$fileOkOptionsOut, 'error'=>$fileErrorOptionsOut));
$fluxoutM = new Application_Model_Sdv1FluxFileOut();
$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');
if ( $opts->cron ) {
$fluxoutM->insert(array(
'client' => $client,
'name' => $prestation,
'nbLines' => $rows,
'dateBegin' => $dateBegin,
'dateEnd' => $dateEnd,
'fileOut' => $filename,
'depotType' => $typeDepot,
'depotDate' => '0000-00-00 00:00:00',
));
}
}
if ( $opts->cron ) {
//Ecrire la date d'execution dans flux_filein
$fluxinM->update(array(
'dateExecute' => $dateEnd,
), 'id='.$p->id);
}
}
/**
*
* @param array $values
* @param string $seq
* @param string $debug
* @return array
*/
function execInternal($values, $seq, $debug = false)
{
$error = 0;
$siren = $values['siren'];
echo "$siren";
$classInsee = new MInsee();
$values['code'] = '';
//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' => $seq,
'siren' => $siren,
'NbLignes' => $values['nbLignes'],
'NbContrats' => $values[''],
'DateContrat' => $values['dateContrat'],
'IR' => $values['ir'],
'IdVOR' => $values['idVOR'],
'comment' => $values['comment'],
'PO' => $values['PO'],
'debug' => json_encode($valuesDebug),
'error' => $values['code'],
));
}
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, $header['idDemande'], 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']);
}