display(); } function addUserPluginVersion() { $pluginId = (int)trim(JRequest::getVar('useraddpluginid')); $pluginVersion = trim(JRequest::getVar('useraddpluginversion')); $pluginRemarks = trim(JRequest::getVar('useraddpluginremarks')); $userId = (int)trim(JRequest::getVar('userId')); $modelUser =& $this->getModel('user'); if ($userId && $pluginId && $pluginVersion) { $modelUser->SetId($userId); $modelUser->addPluginVersion($pluginId, $pluginVersion, $pluginRemarks); } $this->display(); } function deleteUserPluginVersion() { $pluginVersionId = (int)trim(JRequest::getVar('pluginVersionId')); $userId = (int)trim(JRequest::getVar('userId')); $modelUser =& $this->getModel('user'); if ($userId && $pluginVersionId) { $modelUser->SetId($userId); $modelUser->deletePluginVersion($pluginVersionId); } $this->display(); } function changeDefaultPluginVersion() { $modelPlugins =& $this->getModel('plugins'); $pluginId = (int)trim(JRequest::getVar('useraddpluginid')); $pluginVersion = trim(JRequest::getVar('useraddpluginversion')); if ($pluginId) { $modelPlugins->changeDefaultVersion($pluginId, $pluginVersion); } $this->display(); } function parse_csv($file, $comma = ',', $quote = '"', $newline = "\n") { $db_quote = $quote . $quote; // Clean up file $file = trim($file); $file = str_replace("\r\n", $newline, $file); $file = str_replace($db_quote, '"', $file); // replace double quotes with " HTML entities $file = str_replace(',",', ',,', $file); // handle ,"", empty cells correctly $file .= $comma; // Put a comma on the end, so we parse last cell $inquotes = false; $start_point = 0; $row = 0; for ($i = 0; $i < strlen($file); $i++) { $char = $file[$i]; if ($char == $quote) { if ($inquotes) { $inquotes = false; } else { $inquotes = true; } } if (($char == $comma or $char == $newline) and !$inquotes) { $cell = substr($file, $start_point, $i - $start_point); $cell = str_replace($quote, '', $cell); // Remove delimiter quotes $cell = str_replace('"', $quote, $cell); // Add in data quotes $data[$row][] = $cell; $start_point = $i + 1; if ($char == $newline) { $row++; } } } return $data; } function groupcreation() { $texto = JRequest::getVar('memousers'); $users = $this->parse_csv($texto); $modelUser =& $this->getModel('user'); $curUser = & $modelUser->getData(); $franchiseId = $curUser->franchise; if ($franchiseId == 0) { JError::raise(E_NOTICE, JText::_('Error'), JText::_('Couldn\'t find franchise from current user')); $this->display(); return; } $groupName = JRequest::getVar('txtgroup'); $selManager = JRequest::getVar('selManager'); if (!$selManager) { JError::raise(E_NOTICE, JText::_('Error'), JText::_('No manager selected')); $this->display(); return; } $modelGroup =& $this->getModel('group'); $group =& $modelGroup->getGroupByName($groupName); if ($group) { $groupId = $group->id; $oldManager = $group->manager; } if (!$groupId || $oldManager != $selManager) { $dataGroup = array(); if ($groupId) $dataGroup['id'] = $groupId; $dataGroup['name'] = $groupName; $dataGroup['franchise'] = $franchiseId; $dataGroup['manager'] = $selManager; $modelGroup->store($dataGroup); $groupId = $dataGroup['id']; if ($groupId == 0) { JError::raise(E_NOTICE, JText::_('Error'), JText::_('Couldn\'t create group. Duplicated name')); $this->display(); return; } } $data = array(); $data['franchise'] = $franchiseId; $data['group'] = $groupId; $usersCreated = 0; foreach ($users as $user) { if (count($user) != 4) continue; $username = $user[0]; $pass = $user[1]; $name = $user[2]; $email = $user[3]; $data['id'] = null; $data['name'] = $name; $data['username'] = $username; $data['email'] = $email; $data['password'] = $pass; $data['password2'] = $pass; $modelUser =& $this->getModel('user'); $modelUser->SetId(null); // Comprobamos si ya existe algún usuario con ese nombre de usuario o e-mail $res = array(); $modelUser->checkUserData($data, $res); $good = true; if (!$res['username']) { JError::raise(E_NOTICE, JText::_('Error'), $data['username'] . ": " . JText::_('Repeated username. Please enter a different one')); $good = false; continue; } if (!$res['email']) { JError::raise(E_NOTICE, JText::_('Error'), $data['email'] . ": " . JText::_('Repeated email. Please enter a different one')); $good = false; continue; } if ($good) { if (!$modelUser->store($data)) { JError::raise(E_NOTICE, JText::_('Error'), $data['username'] . ": " . JText::_('Error creating user')); continue; } $usersCreated++; } } echo "$usersCreated users created"; $this->display(); } function recoversettings() { $modelSettings =& $this->getModel('settings'); $modelSettings->recoverBackup(); $this->display(); } function savesettings() { $modelSettings =& $this->getModel('settings'); $settings = trim(JRequest::getVar('memosettings')); $modelSettings->storeAsText($settings); $this->display(); } function saveholidays() { $modelHolidays =& $this->getModel('holidays'); $holidays = trim(JRequest::getVar('memoholidays')); $modelHolidays->storeAsText($holidays); $this->display(); } function addSelectedModelToUser() { $modelUserPrefabModel =& $this->getModel('userprefabmodel'); $userId = trim(JRequest::getVar('userid')); $modelId = trim(JRequest::getVar('availablemodels')); if ($userId && $modelId) { $data = array(); $data['userid'] = $userId; $data['prefabmodel'] = $modelId; $modelUserPrefabModel->store($data); } $this->display(); } function removeSelectedModelFromUser() { $modelUserPrefabModel =& $this->getModel('userprefabmodel'); $userId = trim(JRequest::getVar('userid')); $modelId = trim(JRequest::getVar('selectedmodels')); if ($userId && $modelId) { $data = array(); $data['userid'] = $userId; $data['prefabmodel'] = $modelId; $modelUserPrefabModel->deleteByData($data); } $this->display(); } function saveCustomModel() { $modelId = trim(JRequest::getVar('modelid')); $modelName = trim(JRequest::getVar('modelname')); $modelTemplate = trim(JRequest::getVar('modeltemplate')); if ($modelName && $modelTemplate) { $modelCustomModel =& $this->getModel('custommodel'); $data = array(); if ($modelId) $data['id'] = $modelId; $data['name'] = $modelName; $data['template'] = $modelTemplate; $modelCustomModel->store($data); JRequest::setVar('modelid', $data['id']); } $this->display(); } function addTemplate() { $templateName = trim(JRequest::getVar('templatename')); if ($templateName) { $modelTemplate =& $this->getModel('template'); $data = array(); $data['name'] = $templateName; $modelTemplate->store($data); } $this->display(); } function saveReceiptData() { $paymentDate = JRequest::getVar('receiptpaydate'); $modelReceipt =& $this->getModel('receipt'); $receiptId = JRequest::getVar('receiptId'); $modelReceipt->SetId($receiptId); $data = array(); $data['id'] = $receiptId; if ($paymentDate) { $paymentDate = str_replace('-', '/', $paymentDate); $month = 0; $year = 0; $hour = 0; $minute = 0; $assigned = sscanf($paymentDate, "%d/%d/%d %d:%d", $day, $month, $year, $hour, $minute); if ($assigned >= 3) $data['paid_date'] = sprintf("%d-%d-%d", $year, $month, $day); } $modelReceipt->store($data); $this->display(); } function getInsoleCategories() { $modelSettings =& $this->getModel('settings'); $insoleCategories = array(); $catCount = (int)$modelSettings->getVar('insoleCategories.count', 0); for ($i = 0; $i < $catCount; $i++) { $name = $modelSettings->getVar("insoleCategorie$i.name", ''); $options = explode(',', $modelSettings->getVar("insoleCategorie$i.insoleOptionsValues", '')); $productOptions = explode(',', $modelSettings->getVar("insoleCategorie$i.productValues", '')); $insoleCategories[$i] = array('name' => $name, 'options' => $options, 'productOptions' => $productOptions); } return $insoleCategories; } public function scheduleOrderProduction($orderId, $checked_date) { return $this->_scheduleOrderProduction($orderId, $checked_date); } /** * Realiza la planificación de producción para un pedido * @param $orderId Id del pedido * @param $checked_date Fecha de revisión del pedido */ protected function _scheduleOrderProduction($orderId, $checked_date) { $orderId = (int)$orderId; if (!$orderId) return; $modelOrder =& $this->getModel('order'); $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); if ($order->payment_methodnameid == 'TEST') // Doble chequeo de que no se planifiquen los pedidos de test return; $insoleCategories = $this->getInsoleCategories(); $orderDistribution = $modelOrder->getOrderDistribution($insoleCategories); // Calculamos la fecha de fabricación del pedido $manufacturing_date = $this->getEstimatedManufacturingDate($orderDistribution, $checked_date); // Ponemos la fecha de fabricacion al pedido $data = array(); $data['id'] = $orderId; $data['manufacturing_date'] = $manufacturing_date; $modelOrder->store($data); $this->checkBatchDeliveryEstimation($order->batch); } function checkBatchDeliveryEstimation($batchId) { $modelBatch =& $this->getModel('batch'); $batchId = (int)$batchId; if (!$batchId) return; $modelBatch->SetId($batchId); $batch =& $modelBatch->getData(); $batchPaid = ($batch->payment_date != null); $allBatchChecked = $modelBatch->isBatchChecked(); // Calcularemos la fecha de entrega si el lote está pagado // y todos los pedidos revisados if (!$batchPaid || !$allBatchChecked) return; // Calculamos la fecha de entrega del lote como el maximo entre la fecha de fabricacion +1 // y la fecha de revision +5 $batchOrders =& $modelBatch->getOrders(); $insoleCategories = $this->getInsoleCategories(); $batchOrderDistribution = $modelBatch->getOrderDistribution($insoleCategories); // Calculamos la fecha de fabricacion mas alejada en el tiempo $last_manufacturing_date = null; foreach ($batchOrders as $order) { // Calculamos la fecha de fabricación del pedido $manufacturing_date = $order->manufacturing_date; if ($last_manufacturing_date === null) $last_manufacturing_date = $manufacturing_date; else { if (strtotime($manufacturing_date) > strtotime($last_manufacturing_date)) $last_manufacturing_date = $manufacturing_date; } } if (!$last_manufacturing_date) { $dateNow = new JDate(); $last_manufacturing_date = $dateNow->toMySQL(); } $dataBatch = array(); $dataBatch['id'] = $batchId; $dataBatch['est_shipping_date'] = $this->getEstimatedDeliveryDate($batchOrderDistribution, $last_manufacturing_date); $modelBatch->store($dataBatch); // Mandamos un e-mail y un SMS con la fecha de entrega $userId = $batch->payment_user; if ($userId) { // Recogemos información sobre el usuario del pedido $modelUser =& $this->getModel('user'); $modelUser->SetId($userId); $userObj =& $modelUser->getData(); // Mandamos un SMS sólo si estamos en el servidor de deployment if ($_SERVER['SERVER_NAME'] == 'www.tecnoinsole.com' || $_SERVER['SERVER_NAME'] == 'new.tecnoinsole.com'|| $_SERVER['SERVER_NAME'] == 'app.tecnoinsole.com') { $phone = trim($userObj->phone); $delimiters = array(" ", "/", "-"); $phone = str_replace($delimiters, " ", $phone); $phoneArray = explode(" ", $phone); foreach ($phoneArray as $phoneNumber) { $phoneNumber = trim($phoneNumber); if (!$phoneNumber) continue; // Comprobacion de que es un número móvil if ($phoneNumber{0} == '6' && strlen($phoneNumber) == 9) { require_once(JPATH_BASE . "/components/com_vxc/assets/mensatek/mensatek.inc"); $date = new JDate($dataBatch['est_shipping_date']); $date->setOffset(date('Z') / 3600.0); $fechaS = $date->toFormat('%d/%m/%Y'); $Mensatek = new cMensatek("info@tecnoinsole.com", "wethonsed"); $variables = array( "Remitente" => "TecnoInsole", //Remitente que aparece, puede ser número de móvil o texto (hasta 11 caracteres) "Destinatarios" => $phoneNumber, // Destinatarios del mensaje, si es más de 1 sepárelos por punto y coma "Mensaje" => "Su lote de plantillas numero " . $batchId . " tiene programada la entrega el dia " . $fechaS, //Mensaje, si se envían más de 160 caracteres se enviará en varios mensajes "Flash" => 0, // Formato Flash "Report" => 1, //Report de entrega al correo electrónico por defecto "Descuento" => 0 // Si utiliza descuento o no ); // Ejemplo de envío $res = $Mensatek->enviar($variables); break; } } } // Mandamos un e-mail // Preparamos la direccion de e-mail $email = trim($userObj->invoice_email); if (!$email) $email = trim($userObj->email); if ($email) // Si tiene direccion de e-mail { $mailer =& JFactory::getMailer(); $sender = array($userObj->franchiseemail, $userObj->franchisename); $mailer->setSender($sender); $mailer->IsHTML(true); $mailer->ClearAllRecipients(); $mailer->addRecipient($email); $subject = $userObj->franchisename . ": "; //$subject .= JText::sprintf("BADORDER_SUBJECT_MAIL",$id); $subject .= 'Fecha estimada de entrega del lote ' . $batchId; $mailer->setSubject($subject); $date = new JDate($dataBatch['est_shipping_date']); $date->setOffset(date('Z') / 3600.0); $fechaS = $date->toFormat('%d/%m/%Y'); $body = "El departamento de producción le informa que recibirá su lote aproximadamente el {$fechaS}."; $body .= "

"; $body .= "Incluye los siguientes pedidos:
"; $body .= "
"; foreach ($batchOrders as $batchOrder) { $body .= $batchOrder->id . " "; if ($batchOrder->reference) $body .= $batchOrder->reference . " "; if ($batchOrder->customerfullname) $body .= $batchOrder->customerfullname; $body .= "
"; } $mailer->setBody($body); $mailer->Send(); } } } // funcion para mandar la produccion de una lista de pedidos a otra franquicia para ser fabricado protected function _outsource($cid) { $modelOrder =& $this->getModel('order'); // Obtenemos los parametros de outsourcing (a que franquicia va y a que usuario) $outsourceParams = NULL; if (!SiteOptionsHelper::outsourceProduction($outsourceParams)) { $msg = 'Orders ' . implode(',', $cid) . " couldn't be outsourced. There are no outsourcing parameters defined."; JError::raise(E_NOTICE, JText::_('Error'), $msg); return false; } if (count($cid) > 0) foreach ($cid as $orderId) { $modelOrder->SetId($orderId); $modelOrder->outsource($outsourceParams); } return true; } // funcion para mandar la produccion de una lista de pedidos a otra franquicia para ser fabricado function outsource() { $cid = JRequest::getVar('cid'); $this->_outsource($cid); $this->display(); } function checkOrders() { $cid = JRequest::getVar('cid'); $action = (JRequest::getVar('errorType') == 1) ? 'MARKASBAD' : 'MARKASGOOD'; $reason = trim(JRequest::getVar('errorDesc')); $outsource = (JRequest::getVar('outsource') == 1); $redirectJoomlaToMiddleware = LegacyHelper::getPHPGlobalVar('redirectJoomlaToMiddleware')==1; if ($this->_checkOrders($cid, $action, $reason, $outsource)) { if ($action == 'MARKASGOOD') { $modelOrder =& $this->getModel('order'); if (count($cid) > 0) foreach ($cid as $orderId) { $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); if ($order->manufacturing_date) { $date = new JDate($order->manufacturing_date); $date->setOffset(date('Z') / 3600.0); $fechaS = $date->toFormat('%d/%m/%Y'); echo "Planificado el pedido " . $order->id . " para su fabricación el día " . $fechaS . "
"; } } } } $this->display(); } protected function _checkOrders($cid, $action, $reason = '', $outsource = FALSE) { if ($action == 'MARKASGOOD' && !$reason) $reason = JText::_('Checked'); $modelOrder =& $this->getModel('order'); $modelUser =& $this->getModel('user'); $myUserId = LegacyHelper::getUserId(); $modelUser->SetId($myUserId); $myUser =& $modelUser->getData(); $franchiseName = SiteOptionsHelper::getFranchiseName(); if ($action == 'MARKASBAD' && !$reason) return false; $outsourceParams = NULL; if ($action == 'MARKASGOOD' && $outsource && !SiteOptionsHelper::outsourceProduction($outsourceParams)) { $msg = 'Orders ' . implode(',', $cid) . " couldn't be outsourced. There are no outsourcing parameters defined."; JError::raise(E_NOTICE, JText::_('Error'), $msg); return false; } if (count($cid) > 0) { // Preparamos el envio de e-mails con las fechas de entrega o bien // las razones por las cuales su pedido no ha podido ser revisado correctamente $mailer =& JFactory::getMailer(); $sender = array($myUser->franchiseemail, $myUser->franchisename); $mailer->setSender($sender); $mailer->IsHTML(true); foreach ($cid as $id) { if ($action == 'MARKASGOOD' && $franchiseName == 'ppr' && $_SERVER['SERVER_NAME'] != 'test.soletec.de' && $_SERVER['SERVER_NAME'] != 'test.orthocad.de' && $_SERVER['SERVER_NAME'] != 'devorthocad' && $_SERVER['SERVER_NAME'] != 'demo.orthocad.de' ) if (!$this->SendOrderToPPRSAP($id)) { $msg = 'Order ' . $id . " couldn't be sent to the SAP system. The order won't be checked as good."; JError::raise(E_NOTICE, JText::_('Warning'), $msg); continue; } $modelOrder->SetId($id); $modelOrder->setAction($action, $reason); if ($action == 'MARKASBAD') { $data = array(); $data['id'] = $id; $data['currentStep'] = CHECKOUT_STEP; $modelOrder->store($data); $order =& $modelOrder->getData(); $userId = $order->user; if ($userId) { $modelUser->SetId($userId); $userObj =& $modelUser->getData(); $email = trim($userObj->invoice_email); if (!$email) $email = trim($userObj->email); if ($email) { $mailer->ClearAllRecipients(); $mailer->addRecipient($email); $subject = $userObj->franchisename . ": "; $subject .= JText::sprintf("BADORDER_SUBJECT_MAIL", $id); $mailer->setSubject($subject); $body = JText::sprintf("BADORDER_BODY_MAIL", $id); $body .= ":
" . $reason . "
"; $body .= JText::_("BADORDER_LINK_MAIL") . ":
"; $link = "http://" . $_SERVER['SERVER_NAME'] . JRoute::_('/index.php?option=com_vxc&controller=routingorder&orderId=' . $id . '&task=gotoStep&noSave=1&step=' . CHECKOUT_STEP); $body .= "" . JText::_('Open') . ""; $mailer->setBody($body); $mailer->Send(); } } } else { $data = array(); $data['id'] = $id; $dateNow = new JDate(); $data['checked_date'] = $dateNow->toMySQL(); $data['checking_user'] = $myUserId; $modelOrder->store($data); // $this->imCustomUpdateOrderStatus($id,'MFACT'); if ($outsourceParams) $modelOrder->outsource($outsourceParams); else if (SiteOptionsHelper::scheduleProduction()) { $order =& $modelOrder->getData(); if ($order->payment_methodnameid != 'TEST') { // Realizamos la planificacion de la produccion para este pedido $review_date = $data['checked_date']; $this->_scheduleOrderProduction($order->id, $review_date); } } } } } return true; } function showPDFInvoiceLine() { JRequest::setVar('layout', 'customerinvoice'); $this->display(); } function showPDFCommissions() { JRequest::setVar('layout', 'commissions'); $this->display(); } function resetCurrentUserPassword() { $newpass = JRequest::getVar('newpass'); $this->_resetUserPassword(LegacyHelper::getUserId(), $newpass); $this->display(); } function resetUserPassword() { $userId = JRequest::getVar('userId'); $newpass = JRequest::getVar('newpass'); $this->_resetUserPassword($userId, $newpass); $this->display(); } protected function _resetUserPassword($userId, $newpass) { if (!(int)$userId) return; $modelUser =& $this->getModel('user'); $modelUser->SetId($userId); $modelUser->changePassword($newpass); } function deleteUser() { $userId = JRequest::getVar('userId'); if ((int)$userId) { $modelUser =& $this->getModel('user'); $modelUser->SetId($userId); $modelUser->delete(); } $this->display(); } function deleteUserPrivilege() { $userId = JRequest::getVar('userId'); $priv = JRequest::getVar('priv'); if ((int)$userId) { $modelUser =& $this->getModel('user'); $modelUser->SetId($userId); $modelUser->clearPrivilege($priv); } $this->display(); } function addUserPrivilege() { $userId = JRequest::getVar('userId'); $priv = JRequest::getVar('userprivilege'); if ((int)$userId) { $modelUser =& $this->getModel('user'); $modelUser->SetId($userId); $modelUser->setPrivilege($priv); } $this->display(); } function createUsersByInterval() { $prefix = trim(JRequest::getVar('userusername')); $startInterval = (int)trim(JRequest::getVar('startUserAccountInterval')); $endInterval = (int)trim(JRequest::getVar('endUserAccountInterval')); if (!$prefix || $endInterval < $startInterval) { $this->display(); return; } $data = array(); $data['franchise'] = trim(JRequest::getVar('searchfranchise')); $data['group'] = trim(JRequest::getVar('searchgroup')); for ($i = $startInterval; $i <= $endInterval; $i++) { if ($startInterval > 99 || $endInterval > 99) $name = sprintf("%s%03d", $prefix, $i); else $name = sprintf("%s%02d", $prefix, $i); $data['id'] = null; $data['name'] = $name; $data['username'] = $name; $data['email'] = $name . "@" . $name . ".com"; $pass = $name; $data['password'] = $pass; $data['password2'] = $pass; $modelUser =& $this->getModel('user'); $modelUser->SetId(null); // Comprobamos si ya existe algún usuario con ese nombre de usuario o e-mail $res = array(); $modelUser->checkUserData($data, $res); $good = true; if (!$res['username']) { JError::raise(E_NOTICE, JText::_('Error'), $data['username'] . ": " . JText::_('Repeated username. Please enter a different one')); $good = false; break; } if (!$res['email']) { JError::raise(E_NOTICE, JText::_('Error'), $data['email'] . ": " . JText::_('Repeated email. Please enter a different one')); $good = false; break; } if ($good) { if (!$modelUser->store($data)) { JError::raise(E_NOTICE, JText::_('Error'), $data['username'] . ": " . JText::_('Error creating user')); break; } } } $this->display(); } function saveUserInfo() { $data = array(); $data['id'] = JRequest::getVar('userId'); $data['franchise'] = trim(JRequest::getVar('searchfranchise')); $data['name'] = trim(JRequest::getVar('username')); $data['username'] = trim(JRequest::getVar('userusername')); $data['email'] = trim(JRequest::getVar('useremail')); $pass = trim(JRequest::getVar('userpassword')); if (!trim($data['email']) || !trim($data['username']) || !trim($data['name']) || (!(int)$data['id'] && !trim($pass))) { JError::raise(E_NOTICE, JText::_('Error'), JText::_('Missing required fields')); $this->display(); return; } if ($pass) { $data['password'] = $pass; $data['password2'] = $pass; } $data['address'] = trim(JRequest::getVar('useraddress')); $data['pcode'] = trim(JRequest::getVar('userzipcode')); $data['country'] = trim(JRequest::getVar('usercountry')); $data['city'] = trim(JRequest::getVar('usercity')); $data['phone'] = trim(JRequest::getVar('userphone')); $data['cif'] = trim(JRequest::getVar('uservatnumber')); $data['location'] = trim(JRequest::getVar('userlocation')); $data['customid'] = trim(JRequest::getVar('usercustomid')); $data['cashondelivery_charge'] = trim(JRequest::getVar('usercashondelivery_charge')); if (JRequest::getVar('usercreditlimit') !== null) $data['credit_limit'] = trim(JRequest::getVar('usercreditlimit')); if (JRequest::getVar('userequivalence_charge') !== null) $data['equivalence_charge'] = round(JRequest::getVar('userequivalence_charge'), 2); $data['no_vat'] = (JRequest::getVar('usernovat') == '1') ? 1 : 0; if (JRequest::getVar('hidSaveGroups') == 1) $data['groups'] = JRequest::getVar('usergroups', array(), '', 'array'); $data['review_predesign'] = (JRequest::getVar('userpredesignreview') == '1') ? 1 : 0; $data['invoice_email'] = trim(JRequest::getVar('userinvoiceemail')); $modelUser =& $this->getModel('user'); $modelUser->SetId($data['id']); $newUser = ($data['id'] == ''); // Comprobamos si ya existe algún usuario con ese nombre de usuario o e-mail $res = array(); $modelUser->checkUserData($data, $res); $good = true; if (!$res['username']) { JError::raise(E_NOTICE, JText::_('Error'), JText::_('Repeated username. Please enter a different one')); $good = false; } if (!$res['email']) { JError::raise(E_NOTICE, JText::_('Error'), JText::_('Repeated email. Please enter a different one')); $good = false; } if ($good) { if (!$modelUser->store($data)) JError::raise(E_NOTICE, JText::_('Error'), JText::_('Error creating user')); else { if ($newUser) $modelUser->changePassword($pass); if (JRequest::getVar('useraddtocredit') !== null) { $amount = (float)JRequest::getVar('useraddtocredit'); $remarks = trim(JRequest::getVar('usercreditremarks')); if (abs($amount) >= 0.005) { $modelUser->clearPrivilege("Don't generate invoice on credit payment"); $modelUser->makePayment($amount, $remarks); } } JRequest::setVar('userId', $data['id']); } } $this->display(); } function addFranchiseAgency() { $modelAgency =& $this->getModel('agency'); $franchiseId = JRequest::getVar('franchiseId'); $franchiseagency = JRequest::getVar('availagency'); $data = array(); $data['id'] = null; $data['franchise'] = $franchiseId; $data['agency'] = $franchiseagency; $modelAgency->storeByFranchise($data); $this->display(); } function saveFranchiseAgency() { $modelAgency =& $this->getModel('agency'); $franAgencyId = JRequest::getVar('franAgencyId'); $data = array(); $data['id'] = $franAgencyId; $data['price'] = trim(JRequest::getVar('agency' . $franAgencyId . 'price')); $data['description'] = trim(JRequest::getVar('agency' . $franAgencyId . 'desc')); $data['default_off'] = (trim(JRequest::getVar('agency' . $franAgencyId . 'default_off')) == '1') ? '1' : '0'; $modelAgency->storeByFranchise($data); $this->display(); } function deleteFranchiseAgency() { $modelAgency =& $this->getModel('agency'); $franAgencyId = JRequest::getVar('franAgencyId'); $modelAgency->deleteByFranchise($franAgencyId); $this->display(); } function saveFranchiseData() { $modelUser =& $this->getModel('user'); $userObj =& $modelUser->getData(); $modelFranchise =& $this->getModel('franchise'); $franchiseId = $userObj->franchise; $modelFranchise->SetId($franchiseId); $data = array(); $data['id'] = $franchiseId; $data['name'] = trim(JRequest::getVar('franchisename')); $data['address'] = trim(JRequest::getVar('franchiseaddress')); $data['address2'] = trim(JRequest::getVar('franchiseaddress2')); $data['email'] = trim(JRequest::getVar('franchiseemail')); $data['telephone'] = trim(JRequest::getVar('franchisetelephone')); $data['mobile'] = trim(JRequest::getVar('franchisemobile')); $data['fax'] = trim(JRequest::getVar('franchisefax')); $data['vat_number'] = trim(JRequest::getVar('franchisevatnumber')); $data['country'] = trim(JRequest::getVar('franchisecountry')); $data['vat_percent'] = trim(JRequest::getVar('franchisevatpercent')); $data['company_number'] = trim(JRequest::getVar('franchisecompanynumber')); $data['acct_number'] = trim(JRequest::getVar('franchiseacctnumber')); $data['website'] = trim(JRequest::getVar('franchisewebsite')); $modelFranchise->store($data); $this->display(); } function addInvoiceLine() { $modelInvoice =& $this->getModel('invoice'); $invoiceId = JRequest::getVar('invoiceId'); $modelInvoice->SetId($invoiceId); $data = array(); $data['id'] = null; $data['invoice'] = $invoiceId; $data['concept'] = ''; $data['amount'] = 1; $data['price'] = 0; $data['vat'] = 0; $data['discount'] = 0; $data['equivalence_charge'] = 0; $data['total'] = $data['price'] * $data['amount'] * (1.0 - $data['discount'] / 100.0) * (1.0 + $data['vat'] / 100.0); $data['patient_price'] = 0; $data['patient_total'] = 0; $data['franchise_to_company_fee'] = 0; $data['voxelcare_to_franchise_fee'] = 0; $modelInvoice->storeLine($data); JRequest::setVar('invoiceLineId', $data['id']); $this->display(); } function deleteDeliveryNote() { $deliveryNoteId = (int)JRequest::getVar('deliveryNoteId'); if ($deliveryNoteId) { $modelDeliveryNotes =& $this->getModel('deliverynotes'); $modelDeliveryNotes->delete(array($deliveryNoteId)); } $this->display(); } function saveDeliveryNote() { $deliveryNoteId = (int)JRequest::getVar('deliveryNoteId'); $modelDeliveryNote =& $this->getModel('deliverynote'); $modelDeliveryNote->SetId($deliveryNoteId); $data = array(); $data['id'] = ($deliveryNoteId) ? $deliveryNoteId : null; $data['concept'] = trim(JRequest::getVar('deliverynoteconcept')); $data['price'] = trim(JRequest::getVar('deliverynoteprice')); $data['vat'] = trim(JRequest::getVar('deliverynotevat')); $data['paid'] = (trim(JRequest::getVar('deliverynotepaid')) == '1') ? 1 : 0; $data['userid'] = trim(JRequest::getVar('deliverynoteuserid')); $data['price'] = trim(JRequest::getVar('deliverynoteprice')); $data['amount'] = (int)trim(JRequest::getVar('deliverynoteamount')); $price = round($data['price'], 3); $vat = round($data['vat'], 2); $amount = $data['amount']; $data['total'] = $amount * $price * (1.0 + $vat / 100.0); $modelDeliveryNote->store($data); $this->display(); } function saveInvoiceLine() { $modelInvoice =& $this->getModel('invoice'); $invoiceId = JRequest::getVar('invoiceId'); $invoiceLineId = JRequest::getVar('invoiceLineId'); $modelInvoice->SetId($invoiceId); $amount = trim(JRequest::getVar('invoicelineamount')); $price = trim(JRequest::getVar('invoicelineprice')); $vat = trim(JRequest::getVar('invoicelinevat')); $discount = trim(JRequest::getVar('invoicelinediscount')); $referred_order = trim(JRequest::getVar('invoicelinereferredorder')); if (!(int)$referred_order) $referred_order = 'NULL'; $data = array(); $data['id'] = $invoiceLineId; if (JRequest::getVar('invoicelineconcept') !== null) { $concept = trim(JRequest::getVar('invoicelineconcept')); $data['concept'] = $concept; } $priceType = trim(JRequest::getVar('priceType')); switch ($priceType) { case 'pp': $column = 'patient_price'; break; case 'cp': $column = 'price'; break; case 'cf': $column = 'franchise_to_company_fee'; break; case 'ff': $column = 'voxelcare_to_franchise_fee'; break; } $data['amount'] = (float)$amount; $data[$column] = (float)$price; $data['vat'] = (float)$vat; $data['discount'] = (float)$discount; $data['referred_order'] = $referred_order; if (JRequest::getVar('invoicelineequivalence_charge') !== null) $data['equivalence_charge'] = round(JRequest::getVar('invoicelineequivalence_charge'), 2); else $data['equivalence_charge'] = 0; if ($priceType == 'cp') $data['total'] = $data['price'] * $data['amount'] * (1.0 - $data['discount'] / 100.0) * (1.0 + ($data['vat'] + $data['equivalence_charge']) / 100.0); else if ($priceType = 'pp') $data['patient_total'] = $data['patient_price'] * $data['amount'] * (1.0 + $data['vat'] / 100.0); $modelInvoice->storeLine($data); $modelInvoice->updateTotals(); $this->display(); } function deleteInvoiceLine() { $invoiceId = JRequest::getVar('invoiceId'); $invoiceLineId = JRequest::getVar('invoiceLineId'); $modelInvoice =& $this->getModel('invoice'); $modelInvoice->SetId($invoiceId); $modelInvoice->deleteLine($invoiceLineId); $modelInvoice->updateTotals(); JRequest::setVar('invoiceLineId', ''); $this->display(); } function saveInvoiceData() { $modelInvoice =& $this->getModel('invoice'); $invoiceId = JRequest::getVar('invoiceId'); if (!$invoiceId) { $this->display(); return; } $modelInvoice->SetId($invoiceId); $data = array(); $data['id'] = $invoiceId; $data['comments'] = trim(JRequest::getVar('invoicecomments')); $modelInvoice->store($data); $this->display(); } function saveCustomerInvoiceData() { $modelInvoice =& $this->getModel('customerinvoice'); $invoiceId = JRequest::getVar('invoiceId'); if (!$invoiceId) { $this->display(); return; } $modelInvoice->SetId($invoiceId); $data = array(); $data['id'] = $invoiceId; $data['comments'] = trim(JRequest::getVar('invoicecomments')); $price = round((float)JRequest::getVar('cinvoiceprice'), 2); $vat = round((float)JRequest::getVar('cinvoicevat'), 2); $taxes = round($price * $vat / 100.0, 2); $total = round($taxes + $price, 2); $data['price'] = $price; $data['vat'] = $vat; $data['taxes'] = $taxes; $data['total'] = $total; $modelInvoice->store($data); $this->display(); } function SaveShippingBatch() { $modelBatch =& $this->getModel('batch'); $batchId = JRequest::getVar('batchId'); $modelBatch->SetId($batchId); $data = array(); $data['id'] = $batchId; $data['tracking_number'] = trim(JRequest::getVar('trackingnumberbatch')); $data['agency'] = JRequest::getVar('agencybatch'); $shipDate = trim(JRequest::getVar('shippingdatebatch')); if ($shipDate) { $shipDate = str_replace('-', '/', $shipDate); $month = 0; $year = 0; $hour = 0; $minute = 0; $assigned = sscanf($shipDate, "%d/%d/%d %d:%d", $day, $month, $year, $hour, $minute); /* if ($assigned ==3) $data['shipping_date'] = sprintf("%d-%d-%d",$year,$month,$day); else if ($assigned == 5) $data['shipping_date'] = sprintf("%d-%d-%d %d:%d",$year,$month,$day,$hour,$minute); */ if ($assigned >= 3) $data['shipping_date'] = sprintf("%d-%d-%d", $year, $month, $day); } $modelBatch->store($data); $this->display(); } function deletePricingInfo() { $itemId = JRequest::getVar('pricing'); $modelPricing =& $this->getModel('pricing'); $modelPricing->deletePrice($itemId, JRequest::getVar('part')); $this->display(); } function savePricingInfo() { $franchiseId = JRequest::getVar('franchise'); $companyId = JRequest::getVar('company'); $itemId = JRequest::getVar('item'); $pricingId = JRequest::getVar('pricing'); $patientPrice = JRequest::getVar('patientPrice'); $companyPrice = JRequest::getVar('companyPrice'); $companyFee = JRequest::getVar('companyFee'); $franchiseFee = JRequest::getVar('franchiseFee'); $modelPricing =& $this->getModel('pricing'); $pricing = array(); $pricing['franchise'] = $franchiseId; if ((int)$itemId) $pricing['attvalue'] = $itemId; else $pricing['attvalue'] = null; if ((int)$companyId) $pricing['user'] = $companyId; else $pricing['user'] = null; if ((int)$pricingId) $pricing['id'] = $pricingId; if ($patientPrice !== null) { $patientPrice = trim($patientPrice); if ($patientPrice == "") $pricing['patient_price'] = null; else $pricing['patient_price'] = $patientPrice; } if ($companyPrice !== null) { $companyPrice = trim($companyPrice); if ($companyPrice == "") $pricing['company_price'] = null; else $pricing['company_price'] = $companyPrice; } if ($companyFee !== null) { $companyFee = trim($companyFee); if ($companyFee == "") $pricing['franchise_to_company_fee'] = null; else $pricing['franchise_to_company_fee'] = $companyFee; } if ($franchiseFee !== null) { $franchiseFee = trim($franchiseFee); if ($franchiseFee == "") $pricing['voxelcare_to_franchise_fee'] = null; else $pricing['voxelcare_to_franchise_fee'] = $franchiseFee; } $modelPricing->store($pricing); $this->display(); } function downloadInvoicesZIP() { JRequest::setVar('layout', 'invoiceszip'); $this->display(); } function downloadInvoicesSummary() { if (JRequest::getVar('summaryformat') == 'PDF') JRequest::setVar('layout', 'invoicessummarypdf'); else if (JRequest::getVar('summaryformat') == 'XLS') JRequest::setVar('layout', 'invoicessummaryxls'); else JRequest::setVar('layout', 'invoicessummarycontaplus'); $this->display(); } function downloadFeesPDF() { JRequest::setVar('layout', 'feesPDF'); $this->display(); } function markAsReadyToPay() { $modelInvoice =& $this->getModel('invoice'); $cid = JRequest::getVar('cid', 'array', array()); if (is_array($cid)) foreach ($cid as $id) { $data = array(); $data['id'] = $id; $data['paid'] = 0; $data['returned'] = 0; $modelInvoice->store($data); } $this->display(); } function customerMarkAsReadyToPay() { $modelInvoice =& $this->getModel('customerinvoice'); $cid = JRequest::getVar('cid', 'array', array()); if (is_array($cid)) foreach ($cid as $id) { $data = array(); $data['id'] = $id; $data['paid'] = 0; $data['returned'] = 0; $modelInvoice->store($data); } $this->display(); } protected function _markAsPaid($cid) { $modelInvoice =& $this->getModel('invoice'); $modelUser =& $this->getModel('user'); if (is_array($cid)) foreach ($cid as $id) { $modelInvoice->SetId($id); $invoice =& $modelInvoice->getData(); if (!$invoice->paid) { $data = array(); $data['id'] = $id; $data['paid'] = 1; $data['returned'] = 0; $modelInvoice->store($data); $amount = $invoice->total; if (abs($amount) >= 0.01) { $modelUser->SetId($invoice->payment_user); $modelUser->makePayment($amount); } } } } protected function _customerMarkAsPaid($cid) { $modelInvoice =& $this->getModel('customerinvoice'); $modelUser =& $this->getModel('user'); if (is_array($cid)) foreach ($cid as $id) { $modelInvoice->SetId($id); $invoice =& $modelInvoice->getData(); if (!$invoice->paid) { $data = array(); $data['id'] = $id; $data['paid'] = 1; $data['returned'] = 0; $modelInvoice->store($data); } } } function receiptMarkAsPaid() { $cid = JRequest::getVar('cid', 'array', array()); $this->_receiptMark($cid, true); $this->display(); } function receiptMarkAsNotPaid() { $cid = JRequest::getVar('cid', 'array', array()); $this->_receiptMark($cid, false); $this->display(); } protected function _receiptMark(&$cid, $paid) { if (!count($cid)) return; $modelReceipt =& $this->getModel('receipt'); $modelOrder =& $this->getModel('order'); foreach ($cid as $id) { $data = array(); $data['id'] = $id; $data['paid'] = $paid ? '1' : '0'; if ($paid) { $nowDate = new JDate(); $data['paid_date'] = $nowDate->toMySQL(); } $modelReceipt->store($data); $receipt =& $modelReceipt->getData(); $orderId = $receipt->orderid; if ($paid) { $this->_checkCustomerInvoiceGenerationByReceiptId($id); } $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); $logMessage = JText::_('Receipt') . ': '; $logMessage .= ($paid) ? JText::_('Mark as paid') : JText::_('Mark as not paid'); $modelOrder->saveLog($order->statenameid, $logMessage, FRANCHISEMAN_VISLEVEL); } } function getEstimatedDeliveryDate($batchOrderDistribution, $manufacturing_date) { $dateNow = new JDate(); $today_date = $dateNow->toMySQL(); $modelHolidays =& $this->getModel('holidays'); $holidays = array_map('trim', explode("\n", $modelHolidays->getHolidaysAsText())); // La fecha estimada de entrega sera el maximo entre la fecha de revisión del ultimo pedido // incrementado en 5, y la fecha de fabricación maxima incrementada en 1 $modelSettings =& $this->getModel('settings'); $minDaysFromCheckingToDelivery = $this->getConditionedVar('minDaysFromCheckingToDelivery', $batchOrderDistribution, 'max'); $daysToAdd = $minDaysFromCheckingToDelivery; $tmpMinDate = $this->_add_business_days($batchOrderDistribution, $today_date, $daysToAdd, $holidays, 'Y-n-j', false); $minDaysFromManufacturingToDelivery = $this->getConditionedVar('minDaysFromManufacturingToDelivery', $batchOrderDistribution, 'max'); //echo 'minDaysFromManufacturingToDelivery:'.$minDaysFromManufacturingToDelivery.'
'; $daysToAdd = $minDaysFromManufacturingToDelivery; //$daysToAdd = (int)$modelSettings->getVar('minDaysFromManufacturingToDelivery',1); $tmpManuDate = $this->_add_business_days($batchOrderDistribution, $manufacturing_date, $daysToAdd, $holidays, 'Y-n-j', false); if (strtotime($tmpMinDate) > strtotime($tmpManuDate)) return $tmpMinDate; else return $tmpManuDate; } function getPlanningConditions($batchOrderDistribution = array()) { $modelSettings =& $this->getModel('settings'); $conditionCount = (int)$modelSettings->getVar('planningConditions.count', 0); $batchCats = array(); foreach ($batchOrderDistribution as $cat => $count) $batchCats[] = $cat; $conditions = array(); for ($i = 0; $i < $conditionCount; $i++) { $prefix = 'planningCondition' . $i . '.'; $cats = explode(',', $modelSettings->getVar($prefix . 'categories', '')); $isApplicable = false; foreach ($batchCats as $cat) if (in_array($cat, $cats)) { $isApplicable = true; break; } if ($isApplicable) { $condition = array(); $condition['categories'] = $cats; $condition['maxProductionPerDay'] = $modelSettings->getVar($prefix . 'maxProductionPerDay', null); $condition['minDaysFromCheckingToManufacture'] = $modelSettings->getVar($prefix . 'minDaysFromCheckingToManufacture', null); $condition['minDaysFromCheckingToDelivery'] = $modelSettings->getVar($prefix . 'minDaysFromCheckingToDelivery', null); $condition['minDaysFromManufacturingToDelivery'] = $modelSettings->getVar($prefix . 'minDaysFromManufacturingToDelivery', null); $conditions[] = $condition; } } return $conditions; } function getConditionedVar($varName, $batchOrderDistribution, $op) { $modelSettings =& $this->getModel('settings'); $defaultValue = $modelSettings->getVar($varName, null); if ($defaultValue !== null) $defaultValue = (int)$defaultValue; $conditions = $this->getPlanningConditions($batchOrderDistribution); $value = null; if (count($conditions) > 0) foreach ($conditions as $cond) { $apCat = $cond['categorie']; $newValue = $cond[$varName]; if ($newValue !== null) { $newValue = (int)$newValue; if ($value === null) { $value = $newValue; } else { if ($op == 'max') { if ($newValue > $value) { $value = $newValue; } } else { if ($newValue < $value) { $value = $newValue; } } } } } if ($value === null) $value = $defaultValue; return $value; } function getEstimatedManufacturingDate($batchOrderDistribution, $date) { $modelSettings =& $this->getModel('settings'); $minDaysFromCheckingToManufacture = $this->getConditionedVar('minDaysFromCheckingToManufacture', $batchOrderDistribution, 'max'); //echo 'minDaysFromCheckingToManufacture:'.$minDaysFromCheckingToManufacture.'
'; $daysToAdd = $minDaysFromCheckingToManufacture; $modelHolidays =& $this->getModel('holidays'); $holidays = array_map('trim', explode("\n", $modelHolidays->getHolidaysAsText())); return $this->_add_business_days($batchOrderDistribution, $date, $daysToAdd, $holidays, 'Y-n-j', true); } protected function _checkCustomerInvoiceGenerationByReceiptId($receiptId) { $modelCustomerInvoice = & $this->getModel('customerinvoice'); $modelReceipt =& $this->getModel('receipt'); $modelReceipt->SetId($receiptId); $receipt =& $modelReceipt->getData(); $invoice =& $modelCustomerInvoice->getInvoiceByOrderId($receipt->orderid); if ($receipt->paid && $receipt->batch && (!$invoice || !$invoice->id)) $this->generateInvoiceByOrder($receipt->orderid, true); } function markAsPaid() { $cid = JRequest::getVar('cid', 'array', array()); $this->_markAsPaid($cid); $this->display(); } function customerMarkAsPaid() { $cid = JRequest::getVar('cid', 'array', array()); $this->_customerMarkAsPaid($cid); $this->display(); } function markAsReturned() { $modelInvoice =& $this->getModel('invoice'); $modelUser =& $this->getModel('user'); $cid = JRequest::getVar('cid', 'array', array()); if (is_array($cid)) foreach ($cid as $id) { $data = array(); $modelInvoice->SetId($id); $invoice =& $modelInvoice->getData(); if ($invoice->paid) { $data['id'] = $id; $data['returned'] = 1; $data['paid'] = 0; $modelInvoice->store($data); $amount = $invoice->total; if (abs($amount) >= 0.01) { $modelUser->SetId($invoice->payment_user); $modelUser->makePayment(-$amount); } } } $this->display(); } function customerMarkAsReturned() { $modelInvoice =& $this->getModel('customerinvoice'); $modelUser =& $this->getModel('user'); $cid = JRequest::getVar('cid', 'array', array()); if (is_array($cid)) foreach ($cid as $id) { $data = array(); $modelInvoice->SetId($id); $invoice =& $modelInvoice->getData(); if ($invoice->paid) { $data['id'] = $id; $data['returned'] = 1; $data['paid'] = 0; $modelInvoice->store($data); } } $this->display(); } function downloadNorma58() { JRequest::setVar('layout', 'norma58'); $this->display(); } function generateInvoices() { $this->_generateInvoices(); $this->display(); } function generateInvoiceByBatch($batchId, $forcePaid = false) { $modelInvoice =& $this->getModel('invoice'); $modelBatch =& $this->getModel('batch'); $modelBatch->SetId($batchId); $batch =& $modelBatch->getData(); $pendingOrders =& $modelBatch->getOrders(); $deliveryNotes =& $modelBatch->getDeliveryNotes(); $dateNow = new JDate(); $dataInvoice = array(); $dataInvoice['id'] = 0; $dataInvoice['batch'] = $batchId; $dataInvoice['shipping_cost'] = 0; $dataInvoice['deliverynotes_cost'] = $batch->deliverynotes_cost; $paid = 0; if ($forcePaid) { $paid = 1; } else { switch ($batch->payment_methodnameid) { case 'SAMPLE': case 'TEST': case 'CREDIT': case 'PAYPAL': case 'CREDITCARD': $paid = 1; break; } } switch ($batch->payment_methodnameid) { case 'SAMPLE': case 'TEST': case 'CASHONDELIVERY': $dataInvoice['reference'] = ''; return; case 'BUDGET': $dataInvoice['reference'] = $modelInvoice->getNextBudgetReference($dateNow, $batch->payment_user); break; default: $dataInvoice['reference'] = $modelInvoice->getNextInvoiceReference($dateNow, $batch->payment_user); } $dataInvoice['paid'] = $paid; $dataInvoice['returned'] = 0; $dataInvoice['generation_date'] = $dateNow->toMySQL(); $modelInvoice->store($dataInvoice); foreach ($pendingOrders as $order) { $dataLine = array(); $dataLine['invoice'] = $dataInvoice['id']; $dataLine['orderid'] = $order->id; $dataLine['amount'] = 1; $dataLine['price'] = $order->price; $dataLine['vat'] = $batch->taxpercent; $dataLine['equivalence_charge'] = $batch->equivalence_charge; $dataLine['discount'] = $batch->discount; $dataLine['total'] = $dataLine['price'] * (1.0 - $dataLine['discount'] / 100.0) * (1.0 + ($dataLine['vat'] + $dataLine['equivalence_charge']) / 100.0); $dataLine['patient_price'] = $order->patient_price; $dataLine['patient_total'] = $dataLine['patient_price'] * (1.0 + $dataLine['vat'] / 100.0); $dataLine['franchise_to_company_fee'] = $order->franchise_to_company_fee; $dataLine['voxelcare_to_franchise_fee'] = $order->voxelcare_to_franchise_fee; $modelInvoice->storeLine($dataLine); } foreach ($deliveryNotes as $deliveryNote) { $dataLine = array(); $dataLine['invoice'] = $dataInvoice['id']; $dataLine['deliverynote'] = $deliveryNote->id; $dataLine['amount'] = $deliveryNote->amount; $dataLine['price'] = $deliveryNote->price; $dataLine['vat'] = $deliveryNote->vat; $dataLine['concept'] = $deliveryNote->concept; $dataLine['discount'] = 0; $dataLine['total'] = $deliveryNote->total; $modelInvoice->storeLine($dataLine); } if ($batch->shipping_cost != 0) { $dataLine = array(); $dataLine['invoice'] = $dataInvoice['id']; $dataLine['amount'] = 1; $dataLine['price'] = $batch->shipping_cost; $dataLine['vat'] = $batch->shipping_vat; $dataLine['concept'] = JText::_('Shipping costs'); $dataLine['discount'] = 0; $dataLine['total'] = round($batch->shipping_cost * (1.0 + $batch->shipping_vat / 100.0), 2); $modelInvoice->storeLine($dataLine); } $modelInvoice->store($dataInvoice); $modelInvoice->updateTotals(); $this->sendInvoiceEmail($dataInvoice['id']); $this->_processGiros(); } function generateInvoiceByOrder($orderId, $forcePaid = false) { $modelInvoice =& $this->getModel('customerinvoice'); $modelOrder =& $this->getModel('order'); $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); $dateNow = new JDate(); $dataInvoice = array(); $dataInvoice['id'] = 0; $dataInvoice['orderid'] = $orderId; $paid = 0; if ($forcePaid) { $paid = 1; } else { switch ($order->payment_methodnameid) { case 'SAMPLE': case 'TEST': case 'CREDIT': case 'PAYPAL': case 'CREDITCARD': $paid = 1; break; } } switch ($order->payment_methodnameid) { case 'SAMPLE': case 'TEST': case 'CASHONDELIVERY': $dataInvoice['reference'] = ''; return; case 'BUDGET': $dataInvoice['reference'] = $modelInvoice->getNextBudgetReference($dateNow, $order->payment_user); break; default: $dataInvoice['reference'] = $modelInvoice->getNextInvoiceReference($dateNow, $order->payment_user); // $dataInvoice['reference'] = 'cucu'; } $dataInvoice['paid'] = $paid; $dataInvoice['returned'] = 0; $dataInvoice['generation_date'] = $dateNow->toMySQL(); $dataInvoice['price'] = $order->patient_price; $dataInvoice['vat'] = $order->taxpercent; $dataInvoice['taxes'] = $dataInvoice['price'] * ($order->taxpercent / 100.0); $dataInvoice['total'] = $dataInvoice['price'] + $dataInvoice['taxes']; $modelInvoice->store($dataInvoice); } function sendInvoiceEmail($invoiceId) { if (!(int)$invoiceId) return; $modelInvoice =& $this->getModel('invoice'); $modelInvoice->SetId($invoiceId); $modelUser =& $this->getModel('user'); $myUser =& $modelUser->getData(); $sender = array($myUser->franchiseemail, $myUser->franchisename); $invoice =& $modelInvoice->getData(); $userId = $invoice->payment_user; if (!$userId) return; $modelUser->SetId($userId); $userObj =& $modelUser->getData(); $recipient = trim($userObj->invoice_email); if (!$recipient) return; $pdf = null; $modelInvoice->_printPDF($pdf, false); $str = ''; $nombre_archivo_tmp = ''; if ($pdf) { $str =& $pdf->Output('', 'S'); $nombre_archivo_tmp = tempnam("", "FOO"); $gestor = fopen($nombre_archivo_tmp, "w"); fwrite($gestor, $str); fclose($gestor); } $mailer =& JFactory::getMailer(); $mailer->setSender($sender); $mailer->IsHTML(true); $mailer->ClearAllRecipients(); $mailer->addRecipient($recipient); $fileName = JText::_("invoice") . $invoice->reference . ".pdf"; $mailer->AddAttachment($nombre_archivo_tmp, $fileName); $subject = $userObj->franchisename . ": "; $subject .= JText::sprintf("INVOICE_SUBJECT_MAIL", $invoice->batch); $mailer->setSubject($subject); $body = JText::sprintf("INVOICE_BODY_MAIL", $invoice->batch); $mailer->setBody($body); $mailer->Send(); @unlink($nombre_archivo_tmp); } function processGiros() { $this->_processGiros(); $this->display(); } protected function _processGiros() { $modelGiros =& $this->getModel('giros'); $modelGiro =& $this->getModel('giro'); $modelInvoice =& $this->getModel('invoice'); $pendingInvoices =& $modelGiros->getPendingInvoices(); if (count($pendingInvoices) == 0) return; $date = new JDate(); $fechaEmision = $date->toMySQL(); $new_date = strtotime("+15 day", strtotime($date->toFormat("%d-%m-%Y"))); $fechaVencimiento = date('Y-m-d', $new_date); $lines = array(); $idstopay = array(); foreach ($pendingInvoices as $inv) { if (strlen(trim($inv->acctnumber)) != 20) continue; $idstopay[] = $inv->id; $line = array(); $line['ccc'] = trim($inv->acctnumber); $line['dias_vencimiento'] = 15; $line['invoice'] = $inv->id; $lines[] = $line; } $this->_markAsPaid($idstopay); if (count($lines) > 0) { $data = array(); $data['id'] = null; $data['nif_emisor'] = "B53905667"; $data['sufijo_emisor'] = "000"; $data['fecha_emision'] = $fechaEmision; $data['codigoINE'] = ""; $data['ordenante'] = "VoxelWorks S.L."; $data['entidad_emisor'] = "0128"; $data['oficina_emisor'] = "0644"; $data['ccontrol_emisor'] = "00"; $data['cuenta_emisor'] = "0500001194"; $modelGiro->store($data); $giroId = $data['id']; foreach ($lines as $line) { $line['id'] = null; $line['giro'] = $giroId; $modelGiro->storeLine($line); } } } function seeInvoice() { JRequest::setVar('layout', 'invoice'); $this->display(); } function changeOrderUser() { $orderId = JRequest::getVar('orderId'); $userId = JRequest::getVar('userId'); if ($orderId && $userId) $this->_changeOrderUser($orderId, $userId); $this->display(); } protected function _changeOrderUser($orderId, $userId) { $modelOrder =& $this->getModel('order'); $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); $modelOrder->saveLog($order->statenameid, JText::_('User change'), FRANCHISEMAN_VISLEVEL); $data = array(); $data['id'] = $orderId; $data['user'] = $userId; $modelOrder->store($data); if ($order->batch) { $modelBatch =& $this->getModel('batch'); $modelBatch->SetId($order->batch); $dataBatch = array(); $dataBatch['id'] = $order->batch; $dataBatch['payment_user'] = $userId; $modelBatch->store($dataBatch); } } function changeOrderState() { $orderId = JRequest::getVar('orderId'); $stateNameId = JRequest::getVar('stateId'); if ($orderId && $stateNameId) { $modelOrder =& $this->getModel('order'); $modelOrderState =& $this->getModel('orderstates'); $stateId = $modelOrderState->getIdFromName($stateNameId); $modelOrder->SetId($orderId); $data = array(); $data['id'] = $orderId; $data['state'] = $stateId; $modelOrder->store($data); $modelOrder->saveLog($stateNameId); } $this->display(); } function manufacturePDF() { JRequest::setVar('layout', 'manureport'); $this->display(); } function manufactureInvoicesPDF() { JRequest::setVar('view', 'macustomerinvoicing'); JRequest::setVar('layout', 'customerinvoices'); $this->display(); } function newmanufacturePDF() { JRequest::setVar('layout', 'newmanureport'); $this->display(); } function markSent() { $cid = JRequest::getVar('cid', 'array', array()); $modelBatch =& $this->getModel('batch'); $modelOrder =& $this->getModel('order'); if (is_array($cid)) { foreach ($cid as $id) { $modelBatch->SetId($id); $batch =& $modelBatch->getData(); if ($batch->statenameid != 'COMPLETED') continue; $modelBatch->SetStateName('SHIPPED'); $batchOrders =& $modelBatch->getOrders(); foreach ($batchOrders as $order) { $modelOrder->SetId($order->id); $modelOrder->SetAction('SHIPPED'); // $this->imCustomUpdateOrderStatus($order->id,'SHIP'); } } } $this->display(); } function saveBatchs() { $tracking_numbers = JRequest::getVar('tracking_numbers', 'array', array()); $agencies = JRequest::getVar('agencies', 'array', array()); $modelBatch =& $this->getModel('batch'); if (is_array($tracking_numbers)) foreach ($tracking_numbers as $key => $tk) { $data = array(); $data['id'] = $key; $data['tracking_number'] = $tk; $modelBatch->store($data); } if (is_array($agencies)) foreach ($agencies as $key => $tk) { $data = array(); $data['id'] = $key; $data['agency'] = $tk; $modelBatch->store($data); } $this->display(); } function cancelEditBatchs() { JRequest::setVar('editBatchs', array()); $this->display(); } function editBatchs() { $cid = JRequest::getVar('cid', 'array', array()); JRequest::setVar('editBatchs', $cid); $this->display(); } function cancelProduction() { $cid = JRequest::getVar('cid', 'array', array()); $action = 'CANCELMANUFACTURING'; $modelOrder =& $this->getModel('order'); if (is_array($cid)) foreach ($cid as $id) { $modelOrder->SetId($id); $modelOrder->setAction($action); } $this->display(); } function generateLabelsPDF() { if (JRequest::getVar('printLabels') == 1) $ids = JRequest::getVar('cid', 'array', array()); else { $ordersStr = JRequest::getVar('txtordernumbers'); $ordersStr = str_replace(' ', '', $ordersStr); if (!$ordersStr) $ids = JRequest::getVar('cid', 'array', array()); else $ids = explode(',', $ordersStr); } JRequest::setVar('orders', implode(',', $ids)); JRequest::setVar('layout', 'labels'); $this->display(); } function printLabels() { if (JRequest::getVar('printLabels') == 1) $ids = JRequest::getVar('cid', 'array', array()); else { $ordersStr = JRequest::getVar('txtordernumbers'); $ordersStr = str_replace(' ', '', $ordersStr); $ids = explode(',', $ordersStr); } $this->_printLabels($ids); $this->display(); } protected function _printLabels($ids) { $modelOrder =& $this->getModel('order'); if (count($ids) > 0) foreach ($ids as $id) { $modelOrder->SetId($id); $modelOrder->setManuAction('PRINT_LABEL'); } } function startManufacturing() { $printLabels = JRequest::getVar('printLabels'); $this->processManufacture(); JRequest::setVar('searchstate', 'MANUFACTURING'); if ($printLabels == 1) { $ids = JRequest::getVar('cid', 'array', array()); $this->_printLabels($ids); } $this->display(); } function expedition() { $this->processManufacture(); $this->display(); } function processManufacture() { $cid = JRequest::getVar('cid', 'array', array()); $action = ''; switch (JRequest::getVar('searchstate', 'string', '')) { case 'CHECKED': $action = 'STARTMANUFACTURING'; break; case 'MANUFACTURING': $action = 'ENDMANUFACTURING'; break; } $this->_processManufacture($cid, $action); } function _processManufacture($cid, $action) { if (!$action) return; $modelOrder =& $this->getModel('order'); if (is_array($cid)) foreach ($cid as $id) { $modelOrder->SetId($id); $modelOrder->setAction($action); if ($action == 'ENDMANUFACTURING') $this->completeOrderManufacturing($id); } } function completeOrderManufacturing($orderId) { $modelOrder =& $this->getModel('order'); $modelOrder->SetId($orderId); $data = array(); $data['id'] = $orderId; $dateNow = new JDate(); $data['manufactured_date'] = $dateNow->toMySQL(); $modelOrder->store($data); $order =& $modelOrder->getData(); if ($order->batch) { $modelBatch =& $this->getModel('batch'); $modelBatch->SetId($order->batch); $modelBatch->UpdateState(); } } function postHttps($url, $data) { $fic = fopen($_SERVER['DOCUMENT_ROOT'] . "/paypal.log", "a"); if ($fic) { $txt = date("YmdHis") . " "; foreach ($data as $key => $value) $txt .= $key . ":" . $value; $txt .= "\n"; fwrite($fic, $txt); fclose($fic); } $params = ""; foreach ($data as $key => $value) { if ($params != "") $params .= "&"; $params .= urlencode($key) . "=" . urlencode($value); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300); curl_setopt($ch, CURLOPT_TIMEOUT, 300); curl_setopt($ch, CURLOPT_POST, 1); // set POST method curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $result = curl_exec($ch); curl_close($ch); return $result; } function _paypalSecond() { $session = & JFactory::getSession(); $amount = (float)$session->get('amounttopay', '0'); if ($amount <= 0) return; $token = JRequest::getVar('token'); $payerId = JRequest::getVar('PayerID'); $data = $this->getPaypalData('DoExpressCheckoutPayment', $amount); $data['TOKEN'] = $token; $data['PAYERID'] = $payerId; if ($_SERVER['SERVER_NAME'] == 'tecnoinsole' || $_SERVER['SERVER_NAME'] == 'localtecnoinsole') $urlGetToken = 'https://api-3t.sandbox.paypal.com/nvp'; else $urlGetToken = 'https://api-3t.paypal.com/nvp'; $res = $this->postHttps($urlGetToken, $data); $arr = explode("&", $res); $vars = array(); for ($i = 0; $i < count($arr); $i++) { $reg = explode("=", $arr[$i]); $vars[$reg[0]] = $reg[1]; } $ack = $vars['ACK']; if ($ack == 'Success') { $modelUser =& $this->getModel('user'); $modelUser->makePayment($amount); } return $vars; } function &getPaypalData($method, $amount, $successUrl = '', $errorUrl = '') { if ($_SERVER['SERVER_NAME'] == 'tecnoinsole' || $_SERVER['SERVER_NAME'] == 'localtecnoinsole') { //tecnoinsole $userPaypal = 'sledes_1193686202_biz_api1.gmail.com'; $passPaypal = '1193686224'; $signature = 'A88c2y1ROjs4QgbJYwTzC7g6qxDDA9vC76F3Itz55v0GrTIvksQSKwVI'; } else { /* // tecnoinsole $userPaypal = 'info_api1.tecnoinsole.com'; $passPaypal = 'ML7MASW3NZ5B3T5M'; $signature = 'AFcWxV21C7fd0v3bYYYRCpSSRl31AFseIP4.ObXZrw.B0Jo40vPXxdqw'; */ // voxelworks.com $userPaypal = 'support_api1.voxelworks.com'; $passPaypal = 'BSGTPYV7Z9S5NQFJ'; $signature = 'AszW-L2evmOIy2u8vkcS5THQdXzoAeQR6NP70Zfldpc77RkLbWerSQue'; } $data = array( 'USER' => $userPaypal, 'PWD' => $passPaypal, 'SIGNATURE' => $signature, 'VERSION' => '51.0', 'METHOD' => $method, 'PAYMENTACTION' => 'Sale', 'AMT' => sprintf("%0.02f", $amount), 'RETURNURL' => "http://" . $_SERVER['HTTP_HOST'] . $successUrl, 'CANCELURL' => "http://" . $_SERVER['HTTP_HOST'] . $errorUrl, 'CURRENCYCODE' => 'EUR' ); return $data; } function _paypalFirst(&$paypalData) { if ($_SERVER['SERVER_NAME'] == 'tecnoinsole' || $_SERVER['SERVER_NAME'] == 'localtecnoinsole') { $urlGetToken = 'https://api-3t.sandbox.paypal.com/nvp'; $urlPortal = 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&useraction=commit'; } else { $urlGetToken = 'https://api-3t.paypal.com/nvp'; $urlPortal = 'https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&useraction=commit'; } $res = $this->postHttps($urlGetToken, $paypalData); //$res=urldecode($res); $arr = explode("&", $res); $vars = array(); for ($i = 0; $i < count($arr); $i++) { $reg = explode("=", $arr[$i]); $vars[$reg[0]] = $reg[1]; } $token = $vars['TOKEN']; $session = & JFactory::getSession(); $session->set('amounttopay', $paypalData['AMT']); $this->setRedirect($urlPortal . "&token=$token"); } function buyCredit() { $amount = (float)str_replace(',', '.', JRequest::getVar('amount')); if ($amount <= 0) { JRequest::setVar('view', 'payment'); JRequest::setVar('layout', 'success'); $this->display(); return; } $successUrl = '/index.php?option=com_vxc&controller=myaccount&task=buyCreditPass2'; $errorUrl = '/index.php?option=com_vxc&view=payment&layout=failure'; $data = $this->getPaypalData('SetExpressCheckout', $amount, $successUrl, $errorUrl); $this->_paypalFirst($data); } function buyCreditPass2() { $vars = $this->_paypalSecond(); $ack = $vars['ACK']; if ($ack == 'Success') JRequest::setVar('layout', 'success'); else JRequest::setVar('layout', 'failure'); JRequest::setVar('view', 'payment'); $this->display(); } protected function _canIAddNInsolesToThisDay($wantedDate, $holidays, $checkFull, $batchOrderDistribution = array()) { $day = date('N', $wantedDate); $date = date('Y-m-d', $wantedDate); // Comprobamos si cae en festivo $festivo = in_array($date, $holidays); if ($day >= 6 || $festivo) return false; if (!$checkFull) return true; // Comprobamos si el dia esta completo $modelSettings =& $this->getModel('settings'); $nInsoles = 0; foreach ($batchOrderDistribution as $el) $nInsoles += (int)$el; //echo 'Numero total de pedidos en el lote: '.$nInsoles. '
'; $modelOrders =& $this->getModel('orders'); // Comprobamos si cumple el limite global de plantillas por dia $globalLimit = $modelSettings->getVar('maxProductionPerDay', 0); //echo 'Limite global de produccion: '.$globalLimit. '
'; $globalCount = (int)$modelOrders->getManufacturingInsoleCountPerDate($date); //echo 'Numero global de plantillas ara el dia '. $date .' : '.$globalCount. '
'; $noCabe = ($globalLimit - $globalCount) < $nInsoles; /* if ($noCabe) echo 'Limite global alcazado
'; else echo 'Limite global no alcazado
';*/ if (!$noCabe) { //echo 'Comprobamos condiciones
'; // Si cumple el limite global pasamos a comprobar cada una de las condiciones // del fichero de configuracion que afectan al lote. Si no cumple alguna // de las condiciones. Tendremos que pasarlo a otro dia $conditions =& $this->getPlanningConditions($batchOrderDistribution); $categories =& $this->getInsoleCategories(); $catOptions = array(); if (count($categories) > 0) foreach ($categories as $cat) { if (!$catOptions[$cat['name']]) $catOptions[$cat['name']] = array(); $catOptions[$cat['name']]['insoleOptions'] = $cat['options']; $catOptions[$cat['name']]['productOptions'] = $cat['productOptions']; } // Recorremos todas las condiciones aplicables al pedido if (count($conditions) > 0) foreach ($conditions as $cond) { $limit = $cond['maxProductionPerDay']; if ($limit === null) continue; $limit = (int)$limit; $condCats = $cond['categories']; //echo 'Categorias de la condicion: '.print_r($condCats,true); //echo 'Limite de produccion de la condicion: ' . $limit . '
'; // Formamos un array de las insoleOptions de las plantillas que forman parte de la condicion $insoleOptions = array(); $productOptions = array(); if (count($condCats) > 0) foreach ($condCats as $condCat) { if (count($catOptions[$condCat]['insoleOptions']) > 0) foreach ($catOptions[$condCat]['insoleOptions'] as $opt) $insoleOptions[] = $opt; if (count($catOptions[$condCat]['productOptions']) > 0) foreach ($catOptions[$condCat]['productOptions'] as $opt) $productOptions[] = $opt; } //echo 'InsoleOptions a consultar: '.print_r($insoleOptions,true); // Obtenemos para la fecha dada, el numero de plantilla que intervienen en esta condicion $count = $modelOrders->getManufacturingInsoleCountPerDate($date, $insoleOptions, $productOptions); //echo 'Plantillas en produccion para el dia '.$date.' con condiciones: ' . $count . '
'; // Suma de las plantillas del lote que forman parte de la condicion $nInsoles = 0; foreach ($batchOrderDistribution as $key => $el) if (in_array($key, $condCats)) $nInsoles += (int)$el; //echo 'Suma de las plantillas con ese tipo del lote' . $nInsoles; // Comprobamos si cabe en el día if (($limit - $count) < $nInsoles) { $noCabe = true; //echo 'No cumple la condicion
'; break; } /* else echo 'Cumple la condicion
';*/ } } // Si no cabe pero el dia esta vacío , lo metemos ahi igualmente if ($noCabe && $globalCount == 0) { //echo 'No tenemos mas remedio que ponerno en este dia'; return true; } /* if ($noCabe) echo "No aceptamos el dia
"; else echo "Aceptamos el dia
"; */ if ($noCabe) return false; return true; } function getNextBusinessDay($startdate, $daystoadd) { $modelHolidays =& $this->getModel('holidays'); $holidays = array_map('trim', explode("\n", $modelHolidays->getHolidaysAsText())); $modelSettings =& $this->getModel('settings'); return $this->_add_business_days(null, $startdate, $daystoadd, $holidays, 'Y-n-j', false); } protected function _add_business_days($batchOrderDistribution, $startdate, $buisnessdays, $holidays = array(), $dateformat = 'Y-m-d', $checkProduction) { $i = 0; $dayx = strtotime($startdate); $buisnessdays = ceil($buisnessdays); $hour = date('H', $dayx); $hour += date('Z') / 3600.0; $day = date('N', $dayx); $date = date('Y-m-d', $dayx); if ($this->_canIAddNInsolesToThisDay($dayx, $holidays, false)) { if ($checkProduction && ($hour >= 15)) $buisnessdays++; } while ($i < $buisnessdays) { $day = date('N', $dayx); $date = date('Y-m-d', $dayx); if ($this->_canIAddNInsolesToThisDay($dayx, $holidays, false)) $i++; $dayx = strtotime($date . ' +1 day'); } ## If the calculated day falls on a weekend or is a holiday, then add days to the next business day $day = date('N', $dayx); $date = date('Y-m-d', $dayx); while (!$this->_canIAddNInsolesToThisDay($dayx, $holidays, $checkProduction, $batchOrderDistribution)) { $dayx = strtotime($date . ' +1 day'); $day = date('N', $dayx); $date = date('Y-m-d', $dayx); } return date($dateformat, $dayx); } // Añade una entidad OrderDetail con un pedido del sistema Voxelcare a IMCustom function imCustomAddProduct() { $orderId = JRequest::getVar('orderId'); $this->_imCustomAddProduct($orderId); header('Content-type: application/json'); echo '{"result":"ok","data":{}}'; exit; } // Alias de retrocompatiblidad para imCustomAddProduct function mvcPayOrder() { $this->imCustomAddProduct(); } /** * Añade un productDetail al pedido de imcustom relacionado con el orderId pasado por parametro * @param $orderId ID del pedido de Voxelcare * @return bool Devuelve true si el producto se añadio correctamente o false en caso contrario */ private function _imCustomAddProduct($orderId) { // Los datos de acceso al middleware de IMCustom vienen en globals definidas en release.json $imCustomMiddleware = LegacyHelper::getPHPGlobalVar('imCustomMiddleware'); $imCustomService = LegacyHelper::getPHPGlobalVar('imCustomService'); if (!$imCustomMiddleware || !$imCustomService) return false; $orderId = (int)$orderId; if (!$orderId) return false; // Obtenemos los datos del pedido en el sistema Voxelcare $modelOrder =& $this->getModel('order'); $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); if (!$order) return false; // Comprobamos que el pedido este asociado a un usuario $userId = $order->user; if (!$userId) return false; $userName = $order->userusername; // Verificamos que tenemos los datos necesarios para actualizar el pedido if (!$userName) return false; // De los atributos del pedido extraemos el numero de ID del pedido en ImCustom,el servidor asociado y el // producto seleccionado del pedido $orderAts =& $modelOrder->getAttributes(); $imCustomOrderId = 0; $imCustomOrderDetailId = 0; $imCustomServer = ''; $size = 0; if ($orderAts && is_array($orderAts)) { foreach ($orderAts as $at) { switch ($at->name) { case "general.customOrderId": $imCustomOrderId = (int)$at->value; break; case "general.imCustomServer": $imCustomServer = $at->value; break; case "general.imCustomOrderDetail": $imCustomOrderDetailId = $at->value; break; case "general.product": $product = $at->value; break; case "insoleOptions.shoeSizeEU.right": case "insoleOptions.shoeSizeEU.left": if ($at->value) $size = max($size, (float)$at->value); break; } } } if ($imCustomOrderDetailId) // Si ya tenemos orderDetailId no hacemos nada return true; // A partir del producto , y utilizando el esquema de datos, extraemos el id del producto IMcustom $schema =& LegacyHelper::getPersistentSchema(); if (!$schema) return false; // Tenemos esquema, consultamos los atributos del nodo attributes.general.product $schemaAts = LegacyHelper::getSchemaNodeAttributes($schema, 'attributes.general.product'); if (!$schemaAts) return false; // Tenemos attributos del nodo, miramos las options del nodo $options = $schemaAts["options"]; if (!$options) return false; // Consultamos las variables asociadas al producto del pedido $productAts = $options[$product]; if (!$productAts) return false; // Extraemos el ID del producto IMCustom $imcustom_product = $productAts['imCustomProductId']; if (isset($imcustom_product) && is_array($imcustom_product)) { foreach ($imcustom_product as $ip) { $server = $ip["server"]; $productId = $ip["productId"]; if ($server == $imCustomServer) { $imcustom_product = $productId; break; } } } // En este punto tenemos toda la informacion necesaria para enviar al middleware $params = array(); $params['imserver'] = $imCustomServer; $params['imcustom_order_id'] = $imCustomOrderId; $params['imcustom_product'] = $imcustom_product; $params['username'] = $userName; $params['size'] = sprintf('%0.1f', $size); $response = null; // Realizamos la llamada al servicio IMCustom con la funcion addOrderProduct if (!$this->imCustomCallService('addOrderProduct', $params, $response)) return false; // Comprobamos si la respuesta es correcta if (!$response || $response->result != 'ok') return false; $orderProductId = $response->data->orderProductId; $atOrderDetailId = new stdClass(); $atOrderDetailId->name = 'general.imCustomOrderDetail'; $atOrderDetailId->value = $orderProductId; $atOrderReference = new stdClass(); $atOrderReference->name = 'general.reference'; $newReference = $imCustomOrderId . '/' . $orderProductId; $atOrderReference->value = $newReference; $newAts = array($atOrderDetailId, $atOrderReference); $options = new stdClass(); $options->attributes = $newAts; $modelOrder->saveNewAttributes($options); $data = array(); $data['id'] = $orderId; $data['reference'] = $newReference; $modelOrder->store($data); // Si to-do va bien marcamos el pedido como completo /* if (!$this->imCustomUpdateOrderStatus($orderId,"COMP")) return false; */ return true; } // Llama a un servicio del middleware GlenGrabJson function imCustomCallService($functionName, $params, &$response) { // Los datos de acceso al middleware de IMCustom vienen en globals definidas en release.json $imCustomMiddleware = LegacyHelper::getPHPGlobalVar('imCustomMiddleware'); $imCustomService = LegacyHelper::getPHPGlobalVar('imCustomService'); if (!$imCustomMiddleware || !$imCustomService) return false; // Como hay pedidos sin servidor asociado, éstos van al servidor inicial if (!$params['imserver']) $params['imserver'] = 'service.imcustom.com'; // Rellenamos el objeto de los parametros a enviar por POST $data = new stdClass(); foreach ($params as $key => $value) $data->{$key} = $value; // Los datos van en formato JSON $json = new Services_JSON(); $statusCode = 0; $headers = array(); // Realizamos la peticion al middleware $url = $imCustomMiddleware . '/' . $imCustomService . '/' . $functionName; $responseStr = LegacyHelper::httpRequest('POST', $url, $json->encode($data), null, $statusCode, $headers); /* $log = "Status: $statusCode\n"; if (count($headers)>0) { foreach( $headers[0] as $key=>$value); $log .= "Header: $key=$value\n"; } $log .= "Content:\n".$responseStr."\n"; file_put_contents("c:\\updateStatus.log",$log, FILE_APPEND); */ // Decodificamos la respuesta y comprobamos que tuvo éxito if ($statusCode != 200) return false; $response = $json->decode($responseStr); if (!$response || $response->result != 'ok') return false; return true; } /** * Actualiza el estado del pedido en IMCustom en el servidor de REST API * @param $orderId Id del pedido en el sistema Voxelcare * @param $status string Nuevo estado del pedido (NEW,MFACT,TOOL,SHIP) * @return bool Devuelve true si el pedido fue actualizado con éxito, false en caso contrario */ function imCustomUpdateOrderStatus($orderId, $status) { // Los datos de acceso al middleware de IMCustom vienen en globals definidas en release.json $imCustomMiddleware = LegacyHelper::getPHPGlobalVar('imCustomMiddleware'); $imCustomService = LegacyHelper::getPHPGlobalVar('imCustomService'); if (!$imCustomMiddleware || !$imCustomService) return false; $orderId = (int)$orderId; if (!$orderId || !$status) return false; // Obtenemos los datos del pedido en el sistema Voxelcare $modelOrder =& $this->getModel('order'); $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); if (!$order) return false; // Comprobamos que el pedido este asociado a un usuario $userId = $order->user; if (!$userId) return false; $userName = $order->userusername; // Verificamos que tenemos los datos necesarios para actualizar el pedido if (!$userName) return false; $url = $imCustomMiddleware . '/' . $imCustomService . '/updateOrderStatus'; $orderAts =& $modelOrder->getAttributes(); // De los atributos del pedido extraemos el numero de ID del pedido en ImCustom y el servidor asociado $imCustomOrderId = 0; $imCustomServer = ''; if ($orderAts && is_array($orderAts)) { foreach ($orderAts as $at) { switch ($at->name) { case "general.customOrderId": $imCustomOrderId = (int)$at->value; break; case "general.imCustomServer": $imCustomServer = $at->value; break; } } } // Rellenamos los parametros $params = array(); $params['username'] = $userName; $params['imcustom_order_id'] = $imCustomOrderId; $params['imserver'] = $imCustomServer; $params['status'] = $status; $response = null; // Realizamos la llamada al servicio IMCustom con la funcion updateOrderStatus if (!$this->imCustomCallService('updateOrderStatus', $params, $response)) return false; // Comprobamos la respuesta recibida if (!$response || $response->result != 'ok') return false; return true; } // Borra el pedido asociado a una entidad OrderDetail de IMCustom function imCustomDeleteOrderDetail() { $imcustom_order_detail_id = JRequest::getVar('imcustom_order_detail_id'); $imserver = JRequest::getVar('imserver'); $options = new stdClass(); $options->imcustom_order_detail_id = $imcustom_order_detail_id; $options->imserver = $imserver; $res = new stdClass(); $this->_imCustomDeleteOrderDetail($options, $res); $json = new Services_JSON(); header('Content-type: application/json'); echo $json->encode($res); exit; } // Metodo privado para borrar el pedido asociado a una entidad OrderDetail private function _imCustomDeleteOrderDetail($params, $res) { $imcustom_order_detail_id = $params->imcustom_order_detail_id; $imserver = $params->imserver; if (!$imcustom_order_detail_id) { $res->result = "error"; $res->error = "Missing imcustom_order_detail_id parameter"; return; } if (!$imserver) { $res->result = "error"; $res->error = "Missing imserver parameter"; return; } $modelOrder =& $this->getModel('order'); $orderId = $modelOrder->getOrderIdFromIMOrderDetail($imcustom_order_detail_id, $imserver); if (!$orderId) { $res->result = "error"; $res->error = "No order found for order detail id $imcustom_order_detail_id"; return; } $modelOrders =& $this->getModel('orders'); $deletedOrders = $modelOrders->delete(array($orderId)); if (!in_array($orderId, $deletedOrders)) { $res->result = "error"; $res->error = "Couldn't delete order detail id $imcustom_order_detail_id"; return; } $res->result = 'ok'; $res->data = new stdClass(); } // Metodo privado para obtener la informacion visible para IMCustom asociada a un OrderDetail private function _imCustomGetOrderDetailInfo($params, $res) { // Obtencion y comprobación de parámetros $imcustom_order_detail_id = $params->imcustom_order_detail_id; $imserver = $params->imserver; if (!$imcustom_order_detail_id) { $res->result = "error"; $res->error = "Missing imcustom_order_detail_id parameter"; return; } if (!$imserver) { $res->result = "error"; $res->error = "Missing imserver parameter"; return; } // Obtencion del orderid asociado al pedido $modelOrder =& $this->getModel('order'); $orderId = $modelOrder->getOrderIdFromIMOrderDetail($imcustom_order_detail_id, $imserver); if (!$orderId) { $res->result = "error"; $res->error = "No order found for order detail id $imcustom_order_detail_id"; return; } // Obtenemos los datos del pedido y devolvemos los que sean visibles para ImCustom $modelOrder->SetId($orderId); $order = $modelOrder->getData(); $res->result = 'ok'; $res->data = new stdClass(); $res->data->id = $order->id; // ID del pedido $res->data->status = $order->statenameid; // Nombre lógico del estado en el que se encuentra $res->data->batch = $order->batch; // ID del lote } // Obtiene la informacion visible para IMCustom asociada a un OrderDetail function imCustomGetOrderDetailInfo() { $imcustom_order_detail_id = JRequest::getVar('imcustom_order_detail_id'); $imserver = JRequest::getVar('imserver'); // Obtenemos la informacion del pedido $options = new stdClass(); $options->imcustom_order_detail_id = $imcustom_order_detail_id; $options->imserver = $imserver; $res = new stdClass(); $this->_imCustomGetOrderDetailInfo($options, $res); // Devolvemos la respuesta $json = new Services_JSON(); header('Content-type: application/json'); echo $json->encode($res); exit; } // Lanza el proceso para pagar los pedidos de un array de entidades Order de ImCustom function imCustomDispatchOrders() { $imcustom_order_ids = JRequest::getVar('imcustom_order_ids'); $imserver = JRequest::getVar('imserver'); $params = new stdClass(); $params->imcustom_order_ids = $imcustom_order_ids; $params->imserver = $imserver; $res = new stdClass(); $this->_imCustomDispatchOrders($params, $res); $json = new Services_JSON(); header('Content-type: application/json'); echo $json->encode($res); exit; } // Metodo privado que lanza el proceso para pagar los pedidos de un array de entidades Order de ImCustom private function _imCustomDispatchOrders($params, $res) { $imcustom_order_ids = $params->imcustom_order_ids; $imserver = $params->imserver; if (!$imcustom_order_ids) { $res->result = "error"; $res->error = "Missing imcustom_order_ids parameter"; return; } if (!$imserver) { $res->result = "error"; $res->error = "Missing imserver parameter"; return; } $imcustom_order_ids = explode(',', $imcustom_order_ids); $res->result = "ok"; $res->data = new stdClass(); $res->data->results = array(); if (count($imcustom_order_ids) > 0) { foreach ($imcustom_order_ids as $imcustom_order_id) { $options = new stdClass(); $options->imcustom_order_id = $imcustom_order_id; $options->imserver = $imserver; $tmp = new stdClass(); $this->_imCustomDispatchOrder($options, $tmp); $res->data->results[] = $tmp; } } } // Realiza el pago de todos los pedidos relacionados con una entidad Order de IMCustom private function _imCustomDispatchOrder($options, $res) { // Rellenamos los parametros $imcustom_order_id = $options->imcustom_order_id; $imserver = $options->imserver; // Comprobación de parametros if (!$imcustom_order_id) { $res->result = "error"; $res->error = "Missing imcustom_order_id parameter"; return; } if (!$imserver) { $res->result = "error"; $res->error = "Missing imserver parameter"; return; } // El acceso a la base de datos lo haremos a través del modelo del order $modelOrder =& $this->getModel('order'); // Obtenemos los pedidos de nuestro sistema asociados al pedido de IMCustom $params = array(); $params['imcustom_order_id'] = $imcustom_order_id; $params['imserver'] = $imserver; $ret = new stdClass(); $modelOrder->getOrdersFromIMOrder($params, $ret); if (!$ret || $ret->result == "error") { $res->result = "error"; $res->error = ($ret ? $ret->error : "Unknown error"); return; } // Obtenemos la lista de aquellos pedidos que no han sido pagados todavia (no tienen lote) $ordersToPay = array(); $userId = $ret->data->userId; $vxOrders = $ret->data->orders; if (count($vxOrders) > 0) { foreach ($vxOrders as $order) { if (!$order->batch) { $ordersToPay[] = $order->id; } } } $batchId = ''; // Si aún queda algun pedido por pagar, procedemos al pago mediante factura if (count($ordersToPay) > 0) { $paymentMethod = 'BYINVOICE'; $agencyId = NULL; $shipping_address = NULL; $modelPaymentMethods =& $this->getModel('paymentmethods'); $modelUser =& $this->getModel('user'); $modelUser->SetId($userId); $methodId = $modelPaymentMethods->GetIdFromNameId($paymentMethod); $batchId = $this->_paymentsuccess($ordersToPay, $methodId, $agencyId, $userId, $shipping_address); if (!$batchId) { $res->result = "error"; $res->error = "Error processing payment"; return; } } // Devolvemos una lista de los pedidos asociados con el id del pedido, el id del order_detail y el id del batch if (count($vxOrders) > 0) { foreach ($vxOrders as $order) { if (!$order->batch) { // Rellenamos los campos del lote con el id del nuevo lote $order->batch = $batchId; } } } $res->result = 'ok'; $res->data = new stdClass(); $res->data->orders = $vxOrders; } function _paymentsuccess($cid, $method, $agencyId, $userId = 0, $shipping_address = null) { if (!is_array($cid) || count($cid) <= 0 || !$method) return false; $fakePayment = (LegacyHelper::getPHPGlobalVar('fakePayment') == 1); $modelOrder =& $this->getModel('order'); $orderCount = 0; if (count($cid) > 0) foreach ($cid as $orderId) { $orderCount++; $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); if ($order->batch) // Si algun pedido tiene ya lote, no creamos uno nuevo return false; } $modelBatch =& $this->getModel('batch'); $modelUser =& $this->getModel('user'); $modelReceipt =& $this->getModel('receipt'); if ($userId != 0) $modelUser->SetId($userId); else $userId = $modelUser->GetId(); $modelAgency =& $this->getModel('agency'); if ($agencyId) $modelAgency->SetId($agencyId); $modelBatchStates =& $this->getModel('batchstates'); $data = array(); $data['id'] = null; $dateNow = new JDate(); $dateS = $dateNow->toMySQL(); $data['payment_date'] = $dateS; $data['state'] = $modelBatchStates->getIdFromName('INCOMPLETED'); $data['payment_method'] = $method; $shippingCostInfo = $modelAgency->getShippingCostInfo($modelUser, $orderCount); $data['shipping_cost'] = $shippingCostInfo['price']; $data['shipping_vat'] = $shippingCostInfo['vat']; $data['agency'] = $agencyId; $deliveryNotes =& $modelUser->getPendingDeliveryNotes(); $modelDeliveryNote =& $this->getModel('deliverynote'); $deliveryNotesCost = 0; if (is_array($deliveryNotes)) foreach ($deliveryNotes as $dn) $deliveryNotesCost += $dn->total; $data['deliverynotes_cost'] = round($deliveryNotesCost, 2); $modelPM =& $this->getModel('paymentmethods'); $methodNameId = $modelPM->getNameIdFromId($method); $paymentCharge = $modelUser->getPaymentCharge($methodNameId); $data['payment_inc_cost'] = $paymentCharge; // Si el pedido se paga mediante factura o mediante recibo, se coje el usuario // como el creador del pedido. En otro caso, se usa el usuario activo en este momento if ($methodNameId != 'BYINVOICE' && $methodNameId != 'BYRECEIPT') $data['payment_user'] = $modelUser->GetId(); else { $modelOrder->SetId($cid[0]); $order =& $modelOrder->getData(); $data['payment_user'] = $order->user; $modelUser->SetId($order->user); } switch ($methodNameId) { case 'TEST': case 'SAMPLE': $discount = 100; break; default: $discount = 0; } switch ($methodNameId) { case 'SAMPLE': case 'TEST': case 'BUDGET': case 'CASHONDELIVERY': $vat = 0; $equivalence_charge = 0; break; default: $vat = $modelUser->getVAT(); $equivalence_charge = $modelUser->getEquivalenceCharge(); } $data['discount'] = $discount; $data['taxpercent'] = $vat; $data['equivalence_charge'] = $equivalence_charge; if ($shipping_address) $data['shipping_address'] = $shipping_address; $modelBatch->store($data); // Comprobamos que todos los pedidos han sido pagados // si tienen factura, si hay algun pedido sin recibo pagado $batchId = $data['id']; if ($batchId) { if (is_array($deliveryNotes)) foreach ($deliveryNotes as $dn) { $modelDeliveryNote->SetId($dn->id); $dataDn = array(); $dataDn['id'] = $dn->id; $dataDn['paid'] = 1; $dataDn['batch'] = $batchId; $modelDeliveryNote->store($dataDn); } $shippingVat = $data['shipping_vat']; $shippingVatAmount = round($data['shipping_cost'] * $shippingVat / 100.0, 2); $totalShippingCost = round($data['shipping_cost'] + $shippingVatAmount, 2); $priceTotal = $totalShippingCost + $data['deliverynotes_cost']; if (count($cid) > 0) foreach ($cid as $id) { $modelOrder->SetId($id); $price = 0; $patientPrice = 0; $companyFee = 0; $franchiseFee = 0; $modelOrder->getCurrentPrices($price, $patientPrice, $companyFee, $franchiseFee); $vatAmount = round($price * $vat / 100.0, 2); $equivChargeAmount = round($price * $equivalence_charge / 100.0, 2); $totalAmount = round($price + $vatAmount + $equivChargeAmount, 2); $discountAmount = round($totalAmount * $discount / 100.0, 2); $paid_amount = round($totalAmount - $discountAmount, 2); $orderData = array(); $orderData['id'] = $id; $orderData['price'] = $price; $orderData['patient_price'] = $patientPrice; $orderData['franchise_to_company_fee'] = $companyFee; $orderData['voxelcare_to_franchise_fee'] = $franchiseFee; $orderData['paid_amount'] = $paid_amount; $orderData['batch'] = $batchId; $modelOrder->store($orderData); $useExtendedFees = SiteOptionsHelper::useExtendedFees(); if ($useExtendedFees) { $modelOrderIndia =& $this->getModel('orderindia'); $info = $modelOrderIndia->getOrderIndiaInfo($id); $indiaData = array(); $indiaData['id'] = null; $indiaData['orderid'] = $id; $indiaData['design_fee'] = $info['design_fee']; $indiaData['usage_fee'] = $info['usage_fee']; $indiaData['design_type'] = $info['design_type']; $modelOrderIndia->store($indiaData); } $modelOrder->setAction('PAY'); $priceTotal += $paid_amount; switch ($methodNameId) { case 'TEST': case 'SAMPLE': break; case 'BYRECEIPT': $receiptId = $modelReceipt->getIdFromOrderId($id); if (!$receiptId) // Si no se ha generado el recibo se genera ReceiptGeneratorHelper::generate($this, $id); else //Sino, comprobamos si la factura a cliente ha de generarse ahora $this->_checkCustomerInvoiceGenerationByReceiptId($receiptId); break; default: if ($modelUser->checkPrivilege('Generate customer invoices')) $this->generateInvoiceByOrder($id, true); } } $priceTotal *= (1.0 + $paymentCharge / 100.0); switch ($methodNameId) { case 'TEST': case 'SAMPLE': case 'CASHONDELIVERY': break; default: $modelUser->makeOrder($priceTotal); } if (!$fakePayment && $methodNameId != 'BYRECEIPT' && ($methodNameId != 'CREDIT' || !$modelUser->checkPrivilege("Don't generate invoice on credit payment")) ) $this->generateInvoiceByBatch($batchId); } $session =& JFactory::getSession(); if ($session) { $session->set('batchId', $batchId); $session->set('payingorders', array()); $session->set('payingmethod', ''); $session->set('payingagency', ''); $session->set('payingshipping_address', ''); } return $batchId; } function buyGatewayBatch2() { $session =& JFactory::getSession(); $payingOrders = $session->get('payingorders', array()); $payingMethod = $session->get('payingmethod', null); $payingAgency = $session->get('payingagency', null); $payingShippingAddress = $session->get('payingshipping_address', null); $session->set('payingorders', array()); $session->set('payingmethod', ''); $session->set('payingagency', ''); $session->set('payingshipping_address', ''); $good = false; $modelPaymentMethods =& $this->getModel('paymentmethods'); $methodName = $modelPaymentMethods->getNameIdFromId($payingMethod); if ($methodName != 'PAYPAL') { $good = true; } else { $vars = $this->_paypalSecond(); $good = ($vars['ACK'] == 'Success'); if ($good) $this->_paymentsuccess($payingOrders, $payingMethod, $payingAgency, 0, $payingShippingAddress); } JRequest::setVar('layout', $good?'success':'failure'); JRequest::setVar('view', 'payment'); $this->display(); } function processLaCaixaResponse() { $ordersId = JRequest::getVar('payingorders'); $cid = explode(',', $ordersId); $methodId = JRequest::getVar('payingmethod'); $agencyId = JRequest::getVar('payingagency'); $shipping_address = JRequest::getVar('payingshipping_address'); $userId = (int)JRequest::getVar('payinguser'); // NEW PARAMETERS $signature = strtr(JRequest::getVar('Ds_Signature'), '-_', '+/'); $signatureVersion = JRequest::getVar('Ds_SignatureVersion'); $encodedMerchantParameters = JRequest::getVar('Ds_MerchantParameters'); $json = new Services_JSON(); $decodedMerchantParameters = base64_decode(strtr($encodedMerchantParameters, '-_', '+/')); $merchantParameters = $json->decode($decodedMerchantParameters); $response = $merchantParameters->{'Ds_Response'}; $amount = $merchantParameters->{'Ds_Amount'}; $order = $merchantParameters->{'Ds_Order'}; $code = $merchantParameters->{'Ds_MerchantCode'}; $currency = $merchantParameters->{'Ds_Currency'}; /* OLD PARAMETERS */ /* $response = JRequest::getVar('Ds_Response'); $signature = JRequest::getVar('Ds_Signature'); $amount = JRequest::getVar('Ds_Amount'); $order = JRequest::getVar('Ds_Order'); $code = JRequest::getVar('Ds_MerchantCode'); $currency = JRequest::getVar('Ds_Currency'); switch ($_SERVER['HTTP_HOST']) { case 'local.voxelcare.com': case 'elche.voxelcare.com': case 'voxelcare': case 'devtecnoinsole': case 'test.tecnoinsole.com': case 'tecnoinsole': case 'localtecnoinsole': $clave = 'qwertyasdf0123456789'; // clave TEST break; default: $clave = '5M3M2OHB9QVQ16IM'; } $message = $amount . $order . $code . $currency . $response . $clave; $goodSignature = strtoupper(sha1($message)); */ switch ($_SERVER['HTTP_HOST']) { case 'local.voxelcare.com': case 'elche.voxelcare.com': case 'voxelcare': case 'devtecnoinsole': case 'test.tecnoinsole.com': case 'tecnoinsole': case 'localtecnoinsole': $clave = 'sq7HjrUOBfKmC576ILgskD5srU870gJ7'; // clave TEST break; default: $clave = 'vNk6Ayc4md37QnIlTQKdvJGvSKdBlHi9'; } $clave = base64_decode($clave); $clave = mcrypt_encrypt(MCRYPT_3DES, $clave, $merchantParameters->{'Ds_Order'}, MCRYPT_MODE_CBC, implode(array_map("chr", array(0,0,0,0,0,0,0,0)))); $goodSignature = base64_encode(hash_hmac('sha256', $encodedMerchantParameters , $clave, true)); $good = 'NO'; if ($signature == $goodSignature && (int)$response >= 0 && (int)$response <= 99 && $userId != 0) { $good = 'YES'; $modelUser =& $this->getModel('user'); $modelUser->SetId($userId); $modelUser->makePayment(((float)$amount) / 100.0); $this->_paymentsuccess($cid, $methodId, $agencyId, $userId, $shipping_address); } $today = date("Y-m-d H:i:s"); $logText = "$today Good: $good Server: " . $_SERVER['HTTP_HOST'] . " Orders: $ordersId Payment Method: $methodId Agency: $agencyId Shipping address: $shipping_address User: $userId\n" . "Response: $response Signature: $signature Good signature: $goodSignature Message: $decodedMerchantParameters Amount: $amount Order: $order MerchantCode: $code Currency: $currency\n"; @file_put_contents('paymentslacaixa.log', $logText, FILE_APPEND); exit; } function buyBatch() { $method = JRequest::getVar('method'); $agencyId = JRequest::getVar('agency'); $shipping_address = JRequest::getVar('shipping_address'); $cid = JRequest::getVar('cid', 'array', array()); $modelPaymentMethods =& $this->getModel('paymentmethods'); $modelUser =& $this->getModel('user'); $modelOrder =& $this->getModel('order'); $methodId = $modelPaymentMethods->GetIdFromNameId($method); $errorIds = array(); if (count($cid) > 0) foreach ($cid as $orderId) { $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); if ($order->batch) { $errorIds[] = $orderId; } } if (count($errorIds) > 0) { $errorMsg = JText::_('PAY_BATCH_WITH_ALREADY_PAID_ORDERS_MSG'); if ($errorMsg == 'PAY_BATCH_WITH_ALREADY_PAID_ORDERS_MSG') { $errorMsg = 'Batch contains orders already paid.
This can occur when the state of the order has been manually changed or when two or more payments commands has been sent by the user.
To solve this, change again the order state to its previous status or ignore this message if the orders have been correctly paid.'; } $errorMsg .= '
' . JText::_('Orders') . ': ' . implode(',', $errorIds); JRequest::setVar('error', $errorMsg); JRequest::setVar('view', 'payment'); JRequest::setVar('layout', 'failure'); $this->display(); return; } $paymentCharge = $modelUser->getPaymentCharge($methodId); switch ($method) { case 'PAYPAL': case 'CREDITCARD': $session =& JFactory::getSession(); $session->set('payingorders', $cid); $session->set('payingmethod', $methodId); $session->set('payingagency', $agencyId); $session->set('payingshipping_address', $shipping_address); $successUrl = ''; $errorUrl = ''; if (LegacyHelper::getNewMode()) { $successUrl .= '/joomla'; $errorUrl .= '/joomla'; } $successUrl .= '/index.php?option=com_vxc&controller=myaccount&task=buyGatewayBatch2'; $errorUrl .= '/index.php?option=com_vxc&controller=myaccount&view=payment&layout=failure'; $modelAgency =& $this->getModel('agency'); $modelAgency->SetId($agencyId); $amount = 0; $deliveryNotesCost = $modelUser->getPendingDeliveryNotesCost(); if (count($cid) > 0) foreach ($cid as $id) { $modelOrder->SetId($id); $price = $modelOrder->getCurrentCompanyPrice(); $amount += $price; } if ($amount >= 0.01 || $deliveryNotesCost >= 0.01) { $vat = $modelUser->getVAT(); $equivalence_charge = $modelUser->getEquivalenceCharge(); $amount *= (1.0 + ($vat + $equivalence_charge) / 100.0); $shippingCostInfo = $modelAgency->getShippingCostInfo($modelUser, count($cid)); $shippingCost = $shippingCostInfo['price']; $shippingVat = $shippingCostInfo['vat']; $shippingTotalCost = round($shippingCost * (1.0 + $shippingVat / 100.0), 2); $amount += $shippingTotalCost; $amount += $deliveryNotesCost; $amount *= (1.0 + $paymentCharge / 100.0); if ($method == 'PAYPAL') { $data = $this->getPaypalData('SetExpressCheckout', $amount, $successUrl, $errorUrl); $this->_paypalFirst($data); } else if ($method == 'CREDITCARD') { JRequest::setVar('successUrl', $successUrl); JRequest::setVar('errorUrl', $errorUrl); JRequest::setVar('amount', $amount); JRequest::setVar('view', 'lacaixagateway'); JRequest::setVar('task', 'display'); $this->display(); } } else { $this->_paymentsuccess($cid, $methodId, $agencyId, 0, $shipping_address); JRequest::setVar('view', 'payment'); JRequest::setVar('layout', 'success'); $this->display(); } break; default: $this->_paymentsuccess($cid, $methodId, $agencyId, 0, $shipping_address); JRequest::setVar('view', 'payment'); JRequest::setVar('layout', 'success'); $this->display(); } } function confirmOrders() { $userId = 0; // Usar userId actual $paymentMethod = 'CREDIT'; $agencyId = NULL; $shipping_address = NULL; // ID's de los pedidos a confirmar $cid = JRequest::getVar('cid', 'array', array()); $redirectJoomlaToMiddleware = LegacyHelper::getPHPGlobalVar('redirectJoomlaToMiddleware')==1; $result = false; $errorStr = JText::_('Error processing confirmation'); if ($redirectJoomlaToMiddleware) { $headers = array(); $statusCode = 0; $requestHeaders = array(); $authToken = LegacyHelper::getMVCAuthToken(); $orderIds = implode(',',$cid); $url = LegacyHelper::getMiddlewareServiceURL().'/buyBatch?authToken='.urlencode($authToken).'&orderIds='.urlencode($orderIds); $responseStr = LegacyHelper::httpRequest('GET', $url, null, $requestHeaders, $statusCode, $headers); if ($statusCode == 200) { // Los datos van en formato JSON $json = new Services_JSON(); $response = $json->decode($responseStr); if ($response) { if ($response->result == 'ok') $result = true; else $errorStr .= ": ".$response->error; } else $errorStr .= ": Empty response"; } } else { $modelPaymentMethods =& $this->getModel('paymentmethods'); $methodId = $modelPaymentMethods->GetIdFromNameId($paymentMethod); $result = $this->_paymentsuccess($cid, $methodId, $agencyId, $userId, $shipping_address); } if ($result) JError::raise(E_NOTICE, JText::_('Information'), JText::_('Orders confirmed')); else JError::raise(E_NOTICE, JText::_('Error'), $errorStr); $this->display(); } function payBatch() { JRequest::setVar('view', 'payment'); $this->display(); } function deleteOrderFromShoppingCart() { $cid = JRequest::getVar('cid', 'array', array()); $modelOrders =& $this->getModel('orders'); $modelOrders->deleteFromShoppingCart($cid); JRequest::setVar('view', 'mapendingorders'); $this->display(); } function deleteOrder() { $cid = JRequest::getVar('cid', 'array', array()); $modelOrders =& $this->getModel('orders'); $modelOrders->delete($cid); JRequest::setVar('view', 'maorders'); $this->display(); } function duplicateOrderToGroup() { $cid = JRequest::getVar('cid', 'array', array()); $groupId = JRequest::getVar('group'); if (!$groupId || $groupId == -1) { JError::raise(E_NOTICE, JText::_('Error'), JText::_('No group selected')); JRequest::setVar('view', 'maorders'); $this->display(); return; } $this->_duplicateOrder($cid, $groupId); echo "Orders duplicated correctly"; JRequest::setVar('view', 'maorders'); $this->display(); } protected function _duplicateOrder(&$cid, $groupId = -1) { $modelOrder =& $this->getModel('order'); if (count($cid) > 0) foreach ($cid as $id) { $modelOrder->SetId($id); if ($groupId != -1) { $modelUserGroup =& $this->getModel('usergroup'); $users =& $modelUserGroup->getUsersByGroup($groupId); foreach ($users as $userObj) { $modelOrder->duplicate(); $this->_changeOrderUser($modelOrder->_id, $userObj->user); } } else $modelOrder->duplicate(); } } function duplicateOrder() { $cid = JRequest::getVar('cid', 'array', array()); $this->_duplicateOrder($cid); JRequest::setVar('view', 'maorders'); $this->display(); } function deleteToMill() { $modelMill =& $this->getModel('millqueue'); $cid = JRequest::getVar('cid', 'array', array()); if (is_array($cid)) { foreach ($cid as $id) $modelMill->removeOrderToMill($id); } $this->display(); } function deleteFromCurrentBatch() { $modelBatch =& $this->getModel('currentbatch'); $cid = JRequest::getVar('cid', 'array', array()); if (is_array($cid)) foreach ($cid as $id) $modelBatch->removeOrder($id); JRequest::setVar('view', 'mapendingorders'); $this->display(); } function addToCurrentBatch() { $cid = JRequest::getVar('cid'); $modelBatch =& $this->getModel('currentbatch'); if (count($cid) > 0) { foreach ($cid as $id) $modelBatch->addOrder($id); //$mainframe->enqueueMessage('Orders: '.print_r($modelMill->getQueue(),true)); } JRequest::setVar('view', 'mapendingorders'); $this->display(); } function archiveOrders() { $cid = JRequest::getVar('cid'); $modelOrder =& $this->getModel('order'); if (count($cid) > 0) foreach ($cid as $orderId) { $modelOrder->SetId($orderId); $modelOrder->setArchived(true); } $this->display(); } function millOrder() { global $mainframe; $cid = JRequest::getVar('cid'); $add = JRequest::getVar('add', 'int', 0); $modelMill =& $this->getModel('millqueue'); if (!$add) $modelMill->clear(); if (count($cid) > 0) { foreach ($cid as $id) $modelMill->addOrderToMill($id); } $this->display(); } function deleteAddress() { $addressId = JRequest::getVar('addressId'); $modelUserAddress =& $this->getModel('useraddress'); $modelUserAddress->SetId($addressId); $addressData = array(); $addressData['id'] = $addressId; $addressData['deleted'] = 1; $modelUserAddress->store($addressData); $this->display(); } function saveAddress() { $cid = JRequest::getVar('cid'); $cid = (int)$cid[0]; $userId = JRequest::getVar('userId'); if ($userId) { $modelUserAddress =& $this->getModel('useraddress'); $post =& JRequest::get('post'); $company = trim($post['company']); $address = trim($post['address']); $city = trim($post['city']); $province = trim($post['province']); $pcode = trim($post['pcode']); $country = trim($post['country']); $phone = trim($post['phone']); $delivery_schedule = trim($post['delivery_schedule']); $addressData = array(); if ($cid) $addressData['id'] = $cid; else $addressData['id'] = null; $addressData['userid'] = $userId; $addressData['company'] = $company; $addressData['address'] = $address; $addressData['city'] = $city; $addressData['province'] = $province; $addressData['pcode'] = $pcode; $addressData['country'] = $country; $addressData['phone'] = $phone; $addressData['delivery_schedule'] = $delivery_schedule; $modelUserAddress->store($addressData); JRequest::setVar('addressId', $addressData['id']); $addressId = $modelUserAddress->_id; $orderId = JRequest::getVar('orderId'); if ($orderId && $addressId) { $modelOrder =& $this->getModel('order'); $orderData = array(); $orderData['id'] = $orderId; $orderData['shipping_address'] = $addressId; $modelOrder->store($orderData); } } JRequest::setVar('closeWindow', 'yes'); $this->display(); } function saveCustomer() { $cid = JRequest::getVar('cid'); $cid = (int)$cid[0]; $userId = LegacyHelper::getUserId(); $post =& JRequest::get('post'); $customerData = $post; $customerData['id'] = $cid; $customerData['user'] = $userId; $name = trim($post['name']); $surname = trim($post['surname']); $modelCustomer =& $this->getModel('customer'); if ($name && $surname) { if ($customerData['birthdate']) { $dateS = str_replace('-', '/', trim($customerData['birthdate'])); $day = 0; $month = 0; $year = 0; sscanf($dateS, "%d/%d/%d", $day, $month, $year); $dateBirth = new JDate($year . '-' . $month . '-' . $day); $customerData['birthdate'] = $dateBirth->toMySQL(); } else $customerData['birthdate'] = null; $customerData['receive_info'] = $customerData['receive_info'] ? 1 : 0; $modelCustomer->store($customerData); } JRequest::setVar('closeWindow', 'yes'); $this->display(); } function saveUserData() { $post =& JRequest::get('post'); if (!LegacyHelper::getNewMode()) { $user =& JFactory::getUser(); $user->name = ($post['name']); $user->email = addslashes($post['email']); $user->save(true); } $modelUser =& $this->getModel('user'); $userId = LegacyHelper::getUserId(); $modelUser->SetId($userId); $data = array(); $data['id'] = $userId; $data['name'] = trim($post['name']); $data['email'] = trim($post['email']); $data['invoice_email'] = trim($post['invoice_email']); $modelUser->store($data); $this->display(); } function display() { if ($this->avoidDisplay) { parent::display(); return; } $userId = LegacyHelper::getUserId(); if (!$userId) { $this->setRedirect(LegacyHelper::getNotLoggedUrl()); return; } $document =& JFactory::getDocument(); $viewType = $document->getType(); $viewName = JRequest::getCmd('view', $this->getName()); $view = & $this->getView($viewName, $viewType, '', array('base_path' => $this->_basePath)); $modelOrders =& $this->getModel('orders'); $modelOrder =& $this->getModel('order'); $modelCustomers =& $this->getModel('customers'); $modelCustomer =& $this->getModel('customer'); $modelOrderAttribute =& $this->getModel('orderattribute'); $modelMillingQueue =& $this->getModel('millqueue'); $modelCurrentBatch =& $this->getModel('currentbatch'); $modelPendingOrders =& $this->getModel('pendingorders'); $modelManuOrders =& $this->getModel('manufacturingorders'); $modelPredesignOrders =& $this->getModel('predesignorders'); $modelOrderStates =& $this->getModel('orderstates'); $modelBatch =& $this->getModel('batch'); $modelGiros =& $this->getModel('giros'); $modelGiro =& $this->getModel('giro'); $modelInvoicing =& $this->getModel('invoicing'); $modelInvoice =& $this->getModel('invoice'); $modelPayment =& $this->getModel('payment'); $modelBatchStates =& $this->getModel('batchstates'); $modelShippingBatchs =& $this->getModel('shippingbatchs'); $modelOrderLog =& $this->getModel('orderlog'); $modelOrderLogs =& $this->getModel('orderlogs'); $modelManuStates =& $this->getModel('manufacturestates'); $modelUser =& $this->getModel('user'); $modelFranchises =& $this->getModel('franchises'); $modelFranchise =& $this->getModel('franchise'); $modelItems =& $this->getModel('items'); $modelPricing =& $this->getModel('pricing'); $modelUsers =& $this->getModel('users'); $modelCountries =& $this->getModel('countries'); $modelAgencies =& $this->getModel('agencies'); $modelAgency =& $this->getModel('agency'); $modelCheckingOrders =& $this->getModel('checkingorders'); $modelTitles =& $this->getModel('titles'); $modelReceipts =& $this->getModel('receipts'); $modelReceipt =& $this->getModel('receipt'); $modelCustomerInvoicing =& $this->getModel('customerinvoicing'); $modelCustomerInvoice =& $this->getModel('customerinvoice'); $modelUserPrefabModel =& $this->getModel('userprefabmodel'); $modelTemplates =& $this->getModel('templates'); $modelCustomModel =& $this->getModel('custommodel'); $modelCustomModels =& $this->getModel('custommodels'); $modelHolidays =& $this->getModel('holidays'); $modelDeliveryNotes =& $this->getModel('deliverynotes'); $modelDeliveryNote =& $this->getModel('deliverynote'); $modelSettings =& $this->getModel('settings'); $modelIndiaFees =& $this->getModel('indiafees'); $modelReports =& $this->getModel('reports'); $modelpaymentmethods = & $this->getModel('paymentmethods'); $modelUserAddress =& $this->getModel('useraddress'); $modelPlugins =& $this->getModel('plugins'); $view->setModel($modelPlugins); $view->setModel($modelUserAddress); $view->setModel($modelpaymentmethods); $view->setModel($modelDeliveryNote); $view->setModel($modelDeliveryNotes); $view->setModel($modelHolidays); $view->setModel($modelIndiaFees); $view->setModel($modelSettings); $view->setModel($modelUserPrefabModel); $view->setModel($modelCustomModel); $view->setModel($modelCustomModels); $view->setModel($modelTemplates); $view->setModel($modelCustomerInvoice); $view->setModel($modelCustomerInvoicing); $view->setModel($modelTitles); $view->setModel($modelCheckingOrders); $view->setModel($modelAgency); $view->setModel($modelCountries); $view->setModel($modelUsers); $view->setModel($modelUser); $view->setModel($modelManuStates); $view->setModel($modelInvoicing); $view->setModel($modelInvoice); $view->setModel($modelGiro); $view->setModel($modelGiros); $view->setModel($modelOrder); $view->setModel($modelOrderLogs); $view->setModel($modelBatch); $view->setModel($modelShippingBatchs); $view->setModel($modelBatchStates); $view->setModel($modelPayment); $view->setModel($modelCurrentBatch); $view->setModel($modelOrderStates); $view->setModel($modelPendingOrders); $view->setModel($modelOrders); $view->setModel($modelCustomers); $view->setModel($modelCustomer); $view->setModel($modelOrderAttribute); $view->setModel($modelMillingQueue); $view->setModel($modelManuOrders); $view->setModel($modelPredesignOrders); $view->setModel($modelFranchises); $view->setModel($modelFranchise); $view->setModel($modelItems); $view->setModel($modelPricing); $view->setModel($modelAgencies); $view->setModel($modelReceipts); $view->setModel($modelReceipt); $view->setModel($modelReports); parent::display(); } function processQuickManuFinish() { $content = $_POST['content']; $lines = explode("\n", $content); $cid = array(); foreach ($lines as $line) { $line = trim($line); $orderId = (int)$line; if (!$orderId) continue; $cid[] = $orderId; } $this->_processManufacture($cid, 'ENDMANUFACTURING'); echo JText::_('Orders') . ': ' . implode(',', $cid) . ' ' . JText::_('manufactured'); $this->display(); } function generateExpeditionPDF() { JRequest::setVar('view', 'mashipping'); JRequest::setVar('layout', 'listing'); $dateNow = new JDate(); $today_date = $dateNow->toMySQL(); JRequest::setVar('todayDate', $this->getNextBusinessDay($today_date, 1)); $this->display(); } function generateExpeditionLabelsPDF() { $content = $_POST['content']; $batchIds = array(); $trackings = array(); $this->_getBatchesFromMemo($content, $batchIds, $trackings); JRequest::setVar('batchIds', $batchIds); JRequest::setVar('layout', 'labels'); $this->display(); } protected function _getBatchesFromMemo(&$content, &$batchIds, &$trackings) { $lines = explode("\n", $content); $batchIds = array(); $trackings = array(); foreach ($lines as $line) { $line = trim($line); $trackingNumber = ''; $spacePos = strpos($line, ' '); if ($spacePos !== FALSE) { $batchId = trim(substr($line, 0, $spacePos)); $trackingNumber = trim(substr($line, $spacePos + 1)); } else $batchId = $line; if (!$batchId) continue; $batchIds[] = $batchId; $trackings[] = $trackingNumber; } } function processQuickShipping() { $content = $_POST['content']; $modelOrder =& $this->getModel('order'); $modelBatch =& $this->getModel('batch'); $batchIds = array(); $trackings = array(); $this->_getBatchesFromMemo($content, $batchIds, $trackings); $validOrderIds = array(); for ($k = 0; $k < count($batchIds); $k++) { $batchId = $batchIds[$k]; if (substr($batchId, 0, 1) == 'P') // Si nos pasan un pedido { // Realizamos el adelanto de este pedido para "mañana" $orderId = substr($batchId, 1); echo "Adelanto pedido " . $orderId . " "; $this->_processPutForward(array($orderId), '', $validOrderIds); $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); $batchId = $order->batch; // Realizamos la expedicion del lote } $trackingNumber = $trackings[$k]; $modelBatch->SetId($batchId); $batchOrders =& $modelBatch->getOrders(); foreach ($batchOrders as $order) switch ($order->statenameid) { case 'MANUFACTURED': case 'SHIPPED': $modelOrder->SetId($order->id); $modelOrder->SetAction('SHIPPED'); break; default: $modelOrder->SetId($order->id); $modelOrder->setAction('ENDMANUFACTURING'); $this->completeOrderManufacturing($order->id); $modelOrder->SetId($order->id); $modelOrder->SetAction('SHIPPED'); } $modelBatch->SetStateName('SHIPPED'); echo JText::_('Batch') . ': ' . $batchId . ' ' . JText::_('Shipped') . "
"; if ($trackingNumber) { $data = array(); $data['id'] = $batchId; $data['tracking_number'] = $trackingNumber; $modelBatch->store($data); } } JRequest::setVar('batchIds', $batchIds); JRequest::setVar('orderIds', $validOrderIds); // JRequest::setVar('layout','labels'); $this->display(); } function processPutForward() { $content = $_POST['content']; $lines = explode("\n", $content); $validOrderIds = array(); // Aqui vamos a almacenar los nuevos pedidos que vayamos modificando // o que modifiquemos foreach ($lines as $line) { $line = trim($line); $shippingDate = ''; $orderIds = array(); $spacePos = strrpos($line, ' '); if ($spacePos !== FALSE) { $orderIdsStr = trim(substr($line, 0, $spacePos)); $orderIds = explode(' ', $orderIdsStr); $aux = $orderIds; $orderIds = array(); foreach ($aux as $orderId) { $orderId = trim($orderId); if ($orderId) $orderIds[] = $orderId; } $shippingDate = trim(substr($line, $spacePos + 1)); } else if (trim($line)) $orderIds[] = trim($line); if (count($orderIds) == 0) continue; $this->_processPutForward($orderIds, $shippingDate, $validOrderIds); } JRequest::setVar('orderIds', $validOrderIds); JRequest::setVar('layout', 'labels'); $this->display(); } protected function _processPutForward($orderIds, $newShippingDate, &$validOrderIds) { $modelOrder =& $this->getModel('order'); $modelBatch =& $this->getModel('batch'); $dateNow = new JDate(); $today_date = $dateNow->toMySQL(); $nextBusinessDay = $this->getNextBusinessDay($today_date, 1); JRequest::setVar('todayDate', $nextBusinessDay); $year = 0; $month = 0; $day = 0; if (!$newShippingDate) { $read = sscanf($nextBusinessDay, "%d-%d-%d", $year, $month, $day); if ($read != 3) return; } else { $dateS = str_replace('-', '/', trim($newShippingDate)); $read = sscanf($dateS, "%d/%d/%d", $day, $month, $year); if ($read != 3) return; } $shippingDate = new JDate($year . '-' . $month . '-' . $day); $shippingDateSQL = $shippingDate->toMySQL(); $manufacturingDateSQL = date("Y-m-d", strtotime(date("Y-m-d", strtotime($year . '-' . $month . '-' . $day)) . " -1 day")); // Obtenemos el lote del primer pedido $modelOrder->SetId($orderIds[0]); $batchId = $modelOrder->getBatchId(); // Comprobamos que todos los pedidos estan asignados al mismo lote $invalid = false; for ($i = 1; $i < count($orderIds); $i++) { $modelOrder->SetId($orderIds[$i]); if ($modelOrder->getBatchId() != $batchId) { $invalid = true; break; } } if ($invalid) return; // Si no tienen el mismo lote no se realiza ningun cambio // Cogemos todos los pedidos del lote $modelBatch->SetId($batchId); $oldBatchId = $batchId; $orders =& $modelBatch->getOrders(); // Si no todos los pedidos del lote están dentro de la lista de los pedidos a adelantar, // se tiene que crear un lote nuevo y reasignar los pedidos al nuevo lote $allIn = true; foreach ($orders as $order) if (!in_array($order->id, $orderIds)) { $allIn = false; break; } $batch =& $modelBatch->getData(); //Obtenemos la informacion del lote antiguo $oldShippingDate = $batch->est_shipping_date; if (!$allIn) { // Creamos un nuevo lote con la informacion del antiguo $dataBatch = array(); $dataBatch['id'] = null; $dataBatch['state'] = $batch->state; $dataBatch['agency'] = $batch->agency; $dataBatch['payment_method'] = $batch->payment_method; $dataBatch['shipping_date'] = $batch->shipping_date; $dataBatch['payment_date'] = $batch->payment_date; $dataBatch['payment_user'] = $batch->payment_user; $dataBatch['tracking_number'] = $batch->tracking_number; $dataBatch['taxpercent'] = $batch->taxpercent; $dataBatch['discount'] = $batch->discount; $dataBatch['shipping_cost'] = $batch->shipping_cost; $dataBatch['shipping_vat'] = $batch->shipping_vat; $dataBatch['est_shipping_date'] = $shippingDateSQL; $dataBatch['payment_inc_cost'] = 0; $dataBatch['deliverynotes_cost'] = 0; $dataBatch['equivalence_charge'] = 0; $dataBatch['forwarded'] = 1; $dataBatch['shipping_address'] = $batch->shipping_address; $modelBatch->store($dataBatch); // Añadimos el lote antiguo a la lista de etiquetas a mostrar $batchIds[] = $batchId; $batchId = $dataBatch['id']; //Actualizamos el id del lote a cambiar } else { // Si todos los pedidos del lote estan dentro de la lista de los pedidos a adelantar, // simplemente cambiamos la fecha de expedición $dataBatch = array(); $dataBatch['id'] = $batchId; $dataBatch['forwarded'] = 1; $dataBatch['est_shipping_date'] = $shippingDateSQL; $modelBatch->store($dataBatch); } // Ahora actualizamos los pedidos involucrados, reasignándolos al nuevo lote // y modificando la fecha de fabricacion foreach ($orderIds as $orderId) { $modelOrder->SetId($orderId); $dataOrder = array(); $dataOrder['id'] = $orderId; $dataOrder['batch'] = $batchId; $dataOrder['manufacturing_date'] = $manufacturingDateSQL; $modelOrder->store($dataOrder); $order =& $modelOrder->getData(); if ($oldBatchId != $batchId) $logMessage = 'ADELANTO: Lote antiguo (' . $oldBatchId . ') Nuevo lote (' . $batchId . ')'; else $logMessage = 'ADELANTO: Cambio de fecha de lote ' . $batchId; $logMessage .= ' Fecha antigua ' . $oldShippingDate . ' Fecha nueva ' . $shippingDateSQL; $modelOrder->saveLog($order->statenameid, $logMessage, FRANCHISEMAN_VISLEVEL); $validOrderIds[] = $orderId; } } function SendOrderToPPRSAP($orderId) { if (!$orderId) return false; $modelBatch =& $this->getModel('batch'); $modelOrder =& $this->getModel('order'); $modelUser =& $this->getModel('user'); $modelPPRSAPLog =& $this->getModel('pprsaplog'); if ($modelPPRSAPLog->checkIfOrderAlreadyInSystem($orderId)) { echo 'Order: ' . $orderId . " already in SAP system. It won't be sent again.
"; return true; } $modelOrder->SetId($orderId); $order =& $modelOrder->getData(); if (!$order->batch) return false; $batchId = $order->batch; $modelBatch->SetId($batchId); $batchOrders =& $modelBatch->getOrders(); foreach ($batchOrders as $batchOrder) { if ($batchOrder->id != $orderId) { switch ($batchOrder->statenameid) { case 'INCOMPLETED': case 'COMPLETED': case 'PREDESIGNING': case 'PENDING_APPROVAL': case 'PRECONFIRMED': case 'CONFIRMED': return true; } } } $modelUser->SetId($order->user); $userObj =& $modelUser->getData(); $request = array(); $request['username'] = $userObj->username; //Nombre de usuario $request['userid'] = $userObj->customid; // Id de usuario $request['orders'] = array(); foreach ($batchOrders as $batchOrder) { $modelOrder->SetId($batchOrder->id); $order =& $modelOrder->getData(); $order->atts = $modelOrder->getAttributes(); $prefab = '/'; $numberInsoles = 1; $product = 1; $model = '/'; $material = '/'; $materialType = '/'; $materialArt = 3; $size = 0; $finishing = '/'; $brandsole = '/'; $coverType = '/'; $sides = 1; $prodFinish = 1; $schalenForm = '/'; $seite = 1; if ($order->uuid) { $shoeSizeLeft = ''; $shoeSizeRight = ''; foreach ($order->atts as $att) { switch ($att->name) { case 'insoleOptions.orderedFeet': if ($att->value == "onlyright") $seite = 3; else if ($att->value == "onlyleft") $seite = 2; else $seite = 1; break; case 'insoleOptions.insoleAmount': $numberInsoles = (int)$att->value; break; case 'general.product': switch ($att->value) { case 'lasts': $model = 'LEI'; $product = 2; break; default: $model = 'IND'; } break; case 'insoleOptions.milling': switch ($att->value) { case 'topBottomMilling': $sides = 2; break; case 'topMilling': $sides = 1; break; } break; case 'insoleOptions.finishing': switch ($att->value) { case 'nonFinished': $prodFinish = 1; break; case 'finished': $prodFinish = 2; break; } break; case 'insoleOptions.roughnessMilling': switch ($att->value) { case '1': $finishing = 'F'; break; case '1.5': $finishing = 'M'; break; case '2': $finishing = 'G'; break; } break; case 'insoleOptions.shoeSizeEU.left': $shoeSizeLeft = $att->value; break; case 'insoleOptions.shoeSizeEU.right': $shoeSizeRight = $att->value; break; case 'insoleOptions.material': if ($att->value) $material = $att->value; switch ($att->value) { case "PUR": $materialType = 'PU'; break; case "M30BR": case "M30B": case "M30GE": case "M30R": case "M30TB": case "M35GN": case "M40A": case "M40S": case "M40B": case "M40G": case "M40RB": case "M50B": case "PUPM33": case "PUPM81": case "CADESD": $materialType = 'MO'; break; case "C3050GB": case "C3050SK": case "C4060GS": case "PUPC3381": case "PUPC3581": $materialType = 'CO'; break; case "D4025GO": case "D5020BB": case "D5030BR": case "D3555GS": case "D3055TBS": $materialType = 'DU'; break; case "T302055RCS": case "T402055RCS": case "T402555GOB": case "T502060BBS": case "T503060BRS": case "PUPT353381": case "T355555GSS": case "T305555BSS": $materialType = 'TR'; break; case "Q11212": $materialType = 'QU'; break; } switch ($att->value) { case "PUR": $materialArt = 3; break; case "D3555GS": case "M30BR": case "M30B": case "M30GE": case "M30R": case "M30TB": case "M35GN": case "M40A": case "M40S": case "M40B": case "M40G": case "M40RB": case "M50B": case "C3050GB": case "C3050SK": case "C4060GS": case "D4025GO": case "D5020BB": case "D5030BR": case "D3055TBS": case "T302055RCS": case "T402055RCS": case "T402555GOB": case "T502060BBS": case "T503060BRS": case "T355555GSS": case "T305555BSS": case "CADESD": case "Q11212": $materialArt = 1; break; case "PUPM33": case "PUPM81": case "PUPC3381": case "PUPC3581": case "PUPT353381": $materialArt = 2; break; } break; } } switch ($seite) { case 1: if ($shoeSizeLeft && $shoeSizeRight) $size = max($shoeSizeLeft, $shoeSizeRight); break; case 2: if ($shoeSizeLeft) $size = $shoeSizeLeft; break; case 3: if ($shoeSizeRight) $size = $shoeSizeRight; break; } } else { foreach ($order->atts as $att) { switch ($att->typename) { case 'InsoleCADProject': if ($att->value_left == '1' && $att->value_right == '1') $seite = 1; else if ($att->value_left == '1') $seite = 2; else if ($att->value_right == '1') $seite = 3; break; case 'PPR_Model': switch ($att->mvalueleft) { case 'Pronation foot': $prefab = 'C1010'; break; case 'Equines foot': $prefab = 'C1015'; break; case 'Cavus varus foot': $prefab = 'C1020'; break; case 'Heel spur insole': $prefab = 'C1035'; break; case 'Comfort shoe insole': $prefab = 'C1040'; break; case 'Pronation-equines': $prefab = 'C1030'; break; case 'Walking': $prefab = 'C1045'; break; case 'Ball sports': $prefab = 'C1050'; break; case 'Racket sport': $prefab = 'C1055'; break; case 'Senso basic': $prefab = 'C1060'; break; case 'Cavus valgus foot': $prefab = 'C1025'; break; case 'Planus/Pronation foot': $prefab = 'C1065'; break; } break; case 'PPR_InsoleCup': switch ($att->mvalueleft) { case 'Yes': $schalenForm = 'H'; break; case 'No': $schalenForm = 'N'; break; } break; case 'PPR_NumberInsoles': $numberInsoles = (int)$att->value_left; break; case 'PPR_EinlagenVarianten': switch ($att->mvalueleft) { case 'Individuell': case 'Foambox positive': $model = 'IND'; break; case 'Prefab Standard': $model = 'PFS'; break; case 'Prefab Advanced': $model = 'PFA'; break; case 'Positive cast': $model = 'LEI'; $product = 2; break; } break; case 'PPR_BrandsoleType': switch ($att->mvalueleft) { case 'Finn': $brandsole = 'F'; break; case 'Küper': $brandsole = 'U'; break; case 'Sport': $brandsole = 'S'; break; } break; case 'PPR_Produkt': switch ($att->mvalueleft) { case 'Einlage - Einseitig': $sides = 1; break; case 'Einlage - Beidseitig': $sides = 2; break; } break; case 'PPR_ProductionBlock': switch ($att->mvalueleft) { case 'INSOLEINBLOCK': $prodFinish = 1; break; case 'INSOLEFINISHED': $prodFinish = 2; break; } break; case 'PPR_MatMono': switch ($att->mvalueleft) { case '30 Sh;Rot;EVA': $material = 'M30R'; $materialType = 'MO'; $materialArt = 1; break; case '40 Sh;Grau;EVA': $material = 'M40G'; $materialType = 'MO'; $materialArt = 1; break; case '50 Sh;Blau;EVA': $material = 'M50B'; $materialType = 'MO'; $materialArt = 1; break; case '30 Sh;Dunkelblau;EVA': $material = 'M30B'; $materialType = 'MO'; $materialArt = 1; break; case '30 Sh;Anthrazit;EVA': $material = 'M30A'; $materialType = 'MO'; $materialArt = 1; break; case '30 Sh;Gelb;EVA': $material = 'M30GE'; $materialType = 'MO'; $materialArt = 1; break; case '30 Sh;Braun;EVA': $material = 'M30BR'; $materialType = 'MO'; $materialArt = 1; break; case '40 Sh;Schwarz;EVA': $material = 'M40S'; $materialType = 'MO'; $materialArt = 1; break; case '40 Sh;Anthrazit;EVA': $material = 'M40A'; $materialType = 'MO'; $materialArt = 1; break; case '40 Sh;Röckblau;EVA': $material = 'M40RB'; $materialType = 'MO'; $materialArt = 1; break; case '35 Sh;Grün;EVA': $material = 'M35GN'; $materialType = 'MO'; $materialArt = 1; break; case '40 Sh;Blau;EVA': $material = 'M40B'; $materialType = 'MO'; $materialArt = 1; break; case '30 Sh;Taubenblau;EVA': $material = 'M30TB'; $materialType = 'MO'; $materialArt = 1; break; case 'PUP-Mono dunkelblau': $material = 'PUPM33'; $materialType = 'MO'; $materialArt = 2; break; case 'PUP-Mono weiß': $material = 'PUPM81'; $materialType = 'MO'; $materialArt = 2; break; case 'CAD ESD': $material = 'CADESD'; $materialType = 'MO'; $materialArt = 1; break; } break; case 'PPR_MatCombi': switch ($att->mvalueleft) { case '30/50 Sh;Grau/Blau;EVA/EVA': $material = 'C3050GB'; $materialType = 'CO'; $materialArt = 1; break; case '40/60 Sh;Grau/Schwarz;EVA/EVA': $material = 'C4060GS'; $materialType = 'CO'; $materialArt = 1; break; case '30/50 Sh;Schwarz/Kork;EVA/Kork': $material = 'C3050SK'; $materialType = 'CO'; $materialArt = 1; break; case 'PUP-Combi dunkelblau/weiß': $material = 'PUPC3381'; $materialType = 'CO'; $materialArt = 2; break; case 'PUP-Combi hellblau/weiß': $material = 'PUPC3581'; $materialType = 'CO'; $materialArt = 2; break; } break; case 'PPR_MatTri': switch ($att->mvalueleft) { case '40/25 Sh;Grau/Orange;EVA/EVA': $material = 'D4025GO'; $materialType = 'DU'; $materialArt = 1; break; case '50/20 Sh;Blau/Hellblau;EVA/EVA': $material = 'D5020BB'; $materialType = 'DU'; $materialArt = 1; break; case '50/30 Sh;Blau/Rot;EVA/EVA': $material = 'D5030BR'; $materialType = 'DU'; $materialArt = 1; break; case 'Tri 40/25/55': $material = 'T402555GOB'; $materialType = 'TR'; $materialArt = 1; break; case 'Tri 50/20/60': $material = 'T502060BBS'; $materialType = 'TR'; $materialArt = 1; break; case 'Tri 50/30/60': $material = 'T503060BRS'; $materialType = 'TR'; $materialArt = 1; break; case 'Tri schwarz/rot/schwarz': $material = 'T11212'; $materialType = 'TR'; $materialArt = 1; break; case 'Tri schwarz/grau/schwarz': $material = 'T12540'; $materialType = 'TR'; $materialArt = 1; break; case 'Quattro weiß/schwarz/blau/schwarz': $material = 'Q11212'; $materialType = 'QU'; $materialArt = 1; break; case 'Duo 40/30 grau/rot': $material = 'D4030GR'; $materialType = 'DU'; $materialArt = 1; break; case 'Duo 40/35 blau/grün': $material = 'D4035BG'; $materialType = 'DU'; $materialArt = 1; break; case 'Duo 30/35 blau/grün': $material = 'D3035BG'; $materialType = 'DU'; $materialArt = 1; break; case 'Duo 40/35 weiß/grün': $material = 'D4035WG'; $materialType = 'DU'; $materialArt = 1; break; case 'PUP-Tri hellblau/dunkelblau/weiß': $material = 'PUPT353381'; $materialType = 'TR'; $materialArt = 2; break; } break; case 'PPR_ShoeSize': if (!$att->value_right) $size = $att->value_left; else $size = max($att->value_left, $att->value_right); break; case 'PPR_SurfaceMilling': switch ($att->mvalueleft) { case 'Normal 1.5mm': $finishing = 'M'; break; case 'Rough 2.0mm': $finishing = 'G'; break; case 'Fine 1.0mm': $finishing = 'F'; break; } break; } } } if ($sides == 2) { if ($prodFinish == 2) $bearbeitung = 3; // Two-side ,finished else $bearbeitung = 4; // Two-side, in block } else { if ($prodFinish == 2) $bearbeitung = 2; // One-side, finished else $bearbeitung = 1; // One-side , in block } if ($product == 2) // Positivo { $size = "0"; $finishing = "/"; $brandsole = "/"; $bearbeitung = "/"; $schalenForm = "/"; $material = 'PUR'; $materialType = 'PU'; $materialArt = 3; } else if ($model == 'IND') // Individual { $prefab = "/"; $brandsole = "/"; $schalenForm = "/"; } $data = array(); $data['id'] = $order->id; $data['qty'] = ($seite==1) ? $numberInsoles : $numberInsoles*0.5; if ($numberInsoles != 0) $data['price'] = $order->price / $numberInsoles; else $data['price'] = 0; $data['atts'] = array(); $data['atts']['C_AUFTRAG'] = $data['id']; $data['atts']['C_PRODUKT'] = $product; $data['atts']['C_MODELL'] = $model; $data['atts']['C_PREFAB'] = $prefab; $data['atts']['C_FORM'] = $brandsole; $data['atts']['C_MATERIALTYP'] = $materialType; $data['atts']['C_MATERIALART'] = $materialArt; $data['atts']['C_MATERIAL'] = $material; $data['atts']['C_GROESSE'] = $size; $data['atts']['C_OBERFLAECHE'] = $finishing; $data['atts']['C_BEARBEITUNG'] = $bearbeitung; $data['atts']['C_VERKLEBUNG'] = $coverType; $data['atts']['C_SEITE'] = $seite; $data['atts']['C_SCHALENFORM'] = $schalenForm; $data['atts']['E_KVARIANTE'] = '/'; if (!$model || ($product == 1 && (!$material || !$materialType))) { echo "Missing data in the order: " . $order->id . "
"; echo nl2br(print_r($data, true)); echo "
"; return false; } $request['orders'][] = $data; } //echo nl2br(print_r($data,true)); $debugInfo = array(); $answer =& PPRSAPHelper::makeRequest($request, $debugInfo); if (!$debugInfo['bigerror']) { $success = true; $return =& $answer->RETURN; if (count($return->item)) foreach ($return->item as $returnItem) if ($returnItem->TYPE == 'E') { $success = false; break; } } else $success = false; $userId = LegacyHelper::getUserId(); foreach ($request['orders'] as $orderData) { $log = array(); $date = new JDate(); $log['id'] = null; $log['invoker_user'] = $userId; $log['date_sent'] = $date->toMySQL(); $log['orderid'] = $orderData['id']; $log['request'] = $debugInfo['request']; $log['answer'] = $debugInfo['answer']; $log['result'] = $success ? 'S' : 'E'; if ($success) $log['salesdocument'] = $answer->SALESDOCUMENT; $modelPPRSAPLog->store($log); } if ($success) echo "Batch: " . $batchId . " sent to SAP system succesfully. Sales document: " . $answer->SALESDOCUMENT . "
"; else { $message = "Request
" . nl2br(print_r($request, true)) . "
Answer:
" . nl2br(print_r($answer, true)); echo "Batch: " . $batchId . " not sent to SAP system succesfully
"; echo "
Estructura de retorno:
" . $message; $mailer =& JFactory::getMailer(); $sender = array($userObj->franchiseemail, $userObj->franchisename); $mailer->setSender($sender); $mailer->IsHTML(true); $mailer->addRecipient('fax@perpedesroeck.de'); $mailer->addRecipient('notifications@voxelcare.com'); $subject = 'OrthoCAD SAP error. Batch: ' . $batchId; $mailer->setSubject($subject); $body = $message; $mailer->setBody($body); $mailer->Send(); } //echo("
Debug:
".nl2br(htmlentities(print_r($debugInfo,true)))); //echo("
Estructura de envio:
".nl2br(print_r($requests,true))); //echo("
Estructura de retorno:
".nl2br(print_r($answer,true))); return $success; } } ?>