Files
votianng/html/tools/auto_trigger_sales_customer_report.php
2026-03-29 10:34:57 +02:00

525 lines
23 KiB
PHP

<?php
/*=======================================================================
*
* auto_trigger_sales_customer_report.php
*
* Autor: Marc Vollmann
*
=======================================================================*/
include_once ("../include/mcglobal.inc.php");
$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
include_once ("../include/auth.inc.php");
$autoMode = false;
else :
if ($argv[1] == "acapella7890") :
$autoMode = true;
endif;
endif;
include_once ('../include/email/htmlMimeMail.php');
// Gets customer list having a finished job during the specified interval
// PRESENTLY NOT IN USE !!!!
function getCustomersWithJobInInterval ($fromDate = "", $toDate = "") {
if ($fromDate == "") : $fromDate = getDateTime("date_firstday_lastmonth_currentyear"); endif;
if ($toDate == "") : $toDate = getDateTime("date_lastday_lastmonth_currentyear"); endif;
$retArr = getColVectorFromDB2ArrayByClause(
"job AS jb, costcenter AS csc, customer AS cs, company AS cmp",
"cs.cs_id",
"jb.jb_status = '2' AND jb.jb_finishtime >= '" . $fromDate . "' AND jb.jb_finishtime <= '" . $toDate . "' AND csc.csc_id = jb.csc_id_payer AND cs.cs_id = csc.cs_id AND cmp.cmp_id = cs.cmp_id AND cmp.cmp_archived = '0' AND cmp.cmp_authenticated = '1'",
"", "", "DISTINCT"
);
return $retArr;
}
// Returns the statement
function getCustomerList ($fromDate, $toDate, $whereClause = "") {
global $db, $customerArr;
if ($fromDate == "") : $fromDate = getDateTime("date_firstday_lastmonth_currentyear"); endif;
if ($toDate == "") : $toDate = getDateTime("date_lastday_lastmonth_currentyear"); endif;
$csArrIsEmpty = true;
if (count($customerArr) > 0) : $csArrIsEmpty = false; endif;
// **** Addidional to the statistic values here all customers being NOT authenticated are excluded !!!! ****
// NACH EXPORTZEIT
/*
$sqlquery = "SELECT cs.cs_id, cs.cs_eid, cmp.cmp_comp, usr.usr_phone, usr.usr_email, COUNT(jb.jb_id) AS count_jobs, SUM(jb.jb_totalprice) AS business_volume"
. " FROM job AS jb, costcenter AS csc, company AS cmp, customer AS cs LEFT JOIN employee AS emp ON cs.cs_admin = emp.emp_id LEFT JOIN user AS usr ON emp.usr_id = usr.usr_id"
. " WHERE jb.jb_status = '2' AND jb.jb_export_time >= '" . $fromDate . "' AND jb.jb_export_time <= '" . $toDate . "' AND "
. " (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND "
. " (NOT isnull(jb.jb_export_time)) AND jb.jb_export_time != '0000-00-00 00:00:00' AND jb.jb_export_time != '9999-12-31 23:59:59' AND "
. " csc.csc_id = jb.csc_id_payer AND cs.cs_id = csc.cs_id AND cmp.cmp_id = cs.cmp_id AND cmp.cmp_archived = '0' AND cmp.cmp_authenticated = '1' " . $whereClause
. " GROUP BY cs.cs_id"
. " ORDER BY cs.cs_eid";
Geprüfte Erweiterungen:
HAVING count_jobs > 1 <= nur mit mehr als einem Auftrag
*/
// NACH ERLEDIGUNGSZEIT
$sqlquery = "SELECT cs.cs_id, cs.cs_eid, cmp.cmp_comp, usr.usr_phone, usr.usr_email, COUNT(jb.jb_id) AS count_jobs, SUM(jb.jb_totalprice) AS business_volume"
. " FROM job AS jb, costcenter AS csc, company AS cmp, customer AS cs LEFT JOIN employee AS emp ON cs.cs_admin = emp.emp_id LEFT JOIN user AS usr ON emp.usr_id = usr.usr_id"
. " WHERE jb.jb_status = '2' AND jb.jb_finishtime >= '" . $fromDate . " 00:00:00' AND jb.jb_finishtime <= '" . $toDate . " 23:59:59' AND "
. " (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND "
. " csc.csc_id = jb.csc_id_payer AND cs.cs_id = csc.cs_id AND cmp.cmp_id = cs.cmp_id AND cmp.cmp_archived = '0' AND cmp.cmp_authenticated = '1' " . $whereClause
. " GROUP BY cs.cs_id"
. " ORDER BY cs.cs_eid";
// echo $sqlquery . "\n\n";
$result = $db->query($sqlquery);
if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
while ($row = $result->fetch_assoc()):
if ($csArrIsEmpty) :
$customerArr[$row["cs_id"]] = array($row["cs_eid"], $row["cmp_comp"], $row["usr_phone"], $row["usr_email"], $row["count_jobs"], 0, $row["business_volume"], 0, 0, 0);
else :
if (array_key_exists($row["cs_id"], $customerArr)) :
// Update existing row
$customerArr[$row["cs_id"]][5] = $row["count_jobs"];
$customerArr[$row["cs_id"]][7] = $row["business_volume"];
if ($customerArr[$row["cs_id"]][7] > 0) :
$customerArr[$row["cs_id"]][8] = ((($customerArr[$row["cs_id"]][6] - $customerArr[$row["cs_id"]][7]) / $customerArr[$row["cs_id"]][7]) * 100);
$customerArr[$row["cs_id"]][9] = ($customerArr[$row["cs_id"]][6] / $customerArr[$row["cs_id"]][7]); // Factor "last month / penultimate month"
endif;
else :
$customerArr[$row["cs_id"]] = array($row["cs_eid"], $row["cmp_comp"], $row["usr_phone"], $row["usr_email"], 0, $row["count_jobs"], 0, $row["business_volume"], 100, 1);
endif;
endif;
endwhile;
$result->free();
}
$objType = trim ($argv[2]);
$objId = trim ($argv[3]);
$intervalSendReport = trim ($argv[4]);
if ($intervalSendReport == "" || !is_numeric($intervalSendReport) || $intervalSendReport < 0 || $intervalSendReport > 2) :
$intervalSendReport = 0; // monthly per default
endif;
if ($objId != "" && (is_numeric($objId) && ($objType == "cs" || $objType == "cs_meta" || $objType == "cs_grp" || $objType == "hq" || $objType == "hq_all"))) :
if ($autoMode || $usr_id == "00000") :
// Get user
$usrName = "";
$usrFirstname = "";
if (!$autoMode) :
$usrName = getFieldValueFromId("user","usr_id",$usr_id,"usr_name");
$usrFirstname = getFieldValueFromId("user","usr_id",$usr_id,"usr_firstname");
endif;
// Get headquarters
$hqId = "0";
$hqName = "";
if ($objType == "hq_all") :
$hqName = "[ALLE]";
elseif ($objType == "hq") :
if (is_numeric($objId) && $objId > "0") :
$hqId = $objId;
$hqName = getFieldValueFromId("headquarters","hq_id",$objId,"hq_name");
endif;
endif;
// Init
$currentDateTime = getDateTime("0");
if ($intervalSendReport == 0) :
// Monthly
$fromDate = getDateTime("date_firstday_lastmonth_currentyear");
$toDate = getDateTime("date_lastday_lastmonth_currentyear");
elseif ($intervalSendReport == 1) :
// Quarterly
$curMonth = date("n");
$curYear = date("Y");
$quartals = array(1 => 1,2 => 1,3 => 1,4 => 2,5 => 2,6 => 2,7 => 3,8 => 3,9 => 3,10 => 4,11 => 4,12 => 4);
$currentQuartal = $quartals[$curMonth];
switch ($currentQuartal) {
case 1:
$lastYear = getDateTime("lastyear");
$fromDate = $lastYear . "-10-01 00:00:00";
$toDate = $lastYear . "-12-31 23:59:59";
break;
case 2:
$fromDate = $curYear . "-01-01 00:00:00";
$toDate = $curYear . "-03-31 23:59:59";
break;
case 3:
$fromDate = $curYear . "-04-01 00:00:00";
$toDate = $curYear . "-06-30 23:59:59";
break;
case 4:
$fromDate = $curYear . "-07-01 00:00:00";
$toDate = $curYear . "-09-30 23:59:59";
break;
}
elseif ($intervalSendReport == 2) :
// Yearly
$fromDate = getDateTime("date_firstday_firstmonth_lastyear");
$toDate = getDateTime("date_lastday_lastmonth_lastyear");
else :
// Default monthly
$fromDate = getDateTime("date_firstday_lastmonth_currentyear");
$toDate = getDateTime("date_lastday_lastmonth_currentyear");
endif;
// Get customes WITH jobs during the specified interval
// $csWithJobArr = getCustomersWithJobInInterval($fromDate);
// echo "\n\n"; print_r($csWithJobArr); echo "\n\n"; die();
$sendPerMail = false;
$path = "../temp/download/";
$f_secretFileName = "SALES_REPORT_" . getDateTime("6") . "_" . $objId . ".csv";
// List of all vehicles with special fields
if (true) :
$typeArr = defineOutputFormats();
// Special extensions
// $typeArr["jb_totalprice"] = "float_rounded_2";
// $typeArr["jb_km"] = "float_rounded_2";
// $typeArr["jb_co2"] = "float_rounded_2";
// sendInternalMail("Mindestens einer der Parameter JB_CR_PRICE_THRESHOLD bzw. JB_CR_PRICE_BLOCK existiert nicht!"); die();
$triggerArray = array();
$csvArray = array();
$customerArr = array();
$whereClause = "";
// Interval last month
$sqlFromDateA = getDateTime("date_firstday_lastmonth_currentyear");
$sqlToDateA = getDateTime("date_lastday_lastmonth_currentyear");
// $intervalA = $sqlFromDateA . " - " . $sqlToDateA;
$intervalA = substr($sqlFromDateA,8,2) . "." . substr($sqlFromDateA,5,2) . "." . substr($sqlFromDateA,0,4) . " - " . substr($sqlToDateA,8,2) . "." . substr($sqlToDateA,5,2) . "." . substr($sqlToDateA,0,4);
// Interval month before last month (penultimate month)
$sqlFromDateB = date("Y-m-d",mktime(0,0,0,date("m")-2,1,date("Y")));
$sqlToDateB = date("Y-m-d",mktime(0,0,0,date("m")-1,0,date("Y")));
// $intervalB = $sqlFromDateB . " - " . $sqlToDateB;
$intervalB = substr($sqlFromDateB,8,2) . "." . substr($sqlFromDateB,5,2) . "." . substr($sqlFromDateB,0,4) . " - " . substr($sqlToDateB,8,2) . "." . substr($sqlToDateB,5,2) . "." . substr($sqlToDateB,0,4);
// Insert header
$headerArray = array("Kunde", "Firma", "Rufnummer", "Email", "Aufträge </br>" . $intervalA, "Aufträge </br>" . $intervalB, "Umsatz </br>" . $intervalA, "Umsatz </br>" . $intervalB, "Veränderung&nbsp;[%]");
$fieldArray = array("cs_eid", "cmp_comp", "usr_phone", "usr_email", "count_jobs", "count_jobs2", "business_volume", "business_volume2", "percentValue");
$triggerArray[] = $headerArray;
$csvArray[] = str_replace("&nbsp;"," ",str_replace("</br>","",implode(";", $headerArray)));
// HEADQUARTERS
if ($objType == "hq" && $hqId > "0") :
$whereClause .= " AND jb.hq_id = '" . $hqId . "'";
endif;
// CUSTOMER
if ($objType == "cs") :
// $fieldClause .= "";
// $fromClause .= "";
$whereClause .= " AND cs.cs_id = '" . $objId . "'";
endif;
// META CUSTOMER
if ($objType == "cs_meta") :
// $fieldClause .= "";
$fromClause .= "customer AS cs2";
$whereClause .= " AND cs2.cs_id = '" . $objId . "' AND cs.cs_id_parent = cs2.cs_id";
endif;
// Values of last month
getCustomerList($sqlFromDateA, $sqlToDateA, $whereClause);
// Values of the month before last month (penultimate month)
getCustomerList($sqlFromDateB, $sqlToDateB, $whereClause);
// Sort array by percent value
uasort($customerArr, function($a, $b) {
// Zugriff auf den Wert mit Index 8
return $b[8] <=> $a[8];
});
// Iterate customer list, check total prices regarding 10T € and percent value:
$customerKeysArr = array_keys($customerArr);
$customerKeysArrLen = count($customerKeysArr);
for ($j = 0; $j < $customerKeysArrLen; $j++) :
$key = $customerKeysArr[$j];
// Cases:
// 1. & 2.: When looking at the last and penultimate month, one of the two is 0 and one is >0
// 3.: < 10 TEU total price last Monat and alle Kunden mit Veränderungen +/- 50%
// 4.: >= 10 TEU Umsatz/aktueller Monat, alle Kunden mit Veränderungen +/- 25%
if ($customerArr[$key][6] == 0 && $customerArr[$key][7] > 0 ||
$customerArr[$key][6] > 0 && $customerArr[$key][7] == 0 ||
$customerArr[$key][6] < 10000 && ($customerArr[$key][9] < 0.5 || $customerArr[$key][9] > 1.5) ||
$customerArr[$key][6] >= 10000 && ($customerArr[$key][9] < 0.25 || $customerArr[$key][9] > 1.25)) :
$triggerArray[] = $customerArr[$key];
endif;
endfor;
// print_r($triggerArray); die();
$triggerArrayLen = count($triggerArray);
$triggerOut = "";
// 66CCFF, FF0000, FF0044, FF6633, FFCC33, FFFF33
if ($triggerArrayLen > 1) :
$sendPerMail = true; // At least one event to be mailed
// HTML output
$triggerOut .= "<html>\n";
$triggerOut .= "<body>\n";
/*
$triggerOut .= "<br>";
$triggerOut .= "<table>\n";
$triggerOut .= "<tr>\n";
$triggerOut .= "<td style=\"background-color: #66CCFF;\">&nbsp;&nbsp;KEIN EINTRAG&nbsp;&nbsp;</td>";
$triggerOut .= "<td style=\"background-color: #FFFF33;\">&nbsp;&nbsp;&nbsp;< 6 Monate&nbsp;&nbsp;&nbsp;</td>";
$triggerOut .= "<td style=\"background-color: #FFCC33;\">&nbsp;&nbsp;&nbsp;< 3 Monate&nbsp;&nbsp;&nbsp;</td>";
$triggerOut .= "<td style=\"background-color: #FF6633;\">&nbsp;&nbsp;&nbsp;< 2 Monate&nbsp;&nbsp;&nbsp;</td>";
$triggerOut .= "<td style=\"background-color: #FF0033;\">&nbsp;&nbsp;&nbsp;< 1 Monat&nbsp;&nbsp;&nbsp;&nbsp;</td>";
$triggerOut .= "</tr>\n";
$triggerOut .= "</table>\n";
*/
$triggerOut .= "<br><br>";
$triggerOut .= "<table>\n";
// Headline
$triggerOut .= "<tr>\n";
$tmpArray = $triggerArray[0];
$tmpArrayLen = count($tmpArray);
// $rowColor = $tmpArray[0];
$rowColor = "66CCFF"; // Here a static value
for ($j = 0; $j < $tmpArrayLen; $j++) :
$triggerOut .= "<td style=\"background-color: #" . $rowColor . ";\">&nbsp;" . $tmpArray[$j] . "&nbsp;&nbsp;&nbsp;</td>\n";
endfor;
$triggerOut .= "</tr>\n";
// Body
for ($i = 1; $i < $triggerArrayLen; $i++) :
$tmpArray = $triggerArray[$i];
$tmpArrayLen = count($tmpArray);
$tmpArrayLen--; // Do not show last field(s) [factor, ....]
// Color
// $rowColor = $tmpArray[0];
$rowColor = "66CCFF"; // Here a static value
/*
if ($percentValue <= (100 - ($crPriceThresholdValue + $crPriceMarginValue))) :
$rowColor = "FFCC33";
endif;
if ($percentValue <= (100 - $crPriceBlockValue)) :
$rowColor = "FF6633";
endif;
*/
$triggerOut .= "<tr>\n";
$csvLineArray = array();
for ($j = 0; $j < $tmpArrayLen; $j++) :
if ($fieldArray[$j] == "count_jobs" || $fieldArray[$j] == "count_jobs2") :
$formattedOutput = formatOutput($tmpArray[$j], "number", "1", "0");
$textAlign = "right";
elseif ($fieldArray[$j] == "business_volume" || $fieldArray[$j] == "business_volume2") :
$formattedOutput = formatOutput($tmpArray[$j], "number", "1", "2");
if ($formattedOutput == "0") :
$formattedOutput = "0.00";
endif;
$textAlign = "right";
elseif ($fieldArray[$j] == "percentValue") :
$formattedOutput = formatOutput($tmpArray[$j], "number", "1", "2");
if ($tmpArray[$j] == 0 && $tmpArray[5] == 0) :
$formattedOutput = "";
endif;
$textAlign = "right";
else :
$formattedOutput = formatOutput($tmpArray[$j]);
$textAlign = "left";
endif;
$triggerOut .= "<td style=\"text-align: " . $textAlign . "; background-color: #" . $rowColor . ";\">&nbsp;" . $formattedOutput . ($rowColor == "FF0000" && $j == "6" ? "&nbsp;[überschritten]" : "") . "&nbsp;&nbsp;&nbsp;</td>\n";
$csvLineArray[] = $formattedOutput;
endfor;
$triggerOut .= "</tr>\n";
$csvArray[] = str_replace("&nbsp;","",implode(";", $csvLineArray));
endfor;
$triggerOut .= "</table>\n";
$triggerOut .= "</body>\n";
$triggerOut .= "</html>\n";
// CSV attachment
$csvArrayLen = count($csvArray);
for ($i = 0; $i < $csvArrayLen; $i++) :
writeToFile($path . $f_secretFileName, $csvArray[$i]);
endfor;
endif;
// Send via email
if ($sendPerMail) :
// Log object IDs
$logCsId = 0;
$logCrId = 0;
$logHqId = 0;
$mailSenderAddress = "support@assecutor.de";
/*
// Init receiver of the mail
$mailReceiverAddressArray = array("support@assecutor.de");
if ($objType == "cs" || $objType == "cs_meta") :
// Get receiver email address
$csCmpId = getFieldValueFromId("customer","cs_id",$objId,"cmp_id");
$cmpSustainabilityEmail = getFieldValueFromId("company","cmp_id",$csCmpId,"cmp_sustainability_email");
if ($cmpSustainabilityEmail != "") :
$mailReceiverAddressArray = array($cmpSustainabilityEmail);
endif;
$logCsId = $objId;
$logHqId = getFieldValueFromId("customer","cs_id",$objId,"hq_id");
elseif ($objType == "hq_all" || $objType == "hq") :
if ($hqId != "" && is_numeric($hqId)) :
$mailReceiverAddress = getParameterValue("0", "MAIL_CRON_202_TO_ADDRESS", $hqId);
// Check for split regarding vehicle type
if ($courierOrTruckOnly == "K" || $courierOrTruckOnly == "L") :
if ($courierOrTruckOnly == "K") :
$mailReceiverAddress = getParameterValue("0", "MAIL_CRON_202_A_TO_ADDRESS", $hqId);
else :
$mailReceiverAddress = getParameterValue("0", "MAIL_CRON_202_B_TO_ADDRESS", $hqId);
endif;
endif;
endif;
if ($mailReceiverAddress == "") :
$mailReceiverAddress = getParameterValue("0", "MAIL_CRON_202_TO_ADDRESS", "0");
endif;
if ($mailReceiverAddress != "") :
$mailReceiverAddressArray = spliti(",",$mailReceiverAddress);
endif;
endif;
*/
// Receiver of the mail
$mailReceiverAddressArray = array("support@assecutor.de");
if ($hqId != "" && is_numeric($hqId)) :
$mailReceiverAddress = getParameterValue("0", "MAIL_CRON_108_TO_ADDRESS", $hqId);
endif;
if ($mailReceiverAddress == "") :
$mailReceiverAddress = getParameterValue("0", "MAIL_CRON_108_TO_ADDRESS", "0");
endif;
if ($mailReceiverAddress != "") :
$mailReceiverAddressArray = explode(",",$mailReceiverAddress);
endif;
$reportName = "VERTRIEBLICHER REPORT";
$mailSubject = $reportName . " " . ($hqName != "" ? "[" . $hqName . "]" : "");
$mailCcAddress = "";
$mailBccAddress = "";
$mailtext = $reportName;
$mailtext .= "<br><br>";
$intervalTextA = "Abfragezeitraum: ";
$intervalTextB = "Vergleichszeitraum: ";
$mailtext .= "<table>";
$mailtext .= "<tr><td>" . $intervalTextA . "</td><td>" . $intervalA . "</td></tr>";
$mailtext .= "<tr><td>" . $intervalTextB . "</td><td>" . $intervalB . "</td></tr>";
$mailtext .= "</table>";
$mailtext .= "<br><br>";
if (!$autoMode) :
$mailtext .= "Ausgeführt von: " . $usrFirstname . " " . $usrName;
endif;
$mailtext .= $triggerOut;
$mailObj = new htmlMimeMail();
// Set From address
$mailObj->setFrom($mailSenderAddress);
// Set Cc address
if ($mailCcAddress != "") :
$mailObj->setCc($mailCcAddress);
endif;
// Set Bcc address
$mailBccAddress = "admin@assecutor.de";
if ($mailBccAddress != "") :
$mailObj->setBcc($mailBccAddress);
endif;
// Subject of the mail
$mailObj->setSubject($mailSubject);
// Mail text
$mailObj->setHtml($mailtext, null, "./");
// Attachment
if ($f_secretFileName != "") :
if (file_exists($path . $f_secretFileName)) :
$attachment = $mailObj->getFile($path . $f_secretFileName);
// $mailObj->addAttachment($attachment, $f_secretFileName, $f_mimetype . $f_charset);
$mailObj->addAttachment($attachment, $f_secretFileName, 'text/csv');
endif;
endif;
// echo "mailReceiverAddress = " . $mailReceiverAddress . "\n\n";
// $mailReceiverAddressArray = array("mv@assecutor.de", "ca@assecutor.de");
// $mailReceiverAddressArray = array("mv@assecutor.de", "ca@assecutor.de", "ingo.kublenz@stadtbote.de");
// $mailReceiverAddressArray = array("admin@assecutor.de", "ingo.kublenz@stadtbote.de");
// $mailReceiverAddressArray = array("mv@assecutor.de");
$mailResult = $mailObj->send($mailReceiverAddressArray, 'smtp');
if ($mailResult) :
$sendState = "OK";
else :
$sendState = "NOK";
endif;
// Write logdata into log database
writeToLogDB("190",$logHqId,"","",$logCrId,"",$logCsId,"OBJ_TYPE=" . $objType . "|VERSANDSTATUS=" . $sendState . "|EMAIL=" . implode(",", $mailReceiverAddressArray) . "|DATE_FROM=" . $fromDate . "|DATE_TO=" . $toDate . "|INTERVAL=" . $intervalSendReport);
$mailObj = NULL;
if (file_exists($path . $f_secretFileName)) :
unlink($path . $f_secretFileName);
endif;
$out = "Der Sendevorgang wurde abgeschlossen! Bitte prüfen Sie Ihren Email-Eingangsordner!";
endif;
endif;
else :
$out = "Leider haben Sie zur Ausführung keine Berechtigung!";
endif;
else :
$out = "Die geforderte Auswahlkombination gibt es leider nicht!";
endif;
?>
<?php if (!$autoMode) : ?>
<html>
<head>
</head>
<body>
<center>
<br><br><br>
<b><?php echo $triggerOut ?></b>
</center>
</body>
</html>
<?php endif; ?>