Merge branch 'master' into fronkdev

This commit is contained in:
Frank Schubert
2024-11-19 18:45:04 +01:00
48 changed files with 5969 additions and 1266 deletions
@@ -177,6 +177,8 @@ class CalendarApicontroller extends mfBaseApicontroller
$message[0]['attachments'] = $Calendarevent['data'][0]['attachments']['attachments'];
$message[0]['calendar_name'] = $Calendarevent['data'][0]['calendar_name']['calendar_name'];
$message[0]['isorganizer'] = $Calendarevent['data'][0]['isorganizer']['isorganizer'];
$message[0]['rrule'] = $Calendarevent['data'][0]['rrule']['rrule'];
$message[0]['duration'] = $Calendarevent['data'][0]['duration']['duration'];
$message[0]['mtime'] = $Calendarevent['data'][0]['mtime']['mtime'];
$message[0]['mname'] = $Calendarevent['data'][0]['mname']['mname'];
$message[0]['ctime'] = $Calendarevent['data'][0]['ctime']['ctime'];
@@ -212,6 +212,8 @@ class CalendarController extends mfBaseController
$timerecordingemployees = TimerecordingEmployeeModel::getAll();
$standardCalendarColors = CalendarModel::$standardCalendarColors;
$specialCalendarColors = CalendarModel::$specialCalendarColors;
$this->layout()->set("timerecordingemployees", $timerecordingemployees);
$this->layout()->set("standardCalendarColors", $standardCalendarColors);
$this->layout()->set("specialCalendarColors", $specialCalendarColors);
+98 -5
View File
@@ -118,6 +118,7 @@ class CalendarModel
public static function getCalendarEvents($me, $id = 0, $r = 0)
{
$rrulefreq = array('daily' => 'DAILY', 'weekly' => 'WEEKLY', 'relativeMonthly' => 'MONTHLY', 'yearly' => 'YEARLY');
$calendar = self::search(array("user_id" => $me));
$standardCalendarColors = CalendarModel::$standardCalendarColors;
$calendarColors = json_decode($calendar[0]->colors, true);
@@ -154,13 +155,16 @@ class CalendarModel
$visibleCalendars = $r->visibleCalendars;
if ($visibleCalendars) {
$where .= " AND calendar_id IN (" . implode(",", $visibleCalendars) . ")";
$whereTimeRecording = " AND `Calendar`.`go_calendar_id` IN (" . implode(",", $visibleCalendars) . ")";
}
$sql = "SELECT `cal_events`.id, uuid, calendar_id, `cal_events`.user_id, start_time, end_time, timezone, all_day_event, `cal_events`.name,`cal_calendars`.name calendar_name, description, location, repeat_end_time, reminder, ctime,cname, mtime,mname, muser_id, busy, status, resource_event_id, private, rrule, `cal_events`.background, `cal_events`.files_folder_id, read_only, category_id, exception_for_event_id, recurrence_id, is_organizer,event_type,busy FROM cal_events INNER JOIN `cal_calendars` ON (`cal_calendars`.`id`=`cal_events`.`calendar_id`) WHERE 1=1 $where ";
$sql = "SELECT `cal_events`.id, uuid, calendar_id, `cal_events`.user_id, start_time, end_time, timezone, all_day_event, `cal_events`.name,`cal_calendars`.name calendar_name, description, location, repeat_end_time, reminder, ctime,cname, mtime,mname, muser_id, busy, status, resource_event_id, private, rrule, `cal_events`.background, `cal_events`.files_folder_id, read_only, category_id, exception_for_event_id, recurrence_id, is_organizer,event_type,busy,recurrence FROM cal_events INNER JOIN `cal_calendars` ON (`cal_calendars`.`id`=`cal_events`.`calendar_id`) WHERE 1=1 $where ";
$res = $dbcal->query($sql);
if ($dbcal->num_rows($res)) {
while ($data = $dbcal->fetch_array($res)) {
unset($byweekday);
$rrule = false;
if ($attachments[$data['uuid']]) {
$attachment = 1;
$attachmentLinks = json_encode($attachments[$data['uuid']]['attachments']);
@@ -184,6 +188,40 @@ class CalendarModel
$name = $data['name'];
}
if ($data['recurrence']) {
$recurrence = json_decode($data['recurrence'], true);
if ($rrulefreq[$recurrence['pattern']['type']]) {
unset ($byweekday);
$freq = $rrulefreq[$recurrence['pattern']['type']];
foreach ($recurrence['pattern']['daysOfWeek'] as $value) {
$byweekday[] = strtolower(substr($value, 0, 2));
}
$duration = ($data['end_time'] - $data['start_time']) * 1000;
$until = $recurrence['range']['endDate'];
if ($until == "0001-01-01") {
$until = strtotime("+3 year", time());
$until = date("Y-m-d", $until);
} else {
$until = date("Y-m-d", strtotime($recurrence['range']['endDate']) + 86400);
}
$rrule = [
'freq' => $freq,
'interval' => $recurrence['pattern']['interval'],
'byweekday' => $byweekday,
'dtstart' => date("Y-m-d\TH:i", $data['start_time']),
'until' => $until
];
if ($freq == "MONTHLY") {
$bystpos = array("first" => 1, "second" => 2, "third" => 3, "fourth" => 4, "last" => -1);
$rrule['bysetpos'] = $bystpos[$recurrence['pattern']['index']];
}
}
} else {
$rrule = false;
}
if ($calendarColors[$data['calendar_id']]['bgcolor']) {
$bgcolor = $calendarColors[$data['calendar_id']]['bgcolor'];
$txtcolor = $calendarColors[$data['calendar_id']]['txtcolor'];
@@ -194,7 +232,7 @@ class CalendarModel
}
if ($calenderRights[$data['calendar_id']]) {
$rights = $calenderRights[$data['calendar_id']];
$CalendarUsers[$data['calendar_id']] = $data['calendar_name'];
$rows[] = array(
'id' => array('id' => $data['id']),
'cstart' => array('cstart' => $starttime),
@@ -207,6 +245,8 @@ class CalendarModel
'rights' => array('rights' => $rights, 'order' => $rights),
'location' => array('location' => $data['location']),
'busy' => array('busy' => $data['busy']),
'rrule' => array('rrule' => $rrule),
'duration' => array('duration' => $duration),
'event_type' => array('event_type' => $data['event_type']),
'description' => array('description' => ($data['description'])),
'attachment' => array('attachment' => $attachment),
@@ -218,9 +258,59 @@ class CalendarModel
'mname' => array('mname' => $data['mname']),
'isorganizer' => array('isorganizer' => $data['is_organizer']),
'busy' => array('busy' => $data['busy']),
'timerecording' => array('timerecording' => 0),
);
}
}
$db = FronkDB::singleton();
$sql = "SELECT `Timerecording`.`id`, `Timerecording`.`start` start_time, `Timerecording`.`end` end_time,`Calendar`.`go_calendar_id` calendar_id,`TimerecordingCategory`.`name`,`TimerecordingCategory`.`id` CategoryId,`Timerecording`.`create` ctime,`Timerecording`.`edit` mtime FROM `Timerecording`
INNER JOIN `TimerecordingCategory` ON `TimerecordingCategory`.`id`=`Timerecording`.`timerecordingCategory_id`
INNER JOIN `Calendar` ON `Calendar`.`user_id`=`Timerecording`.`user_id`
WHERE `TimerecordingCategory`.`hourday`!='1' AND `TimerecordingCategory`.`hourday`!='7' AND `TimerecordingCategory`.`hourday`!='5' $whereTimeRecording";
$res = $db->query($sql);
if ($db->num_rows($res)) {
while ($data = $db->fetch_array($res)) {
if ($calendarColors[$data['calendar_id']]['bgcolor']) {
$bgcolor = $calendarColors[$data['calendar_id']]['bgcolor'];
$txtcolor = $calendarColors[$data['calendar_id']]['txtcolor'];
} else {
$bgcolor = $standardCalendarColors[$colorCounter];
$txtcolor = "#000";
$colorCounter++;
}
if ($data['CategoryId'] != 11) {
$starttime = date("Y-m-d", $data['start_time']);
$endtime = date("Y-m-d", $data['end_time']);
if ($starttime != $endtime) {
$endtime = $data['end_time'] + 86400;
$endtime = date("Y-m-d", $endtime);
}
} else {
$starttime = date("Y-m-d H:i", $data['start_time']);
$endtime = date("Y-m-d H:i", $data['end_time']);
}
$rows[] = array(
'id' => array('id' => "9999" . $data['id']),
'category' => array('category' => $data['name']),
'ccategory' => array('ccategory' => $data['name']),
'cstart' => array('cstart' => $starttime),
'cend' => array('cend' => $endtime),
'calendar_id' => array('calendar_id' => $data['calendar_id']),
'ctime' => array('ctime' => date("d.m.Y H:i", $data['ctime'])),
'cname' => array('cname' => $CalendarUsers[$data['calendar_id']]),
'mtime' => array('mtime' => date("d.m.Y H:i", $data['mtime'])),
'mname' => array('mname' => $CalendarUsers[$data['calendar_id']]),
'description' => array('description' => ""),
'bgColor' => array('bgColor' => $bgcolor),
'txtColor' => array('txtColor' => $txtcolor),
'timerecording' => array('timerecording' => 1),
'calendar_name' => array('calendar_name' => $CalendarUsers[$data['calendar_id']]),
);
}
}
$json['success'] = true;
$json['data'] = $rows;
} else {
@@ -347,8 +437,8 @@ class CalendarModel
}
}
if (!$data['accepted'] && $data['busy'] == 1) {
$data['accepted']['ok']=1;
$data['accepted']=json_encode($data['accepted']);
$data['accepted']['ok'] = 1;
$data['accepted'] = json_encode($data['accepted']);
}
$rows = array(
@@ -439,6 +529,7 @@ class CalendarModel
$type = ($r->type);
$busy = ($r->busy);
$users = ($r->users);
$attendees = ($r->attendees);
foreach ($users as $key => $value) {
$user_id = $value;
}
@@ -548,6 +639,8 @@ class CalendarModel
$updateArray['attachments'] = $attachments;
}
if ($attendees)
$updateArray['attendees'] = $attendees;
$json_data = json_encode($updateArray);
$data = [];
$data['ms_user_id'] = $microsoft_user_id;
@@ -718,7 +811,7 @@ class CalendarModel
$data['create_timestamp'] = time();
$data['edit_timestamp'] = time();
$db->insert("tmp_cal_events_attachments", $data);
echo "insert_id: " . $db->insert_id;
// echo "insert_id: " . $db->insert_id;
return $db->insert_id;
}
+185
View File
@@ -792,4 +792,189 @@ class Contract extends mfBaseModel {
$this->log->debug("Cloned Contract $old_id");
}
// ---- CONTRACT VIEW UTILITY FUNCTIONS START ----
public function getContractDetails($getUrl): array {
$contract = $this;
$contract->getProperty("billingaddress");
$contract->getProperty("owner");
$contract->getProperty("product");
$contract->getProperty("sla");
$contract->getProperty("finisher");
$contract->getProperty("canceler");
$contract->getProperty("creator");
$contract->getProperty("editor");
$contract->getProperty("vatrate");
$contract->getProperty("configvalues");
$contract->getProperty("orderproduct");
$contract_details = [];
$contract_details['matchcode'] = ['label' => 'Matchcode', 'value' => $contract->matchcode];
$contract_details['owner'] = ['label' => 'Kunde',
'value' => $contract->owner->getCompanyOrName(),
'url' => $getUrl('Address', 'View', ['id' => $contract->billingaddress->id])];
if ($contract->billingaddress_id) {
$contract_details['billingaddress'] = ['label' => 'Rechnungsadresse',
'value' => $contract->billingaddress->getCompanyOrName(),
'url' => $getUrl('Address', 'View', ['id' => $contract->billingaddress->id])];
}
$productName = $contract->product->name;
$contractProductName = $contract->product_name;
$productId = $contract->product_id;
$contract_details['product'] = ['label' => 'Produkt',
'value' => "$contractProductName ($productName) [$productId]",
'url' => $getUrl('Product', 'Edit', ['id' => $contract->product_id])];
if ($contract->prduct_info) {
$contract_details['product_info'] = ['label' => 'Produktinfo', 'value' => $contract->product_info];
}
$contract_details['sla'] = ['label' => 'SLA', 'value' => $contract->sla->name];
$contract_details['external_product'] = ['label' => 'Externes Produkt', 'value' => $contract->product_external ? "Ja" : "Nein"];
$contract_details['amount'] = ['label' => 'Menge', 'value' => Helper::formatNumber($contract->amount, 3)];
$contract_details['price_net'] = ['label' => 'Preis Periodisch Netto',
'value' => "€ " . Helper::formatNumber($contract->price * $contract->amount, 4),
'class' => $contract->price < 0 ? 'text-danger' : null];
if ($contract->vatrate) {
$contract_details['price_gross'] = ['label' => 'Preis Periodisch Brutto',
'value' => "€ " . Helper::formatNumber($contract->price * $contract->amount * floatval("1." . intval($contract->vatrate)), 4),
'class' => $contract->price < 0 ? 'text-danger' : null];
}
$contract_details['billing_period'] = ['label' => 'Abrechnungsperiode', 'value' => __($contract->billing_period, "billing_period")];
if ($contract->price_setup > 0) {
$vatRateMultiplier = $contract->vatrate ? ("1." . intval($contract->vatrate)) : 1;
$price_net = Helper::formatNumber($contract->price_setup, 4);
$sum_net = Helper::formatNumber($contract->price_setup * $contract->amount, 4);
$price_gross = Helper::formatNumber($contract->price_setup * $contract->amount * $vatRateMultiplier, 4);
$sum_gross = Helper::formatNumber($contract->price_setup * $contract->amount * $vatRateMultiplier, 4);
$contract_details['price_setup'] = ['label' => 'Einrichtungsgebühr',
'value' => "Netto: € {$price_net} (Gesamt: € {$sum_net})\nBrutto: € {$price_gross} (Gesamt: € {$sum_gross})"];
}
if ($contract->billing_delay) $contract_details['billing_delay'] = ['label' => 'Abrechnungsverzögerung',
'value' => $contract->billing_delay . " Monate"];
$contract_details['order_date'] = ['label' => 'Bestelldatum', 'value' => date('d.m.Y', $contract->order_date)];
if ($contract->finish_date) $contract_details['finish_date'] = ['label' => 'Fertigstellung',
'value' => date('d.m.Y', $contract->finish_date) . " (" . $contract->finisher->name . ")"];
if ($contract->cancel_date) $contract_details['cancel_date'] = ['label' => 'Kündigungsdatum',
'value' => date('d.m.Y', $contract->cancel_date) . " (" . $contract->canceler->name . ")"];
$contract_details['create'] = ['label' => 'Erstellt', 'value' => date('d.m.Y', $contract->create) . " (" . $contract->creator->name . ")"];
$contract_details['edit'] = ['label' => 'Geändert', 'value' => date('d.m.Y', $contract->edit) . " (" . $contract->editor->name . ")"];
return $contract_details;
}
public function getContractActions($getUrl): array {
$contract = $this;
$contract_actions = [];
$contract_actions['contractconfig'] = ['url' => $getUrl("Contractconfig", "edit", ["contract_id" => $contract->id]),
'class' => 'btn-outline-info',
'icon' => 'far fa-list-dropdown fa-fw',
'text' => 'Konfiguration bearbeiten'];
$contract_actions['contractaccessletter'] = ['url' => $getUrl("Contractaccessletter", "view", ["contract_id" => $contract->id]),
'class' => 'btn-outline-success',
'icon' => 'far fa-list-numeric fa-fw',
'text' => 'Zugangsdaten anzeigen'];
if ($contract->finish_date && $contract->finish_date < date('U')) {
$contract_actions['contractownerchange'] = ['class' => 'btn-outline-secondary',
'icon' => 'far fa-people-arrows fa-fw',
'text' => 'Inhaberwechsel'];
$contract_actions['productchange'] = ['url' => $getUrl("Contract", "productchange", ["contract_id" => $contract->id]),
'class' => 'btn-outline-purple',
'icon' => 'far fa-truck-container fa-fw',
'text' => 'Produkt-/Standortwechsel'];
$contract_actions['cancel'] = ['url' => $getUrl("Contract", "cancel", ["contract_id" => $contract->id]),
'class' => 'btn-outline-danger',
'icon' => 'far fa-axe fa-fw',
'text' => 'Kündigen'];
} else if (!$contract->finish_date) {
$contract_actions['contractconfig'] = ['url' => $getUrl("Contract", "finishContract", ['contract_id' => $contract->id]),
'class' => 'btn-success',
'icon' => 'far fa-face-confused fa-fw',
'text' => 'Jetzt fertigstellen',
'confirmText' => 'Jetzt fertigstellen und in Verrechnung geben?'];
}
return $contract_actions;
}
public function getContractJournal($getUrl): array {
$contract = $this;
$contract->getProperty("journals");
$contract->getProperty("orderproduct");
$contract->getProperty("product");
$contract_journal = [];
if (is_array($contract->journals) && count($contract->journals)) {
foreach ($contract->journals as $j) {
$entry = [];
$entry['create'] = date('d.m.Y H:i:s', $j->create);
$entry['creator'] = $j->creator->name;
if ($j->type === "text" || $j->type === "phone") {
$entry['icon'] = $j->type === "text" ? "fas fa-comment-dots text-warning " : "fas fa-phone text-warning ";
$entry['iconTitle'] = $j->type === "text" ? "Textnachricht" : "Telefonat";
$entry['text'] = $j->text;
} else if ($j->type === "file") {
$entry['icon'] = "fas fa-download text-primary ";
$entry['iconTitle'] = "Datei";
$entry['text'] = "[URL]";
$entry['url'] = $getUrl("File", "download", ["id" => $j->contractfile->file_id]);
$entry['urlText'] = $j->contractfile->name;
} else if ($j->type === "created_from") {
$entry['icon'] = "fas fa-cogs text-secondary ";
$entry['iconTitle'] = "Vertrag erstellt";
$entry['textClass'] = "font-italic";
if ($j->value == "manual") {
$entry['text'] = "Contract manuell erstellt";
} else if ($j->value == "import") {
$entry['text'] = "Contract importiert: " . $j->text;
} else if ($j->value == "order") {
$entry['text'] = "Vertrag aus Bestellung [URL] erstellt";
$entry['url'] = $getUrl("Order", "", ["id" => $contract->orderproduct->order_id]);
$entry['urlText'] = "#" . $contract->orderproduct->order_id;
} else if ($j->value == "productchange") {
$entry['text'] = "Vertrag erstellt:" . $j->text;
}
} else if ($j->type === "contract_finished") {
$entry['icon'] = "fas fa-flag-checkered text-success ";
$entry['iconTitle'] = "Vertrag fertiggestellt";
$entry['text'] = "Vertrag fertiggestelt";
$entry['textClass'] = "font-italic";
} else if ($j->type === "credit_created") {
$entry['icon'] = "fas fa-credit-card text-gray ";
$entry['iconTitle'] = "Gutschrift";
$entry['text'] = "Gutschrift Vertrag [URL] erstellt";
$entry['textClass'] = "font-italic";
$entry['url'] = $getUrl("Contract", "View", ["contract_id" => $j->value]);
$entry['urlText'] = $j->value;
} else if ($j->type === "link") {
$link = new Contract($j->value);
$entry['icon'] = "fas fa-link text-secondary ";
$entry['iconTitle'] = "Verknüpfung";
$entry['text'] = "Verknüpfung mit [URL] erstellt";
$entry['textClass'] = "font-italic";
$entry['url'] = $getUrl("Contract", "view", ['contract_id' => $link->id]);
$entry['urlText'] = $link->id . " - " . $link->product_name . " - [" . $link->matchcode . "]";
} else if ($j->type === "canceled") {
$entry['icon'] = "fas fa-skull-crossbones bg-danger text-white ";
$entry['iconTitle'] = "Kündigung";
$entry['textClass'] = "font-italic";
$entry['text'] = "Vertrag gekündigt";
}
$contract_journal[] = $entry;
}
}
return $contract_journal;
}
// ---- CONTRACT VIEW UTILITY FUNCTIONS END ----
}
+240 -249
View File
@@ -1,10 +1,8 @@
<?php
class ContractController extends mfBaseController
{
class ContractController extends mfBaseController {
protected function init()
{
protected function init() {
$this->needlogin = true;
$me = new User();
$me->loadMe();
@@ -17,9 +15,8 @@ class ContractController extends mfBaseController
}
protected function indexAction()
{
if(!$this->me->is(["Admin"])) {
protected function indexAction() {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
@@ -59,8 +56,7 @@ class ContractController extends mfBaseController
$this->layout()->set("pagination", $pagination);
}
private function getPreparedFilter($filter)
{
private function getPreparedFilter($filter) {
$new_filter = [];
if (array_key_exists("show_canceled", $filter)) {
@@ -71,8 +67,8 @@ class ContractController extends mfBaseController
$new_filter['add-where'] = " AND (cancel_date IS NULL OR cancel_date > UNIX_TIMESTAMP())";
}
if(array_key_exists("cancel_date", $filter)) {
if($filter["cancel_date"]) {
if (array_key_exists("cancel_date", $filter)) {
if ($filter["cancel_date"]) {
$new_filter["cancel_date"] = true;
}
}
@@ -95,13 +91,49 @@ class ContractController extends mfBaseController
return $new_filter;
}
protected function viewAction()
{
if(!$this->me->is(["Admin"])) {
protected function viewAction() {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$this->layout()->setTemplate("Contract/View");
$id = $this->request->contract_id;
if (!$id) {
$id = $this->request->id;
}
if (!is_numeric($id) || !$id) {
$this->layout()->setFlash("Vertrag nicht gefunden", "error");
$this->redirect("Contract");
}
$contract = new Contract($id);
if (!$contract->id) {
$this->layout()->setFlash("Vertrag nicht gefunden", "error");
$this->redirect("Contract");
}
$getUrlFunc = function($controller, $action, $params = []) {
return $this::getUrl($controller, $action, $params);
};
Helper::renderVue($this, "ContractView", "Contract", ["CONTRACT_DETAILS" => $contract->getContractDetails($getUrlFunc),
"CONTRACT_ID" => $contract->id,
"CONTRACT_ACTIONS" => $contract->getContractActions($getUrlFunc),
"CONTRACT_JOURNAL" => $contract->getContractJournal($getUrlFunc),
"CONTRACT_LINK_TABLE_URL" => self::getUrl("Contract", "contractLinkTableHTML", ["contract_id" => $contract->id]),
"CONTRACT_NEW_JOURNAL_URL" => self::getUrl("Contractjournal", "save"),
"BACK_URL" => isset($_SERVER['HTTP_REFERER']) && str_contains($_SERVER['HTTP_REFERER'], 'Address/View') ? $_SERVER['HTTP_REFERER'] : self::getUrl('Contract', 'Index'),
"EDIT_URL" => self::getUrl('Contract', 'Edit', ['contract_id' => $contract->id, 'f' => 'view']),
"HEADER" => str_contains(strtolower($contract->sla->name), "residential") ? "Privatprodukt" : "Businessprodukt",
"SUB_HEADER" => $contract->product_name . "[" . $contract->id . "]"
]);
}
protected function contractLinkTableHTMLAction() {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$id = $this->request->contract_id;
if (!$id) {
@@ -119,18 +151,11 @@ class ContractController extends mfBaseController
}
$this->layout()->set("contract", $contract);
if ($this->request->filter) {
$this->layout()->set("filter", $this->request->filter);
}
if ($this->request->s) {
$this->layout()->set("filter", $this->request->s);
}
$this->layout()->setTemplate("Contract/LinkTable");
}
protected function cancelAction() {
if(!$this->me->is(["Admin"])) {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$this->layout()->setTemplate("Contract/CancelForm");
@@ -138,7 +163,7 @@ class ContractController extends mfBaseController
$id = $this->request->contract_id;
if (!$id) $id = $this->request->id;
if(!$id) {
if (!$id) {
$id = $this->request->id;
}
if (!is_numeric($id) || !$id) {
@@ -152,7 +177,7 @@ class ContractController extends mfBaseController
$this->redirect("Contract");
}
if(!$contract->billing_period) {
if (!$contract->billing_period) {
$this->layout()->setFlash("Kündigung nicht möglich, Produkt ist Einmalprodukt!", "error");
$this->redirect("Contract", "view", ["contract_id" => $contract->id]);
}
@@ -171,7 +196,7 @@ class ContractController extends mfBaseController
}
protected function saveCancel() {
if(!$this->me->is(["Admin"])) {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$r = $this->request;
@@ -190,23 +215,23 @@ class ContractController extends mfBaseController
try {
$cancel_date = DateTime::createFromFormat("d.m.Y", trim($r->cancel_date), new DateTimeZone("Europe/Vienna"));
$cancel_date->setTime(23,59,59);
} catch(Exception $e) {
$cancel_date->setTime(23, 59, 59);
} catch (Exception $e) {
$this->layout()->setFlash("Ungültiges Datumsformat");
$this->redirect("Contract", "cancel", ["contract_id" => $contract->id]);
}
$contract->cancel_date = $cancel_date->getTimestamp();
$contract->edit_by = $this->me->id;
if(!$contract->save()) {
if (!$contract->save()) {
$this->layout()->setFlash("Fehler beim Speichern", "error");
$this->redirect("Contract", "cancel", ["contract_id" => $contract->id]);
}
$linked_contracts = [];
if(is_array($r->links)) {
foreach($r->links as $link_id => $action) {
if($action == "cancel") {
if (is_array($r->links)) {
foreach ($r->links as $link_id => $action) {
if ($action == "cancel") {
$link_contract = new Contract($link_id);
if (!$link_contract->id) {
@@ -216,11 +241,11 @@ class ContractController extends mfBaseController
$link_contract->cancel_date = $cancel_date->getTimestamp();
$link_contract->edit_by = $this->me->id;
if(!$link_contract->save()) {
if (!$link_contract->save()) {
$this->layout()->setFlash("Fehler beim Speichern von verlinktem Vertrag", "warning");
}
if($link_contract->owner_id != $contract->owner_id) continue;
if ($link_contract->owner_id != $contract->owner_id) continue;
$linked_contracts[] = $link_contract;
}
}
@@ -234,20 +259,20 @@ class ContractController extends mfBaseController
}
protected function sendCancelNotification() {
if(!$this->me->is(["Admin"])) {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$contract_id = $this->request->contract_id;
$contract = new Contract($contract_id);
$linked_contracts = [];
foreach($contract->links as $link) {
if($link->origin_contract_id == $contract_id) {
foreach ($contract->links as $link) {
if ($link->origin_contract_id == $contract_id) {
$link_contract = $link->contract;
} else {
$link_contract = $link->origin;
}
if($link_contract->owner_id != $contract->owner_id) continue;
if ($link_contract->owner_id != $contract->owner_id) continue;
$linked_contracts[] = $link_contract;
}
@@ -259,12 +284,11 @@ class ContractController extends mfBaseController
}
protected function productchangeAction()
{
protected function productchangeAction() {
$this->layout()->setTemplate("Contract/ProductchangeForm");
$f = $this->request->f;
if(!$f) {
if (!$f) {
$f = "c"; // from Contract
}
$this->layout()->set("f", $f);
@@ -275,7 +299,7 @@ class ContractController extends mfBaseController
}
if (!is_numeric($id) || !$id) {
$this->layout()->setFlash("Vertrag nicht gefunden", "error");
if($f == "o") {
if ($f == "o") {
$this->redirect("Order", "addUpgrade");
} else {
$this->redirect("Contract");
@@ -286,28 +310,28 @@ class ContractController extends mfBaseController
$contract = new Contract($id);
if (!$contract->id) {
$this->layout()->setFlash("Vertrag nicht gefunden", "error");
if($f == "o") {
if ($f == "o") {
$this->redirect("Order", "addUpgrade");
} else {
$this->redirect("Contract");
}
}
if($this->me->isAdmin()) {
if ($this->me->isAdmin()) {
$this->layout()->set("terminations", TerminationModel::getAll());
} else {
// check permissions
// check if correct network
// check permissions
// check if correct network
$my_network_ids = [];
foreach($this->me->my_networks as $network) {
foreach ($this->me->my_networks as $network) {
$my_network_ids[] = $network->id;
}
if($contract->termination_id) {
if(!in_array($contract->termination->network_id, $my_network_ids)) {
if($f == "o") {
// from Order, redirect back to Order
if ($contract->termination_id) {
if (!in_array($contract->termination->network_id, $my_network_ids)) {
if ($f == "o") {
// from Order, redirect back to Order
$this->layout()->setFlash("Keine Berechtigung", "error");
$this->redirect("Order", "addUpgrade", ["owner_id" => $contract->owner_id]);
}
@@ -331,24 +355,23 @@ class ContractController extends mfBaseController
}
}
protected function saveProductchangeAction()
{
if(!$this->me->is(["Admin", "salespartner", "netowner"])) {
protected function saveProductchangeAction() {
if (!$this->me->is(["Admin", "salespartner", "netowner"])) {
$this->redirect("Dashboard");
}
$r = $this->request;
//var_dump($r->links);exit;
//var_dump($r->links);exit;
$f = $r->f;
if(!$f) {
if (!$f) {
$f = "c"; // from Contract
}
$id = $r->contract_id;
if (!is_numeric($id) || !$id) {
$this->layout()->setFlash("Vertrag nicht gefunden", "error");
if($f == "o") {
if ($f == "o") {
$this->redirect("Order", "addUpgrade");
} else {
$this->redirect("Contract");
@@ -358,7 +381,7 @@ class ContractController extends mfBaseController
$contract = new Contract($id);
if (!$contract->id) {
$this->layout()->setFlash("Vertrag nicht gefunden", "error");
if($f == "o") {
if ($f == "o") {
$this->redirect("Order", "addUpgrade");
} else {
$this->redirect("Contract");
@@ -382,12 +405,12 @@ class ContractController extends mfBaseController
$contract_data['note'] = trim($r->note);
/*
* termination check
*/
* termination check
*/
$product = new Product($r->product_id);
if (!$product->id) {
$this->layout()->setFlash("Produkt nicht gefunden", "error");
if($f == "o") {
if ($f == "o") {
$this->redirect("Order", "productchange", ["contract_id" => $id]);
} else {
$this->redirect("Contract", "productchange", ["contract_id" => $id]);
@@ -399,35 +422,35 @@ class ContractController extends mfBaseController
$contract_data['product_external_id'] = $product->external_id;
$contract_data['sla_id'] = $product->sla_id;
if($r->finish_date) {
if ($r->finish_date) {
try {
$finish_date = DateTime::createFromFormat("d.m.Y", $r->finish_date, new DateTimeZone("Europe/Vienna"));
} catch (Exception $e) {
$this->layout()->setFlash("Ungültiges Kündigungsdateum", "error");
if($f == "o") {
if ($f == "o") {
$this->redirect("Order", "productchange", ["contract_id" => $id]);
} else {
$this->redirect("Contract", "productchange", ["contract_id" => $id]);
}
}
$finish_date->setTime(0,0,0);
$finish_date->setTime(0, 0, 0);
$contract_data["finish_date"] = $finish_date->getTimestamp();
$contract_cancel_date = clone($finish_date);
$contract_cancel_date->modify("-1 day");
$contract_cancel_date->setTime(23,59,59);
$contract_cancel_date->setTime(23, 59, 59);
}
$require_term = false;
if (array_key_exists(TT_ATTRIB_TERMINATION_REQUIRED_NAME, $product->attributes) && $product->attributes[TT_ATTRIB_TERMINATION_REQUIRED_NAME]->value == 1) {
//var_dump($prod->attributes);
//var_dump($prod->attributes);
$require_term = true;
$termination = new Termination($contract_data['termination_id']);
if (!$contract_data['termination_id'] || !$termination->id) {
$this->layout()->setFlash("Produkt erfordert Anschluss.", "error");
if($f == "o") {
if ($f == "o") {
$this->redirect("Order", "productchange", ["contract_id" => $id]);
} else {
$this->redirect("Contract", "productchange", ["contract_id" => $id]);
@@ -437,12 +460,12 @@ class ContractController extends mfBaseController
$contract_data['termination_id'] = null;
}
//var_dump($r->links);
// lookup credit contract and if it's missing in $r->links
if(!$this->me->is("Admin")) {
//var_dump($r->links);
// lookup credit contract and if it's missing in $r->links
if (!$this->me->is("Admin")) {
$credit_link = ContractLinkModel::includesContractId($contract->id, ["type" => "credit"]);
if($credit_link) {
if(is_array($r->links) && !array_key_exists($credit_link->id, $r->links)) {
if ($credit_link) {
if (is_array($r->links) && !array_key_exists($credit_link->id, $r->links)) {
$r->links[$credit_link->id] = [];
}
$r->links[$credit_link->id]["action"] = "keep";
@@ -450,7 +473,7 @@ class ContractController extends mfBaseController
}
}
//var_dump($r->links);exit;
//var_dump($r->links);exit;
$new_contract->update($contract_data);
@@ -458,42 +481,39 @@ class ContractController extends mfBaseController
if (!$new_contract_id) {
$this->layout()->setFlash("Neuer Contract konnte nicht gespeichert werden", "error");
if($f == "o") {
if ($f == "o") {
$this->redirect("Order", "productchange", ["contract_id" => $id]);
} else {
$this->redirect("Contract", "productchange", ["contract_id" => $id]);
}
}
// TODO: Contractconfig übernehmen
// TODO: Contractconfig übernehmen
if($contract_cancel_date) {
if ($contract_cancel_date) {
$contract->cancel_date = $contract_cancel_date->getTimestamp();
$contract->edit_by = $this->me->id;
$contract->save();
}
$journal = ContractjournalModel::create([
'contract_id' => $new_contract->id,
'type' => "created_from",
'value' => "productchange",
'text' => "Produkt-/Standortwechsel von Contract ID ".$contract->id
]);
$journal = ContractjournalModel::create(['contract_id' => $new_contract->id,
'type' => "created_from",
'value' => "productchange",
'text' => "Produkt-/Standortwechsel von Contract ID " . $contract->id]);
$journal->save();
if (is_array($r->links) && count($r->links)) {
foreach ($r->links as $link_id => $link_data) {
$action = $link_data["action"];
$cancel_date = false;
if($link_data["cancel_date"]) {
if ($link_data["cancel_date"]) {
try {
$cancel_date = DateTime::createFromFormat("d.m.Y", $link_data["cancel_date"], new DateTimeZone("Europe/Vienna"));
} catch (Exception $e) {
$this->layout()->setFlash("Ungültiges Kündigungsdatum", "error");
if($f == "o") {
if ($f == "o") {
$this->redirect("Order", "productchange", ["contract_id" => $id]);
} else {
$this->redirect("Contract", "productchange", ["contract_id" => $id]);
@@ -505,7 +525,7 @@ class ContractController extends mfBaseController
$old_link = new ContractLink($link_id);
if (!$old_link->id) continue;
// check if link contains this contract
// check if link contains this contract
if ($old_link->contract_id == $contract->id) {
$origin_id = $old_link->origin_contract_id;
$link_contract_id = $old_link->contract_id;
@@ -522,25 +542,23 @@ class ContractController extends mfBaseController
continue;
}
if($action != "cancel" && $old_link->type != "credit") {
$new_link = ContractLinkModel::create([
'contract_id' => $new_link_contract_id,
'origin_contract_id' => $new_link_origin_id,
'type' => $old_link->type,
]);
if ($action != "cancel" && $old_link->type != "credit") {
$new_link = ContractLinkModel::create(['contract_id' => $new_link_contract_id,
'origin_contract_id' => $new_link_origin_id,
'type' => $old_link->type,]);
if (!$new_link->save()) {
$this->layout()->setFlash("Konnte neuen Link nicht speichern", "warn");
}
}
if ($action == "cancel") {
if($cancel_date && $contract_cancel_date) {
// insert cancel_date in old contract
if ($cancel_date && $contract_cancel_date) {
// insert cancel_date in old contract
$lc = new Contract($origin_id);
$lc->cancel_date = $cancel_date->getTimestamp();
$lc->save();
} else {
// leave cancellation for later (when finishing upgrade)
// leave cancellation for later (when finishing upgrade)
$old_link->change_action = "cancel";
if (!$old_link->save()) {
$this->layout()->setFlash("Konnte alten Link nicht speichern", "warn");
@@ -550,42 +568,36 @@ class ContractController extends mfBaseController
}
if ($old_link->type == "credit" && $action == "keep") {
// XXX - if we have finish date then recreate credit contract right now
if($contract_cancel_date) {
// XXX - if we have finish date then recreate credit contract right now
if ($contract_cancel_date) {
$new_credit = ContractModel::createCreditForContract($new_contract);
$new_credit->save();
// create journal for credit
$journal = ContractjournalModel::create([
'contract_id' => $new_credit->id,
'type' => "created_from",
'value' => "productchange",
'text' => "Produkt-/Standortwechsel von Contract ID ".$new_link_origin_id
]);
// create journal for credit
$journal = ContractjournalModel::create(['contract_id' => $new_credit->id,
'type' => "created_from",
'value' => "productchange",
'text' => "Produkt-/Standortwechsel von Contract ID " . $new_link_origin_id]);
$journal->save();
$this->log->debug(print_r($new_credit, true));
// set cancel date for old credit
// set cancel date for old credit
$old_credit = new Contract($origin_id);
$old_credit->cancel_date = $contract_cancel_date->getTimestamp();
$old_credit->save();
// create link to new credit contract
$link = ContractLinkModel::create([
"contract_id" => $new_credit->id,
"origin_contract_id" => $new_contract->id,
"type" => "credit"
]);
// create link to new credit contract
$link = ContractLinkModel::create(["contract_id" => $new_credit->id,
"origin_contract_id" => $new_contract->id,
"type" => "credit"]);
$link->save();
// create upgrade link from old to new credit contract
$link = ContractLinkModel::create([
"contract_id" => $new_credit->id,
"origin_contract_id" => $origin_id,
"type" => "upgrade"
]);
// create upgrade link from old to new credit contract
$link = ContractLinkModel::create(["contract_id" => $new_credit->id,
"origin_contract_id" => $origin_id,
"type" => "upgrade"]);
$link->save();
} else {
@@ -595,27 +607,25 @@ class ContractController extends mfBaseController
}
//var_dump($new_link);exit;
//var_dump($new_link);exit;
}
}
/*
* Upgrade Link erstellen
*/
* Upgrade Link erstellen
*/
$change_type = "upgrade";
/*if($contract->product_id != $new_contract->product_id) {
$change_type = "upgrade";
$change_type = "upgrade";
} elseif($contract->matchcode != $new_contract->matchcode) {
$change_type = "relocation";
$change_type = "relocation";
} else {
$change_type = "productchange";
$change_type = "productchange";
}*/
$link = ContractLinkModel::create([
'contract_id' => $new_contract_id,
'origin_contract_id' => $id,
'type' => $change_type
]);
$link = ContractLinkModel::create(['contract_id' => $new_contract_id,
'origin_contract_id' => $id,
'type' => $change_type]);
$link_id = $link->save();
if (!$link_id) {
@@ -625,19 +635,17 @@ class ContractController extends mfBaseController
$new_contract->sendProductchangeNotification($contract);
$this->layout()->setFlash("Produktwechsel erfolgreich erstellt", "success");
if($f == "o") {
$this->redirect("Order","Upgrades");
if ($f == "o") {
$this->redirect("Order", "Upgrades");
} else {
$this->redirect("Contract", "view", ["contract_id" => $new_contract_id]);
}
}
protected function finishContractAction()
{
if(!$this->me->is(["Admin"])) {
protected function finishContractAction() {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$r = $this->request;
@@ -655,27 +663,25 @@ class ContractController extends mfBaseController
}
$now = new DateTime("now");
$now->setTime(0,0,0);
$now->setTime(0, 0, 0);
$contract->finish_date = $now->getTimestamp();
$contract->finish_date_by = $this->me->id;
try {
$saved = $contract->save();
} catch(Exception $e) {
} catch (Exception $e) {
$saved = false;
}
if(!$saved) {
if (!$saved) {
$this->layout()->setFlash("Contract konnte nicht gespeichert werden", "error");
$this->redirect("Contract", "view", ['contract_id' => $id]);
}
// create Journal
$journal = ContractjournalModel::create([
'contract_id' => $contract->id,
'type' => "contract_finished"
]);
// create Journal
$journal = ContractjournalModel::create(['contract_id' => $contract->id,
'type' => "contract_finished"]);
$journal_id = $journal->save();
$this->layout()->setFlash("Contract erfolgreich fertiggestellt", "success");
@@ -683,32 +689,8 @@ class ContractController extends mfBaseController
}
protected function addAction()
{
if(!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$this->layout()->setTemplate("Contract/Form");
$this->layout()->set("terminations", TerminationModel::getAll());
if ($this->request->origin_contract_id) {
$origin = new Contract($this->request->origin_contract_id);
if ($origin->id) {
$contract = new Contract();
$contract->owner_id = $origin->owner_id;
$contract->billingaddress_id = $origin->billingaddress_id;
$contract->matchcode = $origin->matchcode;
//var_dump($contract);exit;
$this->layout()->set("contract", $contract);
$this->layout()->set("origin_contract_id", $origin->id);
}
}
}
protected function editAction()
{
if(!$this->me->is(["Admin"])) {
protected function editAction() {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$id = $this->request->contract_id;
@@ -727,7 +709,7 @@ class ContractController extends mfBaseController
}
$this->layout()->set("contract", $contract);
//var_dump($contract->owner);exit;
//var_dump($contract->owner);exit;
if ($this->request->f == "view") $this->layout()->set("f", "view");
if ($this->request->f != "view") $this->layout()->set("f", "index");
@@ -742,17 +724,37 @@ class ContractController extends mfBaseController
return $this->addAction();
}
protected function saveAction()
{
if(!$this->me->is(["Admin"])) {
protected function addAction() {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$this->layout()->setTemplate("Contract/Form");
$this->layout()->set("terminations", TerminationModel::getAll());
if ($this->request->origin_contract_id) {
$origin = new Contract($this->request->origin_contract_id);
if ($origin->id) {
$contract = new Contract();
$contract->owner_id = $origin->owner_id;
$contract->billingaddress_id = $origin->billingaddress_id;
$contract->matchcode = $origin->matchcode;
//var_dump($contract);exit;
$this->layout()->set("contract", $contract);
$this->layout()->set("origin_contract_id", $origin->id);
}
}
}
protected function saveAction() {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
$r = $this->request;
//var_dump($r);
//var_dump($r);
/*
* add or edit
*/
* add or edit
*/
$id = $r->id;
if (is_numeric($id) && $id > 0) {
$mode = "edit";
@@ -766,32 +768,32 @@ class ContractController extends mfBaseController
$mode = "add";
}
//var_dump($r->get());exit;
//var_dump($r->get());exit;
$contract_data = [];
$contract_data["owner_id"] = (int)$r->owner_id;
$contract_data["billingaddress_id"] = ($r->billingaddress_id) ? (int)$r->billingaddress_id : $r->owner_id;
$contract_data["product_id"] = (int)$r->product_id;
$contract_data["owner_id"] = (int) $r->owner_id;
$contract_data["billingaddress_id"] = ($r->billingaddress_id) ? (int) $r->billingaddress_id : $r->owner_id;
$contract_data["product_id"] = (int) $r->product_id;
$contract_data["matchcode"] = $r->matchcode;
$contract_data["product_name"] = $r->product_name;
$contract_data["product_info"] = $r->product_info;
$contract_data['amount'] = ($r->amount) ? (float)$r->amount : 1;
$contract_data['amount'] = ($r->amount) ? (float) $r->amount : 1;
$contract_data['vatgroup_id'] = $r->vatgroup_id;
$contract_data['sla_id'] = $r->sla_id;
$contract_data['price'] = (float)Layout::commaToDot($r->price);
$contract_data['price_setup'] = (float)Layout::commaToDot($r->price_setup);
$contract_data['price_nne'] = (float)Layout::commaToDot($r->price_nne);
$contract_data['price_nbe'] = (float)Layout::commaToDot($r->price_nbe);
$contract_data['billing_period'] = (int)$r->billing_period;
$contract_data['billing_delay'] = (int)$r->billing_delay;
$contract_data['price'] = (float) Layout::commaToDot($r->price);
$contract_data['price_setup'] = (float) Layout::commaToDot($r->price_setup);
$contract_data['price_nne'] = (float) Layout::commaToDot($r->price_nne);
$contract_data['price_nbe'] = (float) Layout::commaToDot($r->price_nbe);
$contract_data['billing_period'] = (int) $r->billing_period;
$contract_data['billing_delay'] = (int) $r->billing_delay;
$contract_data['note'] = $r->note;
if($r->termination_id) {
if ($r->termination_id) {
$contract_data["termination_id"] = $r->termination_id;
}
if($r->order_date) {
if ($r->order_date) {
$order_date = new DateTime("@" . $this->dateToTimestamp($r->order_date));
$order_date->setTimezone(new DateTimeZone("Europe/Vienna"));
$order_date->setTime(0, 0, 0);
@@ -800,40 +802,40 @@ class ContractController extends mfBaseController
$contract_data['order_date'] = null;
}
if($r->finish_date) {
if ($r->finish_date) {
$finish_date = new DateTime("@" . $this->dateToTimestamp($r->finish_date));
$finish_date->setTimezone(new DateTimeZone("Europe/Vienna"));
$finish_date->setTime(0, 0, 0);
$contract_data['finish_date'] = $finish_date->getTimestamp();
if($mode == "add") {
if ($mode == "add") {
$contract_data['finish_date_by'] = $this->me->id;
} else {
if($contract->finish_date) {
$contract_finish_date = new DateTime("@".$contract->finish_date);
if ($contract->finish_date) {
$contract_finish_date = new DateTime("@" . $contract->finish_date);
$contract_finish_date->setTimezone(new DateTimeZone("Europe/Vienna"));
if($contract_finish_date->format("Y-m-d") != $finish_date->format("Y-m-d")) {
if ($contract_finish_date->format("Y-m-d") != $finish_date->format("Y-m-d")) {
$contract_data['finish_date_by'] = $this->me->id;
}
} else {
$contract_data['finish_date_by'] = $this->me->id;
}
}
} else {
} else {
$contract_data['finish_date'] = null;
}
if($r->cancel_date) {
if ($r->cancel_date) {
$cancel_date = new DateTime("@" . $this->dateToTimestamp($r->cancel_date));
$cancel_date->setTimezone(new DateTimeZone("Europe/Vienna"));
$cancel_date->setTime(0, 0, 0);
$contract_data['cancel_date'] = $cancel_date->getTimestamp();
if($mode == "add") {
if ($mode == "add") {
$contract_data['cancel_date_by'] = $this->me->id;
} else {
if($contract->cancel_date) {
$contract_cancel_date = new DateTime("@".$contract->cancel_date);
if ($contract->cancel_date) {
$contract_cancel_date = new DateTime("@" . $contract->cancel_date);
$contract_cancel_date->setTimezone(new DateTimeZone("Europe/Vienna"));
if($contract_cancel_date->format("Y-m-d") != $cancel_date->format("Y-m-d")) {
if ($contract_cancel_date->format("Y-m-d") != $cancel_date->format("Y-m-d")) {
$contract_data['cancel_date_by'] = $this->me->id;
}
} else {
@@ -845,8 +847,7 @@ class ContractController extends mfBaseController
}
//var_dump($contract_data);exit;
//var_dump($contract_data);exit;
if ($mode == "add") {
$contract = ContractModel::create($contract_data);
@@ -865,7 +866,7 @@ class ContractController extends mfBaseController
$this->layout()->setFlash("Bitte Produkt auswählen.", "error");
return $this->addAction();
}
if (!in_array($contract_data['billing_period'], [0,1,12])) {
if (!in_array($contract_data['billing_period'], [0, 1, 12])) {
$this->layout()->setFlash("Bitte Rechnungsperiode auswählen.", "error");
return $this->addAction();
}
@@ -879,7 +880,7 @@ class ContractController extends mfBaseController
$contract->product_name = $product->name;
}
//var_dump($contract);exit;
//var_dump($contract);exit;
$contract_id = $contract->save();
@@ -889,43 +890,35 @@ class ContractController extends mfBaseController
return $this->addAction();
}
// create journal
// create journal
if ($mode == "add") {
$journal = ContractjournalModel::create([
'contract_id' => $contract_id,
'type' => "created_from",
'value' => "manual"
]);
$journal = ContractjournalModel::create(['contract_id' => $contract_id,
'type' => "created_from",
'value' => "manual"]);
$journal->save();
}
$this->layout()->setFlash("Vertrag erfolgreich gespeichert.", "success");
/*
* Create link to origin contract if set
*/
* Create link to origin contract if set
*/
if ($mode == "add" && $r->origin_contract_id) {
$origin = new Contract($r->origin_contract_id);
if ($origin->id) {
$link = ContractLinkModel::create([
'contract_id' => $contract_id,
'origin_contract_id' => $origin->id,
'type' => 'link'
]);
$link = ContractLinkModel::create(['contract_id' => $contract_id,
'origin_contract_id' => $origin->id,
'type' => 'link']);
$link_id = $link->save();
if ($link_id) {
$journal = ContractjournalModel::create([
'contract_id' => $contract_id,
'type' => "link",
'value' => $origin->id
]);
$journal = ContractjournalModel::create(['contract_id' => $contract_id,
'type' => "link",
'value' => $origin->id]);
$journal->save();
$ojournal = ContractjournalModel::create([
'contract_id' => $origin->id,
'type' => "link",
'value' => $contract_id
]);
$ojournal = ContractjournalModel::create(['contract_id' => $origin->id,
'type' => "link",
'value' => $contract_id]);
$ojournal->save();
}
}
@@ -956,8 +949,7 @@ class ContractController extends mfBaseController
}
protected function apiAction()
{
protected function apiAction() {
if (!$this->me->is(["Admin", "salespartner", "netowner"])) {
$this->redirect("Dashboard");
}
@@ -990,8 +982,7 @@ class ContractController extends mfBaseController
$this->returnJson($data);
}
private function getContractApi()
{
private function getContractApi() {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
@@ -1018,32 +1009,32 @@ class ContractController extends mfBaseController
private function getContractsApi() {
$owner_id = $this->request->owner_id;
if(!$owner_id) return false;
if (!$owner_id) return false;
$return = [];
$contracts = ContractModel::search(["owner_id" => $owner_id]);
if(!$contracts) {
if (!$contracts) {
header("Content-type: application/json");
echo json_encode([]);
exit;
}
$is_valid_owner = false;
if(!$this->me->is("Admin")) {
foreach($contracts as $contract) {
foreach(ContractLinkModel::includesContractId($contract->id) as $link) {
if($link->type != "credit") continue;
if (!$this->me->is("Admin")) {
foreach ($contracts as $contract) {
foreach (ContractLinkModel::includesContractId($contract->id) as $link) {
if ($link->type != "credit") continue;
$link_contract = $link->contract;
if($link->contract_id == $contract->id) $link_contract = $link->origin;
if($link_contract->owner_id == $this->me->address_id) {
if ($link->contract_id == $contract->id) $link_contract = $link->origin;
if ($link_contract->owner_id == $this->me->address_id) {
$is_valid_owner = true;
break;
}
}
}
if(!$is_valid_owner) {
if (!$is_valid_owner) {
header("Content-type: application/json");
echo json_encode([]);
exit;
@@ -1051,8 +1042,7 @@ class ContractController extends mfBaseController
}
foreach($contracts as $contract) {
foreach ($contracts as $contract) {
$c = get_object_vars($contract->data);
$c["id"] = $contract->id;
$return[] = $c;
@@ -1063,8 +1053,7 @@ class ContractController extends mfBaseController
exit;
}
private function findContractApi()
{
private function findContractApi() {
if (!$this->me->is(["Admin"])) {
$this->redirect("Dashboard");
}
@@ -1104,14 +1093,16 @@ class ContractController extends mfBaseController
$results = [];
// return bootstrap-autocomplete format
// return bootstrap-autocomplete format
foreach ($contracts as $contract) {
//$result = ['value' => $contract->id, 'text' => str_replace("'", "\\'", str_replace(["\n", "\r"], " ",$contract->name))];
$result = ['value' => $contract->id, 'text' => $contract->id . ": " . $contract->product_name . " [" . $contract->matchcode . "] (" . $contract->owner->getCompanyOrName() . ", " . $contract->owner->street . ", " . $contract->owner->zip . " " . $contract->owner->city . ")"];
//$result = ['value' => $contract->id, 'text' => str_replace("'", "\\'", str_replace(["\n", "\r"], " ",$contract->name))];
$result = ['value' => $contract->id,
'text' => $contract->id . ": " . $contract->product_name . " [" . $contract->matchcode . "] (" . $contract->owner->getCompanyOrName() . ", " . $contract->owner->street . ", " . $contract->owner->zip . " " . $contract->owner->city . ")"];
$results[] = $result;
if (count($results) > 15) {
$results[] = ['value' => 0, 'text' => "&nbsp;&nbsp;--> &nbsp;&nbsp;Mehr Suchergebnisse vorhanden. Bitte Suchbegriff genauer definieren &nbsp;&nbsp;<--"];
$results[] = ['value' => 0,
'text' => "&nbsp;&nbsp;--> &nbsp;&nbsp;Mehr Suchergebnisse vorhanden. Bitte Suchbegriff genauer definieren &nbsp;&nbsp;<--"];
break;
}
}
@@ -38,11 +38,17 @@ class TimerecordingReportController extends mfBaseController
$dataweek = $this->request->dataweek;
$datamonth = $this->request->datamonth;
$datayear = $this->request->datayear;
$calendar = $this->request->calendar;
if ($calendar) {
$calendar = 1;
} else {
$calendar = 0;
}
$data = [];
switch ($do) {
case "getTimerecordings":
$return = $this->getTimerecordingsApi($datatype, $dataweek, $datamonth, $datayear);
$return = $this->getTimerecordingsApi($datatype, $dataweek, $datamonth, $datayear, $calendar);
break;
case "getTimerecordingsTimes":
$return = $this->getTimerecordingsTimes($datatype, $dataweek, $datamonth, $datayear);
@@ -60,7 +66,8 @@ class TimerecordingReportController extends mfBaseController
$this->returnJson($data);
}
public function getTimerecordingsApi($datatype, $dataweek, $datamonth, $datayear)
public
function getTimerecordingsApi($datatype, $dataweek, $datamonth, $datayear, $calendar = 0)
{
$mustSeconds = 0;
$isSeconds = 0;
@@ -131,6 +138,9 @@ class TimerecordingReportController extends mfBaseController
$lastdate = strtotime(date("Y-12-31 23:59:59", $datayear));
$daycount = date("t", $datamonth);
$lastdate = strtotime(date("Y-m-d", $lastdate) . ' 23:59:59');
if ($calendar == "1") {
$lastdate = strtotime(" +3 years", $lastdate);
}
$searchArray = ['start' => $firstdate, 'end' => $lastdate];
$timestamp = $firstdate;
@@ -2,7 +2,7 @@
class WarehouseArticleController extends TTCrud {
protected string $headerTitle = 'Artikel';
protected string $createText = 'Artikel erstellen';
protected $createText = 'Artikel erstellen';
// @formatter:off
protected array $columns = [
@@ -32,11 +32,26 @@ class WarehouseArticleController extends TTCrud {
];
// @formatter:on
protected array $additionalJSVariables = ['WAREHOUSE_ADMIN' => true];
protected array $infoMessages = ['create' => 'Artikel wurde erstellt',
'update' => 'Artikel wurde aktualisiert',
'delete' => 'Artikel wurde gelöscht',
'noChanges' => 'Keine Änderungen',];
protected function prepareCrudConfig() {
if (!$this->user->can('WarehouseAdmin')) {
// find column with key actions, cheapestPurchasePrice, warningAmount, criticalAmount and set table to false
foreach ($this->columns as $key => $column) {
if (in_array($column['key'], ['actions', 'cheapestPurchasePrice', 'warningAmount', 'criticalAmount'])) {
$this->columns[$key]['table'] = false;
}
}
$this->createText = false;
$this->additionalJSVariables['WAREHOUSE_ADMIN'] = false;
}
}
protected function beforeUpdate($postData): bool {
(new WarehouseHistoryController)->create($postData, $this->mod);
return true;
@@ -430,6 +430,21 @@ class WarehouseEShopOrderController extends TTCrud {
}
protected function readGLSEmailAction() {
function decode_utf8($str){
# paterns
$err="(=\?.{10,13}q\?_?|\?\=)";
$pat = "/=([0-9A-F]{2})/";
$cha="'.chr(hexdec(";
# erase null signs in string
$str = str_replace("\x00", "", $str);
# to decode with eval and replace
eval("\$str='".
preg_replace($pat,$cha."'$1')).'",$str)
."';");
# return
return $str;
}
$host = '{mail.xinon.at:993/imap/ssl/novalidate-cert}INBOX';
$mbox = imap_open($host, 'eshop-versand@xinon.at', 'savemanfb545aw');
$emails = imap_search($mbox, 'ALL');
@@ -443,7 +458,7 @@ class WarehouseEShopOrderController extends TTCrud {
$overview = imap_fetch_overview($mbox, $email_number, 0);
if (strpos($overview[0]->from, 'gls') === false) {
//continue;
continue;
}
$message = imap_fetchbody($mbox, $email_number, 1); // 1 for plain text part
@@ -468,18 +483,43 @@ class WarehouseEShopOrderController extends TTCrud {
$addressLines = explode("\n", $address);
$addressLine = trim(array_shift($addressLines));
$plzCity = trim(array_shift($addressLines));
$plzCityParts = explode(' ', $plzCity);
$plz = $plzCityParts[0];
if (!isset($plzCityParts[1])) {
continue;
}
echo "---------------------------------------\n\n";
$city = $plzCityParts[1];
// convert special characters to normal ones because i get J=C3=B6ss instead of Jöss
$addressLine = decode_utf8($addressLine);
$city = decode_utf8($city);
echo "Found address: $addressLine, $plz, $city" . PHP_EOL;
// END ADDRESS PARSING
// START TRACKING NUMBER PARSING
$trackingNumber = '';
preg_match('/\d{6,}/', $message, $matches);
// $trackingNumber = '';
// preg_match('/\d{6,}/', $message, $matches);
// if (!empty($matches)) {
// // if addrline includes 27
// if (strpos($addressLine, '27') !== false) {
// var_dump($matches);
// die($message);
// }
//
// $trackingNumber = $matches[0];
// }
// grab tracking number from https://gls-group.eu/track/53158006143 (example) from url
preg_match('/track\/(\d+)/', $message, $matches);
if (!empty($matches)) {
$trackingNumber = $matches[0];
$trackingNumber = $matches[1];
}
echo "Found tracking number: $trackingNumber" . PHP_EOL;
// END TRACKING NUMBER PARSING
@@ -487,11 +527,13 @@ class WarehouseEShopOrderController extends TTCrud {
'deliveryAddressPLZ' => $plz,
'deliveryAddressCity' => $city]);
if (empty($orders)) {
echo "No order found with address: $addressLine, $plz, $city" . PHP_EOL;
continue;
}
// now check if the trackingNumber is already set and if not set it and create a history entry
$order = (array) $orders[0];
echo "Found order with address: " . $order['id'] . PHP_EOL;
//
if ($order['trackingNumber']) {
continue;
@@ -509,15 +551,10 @@ class WarehouseEShopOrderController extends TTCrud {
'user_id' => 1,
'create' => date('U')]);
die();
die($address);
echo "Subject: " . $overview[0]->subject . "\n";
echo "From: " . $overview[0]->from . "\n";
echo "Date: " . $overview[0]->date . "\n";
echo "Message:\n" . $message . "\n\n";
echo "---------------------------------------\n\n";
// echo "Subject: " . $overview[0]->subject . "\n";
// echo "From: " . $overview[0]->from . "\n";
// echo "Date: " . $overview[0]->date . "\n";
// echo "Message:\n" . $message . "\n\n";
}
} else {
echo "No emails found.";
@@ -36,21 +36,24 @@ class WarehouseHistoryController {
if (isset($columns[array_search($item['key'], array_column($columns, 'key'))]['modal']['type'])) {
if($columns[array_search($item['key'], array_column($columns, 'key'))]['modal']['type'] === 'checkbox') {
if ($columns[array_search($item['key'], array_column($columns, 'key'))]['modal']['type'] === 'checkbox') {
$item['old_value'] = $item['old_value'] === '1' ? 'Ja' : 'Nein';
$item['new_value'] = $item['new_value'] === '1' ? 'Ja' : 'Nein';
}
if($columns[array_search($item['key'], array_column($columns, 'key'))]['modal']['type'] === 'select') {
if ($columns[array_search($item['key'], array_column($columns, 'key'))]['modal']['type'] === 'select') {
$column = $columns[array_search($item['key'], array_column($columns, 'key'))];
$item['old_value'] = $column['modal']['items'][array_search($item['old_value'], array_column($column['modal']['items'], 'value'))]['text'];
$item['new_value'] = $column['modal']['items'][array_search($item['new_value'], array_column($column['modal']['items'], 'value'))]['text'];
if (isset($column['modal']['items'][array_search($item['old_value'], array_column($column['modal']['items'], 'value'))]) &&
isset($column['modal']['items'][array_search($item['new_value'], array_column($column['modal']['items'], 'value'))])) {
$item['old_value'] = $column['modal']['items'][array_search($item['old_value'], array_column($column['modal']['items'], 'value'))]['text'];
$item['new_value'] = $column['modal']['items'][array_search($item['new_value'], array_column($column['modal']['items'], 'value'))]['text'];
}
}
}
$item['columnHeader'] = $columns[array_search($item['key'], array_column($columns, 'key'))]['text'];
return $item;
}, $history);
@@ -14,7 +14,8 @@ class WarehouseShippingNoteController extends TTCrud {
['key' => 'deliveryAddressName', 'text' => 'L.-Adr. Name', 'required' => true],
['key' => 'deliveryAddressLine', 'text' => 'L.-Adr.', 'required' => true],
['key' => 'deliveryAddressPLZ', 'text' => 'L.-Adr. PLZ', 'required' => true],
['key' => 'deliveryAddressCity', 'text' => 'L.-Adr. Ort', 'required' => true],
['key' => 'deliveryAddressEMail', 'text' => 'L.-Adr. EMail', 'required' => true, 'table' => false],
['key' => 'note', 'text' => 'Notiz', 'required' => true, 'table' => false],
['key' => 'status',
'text' => 'Status',
'required' => true,
@@ -63,6 +64,7 @@ class WarehouseShippingNoteController extends TTCrud {
self::returnJson(['success' => false, 'message' => 'Status muss "Neu" sein']);
die();
}
$postData['positions'] = json_encode($postData['positions']);
return true;
}
@@ -75,6 +77,7 @@ class WarehouseShippingNoteController extends TTCrud {
"\r"], " ", $address->getCompanyOrName())) . " (" . $address->zip . " " . $address->city . ", " . $address->street . ")" . (($address->customer_number) ? " [" . $address->customer_number . "]" : "")];
return $result;
}
return null;
}
protected function beforeUpdate($postData): bool {
@@ -169,6 +172,40 @@ class WarehouseShippingNoteController extends TTCrud {
self::returnJson($textElements);
}
protected function signAction() {
$id = $this->request->id;
if (strlen($id) < 1) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Lieferschein wurde nicht gefunden']);
}
$shippingNote = WarehouseShippingNoteModel::get($id);
if ($shippingNote->signature || $shippingNote->signatureName) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Lieferschein wurde bereits unterschrieben']);
}
$post = json_decode(file_get_contents('php://input'), true);
$shippingNote = (array) $shippingNote;
$shippingNote['signature'] = $post['signature'];
$shippingNote['signatureName'] = $post['signatureName'];
if (strlen($shippingNote['signature']) < 1 || strlen($shippingNote['signatureName']) < 1) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Unterschrift oder Name fehlt']);
}
try {
$shippingNote['signatureDate'] = date("Y-m-d");
WarehouseShippingNoteModel::update($shippingNote);
self::returnJson(['success' => true, 'message' => 'Unterschrift wurde gespeichert']);
} catch (Exception $e) {
http_response_code(500);
self::returnJson(['success' => false, 'message' => 'Unterschrift konnte nicht gespeichert werden']);
}
}
protected function createPDFAction() {
$id = $this->request->id;
if (strlen($id) < 1) {
@@ -194,9 +231,38 @@ class WarehouseShippingNoteController extends TTCrud {
$position['articleDescription'] = $articlePacket->description === $articlePacket->title ? "" : $articlePacket->description;
$position['articleUnit'] = 'Stk.';
$positions[] = $position;
} elseif (isset($position['articleText'])) {
$position['articleTitle'] = $position['articleText'];
$position['articleDescription'] = "";
$position['articleUnit'] = 'Stk.';
$positions[] = $position;
}
}
// json decode hoursEntries and add to positions
$hoursEntries = json_decode($shippingNote->hoursEntries, true);
foreach ($hoursEntries as $hoursEntry) {
$positions[] = [
'articleTitle' => "Arbeitsstunden",
'articleDescription' => "Mitarbeiter: " . UserModel::getOne($hoursEntry['userId'])->name,
'articleUnit' => 'Std.',
'amount' => $hoursEntry['hourCount'],
'price' => $hoursEntry['hourlyPrice'] * $hoursEntry['hourCount'] ?? 0,
];
if ($hoursEntry['carId']) {
$positions[] = [
'articleTitle' => "Fahrkostenpauschale",
'articleDescription' => "Fahrzeug: " . TimerecordingCarModel::getOne($hoursEntry['carId'])->number_plate,
'articleUnit' => 'Km',
'amount' => $hoursEntry['kilometerCount'],
'price' => 1 * $hoursEntry['kilometerCount'] ?? 0,
];
}
}
$textElements = [];
// parse shippingNote.textElements ({"1":true,"2":true}) to array, fetch each text element and put content into array
$shippingNoteTextElements = json_decode($shippingNote->textElements, true);
@@ -259,4 +325,148 @@ class WarehouseShippingNoteController extends TTCrud {
header('Content-Disposition: inline; filename="' . $filename . '"');
readfile($filename);
}
// TODO: either move this to UserController or make it better
protected function userAutoCompleteAction() {
$users = array_map(function($user) {
return ['value' => $user->id, 'text' => $user->name];
}, UserModel::search(['employee' => true]));
$out = null;
$searchedID = $this->request->searchedID;
if (strlen($searchedID) > 0) {
// find user with value searchedID
$out = array_filter($users, function($user) use ($searchedID) {
return $user['value'] == $searchedID;
});
} else {
$out = array_filter($users, function($user) {
;
return strpos(strtolower($user['text']), strtolower($this->request->q)) !== false;
});
$out = array_slice($out, 0, 10);
}
self::returnJson(array_values($out));
}
//TODO: either move this to TimerecordingCarController or make it better
protected function timerecordingCarAutoCompleteAction() {
$timerecordingCars = array_map(function($timerecordingCar) {
return ['value' => $timerecordingCar->id, 'text' => $timerecordingCar->number_plate . " " . $timerecordingCar->brand . " " . $timerecordingCar->model];
}, TimerecordingCarModel::getAll());
$out = null;
$searchedID = $this->request->searchedID;
if (strlen($searchedID) > 0) {
// find user with value searchedID
$out = array_filter($timerecordingCars, function($timerecordingCar) use ($searchedID) {
return $timerecordingCar['value'] == $searchedID;
});
} else {
$out = array_filter($timerecordingCars, function($timerecordingCar) {
return strpos(strtolower($timerecordingCar['text']), strtolower($this->request->q)) !== false;
});
$out = array_slice($out, 0, 10);
}
self::returnJson(array_values($out));
}
protected function timerecordingCarForUserAction() {
$timerecordingCars = TimerecordingCarModel::getAll();
$out = null;
foreach ($timerecordingCars as $timerecordingCar) {
if ($timerecordingCar->user_id == $this->user->id) {
header('Content-Type: application/json');
die(json_encode(['success' => true, 'id' => $timerecordingCar->id]));
}
}
die(json_encode(['success' => true, 'status' => 'USER_NO_CAR']));
}
//TODO: export this to an api class for openstreetmap
protected function getDistanceAction() {
// $filename = TEMP_DIR . "/DeviceMonitoring/interfacesWithCongestion.json";
// use dir TEMP_DIR /OpenStreetMap/from-to.json to cache the results
$filename = TEMP_DIR . "/OpenStreetMap/" . urlencode($this->request->from) . "-" . urlencode($this->request->to) . ".json";
if (file_exists($filename)) {
$data = file_get_contents($filename);
self::returnJson(json_decode($data, true));
}
$from = $this->request->from;
$to = $this->request->to;
$from = urlencode($from);
$to = urlencode($to);
function geocode($address) {
if ($address === 'Xinon GmbH') {
return [['lat' => 46.99555015, 'lon' => 15.77507876755547]];
}
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://nominatim.openstreetmap.org/search?q=$address&format=json",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"accept: application/json",
"accept-language: de-AT,de;q=0.9,en;q=0.8",
"origin: https://routing.openstreetmap.de",
"referer: https://routing.openstreetmap.de/",
"user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
die(json_encode(['success' => false, 'message' => 'Error while geocoding']));
}
curl_close($curl);
return json_decode($response, true);
}
function route($from, $to) {
$fromData = geocode($from);
$toData = geocode($to);
$fromLat = $fromData[0]['lat'];
$fromLon = $fromData[0]['lon'];
$toLat = $toData[0]['lat'];
$toLon = $toData[0]['lon'];
$url = "https://router.project-osrm.org/route/v1/driving/$fromLon,$fromLat;$toLon,$toLat?overview=false";
$data = json_decode(file_get_contents($url), true);
$distance = $data['routes'][0]['distance'];
return $distance;
}
$fromData = geocode($from);
$toData = geocode($to);
$distance = route($from, $to);
$roundedDistanceKm = round($distance / 1000, 0);
if (!file_exists(dirname($filename))) {
mkdir(dirname($filename), 0777, true);
}
file_put_contents($filename, json_encode(['success' => true, 'distance' => $roundedDistanceKm]));
self::returnJson(['success' => true, 'distance' => $roundedDistanceKm]);
}
}
@@ -7,9 +7,15 @@ class WarehouseShippingNoteModel extends TTCrudBaseModel {
public string $deliveryAddressLine;
public string $deliveryAddressPLZ;
public string $deliveryAddressCity;
public string $deliveryAddressEMail;
public string $note;
public string $status; // 'new'|'accepted'|'invoiced'
public string $positions;
public string $textElements;
public string $hoursEntries;
public ?string $signature;
public ?string $signatureName;
public ?string $signatureDate;
public ?int $eShopOrderId;
public int $create;
public int $createBy;