Files
thetool/application/Order/OrderController.php
2024-08-20 15:37:57 +02:00

1426 lines
46 KiB
PHP

<?php
class OrderController extends mfBaseController {
protected function init() {
$this->needlogin=true;
$me = new User();
$me->loadMe();
$this->me = $me;
$this->layout()->set("me",$me);
if(!$me->is(["Admin", "salespartner"])) {
$this->redirect("Dashboard");
}
}
protected function indexAction() {
$this->layout()->setTemplate("Order/Index");
if($this->request->id && $this->me->is("Admin")) {
$order = new Order($this->request->id);
if($order->id) {
$this->layout()->set("orders", [$order]);
$this->layout()->set("highlight", $this->request->id);
$this->layout()->set("mynetworks", NetworkModel::getAll());
if(!is_array($order->terminations) || !count($order->terminations)) {
$special_orders = [];
$voice_orders = [];
$has_bras = false;
$has_voice = false;
if(!is_array($order->products) || !count($order->products)) {
$this->layout()->set("lonelyOrders", [$order]);
$this->layout()->set("showLonelies", true);
} else {
foreach($order->products as $lop) {
//var_dump($lop);exit;
if(array_key_exists("bras_type", $lop->product->attributes) && $lop->product->attributes['bras_type']) {
$has_bras = true;
}
if(array_key_exists("voip_chan", $lop->product->attributes) && $lop->product->attributes['voip_chan']) {
$has_voice = true;
}
}
if(!$has_bras && !$has_voice) {
$this->layout()->set("special_orders", [$order]);
$this->layout()->set("showSpecial", true);
} elseif($has_voice && !$has_bras) {
$this->layout()->set("voice_orders", [$order]);
$this->layout()->set("showVoice", true);
} else {
$this->layout()->set("lonelyOrders", [$order]);
$this->layout()->set("showLonelies", true);
}
}
}
if($this->request->addJournal) {
$this->layout()->set("addJournal", true);
} else {
$this->layout()->set("showDetail", true);
}
return true;
}
}
$rfilter = $this->request->filter;
if(!$rfilter) {
$rfilter = [];
}
$this->layout->set("filter", $rfilter);
$filter = $this->getPreparedFilter($this->request->filter);
// pagination defaults
$pagination = [];
$pagination['start'] = 0;
$pagination['count'] = 20;
$pagination['maxItems'] = 0;
if(is_numeric($this->request->s)) {
$pagination['start'] = intval($this->request->s);
}
$showLonelies = false;
if($this->request->noTermProducts) {
$showLonelies = true;
}
$my_networks = [];
if($this->me->is("Admin")) {
$my_networks = NetworkModel::getAll();
$this->layout()->set("mynetworks", $my_networks);
/*
if(!count($filter)) {
$this->layout()->set("orders", OrderModel::getAll());
return true;
}*/
if(array_key_exists("network_id", $filter) && $filter['network_id']) {
//$this->layout()->set("orders", OrderModel::search(['network_id' => $filter['network_id']]));
$my_networks = [];
$my_networks[] = new Network($filter['network_id']);
}
} else {
$my_networks = $this->me->myNetworks(["salespartner", "netowner"]);
if(array_key_exists("network_id", $filter)) {
$use_filter_network = false;
foreach($my_networks as $mn) {
if($mn->id == $filter['network_id']) {
$use_filter_network = true;
continue;
}
}
if($use_filter_network) {
$my_networks = [];
$my_networks[] = new Network($filter['network_id']);
}
}
$this->layout()->set("mynetworks", $this->me->my_networks);
}
unset($filter['network_id']);
// get Orders in my networks
//var_dump($my_networks);exit;
$my_network_ids = [];
$orders = [];
//var_dump($this->me->my_networks);exit;
foreach($my_networks as $network) {
$my_network_ids[] = $network->id;
}
$order_search = [
'network_id' => $my_network_ids
];
if(is_array($filter) && count($filter)) {
foreach($filter as $name => $value) {
$order_search[$name] = $value;
}
}
$pagination['maxItems'] = OrderModel::count($order_search);
$orders = OrderModel::search($order_search, $pagination, true);
$showLoneliesCount = false;
foreach(["owner", "owner_address", "partner_number"] as $key) {
if(array_key_exists($key, $filter) && $filter[$key]) {
$showLoneliesCount = true;
break;
}
}
// always show counts if filtering for business customers
if(array_key_exists("customer_type", $filter) && $filter['customer_type'] == "business") {
$showLoneliesCount = true;
}
if($this->request->voiceProductsOnly) {
$showLoneliesCount = true;
$this->layout()->set("showVoice", true);
}
if($this->request->specialProductsOnly) {
$showLoneliesCount = true;
$this->layout()->set("showSpecial", true);
}
if($showLonelies || $showLoneliesCount) {
$userIds = $this->me->getAddressOrParent()->getUserIds();
if(!array_key_exists("network_linked_status", $order_search)) {
$lonelyOrders = [];
unset($order_search["network_id"]);
$order_search['product_id'] = null;
// orders without a product
if($this->me->isAdmin()) {
if(!$this->request->filter['network_id']) {
$lonelies = OrderModel::search($order_search);
}
} else {
$order_search['create_by'] = $userIds;
//var_dump($order_search);exit;
$lonelies = OrderModel::search($order_search);
}
foreach($lonelies as $order) {
if(!array_key_exists($order->id, $orders)) {
$lonelyOrders[$order->id] = $order;
}
}
//var_dump($lonelyOrders);exit;
}
// orders with termination product not requiring termination_id
$order_search['product_id'] = ">0";
$order_search['termination_id'] = null;
if($this->me->isAdmin()) {
if(!$this->request->filter['network_id']) {
$lonelies = OrderModel::search($order_search);
}
} else {
$order_search['create_by'] = $userIds;
$lonelies = OrderModel::search($order_search);
}
$special_orders = [];
$voice_orders = [];
foreach($lonelies as $order) {
// check for voice or special products only
//$this->log->debug("Order id ".$order->id);
/*if($order->id == 38) {
var_dump($order);
exit;
}*/
$has_bras = false;
$has_voice = false;
foreach($order->products as $lop) {
if(is_array($lop->product->attributes) && array_key_exists("bras_type", $lop->product->attributes) && $lop->product->attributes['bras_type']) {
$has_bras = true;
}
if(is_array($lop->product->attributes) && array_key_exists("voip_chan", $lop->product->attributes) && $lop->product->attributes['voip_chan']) {
$has_voice = true;
}
}
if(!$has_bras && !$has_voice) {
$special_orders[] = $order;
continue;
}
if($has_voice && !$has_bras) {
$voice_orders[] = $order;
continue;
}
// check for termination
if(!array_key_exists($order->id, $orders)) {
$o = new Order($order->id);
$add = true;
foreach($o->products as $p) {
$attribs = $p->product->attributes;
if(is_array($attribs) && count($attribs)) {
if(array_key_exists(TT_ATTRIB_TERMINATION_REQUIRED_NAME, $attribs)
&& $attribs[TT_ATTRIB_TERMINATION_REQUIRED_NAME]->value == 1) {
//$this->log->debug("found additional order where termination_required 0");
//$lonelyOrders[$order->id] = $order;
$add = false;
break;
}
} else {
$add = true;
}
}
if($add) {
$lonelyOrders[$order->id] = $order;
}
//$lonelyOrders[$order->id] = $order;
}
}
$this->layout()->set("lonelyOrders", $lonelyOrders);
$this->layout()->set("special_orders", $special_orders);
$this->layout()->set("voice_orders", $voice_orders);
}
$this->layout()->set("showLonelies", $showLonelies);
$this->layout()->set("orders", $orders);
$this->layout()->set("pagination", $pagination);
}
private function getPreparedFilter($filter) {
$new_filter = [];
if(is_array($filter) && count($filter)) {
if(is_numeric($filter['networksection_id']) && $filter['networksection_id']) {
$section = new Networksection($filter['networksection_id']);
if($section->id) {
$filter['network_id'] = $section->network_id;
}
}
if(array_key_exists("termination_status", $filter)) {
$status = $filter['termination_status'];
if($status == "term_connected") {
$new_filter["termination_status_code"] = ">=".TT_TERMSTATUS_CONNECTED;
}
if($status == "building_connected") {
$new_filter["building_status_code"] = ">=".TT_BUILDINGSTATUS_CONNECTED;
$new_filter["termination_status_code"] = "<".TT_TERMSTATUS_CONNECTED;
}
if($status == "pipework_needed") {
$new_filter["building_status_code"] = "<".TT_BUILDINGSTATUS_CONNECTED;
$new_filter["termination_status_code"] = "<".TT_TERMSTATUS_CONNECTED;
}
if($status == "systemowner_action_status" && $this->me->is("Admin")) {
$new_filter['network_linked_status'] = [];
foreach(NetworkModel::getAll() as $network) {
if($network->sytemowner_action_status) {
$new_filter['network_linked_status'][$network->id] = $network->sytemowner_action_status;
}
if(!count($new_filter['network_linked_status'])) {
unset($new_filter['network_linked_status']);
}
}
}
}
$new_filter["waiting"] = false;
if(array_key_exists("finish_date", $filter)) {
if($filter["finish_date"] == "1") {
$new_filter["finish_date"] = true;
} else {
$new_filter["finish_date"] = false;
}
if($filter["finish_date"] == "waiting") {
$new_filter["finish_date"] = false;
$new_filter["waiting"] = true;
unset($filter['finish_date']);
}
}
//var_dump($new_filter);exit;
foreach($filter as $name => $value) {
$new_filter[$name] = $value;
}
} else {
$new_filter["finish_date"] = false;
$new_filter["waiting"] = false;
}
//var_dump($new_filter);exit;
return $new_filter;
}
protected function addAction() {
//var_dump($this->request->filter);exit;
// TODO: filter by network permissions
$this->layout()->setTemplate("Order/Form");
$products = [];
if($this->me->is("Admin")) {
//$this->layout()->set("addresses", AddressModel::search(['parents_only' => 1]));
//$this->layout()->set("products", ProductModel::getActive());
$products = ProductModel::getActive();
$this->layout()->set("terminations", TerminationModel::getAll());
} else {
// get all salespartner addresses of my networks
$network_ids = [];
$addresses = [];
// get users from salespartner addresses of my networks
$users = [];
foreach($this->me->my_networks as $network) {
$network_ids[] = $network->id;
}
// get terminations in my networks
$terms = TerminationModel::search(["network_id" => $network_ids]);
$this->layout()->set("terminations", $terms);
// get products assigned to my networks
$products = [];
foreach(ProductNetworkModel::search(["network_id" => $network_ids]) as $pn) {
if(!$pn->product->active) continue;
if(!array_key_exists($pn->product_id, $products)) {
$products[$pn->product_id] = $pn->product;
}
}
}
$order = $this->layout()->get("order");
if($order) {
foreach($order->products as $op) {
if(!$op->product->active) {
$products[$op->product_id] = $op->product;
}
}
}
$this->layout()->set("products", $products);
$countries = CountryModel::getAll();
$this->layout()->set("countries", $countries);
if($this->request->filter) {
$this->layout()->set("filter", $this->request->filter);
}
if($this->request->noTermProducts) {
$this->layout()->set("noTermProducts", $this->request->noTermProducts);
}
if($this->request->s) {
$this->layout()->set("s", $this->request->s);
}
}
protected function editAction() {
$order_id = $this->request->id;
$order = new Order($order_id);
if(!$order->id) {
$this->layout()->setFlash("Bestellung nicht gefunden.", "error");
$this->redirect("Order");
}
$this->layout()->set("order", $order);
return $this->addAction();
}
protected function setwaitingAction() {
$order_id = $this->request->id;
$order = new Order($order_id);
if(!$order->id) {
$this->layout()->setFlash("Bestellung nicht gefunden.", "error");
$this->redirect("Order");
}
//var_dump($this->request);exit;
if($this->request->unset == "1" && $order->waiting == 1) {
$order->waiting = 0;
$order->save();
} elseif(!$this->request->unset && $order->waiting == 0) {
$order->waiting = 1;
$order->save();
}
$sq = "";
$query = [];
if(is_numeric($this->request->s) && $this->request->s > 0) {
$query["s"] = $this->request->s;
}
if (is_array($this->request->filter)) {
$query["filter"] = $this->request->filter;
}
$qs = http_build_query($query);
$this->layout()->setFlash("Wartestatus erfolgreich gespeichert", "success");
$this->redirect("Order","Index", $qs);
}
protected function upgradesAction() {
$this->layout()->setTemplate("Order/Upgrades");
$rfilter = $this->request->filter;
if(!$rfilter) {
$rfilter = [];
}
$this->layout->set("filter", $rfilter);
$filter = $this->getPreparedFilter($this->request->filter);
// pagination defaults
$pagination = [];
$pagination['start'] = 0;
$pagination['count'] = 20;
$pagination['maxItems'] = 0;
if(is_numeric($this->request->s)) {
$pagination['start'] = intval($this->request->s);
}
unset($filter["finish_date"]);
$upgrade_search = $filter;
$upgrade_search["type"] = "upgrade";
$upgrade_search["contract_creator_address_id"] = $this->me->address_id;
$upgrade_search["finish_date_null_or_gte"] = date("U");
$upgrade_search["price>="] = 0;
$pagination["maxItems"] = ContractLinkModel::countWithContracts($upgrade_search);
$upgrades = ContractLinkModel::searchWithContracts($upgrade_search, $pagination);
$this->layout()->set("upgrades", $upgrades);
$this->layout()->set("pagination", $pagination);
}
protected function addUpgrade() {
//$this->layout()->setTemplate("Order/Productchange");
Helper::renderVue($this, "OrderProductchange", "Neuer Produktwechsel", ["CONTRACT_API_URL" => $this->getUrl("Contract", "api"),
"ADDRESS_API_URL" => $this->getUrl("Address", "api"),
"ORDER_PRODUCTCHANGE_URL" => $this->getUrl("Order", "productchange")]);
}
protected function productchangeAction() {
$this->layout()->setTemplate("Order/ProductchangeForm");
$f = $this->request->f;
if(!$f) {
$f = "c"; // from Contract
}
$this->layout()->set("f", $f);
$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("Order", "addUpgrade");
}
$contract = new Contract($id);
if (!$contract->id) {
$this->layout()->setFlash("Vertrag nicht gefunden", "error");
$this->redirect("Order", "addUpgrade");
}
if($this->me->isAdmin()) {
$this->layout()->set("terminations", TerminationModel::getAll());
} else {
// check permissions
// check if correct network
$my_network_ids = [];
foreach($this->me->my_networks as $network) {
$my_network_ids[] = $network->id;
}
if($contract->termination_id) {
if(!in_array($contract->termination->building->network_id, $my_network_ids)) {
$this->layout()->setFlash("Keine Berechtigung", "error");
$this->redirect("Order", "addUpgrade", ["owner_id" => $contract->owner_id]);
}
}
$terms = TerminationModel::search(["network_id" => $my_network_ids]);
$this->layout()->set("terminations", $terms);
}
$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);
}
}
protected function saveAction() {
$r = $this->request;
//var_dump($r->products);
//var_dump($r);
//exit;
$id = $r->id;
if(is_numeric($id) && $id > 0) {
$mode = "edit";
$order = new Order($id);
if(!$order->id) {
$this->layout()->setFlash("Bestellung nicht gefunden", "error");
$this->redirect("Order");
}
// refuse to save if there is a contract already
if($order->finish_date && is_array($order->contracts) && count($order->contracts)) {
$this->layout()->setFlash("Bestellung kann nicht mehr bearbeitet werden, da sie bereits abgeschlossen und in Verrechnung ist.", "error");
$this->redirect("Order", "edit", ['id' => $order->id]);
}
} else {
$id = false;
$mode = "add";
}
/*
* Contacts/Addresses and Billing data
*/
// validate owner
$owner = false;
$owner_new = false;
if(is_numeric($r->owner_id) && $r->owner_id > 0) {
$owner = new Address($r->owner_id);
if(!$owner->id) {
$this->layout()->setFlash("Ungültiger Vertragsinhaber.", "error");
$this->layout()->set("order", $r);
return $this->add();
}
} else {
$owner_new = true;
if(!$r->owner_company && !($r->owner_firstname && $r->owner_lastname)) {
$this->layout()->setFlash("Fehler in Vertragsinhaber: Firmenname oder Vor- und Nachname benötigt.");
$this->layout()->set("order", $r);
return $this->add();
}
foreach(["street", "zip", "city", "phone", "email", "country_id"] as $required) {
if(!$r->{"owner_$required"}) {
$this->layout()->setFlash("Fehler in Vertragsinhaber: Bitte alle benötigten Felder ausfüllen.");
$this->layout()->set("order", $r);
return $this->add();
}
}
}
// validate billindaddress
$billingaddress = false;
if($r->billingaddress_id) {
// billingaddress can be empty
if(is_numeric($r->billingaddress_id)) {
$billingaddress = new Address($r->billingaddress_id);
if(!$billingaddress->id) {
$this->layout()->setFlash("Ungültiger Rechnungsempfänger.", "error");
$this->layout()->set("order", $r);
return $this->add();
}
}
}
// if any required part of new billingaddress is set
$billingaddress_new = false;
if(!$r->billingaddress_id
&& ($r->billing_company || $r->billing_firstname || $r->billing_lastname
|| $r->billing_street || $r->billing_zip || $r->billing_city || $r->billing_phone || $r->billing_email)
) {
$billingaddress_new = true;
if(!$r->billing_company && !($r->billing_firstname && $r->billing_lastname)) {
$this->layout()->setFlash("Fehler in Rechnungsqmpfänger: Firmenname oder Vor- und Nachname benötigt.");
$this->layout()->set("order", $r);
return $this->add();
}
foreach(["street", "zip", "city", "phone", "email", "country_id"] as $required) {
if(!$r->{"billing_$required"}) {
$this->layout()->setFlash("Fehler in Rechnungsempfänger: Bitte alle benötigten Felder ausfüllen.");
$this->layout()->set("order", $r);
return $this->add();
}
}
}
// validate techcontact
$techcontact = false;
if($r->techcontact_id) {
// techcontact can be empty
if(is_numeric($r->techcontact_id)) {
$techcontact = new Address($r->techcontact_id);
if(!$techcontact->id) {
$this->layout()->setFlash("Ungültiger technischer Kontakt.", "error");
$this->layout()->set("order", $r);
return $this->add();
}
}
}
// if any required part of new techcontact is set
$techcontact_new = false;
if(!$r->techcontact_id
&& ($r->techcontact_company || $r->techcontact_firstname || $r->techcontact_lastname
|| $r->techcontact_street || $r->techcontact_zip || $r->techcontact_city || $r->techcontact_phone || $r->techcontact_email)
) {
$techcontact_new = true;
if(!$r->techcontact_company && !$r->techcontact_firstname && !$r->techcontact_lastname) {
$this->layout()->setFlash("Fehler in technischem Kontakt: Firmenname oder Name benötigt.");
$this->layout()->set("order", $r);
return $this->add();
}
if(!$r->techcontact_phone && !$r->techcontact_mobile && !$r->techcontact_email) {
$this->layout()->setFlash("Fehler in technischem Kontakt: Kontaktmöglichkeit benötigt.");
$this->layout()->set("order", $r);
return $this->add();
}
}
// validate sepa
if(!$r->billing_type) {
$this->layout()->setFlash("Ungültige Verrechnungsart.");
$this->layout()->set("order", $r);
return $this->add();
}
if($r->billing_type == "sepa") {
foreach(['bank', 'owner', 'iban', 'bic'] as $required) {
if(!$r->{"bank_account_$required"}) {
$this->layout()->setFlash("Bitte Bankdaten für SEPA ausfüllen.");
$this->layout()->set("order", $r);
return $this->add();
}
}
}
// create objects for saving (if new) but don't save yet
$owner_data = [];
$billing_data = [];
$techcontact_data = [];
$request = $r->get();
foreach($request as $field => $value) {
$m = [];
if(preg_match('/([a-z0-9]+)_(.+)/i', $field, $m)) {
if($m[1] == "owner" && !$owner) {
$owner_data[$m[2]] = $value;
}
if($m[1] == "billing" && !$billingaddress) {
$billing_data[$m[2]] = $value;
}
if($m[1] == "techcontact" && !$techcontact) {
$techcontact_data[$m[2]] = $value;
}
}
}
if($billingaddress_new) {
if($r->billing_type == "sepa") {
$billing_data['billing_type'] = "sepa";
$billing_data['sepa_date'] = date("U");
} else {
$billing_data['billing_type'] = "invoice";
}
if($r->billing_delivery == "paper") {
$billing_data['billing_delivery'] = "paper";
} else {
$billing_data['billing_delivery'] = "email";
}
$billing_data['bank_account_bank'] = $r->bank_account_bank;
$billing_data['bank_account_owner'] = $r->bank_account_owner;
$billing_data['bank_account_iban'] = $r->bank_account_iban;
$billing_data['bank_account_bic'] = $r->bank_account_bic;
} elseif($owner_new) {
if($r->billing_type == "sepa") {
$owner_data['billing_type'] = "sepa";
$owner_data['sepa_date'] = date("U");
} else {
$owner_data['billing_type'] = "invoice";
}
if($r->billing_delivery == "paper") {
$owner_data['billing_delivery'] = "paper";
} else {
$owner_data['billing_delivery'] = "email";
}
$owner_data['bank_account_bank'] = $r->bank_account_bank;
$owner_data['bank_account_owner'] = $r->bank_account_owner;
$owner_data['bank_account_iban'] = $r->bank_account_iban;
$owner_data['bank_account_bic'] = $r->bank_account_bic;
}
if(!$owner) {
$owner = AddressModel::create($owner_data);
}
if(!$billingaddress) {
$billingaddress = AddressModel::create($billing_data);
}
if(!$techcontact) {
$techcontact = AddressModel::create($techcontact_data);
}
// set sepa date if not yet set and sepa is active
if($billingaddress) {
if($billingaddress->billing_type == "sepa" && !$billingaddress->sepa_date) {
$billingaddress->sepa_date = date("U");
$billingaddress->save();
}
} else {
if($owner->billing_type == "sepa" && !$owner->sepa_date) {
$owner->sepa_date = date("U");
$owner->save();
}
}
// create or save Order object
$order_data = [];
if(is_numeric($r->owner_id)) {
$order_data['owner_id'] = $r->owner_id;
}
if(is_numeric($r->billingaddress_id)) {
$order_data['billingaddress_id'] = $r->billingaddress_id;
}
if(is_numeric($r->techcontact_id)) {
$order_data['techcontact_id'] = $r->techcontact_id;
}
$order_data['partner_number'] = $r->partner_number;
$order_data['allow_contact'] = ($r->allow_contact) ? 1 : 0;
$order_data['allow_spin'] = ($r->allow_spin) ? 1 : 0;
$order_data['note'] = $r->note;
$order_data['order_date'] = ($r->order_date) ? Layout::dateToInt($r->order_date) : date("U");
if($r->finish_after) {
$order_data['finish_after'] = Layout::dateToInt($r->finish_after);
if(!$r->finish_after_comment) {
$this->layout()->setFlash("Bitte Verzögerungsgrund angeben.", "warn");
$this->layout()->set("order", $r);
return $this->add();
}
$order_data['finish_after_comment'] = $r->finish_after_comment;
}
$order_data['upgrade'] = 0;
if($r->upgrade === "1") {
$order_data['upgrade'] = 1;
}
$send_to_bill_email = false;
$order_data['edit_by'] = $this->me->id;
//var_dump($r);
if($r->order_finished == "1" && $this->me->is("Admin", "netoperator")) {
if($r->finish_date) {
$order_data['finish_date'] = Layout::dateToInt($r->finish_date);
} else {
$order_data['finish_date'] = date("U");
}
if(!$order->finish_date) {
// first time finishing order
$send_to_bill_email = true;
}
}
//var_dump($order_data);exit;
if($mode == "add") {
$order = OrderModel::create($order_data);
} else {
$order->update($order_data);
}
/*
var_dump($order);
var_dump($owner);
var_dump($billingaddress);
exit;*/
if(!$owner) {
$this->layout()->setFlash("Fehler beim Speichern", "error");
$this->layout()->set("order", $order);
return $this->add();
}
$new_id = $order->save();
if(!$new_id) {
$this->layout()->setFlash("Fehler beim Speichern", "error");
$this->layout()->set("order", $order);
return $this->add();
}
// save owner and billingaddress if new
if(!$r->owner_id) {
$owner_id = $owner->save();
if(!$owner_id) {
$this->layout()->setFlash("Fehler beim Speichern des Inhabers", "error");
$this->redirect("Order", "edit", ['id' => $new_id]);
}
$order->owner_id = $owner_id;
$order->save();
}
if($billingaddress_new) {
$billingaddress_id = $billingaddress->save();
if(!$billingaddress_id) {
$this->layout()->setFlash("Fehler beim Speichern des Rechnungsempfängers", "error");
$this->redirect("Order", "edit", ['id' => $new_id]);
}
// create addresstype (billing)
$at = AddresstypeModel::create(['address_id' => $billingaddress_id, 'type' => "billing"]);
$at->save();
$order->billingaddress_id = $billingaddress_id;
$order->save();
// add billingaddress as AddressLink to owner
$linkdata = [];
$linkdata['address_id'] = $billingaddress->id;
$linkdata['origin_address_id'] = $order->owner_id;
$linkdata['type'] = "billing";
$link = AddressLinkModel::create($linkdata);
$link->save();
}
if($techcontact_new) {
$techcontact_id = $techcontact->save();
if(!$techcontact_id) {
$this->layout()->setFlash("Fehler beim Speichern des technischen Kontakts", "error");
$this->redirect("Order", "edit", ['id' => $new_id]);
}
// create addresstype (techcontact)
$at = AddresstypeModel::create(['address_id' => $techcontact_id, 'type' => "techcontact"]);
$at->save();
$order->techcontact_id = $techcontact_id;
$order->save();
}
// add techcontact as AddressLink to owner if not exists
if($techcontact->id) {
$link = AddressLinkModel::getFirst(['address_id' => $techcontact->id, 'origin_address_id' => $order->owner_id, 'type' => "techcontact"]);
if(!$link) {
$linkdata = [];
$linkdata['address_id'] = $techcontact->id;
$linkdata['origin_address_id'] = $order->owner_id;
$linkdata['type'] = "techcontact";
$link = AddressLinkModel::create($linkdata);
$link->save();
}
}
$ext_products = false;
$int_products = false;
$ext_products_nbe = 0;
//var_dump($r->products);exit;
// validate and add products
if(is_array($r->products) && count($r->products)) {
foreach($r->products as $pos => $p) {
$orderproduct_id = $p["orderproduct_id"];
//var_dump($r);exit;
//var_dump($pos, $p);exit;
if(!$p["product_id"]) {
continue;
}
if($p['delete'] == 1) {
$product = new OrderProduct($orderproduct_id);
$product->delete();
continue;
}
$prod = new Product($p['product_id']);
if(!$prod->id) {
$this->log->warn(__CLASS__."::save() Invalid product: ".$p['product_id']);
continue;
}
$product_data = [];
$product_data["order_id"] = $new_id;
$product_data["product_id"] = $p["product_id"];
$product_data['amount'] = (!empty($p['amount'])) ? $p['amount'] : 1;
$product_data["pos"] = ($p["pos"]) ? $p['pos'] : $order->getNewPos();
$product_data["description"] = $p["description"];
$product_data["price"] = trim($p["price"]) ? Layout::commaToDot(trim($p["price"])) : 0;
$product_data["price_setup"] = trim($p["price_setup"]) ? Layout::commaToDot(trim($p["price_setup"])) : 0;
if($this->me->is("Admin") && $p["price_nne"]) {
$product_data["price_nne"] = Layout::commaToDot($p["price_nne"]);
} else {
$product_data["price_nne"] = $prod->price_nne;
}
if($this->me->is("Admin") && strlen($p["price_nbe"])) {
$product_data["price_nbe"] = Layout::commaToDot($p["price_nbe"]);
} else {
$product_data["price_nbe"] = $prod->price_nbe;
}
$product_data["billing_delay"] = ($p["billing_delay"]) ? $p["billing_delay"] : 0;
if($product_data["billing_delay"] > 6) {
$product_data["billing_delay"] = 6;
}
$product_data["billing_period"] = $p["billing_period"];
$product_data["contract_term"] = $p["contract_term"];
$product_data['upgrade'] = $order_data['upgrade'];
$require_term = false;
if(array_key_exists(TT_ATTRIB_TERMINATION_REQUIRED_NAME, $prod->attributes) && $prod->attributes[TT_ATTRIB_TERMINATION_REQUIRED_NAME]->value == 1) {
//var_dump($prod->attributes);
$require_term = true;
if(!$p['termination_id']) {
$this->layout()->setFlash("Ein oder mehrere Produkte erfordern Anschluss.", "warn");
continue;
}
$product_data['termination_id'] = $p['termination_id'];
$order_termination_id = $p['termination_id'];
} else {
$product_data['termination_id'] = null;
}
if(array_key_exists(TT_ATTRIB_VOICENUMBER_REQUIRED_NAME, $prod->attributes) && $prod->attributes[TT_ATTRIB_VOICENUMBER_REQUIRED_NAME]->value == 1) {
$voicenumbers = [];
//var_dump($p);exit;
//if($p["voicenumber_custom"]);
$numbers = [];
if(array_key_exists("voicenumber", $p) && is_array($p["voicenumber"]) && count($p["voicenumber"])) {
$numbers = $p["voicenumber"];
}
if(array_key_exists("voicenumber_custom", $p) && is_array($p["voicenumber_custom"]) && count($p["voicenumber_custom"])) {
$numbers = array_merge($numbers, $p["voicenumber_custom"]);
}
foreach($numbers as $number) {
if(!$number) continue;
$number = preg_replace('/\D/', '', trim($number));
if(substr($number, 0, 2) == "00") $number = "+" . substr($number, 2);
if(preg_match('/^0[^0]/', $number)) {
$number = "+43" . substr($number, 1);
}
if(substr($number, 0, 1) != "+") $number = "+$number";
//if($number && !in_array($number, $voicenumbers)) $voicenumbers[] = $number;
$voicenumbers[] = $number;
}
if($voicenumbers) {
$product_data['voicenumber'] = json_encode($voicenumbers);
if($p["voiceplan_id"]) {
$product_data["voiceplan_id"] = $p["voiceplan_id"];
} else {
$this->layout()->setFlash("Bitte Sprachtarif bei allen Rufnummern eintragen", "error");
}
//var_dump($product_data);exit;
}
//var_dump($product_data);exit;
} else {
$product_data['voicenumber'] = null;
}
$product_data['edit_by'] = $this->me->id;
if(!$orderproduct_id) {
$product = OrderProductModel::create($product_data);
} else {
$product = new OrderProduct($orderproduct_id);
$product->update($product_data);
}
//var_dump($product);
if(!$product->save()) {
$this->log->warn("Unable to save OrderProduct:".print_r($product, true));
}
// if product is not external and customer is new, create customer_number and service pin
if($prod->external) {
$ext_products = true;
$ext_product_owner_id = $prod->external_id;
$ext_products_nbe += $product_data["price_nbe"];
} else {
$int_products = true;
}
}
//exit;
if(!$ext_products && !$owner->customer_number) {
$last_num = AddressModel::getLastCustomerNumber();
$this->log->debug("last_num: $last_num");
if($last_num) {
$new_num = $last_num + 1;
} else {
$new_num = TT_FIRST_CUSTNUM;
}
if(!AddressModel::search(['customer_number' => $new_num])) {
$owner->customer_number = $new_num;
$owner->save();
}
}
// generate and send Service PIN, only if:
// - owner does not have a Service PIN yet
// - there are no external products
// - owner_id was not set before or owner_id wasn't changed
// TODO: move this to Order class
if(!$ext_products && !$owner->spin && (!property_exists($order->_old_data, "owner_id") || $order->owner_id == $order->_old_data->owner_id)) {
$this->log->debug(__CLASS__."::save(): creating new SPIN for ".$owner->getCompanyOrName()." (".$owner->id.")");
$spin = $owner->generateServicePin();
if($spin && !AddressModel::search(['spin' => $spin])) {
$owner->spin = $spin;
if($owner->save()) {
$order->sendSpinEmail();
}
}
} else {
$this->log->debug(__CLASS__."::save(): NOT creating new SPIN for ".$owner->getCompanyOrName()." (".$owner->id."): SPIN exists or owner of Order was changed or external products");
}
if($mode == "add" && $order->upgrade) {
// send upgrade ticket
$order->sendUpgradeEmail();
}
}
//var_dump($_FILES['OrderFileUpload']);exit;
// handle file upload
if(array_key_exists("OrderFileUpload", $_FILES) && !$_FILES['OrderFileUpload']['error']) {
$upload_error = false;
//var_dump($_FILES);exit;
$upload = new mfUpload("OrderFileUpload");
$upload->setSavepath(MFUPLOAD_FILE_SAVE_PATH."/documents");
if(!$upload->getSize()) {
$this->layout()->setFlash("Dateiupload fehlgeschlagen: Dokument darf nicht leer sein!", "warn");
$upload_error = true;
}
if(substr(strtolower($upload->getFilename()), -3, 3) == "pdf" && !$upload->validatePDF()) {
$this->layout()->setFlash("Dateiupload fehlgeschlagen: PDF-Validierung fehlgeschlagen!", "warn");
$upload_error = true;
}
if(!$upload_error) {
try {
$upload->save();
} catch(Exception $e) {
$this->layout()->setFlash("Dateiupload fehlgeschlagen", "warn");
$upload_error = true;
}
}
if(!$upload_error) {
$file_data = [];
$file_data['name'] = ($r->file_name) ? $r->file_name : $upload->getOriginalFilename();
$file_data['filename'] = ($r->file_filename) ? $r->file_filename : $upload->getOriginalFilename();
$file_data['subfolder'] = "documents";
$file_data['store_filename'] = $upload->getFilename();
$file_data['orig_filename'] = $upload->getOriginalFilename();
$file = FileModel::create($file_data);
$file_id = $file->save();
if(!$file_id) {
$this->layout()->setFlash("Dateiupload fehlgeschlagen", "warn");
unlink($upload->getSavepath()."/".$upload->getFilename());
} else {
$of = [];
$of['order_id'] = $new_id;
$of['file_id'] = $file_id;
$of['name'] = $file->name;
$of['description'] = $r->file_description;
$orderfile = OrderFileModel::create($of);
if(!$orderfile->save()) {
$file->delete();
unlink($upload->getSavepath()."/".$upload->getFilename());
$this->layout()->setFlash("Dateiupload fehlgeschlagen", "warn");
} else {
// send email based on file type
$order->sendFileuploadEmail($orderfile);
}
}
}
}
// send order finish email
if($send_to_bill_email) {
if($ext_products) {
if(!$order->sendExtBillinfoEmail(new Address($ext_product_owner_id))) {
$this->layout()->setFlash("Beim Senden der externen Billing Benachrichtigung ist ein Fehler aufgetreten.", "warning");
}
if($ext_products_nbe) {
// only send nbe mail if there is nbe
if(!$order->sendExtBillNbeInfoEmail(new Address($ext_product_owner_id))) {
//$this->layout()->setFlash("Beim Senden der internen Billing NBE Benachrichtigung ist ein Fehler aufgetreten.", "warning");
}
}
}
/*if($int_products) {
if(!$order->sendIntBillinfoEmail()) {
$this->layout()->setFlash("Beim Senden der Billing Benachrichtigung ist ein Fehler aufgetreten.", "warning");
}
}*/
if($int_products && $ext_products) {
//$this->layout()->setFlash("Eigene und Fremdprodukte gefunden, nur interne Billing Benachrichtigung verschickt.", "warning");
}
}
$sq = "";
$query = [];
if($r->s) {
$query['s'] = $r->s;
}
if($r->noTermProducts) {
$query["noTermProducts"] = $r->noTermProducts;
}
if($r->filter) {
$query["filter"] = $r->filter;
}
if($r->return != "index") {
$query['id'] = $new_id;
}
$qs = http_build_query($query);
$this->layout()->setFlash("Bestellung erfolgreich gespeichert.", "success");
if($r->return == "index") {
$this->redirect("Order", "Index", $qs, "order=$new_id-details");
} else {
$this->redirect("Order", "edit", $qs);
}
}
protected function saveVorortterminAction() {
if(!$this->me->is(["Admin","salespartner"])) {
$this->layout()->setFlash("Keine Berechtigung", "error");
$this->redirect("Order");
}
$r = $this->request;
$order_id = $r->id;
if(!is_numeric($order_id) || $order_id < 1) {
$this->returnJson(["status" => "error", "order" => ['id' => $order_id]]);
}
$order = new Order($order_id);
if(!$order->id) {
$this->returnJson(["status" => "error", "order" => ['id' => $order_id]]);
}
$date = $r->install_date;
if($date === null) {
$this->returnJson(["status" => "error", "order" => ['id' => $order_id]]);
}
if($date) {
$date = Layout::dateToInt($date);
if(!$date) {
$this->returnJson(["status" => "error", "order" => ['id' => $order_id]]);
}
} elseif($date === "") {
$date = null;
}
if($date && !$order->install_date && is_array($order->terminations) && count($order->terminations)) {
$term = $order->terminations[0];
if(!$term->getWorkflowvalue("pop_id")) {
$this->returnJson(["status" => "error", "msg" => "Kein POP im Leitungsbau !", "order" => ['id' => $order_id]]);
}
}
$order->install_date = $date;
$order->cpeprovisioning_enabled = ($date) ? 1 : 0;
$order->save();
$this->returnJson(["status" => "OK", "order" => ['id' => $order_id, 'date' => ($date) ? date('d.m.Y', $date) : ""]]);
}
protected function saveCpeprovisioningAction() {
if(!$this->me->is(["Admin","salespartner"])) {
$this->layout()->setFlash("Keine Berechtigung", "error");
$this->redirect("Order");
}
$r = $this->request;
$order_id = $r->id;
if(!is_numeric($order_id) || $order_id < 1) {
$this->returnJson(["status" => "error", "msg" => "Fehler beim Speichern!", "order" => ['id' => $order_id]]);
}
$order = new Order($order_id);
if(!$order->id) {
$this->returnJson(["status" => "error", "msg" => "Fehler beim Speichern!", "order" => ['id' => $order_id]]);
}
$enabled = $r->enabled;
if($enabled === null || !is_numeric($enabled)) {
$this->returnJson(["status" => "error", "msg" => "Fehler beim Speichern!", "order" => ['id' => $order_id]]);
}
$term = $order->terminations[0];
if($enabled && (!$term->getWorkflowvalue("pop_id") && !$term->getWorkflowvalue("ist_pop_id"))) {
$this->returnJson(["status" => "error", "msg" => "Kein POP im Leitungsbau !", "order" => ['id' => $order_id, "enabled" => 0]]);
}
$order->cpeprovisioning_enabled = ($enabled) ? 1 : 0;
$order->save();
$this->returnJson(["status" => "OK", "order" => ['id' => $order_id]]);
}
protected function deleteAction() {
if(!$this->me->is(["Admin","salespartner"])) {
$this->layout()->setFlash("Keine Berechtigung", "error");
$this->redirect("Order");
}
$id = $this->request->id;
$order = new Order($id);
if(!$order->id || $order->id != $id) {
$this->layout()->setFlash("Bestellung nicht gefunden.", "error");
$this->redirect("Order");
}
if(!$this->me->is("Admin")) {
$my_network_ids = [];
foreach($this->me->my_networks as $network) {
$my_network_ids[] = $network->id;
}
if(!in_array($order->terminations[0]->building->network_id, $my_network_ids) ) {
if($order->create_by != $this->me->id) {
$this->layout()->setFlash("Keine Berechtigung", "error");
$this->redirect("Order");
}
}
}
$order->deleteFiles();
$order->deletePositions();
$order->delete();
$this->layout()->setFlash("Bestellung gelöscht", "success");
$this->redirect("Order");
}
protected function downloadServicePinAction() {
$order_id = $this->request->id;
if(!is_numeric($order_id) || !$order_id) {
$this->layout->setFlash("Adresse nicht gefunden!");
$this->redirect("Order");
}
$order = new Order($order_id);
if(!$order->id) {
$this->layout->setFlash("Bestellung nicht gefunden!");
$this->redirect("Order");
}
$owner = $order->owner;
if(!$owner->customer_number || !$owner->spin) {
$this->layout->setFlash("Vertragsinhaber hat keine Kundennummer oder Service PIN!", "error");
$this->redirect("Order");
}
$pdf_vars = [
'order' => $order,
'owner' => $owner
];
if(TT_CUSTOM_ORDER_PDF_PER_NETOWNER) {
$terms = $order->terminations;
if(is_array($terms) && count($terms) && $terms[0]->id) {
$netowner = $terms[0]->building->network->owner;
} else {
$netowner = new Address(TT_CUSTOM_ORDER_PDF_DEFAULT_OWNER_ID);
}
$pdf_vars['netowner'] = $netowner;
}
// render service pin PDF
$pdf = new PdfForm("Emailtemplates/attachments/new_order_spin.pdf", $pdf_vars);
$pdfpath = $pdf->render();
$tvalue = $pdf->getReturnedValues();
$pdfname = $tvalue['filename'];
$pdf->download($pdfname);
}
protected function sendServicePinAction() {
$order_id = $this->request->id;
if(!is_numeric($order_id) || !$order_id) {
$this->layout->setFlash("Adresse nicht gefunden!");
$this->redirect("Order");
}
$order = new Order($order_id);
if(!$order->id) {
$this->layout->setFlash("Bestellung nicht gefunden!");
$this->redirect("Order");
}
$owner = $order->owner;
if(!$owner->customer_number || !$owner->spin) {
$this->layout->setFlash("Vertragsinhaber hat keine Kundennummer oder Service PIN!", "error");
$this->redirect("Order");
}
if($order->sendSpinEmail()) {
$this->layout()->setFlash("Service PIN wurde erfolgreich versendet.", "success");
} else {
$this->layout()->setFlash("Fehler beim SPIN Versand!", "success");
}
$this->redirect("Order");
}
}