Beispiel #1
0
 function save_module($module)
 {
     global $updateInventoryProductRel_deduct_stock;
     if ($this->HasDirectImageField) {
         $this->insertIntoAttachment($this->id, $module);
     }
     $updateInventoryProductRel_deduct_stock = true;
     //Checking if quote_id is present and updating the quote status
     if ($this->column_fields['quote_id'] != '') {
         $newStatus = GlobalVariable::getVariable('QuoteStatusOnSalesOrderSave', 'Accepted');
         if ($newStatus != 'DoNotChange') {
             $qt_id = $this->column_fields['quote_id'];
             $query1 = 'update vtiger_quotes set quotestage=? where quoteid=?';
             $this->db->pquery($query1, array($newStatus, $qt_id));
         }
     }
     //in ajax save we should not call this function, because this will delete all the existing product values
     if ($_REQUEST['action'] != 'SalesOrderAjax' && $_REQUEST['ajxaction'] != 'DETAILVIEW' && $_REQUEST['action'] != 'MassEditSave' && $_REQUEST['action'] != 'ProcessDuplicates') {
         //Based on the total Number of rows we will save the product relationship with this entity
         saveInventoryProductDetails($this, 'SalesOrder');
         if (vtlib_isModuleActive("InventoryDetails")) {
             InventoryDetails::createInventoryDetails($this, 'SalesOrder');
         }
     } else {
         if ($_REQUEST['action'] == 'SalesOrderAjax' || $_REQUEST['action'] == 'MassEditSave') {
             $updateInventoryProductRel_deduct_stock = false;
         }
     }
     // Update the currency id and the conversion rate for the sales order
     $update_query = "update vtiger_salesorder set currency_id=?, conversion_rate=? where salesorderid=?";
     $update_params = array($this->column_fields['currency_id'], $this->column_fields['conversion_rate'], $this->id);
     $this->db->pquery($update_query, $update_params);
 }
Beispiel #2
0
function duplicaterec($currentModule, $record_id, $bmapname)
{
    global $adb, $current_user;
    $focus = CRMEntity::getInstance($currentModule);
    $focus->retrieve_entity_info($record_id, $currentModule);
    // Retrieve relations map
    //$bmapname = 'BusinessMapping_'.$currentModule.'_DuplicateRelations';
    $cbMapid = GlobalVariable::getVariable('BusinessMapping_' . $bmapname, cbMap::getMapIdByName($bmapname));
    if ($cbMapid) {
        $cbMap = cbMap::getMapByID($cbMapid);
        $maped_relations = $cbMap->DuplicateRelations()->getRelatedModules();
    }
    // Duplicate Records that this Record is dependent of
    if ($cbMapid && $cbMap->DuplicateRelations()->DuplicateDirectRelations()) {
        $invmods = getInventoryModules();
        foreach ($focus->column_fields as $fieldname => $value) {
            $sql = 'SELECT * FROM vtiger_field WHERE columnname = ? AND uitype IN (10,50,51,57,58,59,73,68,76,75,81,78,80)';
            $result = $adb->pquery($sql, array($fieldname));
            if ($adb->num_rows($result) == 1 && !empty($value)) {
                $module = getSalesEntityType($value);
                if (in_array($module, $invmods)) {
                    continue;
                }
                // we can't duplicate these
                $handler = vtws_getModuleHandlerFromName($module, $current_user);
                $meta = $handler->getMeta();
                $entity = CRMEntity::getInstance($module);
                $entity->mode = '';
                $entity->retrieve_entity_info($value, $module);
                $entity->column_fields = DataTransform::sanitizeRetrieveEntityInfo($entity->column_fields, $meta);
                $entity->save($module);
                $focus->column_fields[$fieldname] = $entity->id;
            }
        }
    }
    $handler = vtws_getModuleHandlerFromName($currentModule, $current_user);
    $meta = $handler->getMeta();
    $focus->column_fields = DataTransform::sanitizeRetrieveEntityInfo($focus->column_fields, $meta);
    $focus->saveentity($currentModule);
    // no workflows for this one => so we don't reenter this process
    $new_record_id = $focus->id;
    $curr_tab_id = gettabid($currentModule);
    $related_list = get_related_lists($curr_tab_id, $maped_relations);
    dup_related_lists($new_record_id, $currentModule, $related_list, $record_id, $maped_relations);
    $dependents_list = get_dependent_lists($curr_tab_id);
    $dependent_tables = get_dependent_tables($dependents_list, $currentModule);
    dup_dependent_rec($record_id, $currentModule, $new_record_id, $dependent_tables, $maped_relations);
    return $new_record_id;
}
function cbws_SearchGlobalVar($gvname, $defaultvalue, $gvmodule, $user)
{
    global $log, $adb, $current_user;
    $entityName = 'GlobalVariable';
    $webserviceObject = VtigerWebserviceObject::fromName($adb, $entityName);
    $handlerPath = $webserviceObject->getHandlerPath();
    $handlerClass = $webserviceObject->getHandlerClass();
    require_once $handlerPath;
    $handler = new $handlerClass($webserviceObject, $user, $adb, $log);
    $meta = $handler->getMeta();
    if ($meta->hasReadAccess() !== true) {
        return $defaultvalue;
    }
    require_once 'modules/GlobalVariable/GlobalVariable.php';
    $rdo = GlobalVariable::getVariable($gvname, $defaultvalue, $gvmodule, $user->id);
    VTWS_PreserveGlobal::flush();
    return $rdo;
}
Beispiel #4
0
 function save_module($module)
 {
     global $updateInventoryProductRel_deduct_stock;
     $updateInventoryProductRel_deduct_stock = true;
     //Checking if salesorderid is present and updating the SO status
     if (!empty($this->column_fields['salesorder_id'])) {
         $newStatus = GlobalVariable::getVariable('SalesOrderStatusOnInvoiceSave', 'Approved');
         if ($newStatus != 'DoNotChange') {
             $so_id = $this->column_fields['salesorder_id'];
             $query1 = 'update vtiger_salesorder set sostatus=? where salesorderid=?';
             $this->db->pquery($query1, array($newStatus, $so_id));
         }
     }
     //in ajax save we should not call this function, because this will delete all the existing product values
     if (isset($this->_recurring_mode) && $this->_recurring_mode == 'recurringinvoice_from_so' && isset($this->_salesorderid) && $this->_salesorderid != '') {
         // We are getting called from the RecurringInvoice cron service!
         $this->createRecurringInvoiceFromSO();
         if (vtlib_isModuleActive("InventoryDetails")) {
             InventoryDetails::createInventoryDetails($this, 'Invoice');
         }
     } else {
         if (isset($_REQUEST)) {
             if ($_REQUEST['action'] != 'InvoiceAjax' && $_REQUEST['ajxaction'] != 'DETAILVIEW' && $_REQUEST['action'] != 'MassEditSave' && $_REQUEST['action'] != 'ProcessDuplicates') {
                 //Based on the total Number of rows we will save the product relationship with this entity
                 saveInventoryProductDetails($this, 'Invoice');
                 if (vtlib_isModuleActive("InventoryDetails")) {
                     InventoryDetails::createInventoryDetails($this, 'Invoice');
                 }
             } else {
                 if ($_REQUEST['action'] == 'InvoiceAjax' || $_REQUEST['action'] == 'MassEditSave') {
                     $updateInventoryProductRel_deduct_stock = false;
                 }
             }
         }
     }
     // Update the currency id and the conversion rate for the invoice
     $update_query = "update vtiger_invoice set currency_id=?, conversion_rate=? where invoiceid=?";
     $update_params = array($this->column_fields['currency_id'], $this->column_fields['conversion_rate'], $this->id);
     $this->db->pquery($update_query, $update_params);
 }
Beispiel #5
0
            }
            // Mark the status - running
            $cronTask->markRunning();
            checkFileAccess($cronTask->getHandlerFile());
            $logbg->info('Execute: ' . $cronTask->getHandlerFile());
            require_once $cronTask->getHandlerFile();
            // Mark the status - finished
            $cronTask->markFinished();
        } catch (Exception $e) {
            $msg = sprintf("[ERROR]: %s - cron task execution throwed exception.\n", $cronTask->getName());
            $msg .= $e->getMessage();
            $msg .= "\n";
            echo $msg;
            $logbg->info($msg);
            //Send email with error.
            $mailto = GlobalVariable::getVariable('Debug_Send_VtigerCron_Error', '');
            if ($mailto != '') {
                require_once 'modules/Emails/mail.php';
                require_once 'modules/Emails/Emails.php';
                global $HELPDESK_SUPPORT_EMAIL_ID, $HELPDESK_SUPPORT_NAME;
                $from_name = $HELPDESK_SUPPORT_NAME;
                $form_mail = $HELPDESK_SUPPORT_EMAIL_ID;
                $mailsubject = "[ERROR]: " . $cronTask->getName() . " - cron task execution throwed exception.";
                $mailcontent = '<pre>' . $e . '</pre>';
                send_mail('Emails', $mailto, $from_name, $form_mail, $mailsubject, $mailcontent);
            }
        }
    }
} else {
    echo "Access denied!";
}
Beispiel #6
0
 public function sendEmail()
 {
     require_once 'modules/Emails/mail.php';
     require_once 'modules/Emails/Emails.php';
     global $HELPDESK_SUPPORT_NAME, $HELPDESK_SUPPORT_EMAIL_ID, $currentModule;
     $recipientEmails = $this->getRecipientEmails();
     $emails_to = '';
     foreach ($recipientEmails as $name => $email) {
         $emails_to .= $email . ',';
     }
     $emails_to = trim($emails_to, ',');
     $currentTime = date('Y-m-d H:i:s');
     $subject = $this->reportname . ' - ' . $currentTime . ' (' . DateTimeField::getDBTimeZone() . ')';
     $contents = getTranslatedString('LBL_AUTO_GENERATED_REPORT_EMAIL', $currentModule) . '<br/><br/>';
     $contents .= '<b>' . getTranslatedString('LBL_REPORT_NAME', $currentModule) . ' :</b> ' . $this->reportname . '<br/>';
     $contents .= '<b>' . getTranslatedString('LBL_DESCRIPTION', $currentModule) . ' :</b><br/>' . $this->reportdescription . '<br/><br/>';
     $baseFileName = utf8_decode(preg_replace('/[^a-zA-Z0-9_-\\s]/', '', $this->reportname) . '_' . preg_replace('/[^a-zA-Z0-9_-\\s]/', '', date('YmdHis')));
     $oReportRun = new ReportRun($this->id);
     $reportFormat = $this->scheduledFormat;
     $attachments = array();
     if ($reportFormat == 'pdf' || $reportFormat == 'both') {
         $fileName = $baseFileName . '.pdf';
         $filePath = 'storage/' . $fileName;
         $attachments[$fileName] = $filePath;
         $_REQUEST['filename_hidden_pdf'] = $filePath;
         $pdf = $oReportRun->getReportPDF(NULL);
         $pdf->Output($filePath, 'F');
     }
     if ($reportFormat == 'excel' || $reportFormat == 'both') {
         $fileName = $baseFileName . '.xls';
         $filePath = 'storage/' . $fileName;
         $attachments[$fileName] = $filePath;
         $_REQUEST['filename_hidden_xls'] = $filePath;
         $oReportRun->writeReportToExcelFile($filePath, NULL);
     }
     $sendifempty = GlobalVariable::getVariable('Report_Send_Scheduled_ifEmpty', 1);
     if ($sendifempty or $oReportRun->number_of_rows > 0) {
         $mail_status = send_mail('Emails', $emails_to, $HELPDESK_SUPPORT_NAME, $HELPDESK_SUPPORT_EMAIL_ID, $subject, $contents, '', '', 'attReports');
         foreach ($attachments as $attachmentName => $path) {
             unlink($path);
         }
     }
 }
Beispiel #7
0
/**	Function used to save the Inventory product details for the passed entity
 *	@param object reference $focus - object reference to which we want to save the product details from REQUEST values where as the entity will be Purchase Order, Sales Order, Quotes or Invoice
 *	@param string $module - module name
 *	@param $update_prod_stock - true or false (default), if true we have to update the stock for PO only
 *	@return void
 */
function saveInventoryProductDetails(&$focus, $module, $update_prod_stock = 'false', $updateDemand = '')
{
    global $log, $adb;
    $id = $focus->id;
    $log->debug("Entering into function saveInventoryProductDetails({$module}).");
    //Added to get the convertid
    if (isset($_REQUEST['convert_from']) && $_REQUEST['convert_from'] != '') {
        $id = vtlib_purify($_REQUEST['return_id']);
    } else {
        if (isset($_REQUEST['duplicate_from']) && $_REQUEST['duplicate_from'] != '') {
            $id = vtlib_purify($_REQUEST['duplicate_from']);
        }
    }
    $ipr_cols = $adb->getColumnNames('vtiger_inventoryproductrel');
    $ext_prod_arr = array();
    if ($focus->mode == 'edit') {
        if ($_REQUEST['taxtype'] == 'group') {
            $all_available_taxes = getAllTaxes('available', '', 'edit', $id);
        }
        $return_old_values = '';
        if ($module != 'PurchaseOrder') {
            $return_old_values = 'return_old_values';
        }
        //we will retrieve the existing product details and store it in a array and then delete all the existing product details and save new values, retrieve the old value and update stock only for SO, Quotes and Invoice not for PO
        //$ext_prod_arr = deleteInventoryProductDetails($focus->id,$return_old_values);
        deleteInventoryProductDetails($focus);
    } else {
        if ($_REQUEST['taxtype'] == 'group') {
            $all_available_taxes = getAllTaxes('available', '', 'edit', $id);
        }
    }
    $tot_no_prod = $_REQUEST['totalProductCount'];
    if ($module != 'PurchaseOrder') {
        if (GlobalVariable::getVariable('B2B', '1') == '1') {
            $acvid = $focus->column_fields['account_id'];
        } else {
            $acvid = $focus->column_fields['contact_id'];
        }
    } else {
        $acvid = $focus->column_fields['vendor_id'];
    }
    //If the taxtype is group then retrieve all available taxes, else retrive associated taxes for each product inside loop
    $prod_seq = 1;
    for ($i = 1; $i <= $tot_no_prod; $i++) {
        //if the product is deleted then we should avoid saving the deleted products
        if ($_REQUEST["deleted" . $i] == 1) {
            continue;
        }
        $prod_id = vtlib_purify($_REQUEST['hdnProductId' . $i]);
        if (isset($_REQUEST['productDescription' . $i])) {
            $description = vtlib_purify($_REQUEST['productDescription' . $i]);
        }
        /*else{
        			$desc_duery = "select vtiger_crmentity.description AS product_description from vtiger_crmentity where vtiger_crmentity.crmid=?";
        			$desc_res = $adb->pquery($desc_duery,array($prod_id));
        			$description = $adb->query_result($desc_res,0,"product_description");
        		}	*/
        $qty = vtlib_purify($_REQUEST['qty' . $i]);
        $listprice = vtlib_purify($_REQUEST['listPrice' . $i]);
        $comment = vtlib_purify($_REQUEST['comment' . $i]);
        //we have to update the Product stock for PurchaseOrder if $update_prod_stock is true
        if ($module == 'PurchaseOrder' && $update_prod_stock == 'true') {
            addToProductStock($prod_id, $qty);
        }
        if ($module == 'SalesOrder') {
            if ($updateDemand == '-') {
                deductFromProductDemand($prod_id, $qty);
            } elseif ($updateDemand == '+') {
                addToProductDemand($prod_id, $qty);
            }
        }
        $query = "insert into vtiger_inventoryproductrel(id, productid, sequence_no, quantity, listprice, comment, description) values(?,?,?,?,?,?,?)";
        $qparams = array($focus->id, $prod_id, $prod_seq, $qty, $listprice, $comment, $description);
        $adb->pquery($query, $qparams);
        $lineitem_id = $adb->getLastInsertID();
        $sub_prod_str = $_REQUEST['subproduct_ids' . $i];
        if (!empty($sub_prod_str)) {
            $sub_prod = explode(":", $sub_prod_str);
            for ($j = 0; $j < count($sub_prod); $j++) {
                $query = "insert into vtiger_inventorysubproductrel(id, sequence_no, productid) values(?,?,?)";
                $qparams = array($focus->id, $prod_seq, $sub_prod[$j]);
                $adb->pquery($query, $qparams);
            }
        }
        $prod_seq++;
        if ($module != 'PurchaseOrder') {
            //update the stock with existing details
            updateStk($prod_id, $qty, $focus->mode, $ext_prod_arr, $module);
        }
        //we should update discount and tax details
        $updatequery = "update vtiger_inventoryproductrel set ";
        $updateparams = array();
        //set the discount percentage or discount amount in update query, then set the tax values
        if ($_REQUEST['discount_type' . $i] == 'percentage') {
            $updatequery .= " discount_percent=?,";
            array_push($updateparams, $_REQUEST['discount_percentage' . $i]);
        } elseif ($_REQUEST['discount_type' . $i] == 'amount') {
            $updatequery .= " discount_amount=?,";
            $discount_amount = $_REQUEST['discount_amount' . $i];
            array_push($updateparams, $discount_amount);
        }
        if ($_REQUEST['taxtype'] == 'group') {
            for ($tax_count = 0; $tax_count < count($all_available_taxes); $tax_count++) {
                $tax_name = $all_available_taxes[$tax_count]['taxname'];
                if (!in_array($tax_name, $ipr_cols)) {
                    continue;
                }
                $tax_val = $all_available_taxes[$tax_count]['percentage'];
                $request_tax_name = $tax_name . "_group_percentage";
                if (isset($_REQUEST[$request_tax_name])) {
                    $tax_val = vtlib_purify($_REQUEST[$request_tax_name]);
                }
                $updatequery .= " {$tax_name} = ?,";
                array_push($updateparams, $tax_val);
            }
            $updatequery = trim($updatequery, ',') . " where id=? and productid=? and lineitem_id = ?";
            array_push($updateparams, $focus->id, $prod_id, $lineitem_id);
        } else {
            $taxes_for_product = getTaxDetailsForProduct($prod_id, 'all', $acvid);
            for ($tax_count = 0; $tax_count < count($taxes_for_product); $tax_count++) {
                $tax_name = $taxes_for_product[$tax_count]['taxname'];
                if (!in_array($tax_name, $ipr_cols)) {
                    continue;
                }
                $request_tax_name = $tax_name . "_percentage" . $i;
                $updatequery .= " {$tax_name} = ?,";
                array_push($updateparams, vtlib_purify($_REQUEST[$request_tax_name]));
            }
            $updatequery = trim($updatequery, ',') . " where id=? and productid=? and lineitem_id = ?";
            array_push($updateparams, $focus->id, $prod_id, $lineitem_id);
        }
        // jens 2006/08/19 - protect against empy update queries
        if (!preg_match('/set\\s+where/i', $updatequery)) {
            $adb->pquery($updatequery, $updateparams);
        }
    }
    //we should update the netprice (subtotal), taxtype, group discount, S&H charge, S&H taxes, adjustment and total
    //netprice, group discount, taxtype, S&H amount, adjustment and total to entity table
    $updatequery = " update {$focus->table_name} set ";
    $updateparams = array();
    $subtotal = $_REQUEST['subtotal'];
    $updatequery .= " subtotal=?,";
    array_push($updateparams, $subtotal);
    $updatequery .= " taxtype=?,";
    array_push($updateparams, $_REQUEST['taxtype']);
    //for discount percentage or discount amount
    if ($_REQUEST['discount_type_final'] == 'percentage') {
        $updatequery .= " discount_percent=?,";
        array_push($updateparams, vtlib_purify($_REQUEST['discount_percentage_final']));
    } elseif ($_REQUEST['discount_type_final'] == 'amount') {
        $discount_amount_final = vtlib_purify($_REQUEST['discount_amount_final']);
        $updatequery .= " discount_amount=?,";
        array_push($updateparams, $discount_amount_final);
    }
    $shipping_handling_charge = vtlib_purify($_REQUEST['shipping_handling_charge']);
    $updatequery .= " s_h_amount=?,";
    array_push($updateparams, $shipping_handling_charge);
    //if the user gave - sign in adjustment then add with the value
    $adjustmentType = '';
    if ($_REQUEST['adjustmentType'] == '-') {
        $adjustmentType = vtlib_purify($_REQUEST['adjustmentType']);
    }
    $adjustment = vtlib_purify($_REQUEST['adjustment']);
    $updatequery .= " adjustment=?,";
    array_push($updateparams, $adjustmentType . $adjustment);
    $total = vtlib_purify($_REQUEST['total']);
    $updatequery .= " total=?";
    array_push($updateparams, $total);
    //$id_array = Array('PurchaseOrder'=>'purchaseorderid','SalesOrder'=>'salesorderid','Quotes'=>'quoteid','Invoice'=>'invoiceid');
    //Added where condition to which entity we want to update these values
    $updatequery .= " where " . $focus->table_index . "=?";
    array_push($updateparams, $focus->id);
    $adb->pquery($updatequery, $updateparams);
    //to save the S&H tax details in vtiger_inventoryshippingrel table
    $isr_cols = $adb->getColumnNames('vtiger_inventoryshippingrel');
    $sh_tax_details = getAllTaxes('all', 'sh');
    $sh_query_fields = "id,";
    $sh_query_values = "?,";
    $sh_query_params = array($focus->id);
    for ($i = 0; $i < count($sh_tax_details); $i++) {
        $tax_name = $sh_tax_details[$i]['taxname'] . "_sh_percent";
        if ($_REQUEST[$tax_name] != '' and in_array($sh_tax_details[$i]['taxname'], $isr_cols)) {
            $sh_query_fields .= $sh_tax_details[$i]['taxname'] . ",";
            $sh_query_values .= "?,";
            array_push($sh_query_params, vtlib_purify($_REQUEST[$tax_name]));
        }
    }
    $sh_query_fields = trim($sh_query_fields, ',');
    $sh_query_values = trim($sh_query_values, ',');
    if ($sh_query_fields != 'id') {
        $sh_query = "insert into vtiger_inventoryshippingrel({$sh_query_fields}) values({$sh_query_values})";
        $adb->pquery($sh_query, $sh_query_params);
    }
    $log->debug("Exit from function saveInventoryProductDetails({$module}).");
}
Beispiel #8
0
            $smarty->assign("RETURN_MODULE", 'Emails');
        }
        if (isset($_REQUEST['select'])) {
            $smarty->assign("SELECT", 'enable');
        }
        $alphabetical = AlphabeticalSearch($currentModule, 'Popup', 'notes_title', 'true', 'basic', $popuptype, "", "", $url);
        break;
        // Special case handling (for curr_row value) for Services module
    // Special case handling (for curr_row value) for Services module
    case 'Services':
        if (isset($_REQUEST['curr_row'])) {
            $curr_row = vtlib_purify($_REQUEST['curr_row']);
            $smarty->assign("CURR_ROW", $curr_row);
            $url_string .= "&curr_row=" . vtlib_purify($_REQUEST['curr_row']);
        }
        $smarty->assign('Service_Default_Units', GlobalVariable::getVariable('Service_Default_Units', ''));
        // vtlib customization: Generic hook for Popup selection
    // vtlib customization: Generic hook for Popup selection
    default:
        $smarty->assign("SINGLE_MOD", $currentModule);
        if (isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != '') {
            $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module']));
        }
        $alphabetical = AlphabeticalSearch($currentModule, 'Popup', $focus->def_basicsearch_col, 'true', 'basic', $popuptype, "", "", $url);
        if (isset($_REQUEST['select'])) {
            $smarty->assign("SELECT", 'enable');
        }
        break;
        // END
}
// vtlib customization: Initialize focus to get generic popup
Beispiel #9
0
 /**
  * Load a user based on the user_name in $this
  * @return -- this if load was successul and null if load failed.
  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
  * All Rights Reserved.
  */
 function load_user($user_password)
 {
     $usr_name = $this->column_fields["user_name"];
     $maxFailedLoginAttempts = GlobalVariable::getVariable('Application_MaxFailedLoginAttempts', 5, 'Users');
     if (isset($_SESSION['loginattempts'])) {
         $_SESSION['loginattempts'] += 1;
     } else {
         $_SESSION['loginattempts'] = 1;
     }
     if ($_SESSION['loginattempts'] > $maxFailedLoginAttempts) {
         $this->log->warn("SECURITY: " . $usr_name . " has attempted to login " . $_SESSION['loginattempts'] . " times.");
     }
     $this->log->debug("Starting user load for {$usr_name}");
     if (!isset($this->column_fields["user_name"]) || $this->column_fields["user_name"] == "" || !isset($user_password) || $user_password == "") {
         return null;
     }
     $authCheck = false;
     $authCheck = $this->doLogin($user_password);
     if (!$authCheck) {
         $this->log->warn("User authentication for {$usr_name} failed");
         return null;
     }
     // Get the fields for the user
     $query = "SELECT * from {$this->table_name} where user_name='{$usr_name}'";
     $result = $this->db->requireSingleResult($query, false);
     $row = $this->db->fetchByAssoc($result);
     $this->column_fields = $row;
     $this->id = $row['id'];
     $this->loadPreferencesFromDB($row['user_preferences']);
     // Make sure admin is logging in from authorized IPs
     if ($row['is_admin'] == 'on' or $row['is_admin'] == '1') {
         $AdminLoginIPs = GlobalVariable::getVariable('Application_AdminLoginIPs', '', 'Users');
         if ($AdminLoginIPs != '') {
             $admin_ip_addresses = explode(',', $AdminLoginIPs);
             if (!in_array($_SERVER['REMOTE_ADDR'], $admin_ip_addresses)) {
                 $row['status'] = 'Inactive';
                 $this->authenticated = false;
                 $_SESSION['login_error'] = getTranslatedString('ERR_INVALID_ADMINIPLOGIN', 'Users');
                 $mailsubject = "[Security Alert]: Admin login attempt rejected for login: {$usr_name} from external IP: " . $_SERVER['REMOTE_ADDR'];
                 $this->log->warn($mailsubject);
                 // Send email with authentification error.
                 $mailto = GlobalVariable::getVariable('Debug_Send_AdminLoginIPAuth_Error', '', 'Users');
                 if ($mailto != '') {
                     require_once 'modules/Emails/mail.php';
                     require_once 'modules/Emails/Emails.php';
                     global $HELPDESK_SUPPORT_EMAIL_ID, $HELPDESK_SUPPORT_NAME;
                     $from_name = $HELPDESK_SUPPORT_NAME;
                     $form_mail = $HELPDESK_SUPPORT_EMAIL_ID;
                     $mailcontent = $mailsubject . "\n";
                     send_mail('Emails', $mailto, $from_name, $form_mail, $mailsubject, $mailcontent);
                 }
             }
         }
     }
     if ($row['status'] != 'Inactive') {
         $this->authenticated = true;
     }
     unset($_SESSION['loginattempts']);
     return $this;
 }
Beispiel #10
0
    public static function createPotentialRelatedTo($relatedto, $campaignid)
    {
        global $adb, $current_user;
        $checkrs = $adb->pquery('select 1
			from vtiger_potential
			inner join vtiger_crmentity on crmid=potentialid
			where deleted=0 and related_to=? and campaignid=?', array($relatedto, $campaignid));
        if ($adb->num_rows($checkrs) == 0) {
            require_once 'modules/Potentials/Potentials.php';
            $entity = new Potentials();
            $entity->mode = '';
            $cname = getEntityName('Campaigns', $campaignid);
            $cname = $cname[$campaignid] . ' - ';
            $setype = getSalesEntityType($relatedto);
            $rname = getEntityName($setype, $relatedto);
            $rname = $rname[$relatedto];
            $cbMapid = GlobalVariable::getVariable('BusinessMapping_PotentialOnCampaignRelation', cbMap::getMapIdByName('PotentialOnCampaignRelation'));
            if ($cbMapid) {
                $cmp = CRMEntity::getInstance('Campaigns');
                $cmp->retrieve_entity_info($campaignid, 'Campaigns');
                if ($setype == 'Accounts') {
                    $cmp->column_fields['AccountName'] = $rname;
                    $cmp->column_fields['ContactName'] = '';
                } else {
                    $cmp->column_fields['AccountName'] = '';
                    $cmp->column_fields['ContactName'] = $rname;
                }
                $cbMap = cbMap::getMapByID($cbMapid);
                $entity->column_fields = $cbMap->Mapping($cmp->column_fields, array());
            }
            if (empty($entity->column_fields['assigned_user_id'])) {
                $entity->column_fields['assigned_user_id'] = $current_user->id;
            }
            $entity->column_fields['related_to'] = $relatedto;
            $entity->column_fields['campaignid'] = $campaignid;
            if (empty($entity->column_fields['closingdate'])) {
                $dt = new DateTimeField();
                $entity->column_fields['closingdate'] = $dt->getDisplayDate();
            }
            if (empty($entity->column_fields['potentialname'])) {
                $entity->column_fields['potentialname'] = $cname . $rname;
            }
            if (empty($entity->column_fields['sales_stage'])) {
                $entity->column_fields['sales_stage'] = 'Prospecting';
            }
            $_REQUEST['assigntype'] = 'U';
            $_REQUEST['assigned_user_id'] = $entity->column_fields['assigned_user_id'];
            $entity->save('Potentials');
        }
    }
Beispiel #11
0
/**   Function used to send email
 *   $module		-- current module
 *   $to_email		-- to email address
 *   $from_name	-- currently loggedin user name
 *   $from_email	-- currently loggedin users's email id. you can give as '' if you are not in HelpDesk module
 *   $subject		-- subject of the email you want to send
 *   $contents		-- body of the email you want to send
 *   $cc			-- add email ids with comma seperated. - optional
 *   $bcc			-- add email ids with comma seperated. - optional.
 *   $attachment	-- whether we want to attach the currently selected file or all files.[values = current,all] - optional
 *   $emailid		-- id of the email object which will be used to get the vtiger_attachments
 */
function send_mail($module, $to_email, $from_name, $from_email, $subject, $contents, $cc = '', $bcc = '', $attachment = '', $emailid = '', $logo = '', $replyto = '')
{
    global $adb, $log, $root_directory, $HELPDESK_SUPPORT_EMAIL_ID, $HELPDESK_SUPPORT_NAME;
    $uploaddir = $root_directory . "/test/upload/";
    $adb->println("To id => '" . $to_email . "'\nSubject ==>'" . $subject . "'\nContents ==> '" . $contents . "'");
    $femail = '';
    if (substr($from_email, 0, 8) == 'FROM:::>') {
        $femail = substr($from_email, 8);
        $from_email = '';
    }
    if (empty($from_name) and !empty($from_email)) {
        $sql = "select user_name from vtiger_users where status='Active' and (email1=? or email2=? or secondaryemail=?)";
        $result = $adb->pquery($sql, array($from_email, $from_email, $from_email));
        if ($result and $adb->num_rows($result) > 0) {
            $from_name = $adb->query_result($result, 0, 0);
        }
    }
    //if module is HelpDesk then from_email will come based on support email id
    if ($from_email == '') {
        //if from email is not defined, then use the useremailid as the from address
        $from_email = getUserEmailId('user_name', $from_name);
    }
    if (empty($from_email)) {
        $from_email = $HELPDESK_SUPPORT_EMAIL_ID;
    }
    //if the newly defined from email field is set, then use this email address as the from address
    //and use the username as the reply-to address
    $query = "select * from vtiger_systems where server_type=?";
    $params = array('email');
    $result = $adb->pquery($query, $params);
    $from_email_field = $adb->query_result($result, 0, 'from_email_field');
    if (empty($replyto)) {
        if (isUserInitiated()) {
            global $current_user;
            $reply_to_secondary = GlobalVariable::getVariable('Users_ReplyTo_SecondEmail', 0, $module, $current_user->id);
            if ($reply_to_secondary == 1) {
                $sql = "select secondaryemail from vtiger_users where id=?";
                $result = $adb->pquery($sql, array($current_user->id));
                $second_email = '';
                if ($result and $adb->num_rows($result) > 0) {
                    $second_email = $adb->query_result($result, 0, 'secondaryemail');
                }
            }
            if (!empty($second_email)) {
                $replyToEmail = $second_email;
            } else {
                $replyToEmail = $from_email;
            }
        } else {
            $replyToEmail = $from_email_field;
        }
    } else {
        $replyToEmail = $replyto;
    }
    if (isset($from_email_field) && $from_email_field != '') {
        //setting from _email to the defined email address in the outgoing server configuration
        $from_email = $from_email_field;
    }
    if ($femail != '') {
        $from_email = $femail;
    }
    if ($module != "Calendar") {
        $contents = addSignature($contents, $from_name);
    }
    $mail = new PHPMailer();
    setMailerProperties($mail, $subject, $contents, $from_email, $from_name, trim($to_email, ","), $attachment, $emailid, $module, $logo);
    setCCAddress($mail, 'cc', $cc);
    setCCAddress($mail, 'bcc', $bcc);
    if (!empty($replyToEmail)) {
        $mail->AddReplyTo($replyToEmail);
    }
    // vtmailscanner customization: If Support Reply to is defined use it.
    global $HELPDESK_SUPPORT_EMAIL_REPLY_ID;
    if ($HELPDESK_SUPPORT_EMAIL_REPLY_ID && $HELPDESK_SUPPORT_EMAIL_ID != $HELPDESK_SUPPORT_EMAIL_REPLY_ID) {
        $mail->AddReplyTo($HELPDESK_SUPPORT_EMAIL_REPLY_ID);
    }
    // END
    // Fix: Return immediately if Outgoing server not configured
    if (empty($mail->Host)) {
        return 0;
    }
    $mail_status = MailSend($mail);
    if ($mail_status != 1) {
        $mail_error = getMailError($mail, $mail_status, $mailto);
    } else {
        $mail_error = $mail_status;
    }
    return $mail_error;
}
 * Copyright 2014 JPL TSolucio, S.L. -- This file is a part of TSOLUCIO coreBOS Customizations.
 * Licensed under the vtiger CRM Public License Version 1.1 (the "License"); you may not use this
 * file except in compliance with the License. You can redistribute it and/or modify it
 * under the terms of the License. JPL TSolucio, S.L. reserves all rights not expressly
 * granted by the License. coreBOS distributed by JPL TSolucio S.L. is distributed in
 * the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Unless required by
 * applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT ANY WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing
 * permissions and limitations under the License. You may obtain a copy of the License
 * at <http://corebos.org/documentation/doku.php?id=en:devel:vpl11>
 *************************************************************************************************/
// Product line support
if ($elementType != 'PurchaseOrder') {
    if (GlobalVariable::getVariable('B2B', '1') == '1') {
        $acvid = $element['account_id'];
    } else {
        $acvid = $element['contact_id'];
    }
} else {
    $acvid = $element['vendor_id'];
}
$taxtype = $element['taxtype'];
if (empty($taxtype)) {
    $taxtype = 'group';
}
// Individual
$_REQUEST['taxtype'] = $taxtype;
$subtotal = 0;
$totalwithtax = 0;
Beispiel #13
0
 /** Function to check if the product is member of other product
  */
 function ismember_check()
 {
     global $adb;
     $SubProductBeParent = GlobalVariable::getVariable('Product_Permit_Subproduct_Be_Parent', 'no');
     $ismember = 0;
     if ($SubProductBeParent == 'no') {
         $ismember_query = $adb->pquery(getListQuery("Products") . " AND (vtiger_products.productid IN (SELECT crmid from vtiger_seproductsrel WHERE vtiger_seproductsrel.crmid = ? AND vtiger_seproductsrel.setype='Products'))", array($this->id));
         $ismember = $adb->num_rows($ismember_query);
     }
     return $ismember;
 }
Beispiel #14
0
} else {
    if ($errormessage == 3) {
        $msg = $mod_strings['LBL_UPLOAD_ERROR'];
        $errormessage = "<B><font color='red'>" . $msg . "</font></B> <br><br>";
    } else {
        if ($errormessage == "image") {
            $msg = $mod_strings['LBL_IMAGE_ERROR'];
            $errormessage = "<B><font color='red'>" . $msg . "</font></B> <br><br>";
        } else {
            if ($errormessage == "invalid") {
                $msg = $mod_strings['LBL_INVALID_IMAGE'];
                $errormessage = "<B><font color='red'>" . $msg . "</font></B> <br><br>";
            } else {
                $errormessage = "";
            }
        }
    }
}
if ($errormessage != "") {
    $smarty->assign("ERROR_MESSAGE", $errormessage);
}
$smarty->assign('Product_Maximum_Number_Images', GlobalVariable::getVariable('Product_Maximum_Number_Images', 6));
// Gather the help information associated with fields
$smarty->assign('FIELDHELPINFO', vtlib_getFieldHelpInfo($currentModule));
$picklistDependencyDatasource = Vtiger_DependencyPicklist::getPicklistDependencyDatasource($currentModule);
$smarty->assign("PICKIST_DEPENDENCY_DATASOURCE", Zend_Json::encode($picklistDependencyDatasource));
if ($focus->mode == 'edit') {
    $smarty->display('Inventory/InventoryEditView.tpl');
} else {
    $smarty->display('Inventory/InventoryCreateView.tpl');
}
    $timeValue = $dateTimeField->getDisplayTime();
    $dbDateValue = DateTimeField::convertToDBFormat($dateValue);
    $dateValueArray = explode('-', $dbDateValue);
    $timeValueArray = explode(':', $timeValue);
    $date_data = array('day' => $dateValueArray[2], 'month' => $dateValueArray[1], 'fc_month' => $dateValueArray[1] - 1, 'year' => $dateValueArray[0], 'hour' => $timeValueArray[0], 'min' => $timeValueArray[1]);
}
$smarty->assign('DATE_DATA', $date_data);
$calendar_arr['calendar'] = new Calendar($mysel, $date_data);
$add_to_url = "view=" . $calendar_arr['calendar']->view . "" . $calendar_arr['calendar']->date_time->get_date_str() . "&parenttab=" . $category;
$smarty->assign('CALENDAR_TO_URL', $add_to_url);
if (getFieldVisibilityPermission('Events', $current_user->id, 'eventstatus', 'readwrite') == '0') {
    $Events_Status = $Calendar4You->getActStatusFieldValues('eventstatus', 'vtiger_eventstatus');
}
$smarty->assign('EVENT_STATUS', $Events_Status);
if (getFieldVisibilityPermission('Calendar', $current_user->id, 'taskstatus', 'readwrite') == '0') {
    $Task_Status = $Calendar4You->getActStatusFieldValues('taskstatus', 'vtiger_taskstatus');
}
$smarty->assign('TASK_STATUS', $Task_Status);
if (getFieldVisibilityPermission('Calendar', $current_user->id, 'taskpriority', 'readwrite') == '0') {
    $Task_Status = $Calendar4You->getActStatusFieldValues('taskpriority', 'vtiger_taskpriority');
}
$smarty->assign('TASK_PRIORITY', $Task_Status);
$dat_fmt = $current_user->date_format;
if ($dat_fmt == '') {
    $dat_fmt = 'dd-mm-yyyy';
}
$dat_fmt = str_replace("mm", "MM", $dat_fmt);
$smarty->assign('USER_DATE_FORMAT', $dat_fmt);
$smarty->assign('Calendar_Modules_Panel_Visible', GlobalVariable::getVariable('Calendar_Modules_Panel_Visible', 1));
$smarty->display('modules/Calendar4You/CalendarView.tpl');
include_once 'modules/Calendar4You/addEventUI.php';
Beispiel #16
0
 function getCustomViewModuleInfo($module)
 {
     global $adb, $current_language;
     $current_mod_strings = return_specified_module_language($current_language, $module);
     $block_info = array();
     $modules_list = explode(",", $module);
     if ($module == "Calendar") {
         $module = "Calendar','Events";
         $modules_list = array('Calendar', 'Events');
     }
     // Tabid mapped to the list of block labels to be skipped for that tab.
     $showUserAdvancedBlock = GlobalVariable::getVariable('Webservice_showUserAdvancedBlock', 0);
     if ($showUserAdvancedBlock) {
         $userNoShowBlocks = array('LBL_USER_IMAGE_INFORMATION', 'Asterisk Configuration');
     } else {
         $userNoShowBlocks = array('LBL_USER_IMAGE_INFORMATION', 'LBL_USER_ADV_OPTIONS', 'Asterisk Configuration');
     }
     $skipBlocksList = array(getTabid('HelpDesk') => array('LBL_COMMENTS'), getTabid('Faq') => array('LBL_COMMENT_INFORMATION'), getTabid('Quotes') => array('LBL_RELATED_PRODUCTS'), getTabid('PurchaseOrder') => array('LBL_RELATED_PRODUCTS'), getTabid('SalesOrder') => array('LBL_RELATED_PRODUCTS'), getTabid('Invoice') => array('LBL_RELATED_PRODUCTS'), getTabid('Users') => $userNoShowBlocks);
     $Sql = "select distinct block,vtiger_field.tabid,name,blocklabel from vtiger_field inner join vtiger_blocks on vtiger_blocks.blockid=vtiger_field.block inner join vtiger_tab on vtiger_tab.tabid=vtiger_field.tabid where displaytype != 3 and vtiger_tab.name in (" . generateQuestionMarks($modules_list) . ") and vtiger_field.presence in (0,2) order by block";
     $result = $adb->pquery($Sql, array($modules_list));
     if ($module == "Calendar','Events") {
         $module = "Calendar";
     }
     $pre_block_label = '';
     while ($block_result = $adb->fetch_array($result)) {
         $block_label = $block_result['blocklabel'];
         $tabid = $block_result['tabid'];
         // Skip certain blocks of certain modules
         if (array_key_exists($tabid, $skipBlocksList) && in_array($block_label, $skipBlocksList[$tabid])) {
             continue;
         }
         if (trim($block_label) == '') {
             $block_info[$pre_block_label] = $block_info[$pre_block_label] . "," . $block_result['block'];
         } else {
             $lan_block_label = isset($current_mod_strings[$block_label]) ? $current_mod_strings[$block_label] : $block_label;
             if (isset($block_info[$lan_block_label]) && $block_info[$lan_block_label] != '') {
                 $block_info[$lan_block_label] = $block_info[$lan_block_label] . "," . $block_result['block'];
             } else {
                 $block_info[$lan_block_label] = $block_result['block'];
             }
         }
         $pre_block_label = $lan_block_label;
     }
     $this->module_list[$module] = $block_info;
     return $this->module_list;
 }
Beispiel #17
0
/*+********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 ******************************************************************************* */
require_once 'data/Tracker.php';
require_once 'include/utils/utils.php';
require_once 'include/utils/UserInfoUtil.php';
require_once 'include/Webservices/DescribeObject.php';
require_once 'Smarty_setup.php';
global $currentModule, $app_strings, $log, $current_user, $theme;
$theme_path = "themes/" . $theme . "/";
if (isset($_REQUEST['record'])) {
    $id = vtlib_purify($_REQUEST['record']);
    $log->debug(" the id is " . $id);
}
$category = getParentTab();
require_once 'modules/Leads/ConvertLeadUI.php';
$uiinfo = new ConvertLeadUI($id, $current_user);
$smarty = new vtigerCRM_Smarty();
$smarty->assign('UIINFO', $uiinfo);
$smarty->assign('MODULE', 'Leads');
$smarty->assign('CATEGORY', $category);
$smarty->assign('THEME', $theme_path);
$smarty->assign('DATE_FORMAT', $current_user->date_format);
$smarty->assign('CAL_DATE_FORMAT', parse_calendardate($app_strings['NTC_DATE_FORMAT']));
$smarty->assign('LeadConvertTransferToAccount', GlobalVariable::getVariable('Lead_Convert_TransferToAccount', 'false'));
$smarty->display(vtlib_getModuleTemplate($currentModule, 'ConvertLead.tpl'));
Beispiel #18
0
$record = vtlib_purify($_REQUEST['record']);
$isduplicate = vtlib_purify($_REQUEST['isDuplicate']);
//added to fix the issue4600
$searchurl = getBasic_Advance_SearchURL();
$smarty->assign("SEARCH", $searchurl);
//4600 ends
if (!empty($_REQUEST['related_id'])) {
    switch ($_REQUEST['return_module']) {
        case 'Invoice':
        case 'Quotes':
        case 'SalesOrder':
            $lermod = strtolower($_REQUEST['return_module']);
            $lermods = $lermod == 'quotes' ? 'quote' : $lermod;
            $relq = $adb->pquery('select accountid,contactid,total from vtiger_' . $lermod . ' where ' . $lermods . 'id=?', array($_REQUEST['related_id']));
            $relid = $_REQUEST['parent_id'] = $adb->query_result($relq, 0, 'accountid');
            if (empty($relid) or GlobalVariable::getVariable('B2B', '1') == '0') {
                $relid = $_REQUEST['parent_id'] = $adb->query_result($relq, 0, 'contactid');
            }
            $_REQUEST['parent_id'] = $relid;
            $_REQUEST['amount'] = $adb->query_result($relq, 0, 'total');
            break;
        case 'PurchaseOrder':
            $relq = $adb->pquery('select vendorid,total from vtiger_purchaseorder where purchaseorderid=?', array($_REQUEST['related_id']));
            $_REQUEST['parent_id'] = $adb->query_result($relq, 0, 'vendorid');
            $_REQUEST['amount'] = $adb->query_result($relq, 0, 'total');
            break;
        case 'Potentials':
            $relq = $adb->pquery('select related_to from vtiger_potential where potentialid=?', array($_REQUEST['related_id']));
            $_REQUEST['parent_id'] = $adb->query_result($relq, 0, 0);
            break;
        case 'HelpDesk':
        $cnt_idlist = array_keys($cnt_namelist);
        $smarty->assign("CONTACTSID", implode(';', $cnt_idlist));
        $smarty->assign("CONTACTSNAME", $cnt_namelist);
        $account_id = vtlib_purify($_REQUEST['account_id']);
        $account_name = getAccountName($account_id);
    }
}
if (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    $focus->id = "";
    $focus->mode = '';
}
if (empty($_REQUEST['record']) && $focus->mode != 'edit') {
    $_REQUEST['assigned_user_id'] = empty($_REQUEST['assigned_user_id']) ? $current_user->id : $_REQUEST['assigned_user_id'];
    setObjectValuesFromRequest($focus);
    if (empty($focus->column_fields['reminder_time'])) {
        $focus->column_fields['reminder_time'] = GlobalVariable::getVariable('Calendar_Default_Reminder_Minutes', 0);
    }
}
$userDetails = getOtherUserName($current_user->id);
$to_email = getUserEmailId('id', $current_user->id);
$smarty->assign("CURRENTUSERID", $current_user->id);
$disp_view = getView($focus->mode);
if ($disp_view == 'edit_view') {
    $act_data = getBlocks($tab_type, $disp_view, $focus->mode, $focus->column_fields);
} else {
    $act_data = getBlocks($tab_type, $disp_view, $focus->mode, $focus->column_fields, 'BAS');
}
$smarty->assign("BLOCKS", $act_data);
foreach ($act_data as $header => $blockitem) {
    foreach ($blockitem as $row => $data) {
        foreach ($data as $key => $maindata) {
Beispiel #20
0
function getRelatedAccountContact($entityid, $module = '')
{
    global $adb, $log, $current_user;
    if ($module == '' or $module != 'Accounts' and $module != 'Contacts') {
        if (GlobalVariable::getVariable('B2B', '1')) {
            $module = 'Accounts';
        } else {
            $module = 'Contacts';
        }
    }
    if (strpos($entityid, 'x') > 0 and !is_numeric($entityid)) {
        list($ent, $crmid) = explode('x', $entityid);
    } else {
        $crmid = $entityid;
    }
    $acid = 0;
    if (is_numeric($crmid)) {
        $setype = getSalesEntityType($crmid);
        switch ($setype) {
            case 'Accounts':
                $acid = $crmid;
                break;
            case 'Contacts':
                if ($module == 'Contacts') {
                    $acid = $crmid;
                } else {
                    $rspot = $adb->pquery('select accountid from vtiger_contactdetails where contactid=?', array($crmid));
                    $acid = $adb->query_result($rspot, 0, 'accountid');
                }
                break;
            case 'Potentials':
                $rspot = $adb->pquery("select related_to from vtiger_potential where potentialid=?", array($crmid));
                $acid = $adb->query_result($rspot, 0, 'related_to');
                break;
            case 'HelpDesk':
                $rspot = $adb->pquery("select parent_id from vtiger_troubletickets where ticketid=?", array($crmid));
                $acid = $adb->query_result($rspot, 0, 'parent_id');
                break;
            case 'Quotes':
                $rspot = $adb->pquery("select accountid,contactid from vtiger_quotes where quoteid=?", array($crmid));
                if ($module == 'Accounts') {
                    $acid = $adb->query_result($rspot, 0, 'accountid');
                } else {
                    $acid = $adb->query_result($rspot, 0, 'contactid');
                }
                break;
            case 'SalesOrder':
                $rspot = $adb->pquery("select accountid,contactid from vtiger_salesorder where salesorderid=?", array($crmid));
                if ($module == 'Accounts') {
                    $acid = $adb->query_result($rspot, 0, 'accountid');
                } else {
                    $acid = $adb->query_result($rspot, 0, 'contactid');
                }
                break;
            case 'PurchaseOrder':
                $rspot = $adb->pquery("select contactid from vtiger_purchaseorder where purchaseorderid=?", array($crmid));
                $acid = $adb->query_result($rspot, 0, 'contactid');
                break;
            case 'Invoice':
                $rspot = $adb->pquery("select accountid,contactid from vtiger_invoice where invoiceid=?", array($crmid));
                if ($module == 'Accounts') {
                    $acid = $adb->query_result($rspot, 0, 'accountid');
                } else {
                    $acid = $adb->query_result($rspot, 0, 'contactid');
                }
                break;
            case 'InventoryDetails':
                $rspot = $adb->pquery("select account_id,contact_id from vtiger_inventorydetails where inventorydetailsid=?", array($crmid));
                if ($module == 'Accounts') {
                    $acid = $adb->query_result($rspot, 0, 'account_id');
                } else {
                    $acid = $adb->query_result($rspot, 0, 'contact_id');
                }
                break;
            case 'ServiceContracts':
                $rspot = $adb->pquery("select sc_related_to from vtiger_servicecontracts where servicecontractsid=?", array($crmid));
                $acid = $adb->query_result($rspot, 0, 'sc_related_to');
                break;
            case 'Assets':
                $rspot = $adb->pquery("select account from vtiger_assets where assetsid=?", array($crmid));
                $acid = $adb->query_result($rspot, 0, 'account');
                break;
            case 'ProjectMilestone':
                $rspot = $adb->pquery("select linktoaccountscontacts\n\t\t\t\tfrom vtiger_project\n\t\t\t\tinner join vtiger_projectmilestone on vtiger_project.projectid = vtiger_projectmilestone.projectid\n\t\t\t\twhere projectmilestoneid=?", array($crmid));
                $acid = $adb->query_result($rspot, 0, 'linktoaccountscontacts');
                break;
            case 'ProjectTask':
                $rspot = $adb->pquery("select linktoaccountscontacts\n\t\t\t\tfrom vtiger_project\n\t\t\t\tinner join vtiger_projecttask on vtiger_project.projectid = vtiger_projecttask.projectid\n\t\t\t\twhere projecttaskid=?", array($crmid));
                $acid = $adb->query_result($rspot, 0, 'linktoaccountscontacts');
                break;
            case 'Project':
                $rspot = $adb->pquery("select linktoaccountscontacts from vtiger_project where projectid=?", array($crmid));
                $acid = $adb->query_result($rspot, 0, 'linktoaccountscontacts');
                break;
            case 'CobroPago':
                $rspot = $adb->pquery("select parent_id from vtiger_cobropago where cobropagoid=?", array($crmid));
                $acid = $adb->query_result($rspot, 0, 'parent_id');
                break;
            case 'Calendar':
            case 'Events':
                if ($module == 'Accounts') {
                    $rspot = $adb->pquery("select crmid from vtiger_seactivityrel where activityid=?", array($crmid));
                    if ($rspot and $adb->num_rows($rspot) > 0) {
                        $acid = $adb->query_result($rspot, 0, 'crmid');
                    }
                } else {
                    $rspot = $adb->pquery("select contactid from vtiger_cntactivityrel where activityid=?", array($crmid));
                    if ($rspot and $adb->num_rows($rspot) > 0) {
                        $acid = $adb->query_result($rspot, 0, 'contactid');
                    }
                }
                break;
            default:
                // we look for uitype 10
                $rsfld = $adb->pquery('SELECT fieldname from vtiger_fieldmodulerel
					INNER JOIN vtiger_field on vtiger_field.fieldid=vtiger_fieldmodulerel.fieldid
					WHERE module=? and relmodule=?', array($setype, $module));
                if ($rsfld and $adb->num_rows($rsfld) > 0) {
                    $fname = $adb->query_result($rsfld, 0, 'fieldname');
                    $queryGenerator = new QueryGenerator($setype, $current_user);
                    $queryGenerator->setFields(array($fname));
                    $queryGenerator->addCondition('id', $crmid, 'e');
                    $query = $queryGenerator->getQuery();
                    $rspot = $adb->pquery($query, array());
                    $acid = $adb->query_result($rspot, 0, $fname);
                }
        }
    }
    if ($acid != 0) {
        $actype = getSalesEntityType($acid);
        if ($actype != $module) {
            $acid = 0;
        }
    }
    return $acid;
}
<?php

/*+********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ('License'); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 ********************************************************************************/
require_once 'Smarty_setup.php';
global $app_strings, $mod_strings, $current_user, $theme, $adb;
$image_path = 'themes/' . $theme . '/images/';
$smarty = new vtigerCRM_Smarty();
$smarty->assign('MOD', $mod_strings);
$smarty->assign('APP', $app_strings);
$smarty->assign('THEME', $theme);
$smarty->assign('IMAGE_PATH', $image_path);
$smarty->assign('BillAddressChecked', GlobalVariable::getVariable('Billing_Address_Checked', 'true'));
$smarty->assign('ShipAddressChecked', GlobalVariable::getVariable('Shipping_Address_Checked', 'false'));
$smarty->display('modules/Vendors/SetReturnAddress.tpl');
Beispiel #22
0
/** This function returns the detailed list of vtiger_products associated to a given entity or a record.
* Param $module - module name
* Param $focus - module object
* Param $seid - sales entity id
* Return type is an object array
*/
function getAssociatedProducts($module, $focus, $seid = '')
{
    global $log, $adb, $theme, $current_user;
    $log->debug("Entering getAssociatedProducts(" . $module . "," . get_class($focus) . "," . $seid . "='') method ...");
    $theme_path = "themes/" . $theme . "/";
    $image_path = $theme_path . "images/";
    $product_Detail = array();
    if ($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') {
        $query = "SELECT\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.productcode else vtiger_service.service_no end as productcode,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock,\n\t\t\tcase when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype,\n\t\t\tvtiger_inventoryproductrel.listprice,\n\t\t\tvtiger_inventoryproductrel.description AS product_description,\n\t\t\tvtiger_inventoryproductrel.*\n\t\t\tFROM vtiger_inventoryproductrel\n\t\t\tLEFT JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid\n\t\t\tLEFT JOIN vtiger_service ON vtiger_service.serviceid=vtiger_inventoryproductrel.productid\n\t\t\tWHERE id=? ORDER BY sequence_no";
        $params = array($focus->id);
        if ($module != 'PurchaseOrder') {
            if (GlobalVariable::getVariable('B2B', '1') == '1') {
                $acvid = $focus->column_fields['account_id'];
            } else {
                $acvid = $focus->column_fields['contact_id'];
            }
        } else {
            $acvid = $focus->column_fields['vendor_id'];
        }
    } elseif ($module == 'Potentials') {
        $query = "SELECT vtiger_products.productid, vtiger_products.productname, vtiger_products.productcode,\n\t\t\tvtiger_products.unit_price, vtiger_products.qtyinstock, vtiger_crmentity.description AS product_description,\n\t\t\t'Products' AS entitytype\n\t\t\tFROM vtiger_products\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid\n\t\t\tINNER JOIN vtiger_seproductsrel ON vtiger_seproductsrel.productid=vtiger_products.productid\n\t\t\tWHERE vtiger_seproductsrel.crmid=?";
        $query .= " UNION SELECT vtiger_service.serviceid AS productid, vtiger_service.servicename AS productname,\n\t\t\t'NA' AS productcode, vtiger_service.unit_price AS unit_price, 'NA' AS qtyinstock,\n\t\t\tvtiger_crmentity.description AS product_description, 'Services' AS entitytype\n\t\t\tFROM vtiger_service\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_service.serviceid\n\t\t\tINNER JOIN vtiger_crmentityrel ON vtiger_crmentityrel.relcrmid=vtiger_service.serviceid\n\t\t\tWHERE vtiger_crmentityrel.crmid=?";
        $params = array($seid, $seid);
    } elseif ($module == 'Products') {
        $query = "SELECT vtiger_products.productid, vtiger_products.productcode, vtiger_products.productname,\n\t\t\tvtiger_products.unit_price, vtiger_products.qtyinstock, vtiger_crmentity.description AS product_description,\n\t\t\t'Products' AS entitytype\n\t\t\tFROM vtiger_products\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid\n\t\t\tWHERE vtiger_crmentity.deleted=0 AND productid=?";
        $params = array($seid);
    } elseif ($module == 'Services') {
        $query = "SELECT vtiger_service.serviceid AS productid, 'NA' AS productcode, vtiger_service.servicename AS productname,\n\t\t\tvtiger_service.unit_price AS unit_price, 'NA' AS qtyinstock, vtiger_crmentity.description AS product_description,\n\t\t\t'Services' AS entitytype\n\t\t\tFROM vtiger_service\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_service.serviceid\n\t\t\tWHERE vtiger_crmentity.deleted=0 AND serviceid=?";
        $params = array($seid);
    }
    $cbMap = cbMap::getMapByName($module . 'InventoryDetails', 'MasterDetailLayout');
    $MDMapFound = $cbMap != null;
    if ($MDMapFound) {
        $cbMapFields = $cbMap->MasterDetailLayout();
    }
    $result = $adb->pquery($query, $params);
    $num_rows = $adb->num_rows($result);
    for ($i = 1; $i <= $num_rows; $i++) {
        $hdnProductId = $adb->query_result($result, $i - 1, 'productid');
        $hdnProductcode = $adb->query_result($result, $i - 1, 'productcode');
        $productname = $adb->query_result($result, $i - 1, 'productname');
        $productdescription = $adb->query_result($result, $i - 1, 'product_description');
        $comment = $adb->query_result($result, $i - 1, 'comment');
        $qtyinstock = $adb->query_result($result, $i - 1, 'qtyinstock');
        $qty = $adb->query_result($result, $i - 1, 'quantity');
        $unitprice = $adb->query_result($result, $i - 1, 'unit_price');
        $listprice = $adb->query_result($result, $i - 1, 'listprice');
        $entitytype = $adb->query_result($result, $i - 1, 'entitytype');
        if (!empty($entitytype)) {
            $product_Detail[$i]['entityType' . $i] = $entitytype;
        }
        $product_Detail[$i]['lineitem_id' . $i] = $adb->query_result($result, $i - 1, 'lineitem_id');
        if ($listprice == '') {
            $listprice = $unitprice;
        }
        if ($qty == '') {
            $qty = 1;
        }
        //calculate productTotal
        $productTotal = $qty * $listprice;
        //Delete link in First column
        if ($i != 1) {
            $product_Detail[$i]['delRow' . $i] = "Del";
        }
        if (empty($focus->mode) && $seid != '') {
            $sub_prod_query = $adb->pquery("SELECT crmid as prod_id from vtiger_seproductsrel WHERE productid=? AND setype='Products'", array($seid));
        } else {
            $sub_prod_query = $adb->pquery("SELECT productid as prod_id from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($focus->id, $i));
        }
        $subprodid_str = '';
        $subprodname_str = '';
        $subProductArray = array();
        if ($adb->num_rows($sub_prod_query) > 0) {
            for ($j = 0; $j < $adb->num_rows($sub_prod_query); $j++) {
                $sprod_id = $adb->query_result($sub_prod_query, $j, 'prod_id');
                $sprod_name = $subProductArray[] = getProductName($sprod_id);
                $str_sep = "";
                if ($j > 0) {
                    $str_sep = ":";
                }
                $subprodid_str .= $str_sep . $sprod_id;
                $subprodname_str .= $str_sep . " - " . $sprod_name;
            }
        }
        $subprodname_str = str_replace(":", "<br>", $subprodname_str);
        $product_Detail[$i]['subProductArray' . $i] = $subProductArray;
        $product_Detail[$i]['hdnProductId' . $i] = $hdnProductId;
        $product_Detail[$i]['productName' . $i] = from_html($productname);
        /* Added to fix the issue Product Pop-up name display*/
        if ($_REQUEST['action'] == 'CreateSOPDF' || $_REQUEST['action'] == 'CreatePDF' || $_REQUEST['action'] == 'SendPDFMail') {
            $product_Detail[$i]['productName' . $i] = htmlspecialchars($product_Detail[$i]['productName' . $i]);
        }
        $product_Detail[$i]['hdnProductcode' . $i] = $hdnProductcode;
        $product_Detail[$i]['productDescription' . $i] = from_html($productdescription);
        if ($module == 'Potentials' || $module == 'Products' || $module == 'Services') {
            $product_Detail[$i]['comment' . $i] = $productdescription;
        } else {
            $product_Detail[$i]['comment' . $i] = $comment;
        }
        if ($MDMapFound) {
            foreach ($cbMapFields['detailview']['fields'] as $mdfield) {
                $mdrs = $adb->pquery('select ' . $mdfield['fieldinfo']['name'] . ' from vtiger_inventorydetails
						inner join vtiger_crmentity on crmid=vtiger_inventorydetails.inventorydetailsid
						inner join vtiger_inventorydetailscf on vtiger_inventorydetailscf.inventorydetailsid=vtiger_inventorydetails.inventorydetailsid
						where deleted=0 and related_to=? and lineitem_id=?', array($focus->id, $adb->query_result($result, $i - 1, 'lineitem_id')));
                if ($mdrs) {
                    $col_fields = array();
                    $col_fields[$mdfield['fieldinfo']['name']] = $adb->query_result($mdrs, 0, 0);
                    $foutput = getOutputHtml($mdfield['fieldinfo']['uitype'], $mdfield['fieldinfo']['name'], $mdfield['fieldinfo']['label'], 100, $col_fields, 0, 'InventoryDetails', 'edit', $mdfield['fieldinfo']['typeofdata']);
                    $product_Detail[$i]['moreinfo' . $i][] = $foutput;
                }
            }
        }
        if ($module != 'PurchaseOrder' && $focus->object_name != 'Order') {
            $product_Detail[$i]['qtyInStock' . $i] = $qtyinstock;
        }
        $qty = number_format($qty, 2, '.', '');
        //Convert to 2 decimals
        $listprice = number_format($listprice, 2, '.', '');
        //Convert to 2 decimals
        $product_Detail[$i]['qty' . $i] = $qty;
        $product_Detail[$i]['listPrice' . $i] = $listprice;
        $product_Detail[$i]['unitPrice' . $i] = $unitprice;
        $product_Detail[$i]['productTotal' . $i] = $productTotal;
        $product_Detail[$i]['subproduct_ids' . $i] = $subprodid_str;
        $product_Detail[$i]['subprod_names' . $i] = $subprodname_str;
        $discount_percent = $adb->query_result($result, $i - 1, 'discount_percent');
        $discount_amount = $adb->query_result($result, $i - 1, 'discount_amount');
        $discount_amount = number_format(is_numeric($discount_amount) ? $discount_amount : 0, 2, '.', '');
        //Convert to 2 decimals
        $discountTotal = '0.00';
        //Based on the discount percent or amount we will show the discount details
        //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(for Each Product)
        $product_Detail[$i]['discount_percent' . $i] = 0;
        $product_Detail[$i]['discount_amount' . $i] = 0;
        if ($discount_percent != 'NULL' && $discount_percent != '') {
            $product_Detail[$i]['discount_type' . $i] = "percentage";
            $product_Detail[$i]['discount_percent' . $i] = $discount_percent;
            $product_Detail[$i]['checked_discount_percent' . $i] = ' checked';
            $product_Detail[$i]['style_discount_percent' . $i] = ' style="visibility:visible"';
            $product_Detail[$i]['style_discount_amount' . $i] = ' style="visibility:hidden"';
            $discountTotal = $productTotal * $discount_percent / 100;
        } elseif ($discount_amount != 'NULL' && $discount_amount != '') {
            $product_Detail[$i]['discount_type' . $i] = "amount";
            $product_Detail[$i]['discount_amount' . $i] = $discount_amount;
            $product_Detail[$i]['checked_discount_amount' . $i] = ' checked';
            $product_Detail[$i]['style_discount_amount' . $i] = ' style="visibility:visible"';
            $product_Detail[$i]['style_discount_percent' . $i] = ' style="visibility:hidden"';
            $discountTotal = $discount_amount;
        } else {
            $product_Detail[$i]['checked_discount_zero' . $i] = ' checked';
        }
        $totalAfterDiscount = $productTotal - $discountTotal;
        $product_Detail[$i]['discountTotal' . $i] = $discountTotal;
        $product_Detail[$i]['totalAfterDiscount' . $i] = $totalAfterDiscount;
        $taxTotal = '0.00';
        $product_Detail[$i]['taxTotal' . $i] = $taxTotal;
        //Calculate netprice
        $netPrice = $totalAfterDiscount + $taxTotal;
        //if condition is added to call this function when we create PO/SO/Quotes/Invoice from Product module
        if ($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice') {
            $taxtype = getInventoryTaxType($module, $focus->id);
            if ($taxtype == 'individual') {
                //Add the tax with product total and assign to netprice
                $netPrice = $netPrice + $taxTotal;
            }
        }
        $product_Detail[$i]['netPrice' . $i] = $netPrice;
        //First we will get all associated taxes as array
        $tax_details = getTaxDetailsForProduct($hdnProductId, 'all', $acvid);
        //Now retrieve the tax values from the current query with the name
        for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
            $tax_name = $tax_details[$tax_count]['taxname'];
            $tax_label = $tax_details[$tax_count]['taxlabel'];
            $tax_value = '0.00';
            //condition to avoid this function call when create new PO/SO/Quotes/Invoice from Product module
            if ($focus->id != '') {
                if ($taxtype == 'individual') {
                    //if individual then show the entered tax percentage
                    $tax_value = getInventoryProductTaxValue($focus->id, $hdnProductId, $tax_name);
                } else {
                    //if group tax then we have to show the default value when change to individual tax
                    $tax_value = $tax_details[$tax_count]['percentage'];
                }
            } else {
                //if the above function not called then assign the default associated value of the product
                $tax_value = $tax_details[$tax_count]['percentage'];
            }
            $product_Detail[$i]['taxes'][$tax_count]['taxname'] = $tax_name;
            $product_Detail[$i]['taxes'][$tax_count]['taxlabel'] = $tax_label;
            $product_Detail[$i]['taxes'][$tax_count]['percentage'] = $tax_value;
        }
    }
    //set the taxtype
    $product_Detail[1]['final_details']['taxtype'] = $taxtype;
    //Get the Final Discount, S&H charge, Tax for S&H and Adjustment values
    //To set the Final Discount details
    $finalDiscount = '0.00';
    $product_Detail[1]['final_details']['discount_type_final'] = 'zero';
    $subTotal = $focus->column_fields['hdnSubTotal'] != '' ? $focus->column_fields['hdnSubTotal'] : '0.00';
    $subTotal = number_format($subTotal, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['hdnSubTotal'] = $subTotal;
    $discountPercent = $focus->column_fields['hdnDiscountPercent'] != '' ? $focus->column_fields['hdnDiscountPercent'] : '0.00';
    $discountAmount = $focus->column_fields['hdnDiscountAmount'] != '' ? $focus->column_fields['hdnDiscountAmount'] : '0.00';
    $discountAmount = number_format($discountAmount, 2, '.', '');
    //Convert to 2 decimals
    //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(For Final Discount)
    $product_Detail[1]['final_details']['discount_percentage_final'] = 0;
    $product_Detail[1]['final_details']['discount_amount_final'] = 0;
    if ($focus->column_fields['hdnDiscountPercent'] != '0') {
        $finalDiscount = $subTotal * $discountPercent / 100;
        $product_Detail[1]['final_details']['discount_type_final'] = 'percentage';
        $product_Detail[1]['final_details']['discount_percentage_final'] = $discountPercent;
        $product_Detail[1]['final_details']['checked_discount_percentage_final'] = ' checked';
        $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:visible"';
        $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:hidden"';
    } elseif ($focus->column_fields['hdnDiscountAmount'] != '0') {
        $finalDiscount = $focus->column_fields['hdnDiscountAmount'];
        $product_Detail[1]['final_details']['discount_type_final'] = 'amount';
        $product_Detail[1]['final_details']['discount_amount_final'] = $discountAmount;
        $product_Detail[1]['final_details']['checked_discount_amount_final'] = ' checked';
        $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:visible"';
        $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:hidden"';
    }
    $finalDiscount = number_format($finalDiscount, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['discountTotal_final'] = $finalDiscount;
    //To set the Final Tax values
    //we will get all taxes. if individual then show the product related taxes only else show all taxes
    //suppose user want to change individual to group or vice versa in edit time the we have to show all taxes. so that here we will store all the taxes and based on need we will show the corresponding taxes
    $taxtotal = '0.00';
    //First we should get all available taxes and then retrieve the corresponding tax values
    $tax_details = getAllTaxes('available', '', 'edit', $focus->id);
    $ipr_cols = $adb->getColumnNames('vtiger_inventoryproductrel');
    for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
        $tax_name = $tax_details[$tax_count]['taxname'];
        $tax_label = $tax_details[$tax_count]['taxlabel'];
        //if taxtype is individual and want to change to group during edit time then we have to show the all available taxes and their default values
        //Also taxtype is group and want to change to individual during edit time then we have to provide the asspciated taxes and their default tax values for individual products
        if ($taxtype == 'group') {
            if (in_array($tax_name, $ipr_cols)) {
                $tax_percent = $adb->query_result($result, 0, $tax_name);
            } else {
                $tax_percent = $tax_details[$tax_count]['percentage'];
            }
        } else {
            $tax_percent = $tax_details[$tax_count]['percentage'];
        }
        //$adb->query_result($result,0,$tax_name);
        if ($tax_percent == '' || $tax_percent == 'NULL') {
            $tax_percent = '0.00';
        }
        $taxamount = ($subTotal - $finalDiscount) * $tax_percent / 100;
        $taxamount = number_format($taxamount, 2, '.', '');
        //Convert to 2 decimals
        $taxtotal = $taxtotal + $taxamount;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['taxname'] = $tax_name;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['taxlabel'] = $tax_label;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['percentage'] = $tax_percent;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['amount'] = $taxamount;
    }
    $product_Detail[1]['final_details']['tax_totalamount'] = $taxtotal;
    //To set the Shipping & Handling charge
    $shCharge = $focus->column_fields['hdnS_H_Amount'] != '' ? $focus->column_fields['hdnS_H_Amount'] : '0.00';
    $shCharge = number_format($shCharge, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['shipping_handling_charge'] = $shCharge;
    //To set the Shipping & Handling tax values
    //calculate S&H tax
    $shtaxtotal = '0.00';
    //First we should get all available taxes and then retrieve the corresponding tax values
    $shtax_details = getAllTaxes('available', 'sh', 'edit', $focus->id);
    //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
    for ($shtax_count = 0; $shtax_count < count($shtax_details); $shtax_count++) {
        $shtax_name = $shtax_details[$shtax_count]['taxname'];
        $shtax_label = $shtax_details[$shtax_count]['taxlabel'];
        $shtax_percent = '0.00';
        //if condition is added to call this function when we create PO/SO/Quotes/Invoice from Product module
        if ($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice') {
            $shtax_percent = getInventorySHTaxPercent($focus->id, $shtax_name);
        }
        $shtaxamount = $shCharge * $shtax_percent / 100;
        $shtaxtotal = $shtaxtotal + $shtaxamount;
        $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['taxname'] = $shtax_name;
        $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['taxlabel'] = $shtax_label;
        $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['percentage'] = $shtax_percent;
        $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['amount'] = $shtaxamount;
    }
    $product_Detail[1]['final_details']['shtax_totalamount'] = $shtaxtotal;
    //To set the Adjustment value
    $adjustment = $focus->column_fields['txtAdjustment'] != '' ? $focus->column_fields['txtAdjustment'] : '0.00';
    $adjustment = number_format($adjustment, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['adjustment'] = $adjustment;
    //To set the grand total
    $grandTotal = $focus->column_fields['hdnGrandTotal'] != '' ? $focus->column_fields['hdnGrandTotal'] : '0.00';
    $grandTotal = number_format($grandTotal, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['grandTotal'] = $grandTotal;
    $log->debug("Exiting getAssociatedProducts method ...");
    return $product_Detail;
}
Beispiel #23
0
 function writeReportToExcelFile($fileName, $filterlist = '')
 {
     global $currentModule, $current_language, $current_user;
     $mod_strings = return_module_language($current_language, $currentModule);
     require_once 'include/PHPExcel/PHPExcel.php';
     $xlsrowheight = GlobalVariable::getVariable('Report.Excel.Export.RowHeight', 20);
     $workbook = new PHPExcel();
     $worksheet = $workbook->setActiveSheetIndex(0);
     $fieldinfo = array();
     $arr_val = $this->GenerateReport('PDF', $filterlist, false, $fieldinfo);
     $totalxls = $this->GenerateReport('TOTALXLS', $filterlist);
     $header_styles = array('fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'E1E0F7')), 'font' => array('bold' => true));
     if (isset($arr_val)) {
         $FieldDataTypes = array();
         foreach ($arr_val[0] as $hdr => $value) {
             $FieldDataTypes[$hdr] = $fieldinfo[$hdr]->getFieldDataType();
             if ($fieldinfo[$hdr]->getColumnName() == 'totaltime') {
                 $FieldDataTypes[$hdr] = 'time';
             }
             if ($fieldinfo[$hdr]->getColumnName() == 'totaldaytime') {
                 $FieldDataTypes[$hdr] = 'time';
             }
         }
         $BoolTrue = getTranslatedString('LBL_YES');
         //$BoolFalse = getTranslatedString('LBL_NO');
         $count = 0;
         $rowcount = 1;
         $workbook->getActiveSheet()->getRowDimension($rowcount)->setRowHeight($xlsrowheight);
         //copy the first value details
         $arrayFirstRowValues = $arr_val[0];
         foreach ($arrayFirstRowValues as $key => $value) {
             $worksheet->setCellValueExplicitByColumnAndRow($count, $rowcount, $key, true);
             $worksheet->getStyleByColumnAndRow($count, $rowcount)->applyFromArray($header_styles);
             // NOTE Performance overhead: http://stackoverflow.com/questions/9965476/phpexcel-column-size-issues
             $worksheet->getColumnDimensionByColumn($count)->setAutoSize(true);
             $count = $count + 1;
             if ($FieldDataTypes[$key] == 'currency') {
                 $worksheet->setCellValueExplicitByColumnAndRow($count, $rowcount, getTranslatedString('LBL_CURRENCY'), true);
                 $worksheet->getStyleByColumnAndRow($count, $rowcount)->applyFromArray($header_styles);
                 $worksheet->getColumnDimensionByColumn($count)->setAutoSize(true);
                 $count = $count + 1;
             }
         }
         $rowcount++;
         $workbook->getActiveSheet()->getRowDimension($rowcount)->setRowHeight($xlsrowheight);
         foreach ($arr_val as $key => $array_value) {
             $count = 0;
             foreach ($array_value as $hdr => $value) {
                 $value = decode_html($value);
                 switch ($FieldDataTypes[$hdr]) {
                     case 'boolean':
                         $celltype = PHPExcel_Cell_DataType::TYPE_BOOL;
                         $value = $value == $BoolTrue ? 1 : 0;
                         break;
                     case 'integer':
                     case 'double':
                     case 'currency':
                         $celltype = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                         break;
                     case 'date':
                         $value = DateTimeField::__convertToDBFormat($value, $current_user->date_format);
                         $dt = new DateTime($value);
                         $value = PHPExcel_Shared_Date::PHPToExcel($dt);
                         $celltype = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                         break;
                     case 'time':
                         $dt = new DateTime("1970/01/01 {$value}");
                         $value = PHPExcel_Shared_Date::PHPToExcel($dt);
                         $celltype = PHPExcel_Cell_DataType::TYPE_NUMERIC;
                         break;
                     default:
                         $celltype = PHPExcel_Cell_DataType::TYPE_STRING;
                         break;
                 }
                 if ($FieldDataTypes[$hdr] == 'currency') {
                     $csym = preg_replace('/[0-9,.-]/', '', $value);
                     $value = preg_replace('/[^0-9,.-]/', '', $value);
                     $value = str_replace($current_user->currency_grouping_separator, '', $value);
                     if ($current_user->currency_decimal_separator != '.') {
                         $value = str_replace($current_user->currency_decimal_separator, '.', $value);
                     }
                 }
                 $worksheet->setCellValueExplicitByColumnAndRow($count, $rowcount, $value, $celltype);
                 if ($FieldDataTypes[$hdr] == 'date') {
                     $worksheet->getStyleByColumnAndRow($count, $rowcount)->getNumberFormat()->setFormatCode($current_user->date_format);
                 } elseif ($FieldDataTypes[$hdr] == 'time') {
                     $worksheet->getStyleByColumnAndRow($count, $rowcount)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4);
                 }
                 if ($FieldDataTypes[$hdr] == 'currency') {
                     $count = $count + 1;
                     $worksheet->setCellValueExplicitByColumnAndRow($count, $rowcount, $csym, PHPExcel_Cell_DataType::TYPE_STRING);
                 }
                 $count = $count + 1;
             }
             $rowcount++;
             $workbook->getActiveSheet()->getRowDimension($rowcount)->setRowHeight($xlsrowheight);
         }
         // Summary Total
         $rowcount++;
         $workbook->getActiveSheet()->getRowDimension($rowcount)->setRowHeight($xlsrowheight);
         $count = 0;
         if (isset($totalxls) and is_array($totalxls) and count($totalxls) > 0) {
             if (is_array($totalxls[0])) {
                 $worksheet->setCellValueExplicitByColumnAndRow($count, $rowcount, getTranslatedString('Totals', 'Reports'), PHPExcel_Cell_DataType::TYPE_STRING);
                 $worksheet->getStyleByColumnAndRow($count, $rowcount)->applyFromArray($header_styles);
                 $count = $count + 1;
                 foreach ($totalxls[0] as $key => $value) {
                     $chdr = substr($key, -3, 3);
                     $translated_str = in_array($chdr, array_keys($mod_strings)) ? $mod_strings[$chdr] : $key;
                     $worksheet->setCellValueExplicitByColumnAndRow($count, $rowcount, decode_html($translated_str), PHPExcel_Cell_DataType::TYPE_STRING);
                     $worksheet->getStyleByColumnAndRow($count, $rowcount)->applyFromArray($header_styles);
                     $count = $count + 1;
                 }
             }
             $rowcount++;
             $workbook->getActiveSheet()->getRowDimension($rowcount)->setRowHeight($xlsrowheight);
             foreach ($totalxls as $key => $array_value) {
                 $count = 0;
                 foreach ($array_value as $hdr => $value) {
                     if ($count == 0) {
                         $lbl = substr($hdr, 0, strrpos($hdr, '_'));
                         $mname = substr($lbl, 0, strpos($lbl, '_'));
                         $lbl = substr($lbl, strpos($lbl, '_') + 1);
                         $lbl = str_replace('_', ' ', $lbl);
                         $lbl = getTranslatedString($lbl, $mname);
                         $worksheet->setCellValueExplicitByColumnAndRow($count, $rowcount, decode_html($lbl), PHPExcel_Cell_DataType::TYPE_STRING);
                         $worksheet->getStyleByColumnAndRow($count, $rowcount)->applyFromArray($header_styles);
                         $workbook->getActiveSheet()->getRowDimension($rowcount)->setRowHeight($xlsrowheight);
                         $count = $count + 1;
                     }
                     $value = str_replace($current_user->currency_grouping_separator, '', $value);
                     if ($current_user->currency_decimal_separator != '.') {
                         $value = str_replace($current_user->currency_decimal_separator, '.', $value);
                     }
                     $worksheet->setCellValueExplicitByColumnAndRow($count, $rowcount, $value, PHPExcel_Cell_DataType::TYPE_NUMERIC);
                     $count = $count + 1;
                 }
                 $rowcount++;
             }
         }
     }
     $workbookWriter = PHPExcel_IOFactory::createWriter($workbook, 'Excel5');
     $workbookWriter->save($fileName);
 }
Beispiel #24
0
function createRecords($obj)
{
    global $adb, $VTIGER_BULK_SAVE_MODE;
    $moduleName = $obj->module;
    $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $obj->user);
    $moduleMeta = $moduleHandler->getMeta();
    $moduleObjectId = $moduleMeta->getEntityId();
    $moduleFields = $moduleMeta->getModuleFields();
    include_once 'include/fields/InventoryLineField.php';
    $ilfields = new InventoryLineField();
    $moduleFields = array_merge($moduleFields, $ilfields->getInventoryLineFieldsByObject());
    $focus = CRMEntity::getInstance($moduleName);
    $wsrs = $adb->pquery('select id from vtiger_ws_entity where name=?', array('Products'));
    if ($wsrs and $adb->num_rows($wsrs) == 1) {
        $pdowsid = $adb->query_result($wsrs, 0, 0) . 'x';
    } else {
        $pdowsid = '0x';
    }
    $wsrs = $adb->pquery('select id from vtiger_ws_entity where name=?', array('Services'));
    if ($wsrs and $adb->num_rows($wsrs) == 1) {
        $srvwsid = $adb->query_result($wsrs, 0, 0) . 'x';
    } else {
        $srvwsid = '0x';
    }
    $wsrs = $adb->pquery('select id from vtiger_ws_entity where name=?', array('Users'));
    if ($wsrs and $adb->num_rows($wsrs) == 1) {
        $usrwsid = $adb->query_result($wsrs, 0, 0) . 'x';
    } else {
        $usrwsid = '0x';
    }
    $tableName = Import_Utils::getDbTableName($obj->user);
    $sql = 'SELECT * FROM ' . $tableName . ' WHERE status = ' . Import_Data_Controller::$IMPORT_RECORD_NONE . ' GROUP BY subject';
    if ($obj->batchImport) {
        $importBatchLimit = GlobalVariable::getVariable('Import_Batch_Limit', 100);
        $sql .= ' LIMIT ' . $importBatchLimit;
    }
    $result = $adb->query($sql);
    $numberOfRecords = $adb->num_rows($result);
    if ($numberOfRecords <= 0) {
        return;
    }
    $fieldMapping = $obj->fieldMapping;
    $fieldColumnMapping = $moduleMeta->getFieldColumnMapping();
    for ($i = 0; $i < $numberOfRecords; ++$i) {
        $row = $adb->raw_query_result_rowdata($result, $i);
        $rowId = $row['id'];
        $entityInfo = null;
        $fieldData = array();
        $lineItems = array();
        $subject = $row['subject'];
        $sql = 'SELECT * FROM ' . $tableName . ' WHERE status = ' . Import_Data_Controller::$IMPORT_RECORD_NONE . ' AND subject = "' . str_replace("\"", "\\\"", $subject) . '"';
        $subjectResult = $adb->query($sql);
        $count = $adb->num_rows($subjectResult);
        $subjectRowIDs = array();
        for ($j = 0; $j < $count; ++$j) {
            $subjectRow = $adb->raw_query_result_rowdata($subjectResult, $j);
            if ($subjectRow['productid'] == '' || $subjectRow['quantity'] == '' || $subjectRow['listprice'] == '') {
                continue;
            }
            array_push($subjectRowIDs, $subjectRow['id']);
            $lineItemData = array();
            $lineItemData['discount'] = 0;
            foreach ($fieldMapping as $fieldName => $index) {
                if ($moduleFields[$fieldName]->getTableName() == 'vtiger_inventoryproductrel') {
                    if ($fieldName == 'productid') {
                        $fieldValue = $subjectRow[$fieldName];
                        if (strpos($fieldValue, '::::') > 0) {
                            $fieldValueDetails = explode('::::', $fieldValue);
                        } else {
                            if (strpos($fieldValue, ':::') > 0) {
                                $fieldValueDetails = explode(':::', $fieldValue);
                            } else {
                                $fieldValueDetails = $fieldValue;
                            }
                        }
                        if (count($fieldValueDetails) > 1) {
                            $referenceModuleName = trim($fieldValueDetails[0]);
                            $entityLabel = trim($fieldValueDetails[1]);
                            $entityId = getEntityId($referenceModuleName, $entityLabel);
                        } else {
                            $referencedModules = array('Products', 'Services');
                            $entityLabel = $fieldValue;
                            foreach ($referencedModules as $referenceModule) {
                                $referenceModuleName = $referenceModule;
                                $referenceEntityId = getEntityId($referenceModule, $entityLabel);
                                if ($referenceEntityId != 0) {
                                    $entityId = $referenceEntityId;
                                    break;
                                }
                            }
                        }
                        if (empty($entityId) and in_array($referenceModuleName, array('Products', 'Services'))) {
                            $pdinfo = array();
                            if ($referenceModuleName == 'Services') {
                                $pdoinfo['servicename'] = $entityLabel;
                            } else {
                                $pdoinfo['productname'] = $entityLabel;
                            }
                            $pdoinfo['assigned_user_id'] = $usrwsid . $obj->user->id;
                            try {
                                $VTIGER_BULK_SAVE_MODE = false;
                                $psInfo = vtws_create($referenceModuleName, $pdoinfo, $obj->user);
                                $VTIGER_BULK_SAVE_MODE = true;
                                $entityId = $psInfo['id'];
                            } catch (Exception $e) {
                                continue 2;
                                // ignore this line
                            }
                        } else {
                            if ($referenceModuleName == 'Services') {
                                $entityId = $srvwsid . $entityId;
                            } else {
                                $entityId = $pdowsid . $entityId;
                            }
                        }
                        $lineItemData[$fieldName] = $entityId;
                    } else {
                        $lineItemData[$fieldName] = $subjectRow[$fieldName];
                        if ($fieldName == 'discount_amount' and $subjectRow[$fieldName] > 0) {
                            $lineItemData['discount'] = 1;
                            $lineItemData['discount_type'] = 'amount';
                        }
                        if ($fieldName == 'discount_percent' and $subjectRow[$fieldName] > 0) {
                            $lineItemData['discount'] = 1;
                            $lineItemData['discount_percentage'] = $subjectRow[$fieldName];
                            $lineItemData['discount_type'] = 'percentage';
                        }
                        if ($fieldName == 'quantity') {
                            $lineItemData['qty'] = $subjectRow[$fieldName];
                        }
                    }
                }
            }
            array_push($lineItems, $lineItemData);
        }
        foreach ($fieldMapping as $fieldName => $index) {
            $fieldData[$fieldName] = $row[strtolower($fieldName)];
            if ($fieldName == 'hdnTaxType') {
                $fieldData['taxtype'] = $row[strtolower($fieldName)];
            }
            if ($fieldName == 'txtAdjustment' and $fieldData[$fieldName] != 0) {
                $fieldData['adjustmentType'] = 'add';
                $fieldData['adjustment'] = $fieldData[$fieldName];
            }
        }
        if (!array_key_exists('assigned_user_id', $fieldData)) {
            $fieldData['assigned_user_id'] = $obj->user->id;
        }
        if (!empty($lineItems)) {
            if (method_exists($focus, 'importRecord')) {
                $entityInfo = $focus->importRecord($obj, $fieldData, $lineItems);
            }
        }
        if ($entityInfo == null) {
            $entityInfo = array('id' => null, 'status' => $obj->getImportRecordStatus('failed'));
        }
        foreach ($subjectRowIDs as $id) {
            $obj->importedRecordInfo[$id] = $entityInfo;
            $obj->updateImportStatus($id, $entityInfo);
        }
    }
    unset($result);
    return true;
}
Beispiel #25
0
 /** Function to retrive the information of the given recordid ,module
  * @param $record -- Id:: Type Integer
  * @param $module -- module:: Type varchar
  * This function retrives the information from the database and sets the value in the class columnfields array
  */
 function retrieve_entity_info($record, $module)
 {
     global $adb, $log, $app_strings;
     $result = array();
     foreach ($this->tab_name_index as $table_name => $index) {
         $result[$table_name] = $adb->pquery("select * from {$table_name} where {$index}=?", array($record));
         $isRecordDeleted = $adb->query_result($result["vtiger_crmentity"], 0, "deleted");
         if ($isRecordDeleted !== 0 && $isRecordDeleted !== '0') {
             die("<br><br><center>" . $app_strings['LBL_RECORD_DELETE'] . " {$module}: {$record} <a href='javascript:window.history.back()'>" . $app_strings['LBL_GO_BACK'] . ".</a></center>");
         }
     }
     /* Prasad: Fix for ticket #4595 */
     if (isset($this->table_name)) {
         $mod_index_col = $this->tab_name_index[$this->table_name];
         if ($adb->query_result($result[$this->table_name], 0, $mod_index_col) == '') {
             echo "<br><br><center>" . $app_strings['LBL_RECORD_NOT_FOUND'] . ". <a href='javascript:window.history.back()'>" . $app_strings['LBL_GO_BACK'] . ".</a></center>";
             if (GlobalVariable::getVariable('Debug_Record_Not_Found', false)) {
                 echo "<br><br><center>Looking for " . $this->table_name . '.' . $mod_index_col . ' in <br>' . print_r($result[$this->table_name]->sql, true) . '</center>';
                 echo "<pre>";
                 debug_print_backtrace();
                 echo "</pre>";
             }
             die;
         }
     }
     // Lookup in cache for information
     $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
     if ($cachedModuleFields === false) {
         $tabid = getTabid($module);
         // Let us pick up all the fields first so that we can cache information
         $sql1 = 'SELECT fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence FROM vtiger_field WHERE tabid=?';
         // NOTE: Need to skip in-active fields which we will be done later.
         $result1 = $adb->pquery($sql1, array($tabid));
         $noofrows = $adb->num_rows($result1);
         if ($noofrows) {
             while ($resultrow = $adb->fetch_array($result1)) {
                 // Update information to cache for re-use
                 VTCacheUtils::updateFieldInfo($tabid, $resultrow['fieldname'], $resultrow['fieldid'], $resultrow['fieldlabel'], $resultrow['columnname'], $resultrow['tablename'], $resultrow['uitype'], $resultrow['typeofdata'], $resultrow['presence']);
             }
         }
         // Get only active field information
         $cachedModuleFields = VTCacheUtils::lookupFieldInfo_Module($module);
     }
     if ($cachedModuleFields) {
         foreach ($cachedModuleFields as $fieldname => $fieldinfo) {
             $fieldcolname = $fieldinfo['columnname'];
             $tablename = $fieldinfo['tablename'];
             $fieldname = $fieldinfo['fieldname'];
             // To avoid ADODB execption pick the entries that are in $tablename
             // (ex. when we don't have attachment for troubletickets, $result[vtiger_attachments]
             // will not be set so here we should not retrieve)
             if (isset($result[$tablename])) {
                 $fld_value = $adb->query_result($result[$tablename], 0, $fieldcolname);
             } else {
                 $adb->println("There is no entry for this entity {$record} ({$module}) in the table {$tablename}");
                 $fld_value = "";
             }
             $this->column_fields[$fieldname] = $fld_value;
         }
     }
     if ($module == 'Users') {
         for ($i = 0; $i < $noofrows; $i++) {
             $fieldcolname = $adb->query_result($result1, $i, "columnname");
             $tablename = $adb->query_result($result1, $i, "tablename");
             $fieldname = $adb->query_result($result1, $i, "fieldname");
             $fld_value = $adb->query_result($result[$tablename], 0, $fieldcolname);
             $this->{$fieldname} = $fld_value;
         }
     }
     $this->column_fields["record_id"] = $record;
     $this->column_fields["record_module"] = $module;
 }
    }
} else {
    $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]);
}
//if create SO, get all available product taxes and shipping & Handling taxes
if ($focus->mode != 'edit') {
    $tax_details = getAllTaxes('available');
    $sh_tax_details = getAllTaxes('available', 'sh');
} else {
    $tax_details = getAllTaxes('available', '', $focus->mode, $focus->id);
    $sh_tax_details = getAllTaxes('available', 'sh', 'edit', $focus->id);
}
$smarty->assign('GROUP_TAXES', $tax_details);
$smarty->assign('SH_TAXES', $sh_tax_details);
$smarty->assign("CURRENCIES_LIST", getAllCurrencies());
if ($focus->mode == 'edit') {
    $inventory_cur_info = getInventoryCurrencyInfo('Issuecards', $focus->id);
    $smarty->assign("INV_CURRENCY_ID", $inventory_cur_info['currency_id']);
} else {
    $smarty->assign("INV_CURRENCY_ID", $currencyid);
}
$smarty->assign('CREATEMODE', vtlib_purify($_REQUEST['createmode']));
// Gather the help information associated with fields
$smarty->assign('FIELDHELPINFO', vtlib_getFieldHelpInfo($currentModule));
$picklistDependencyDatasource = Vtiger_DependencyPicklist::getPicklistDependencyDatasource($currentModule);
$smarty->assign("PICKIST_DEPENDENCY_DATASOURCE", Zend_Json::encode($picklistDependencyDatasource));
//Get Service or Product by default when create
$smarty->assign('PRODUCT_OR_SERVICE', GlobalVariable::getVariable('product_service_default', 'Products', $currentModule, $current_user->id));
//Set taxt type group or individual by default when create
$smarty->assign('TAX_TYPE', GlobalVariable::getVariable('Tax_Type_Default', 'individual', $currentModule, $current_user->id));
$smarty->display('Inventory/InventoryEditView.tpl');
Beispiel #27
0
/** This function returns a HTML output of associated vtiger_products for a given entity (Quotes,Invoice,Sales order or Purchase order)
 * Param $module - module name
 * Param $focus - module object
 * Return type string
 */
function getDetailAssociatedProducts($module, $focus)
{
    global $log;
    $log->debug("Entering getDetailAssociatedProducts(" . $module . "," . get_class($focus) . ") method ...");
    global $adb;
    global $mod_strings;
    global $theme;
    global $log;
    global $app_strings, $current_user;
    $theme_path = "themes/" . $theme . "/";
    $image_path = $theme_path . "images/";
    if (vtlib_isModuleActive("Products")) {
        $hide_stock = 'no';
    } else {
        $hide_stock = 'yes';
    }
    if ($module != 'PurchaseOrder') {
        if (GlobalVariable::getVariable('B2B', '1') == '1') {
            $acvid = $focus->column_fields['account_id'];
        } else {
            $acvid = $focus->column_fields['contact_id'];
        }
        if ($hide_stock == 'no') {
            $colspan = '2';
        } else {
            $colspan = '1';
        }
    } else {
        $acvid = $focus->column_fields['vendor_id'];
        $colspan = '1';
    }
    //Get the taxtype of this entity
    $taxtype = getInventoryTaxType($module, $focus->id);
    $currencytype = getInventoryCurrencyInfo($module, $focus->id);
    $output = '';
    //Header Rows
    $output .= '

	<table width="100%"  border="0" align="center" cellpadding="5" cellspacing="0" class="crmTable" id="proTab">
	   <tr valign="top">
	   	<td colspan="' . $colspan . '" class="dvInnerHeader"><b>' . $app_strings['LBL_ITEM_DETAILS'] . '</b></td>
		<td class="dvInnerHeader" align="center" colspan="2"><b>' . $app_strings['LBL_CURRENCY'] . ' : </b>' . getTranslatedCurrencyString($currencytype['currency_name']) . ' (' . $currencytype['currency_symbol'] . ')
		</td>
		<td class="dvInnerHeader" align="center" colspan="2"><b>' . $app_strings['LBL_TAX_MODE'] . ' : </b>' . $app_strings[$taxtype] . '
		</td>
	   </tr>
	   <tr valign="top">
		<td width=40% class="lvtCol"><font color="red">*</font>
			<b>' . $app_strings['LBL_ITEM_NAME'] . '</b>
		</td>';
    //Add Quantity in Stock column for SO, Quotes and Invoice
    if (($module == 'Quotes' || $module == 'SalesOrder' || $module == 'Invoice') && $hide_stock == 'no') {
        $output .= '<td width=10% class="lvtCol"><b>' . $app_strings['LBL_QTY_IN_STOCK'] . '</b></td>';
    }
    $output .= '

		<td width=10% class="lvtCol"><b>' . $app_strings['LBL_QTY'] . '</b></td>
		<td width=10% class="lvtCol" align="right"><b>' . $app_strings['LBL_LIST_PRICE'] . '</b></td>
		<td width=12% nowrap class="lvtCol" align="right"><b>' . $app_strings['LBL_TOTAL'] . '</b></td>
		<td width=13% valign="top" class="lvtCol" align="right"><b>' . $app_strings['LBL_NET_PRICE'] . '</b></td>
	   </tr>
	   	';
    // DG 15 Aug 2006
    // Add "ORDER BY sequence_no" to retain add order on all inventoryproductrel items
    if ($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') {
        $query = "select case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname," . " case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype," . " case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price," . " case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock, vtiger_inventoryproductrel.* " . " from vtiger_inventoryproductrel" . " left join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid " . " left join vtiger_service on vtiger_service.serviceid=vtiger_inventoryproductrel.productid " . " where id=? ORDER BY sequence_no";
    }
    $result = $adb->pquery($query, array($focus->id));
    $num_rows = $adb->num_rows($result);
    $netTotal = '0.00';
    for ($i = 1; $i <= $num_rows; $i++) {
        $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($focus->id, $i));
        $subprodname_str = '';
        if ($adb->num_rows($sub_prod_query) > 0) {
            for ($j = 0; $j < $adb->num_rows($sub_prod_query); $j++) {
                $sprod_id = $adb->query_result($sub_prod_query, $j, 'productid');
                $sprod_name = getProductName($sprod_id);
                $str_sep = "";
                if ($j > 0) {
                    $str_sep = ":";
                }
                $subprodname_str .= $str_sep . " - " . $sprod_name;
            }
        }
        $subprodname_str = str_replace(":", "<br>", $subprodname_str);
        $productid = $adb->query_result($result, $i - 1, 'productid');
        $entitytype = $adb->query_result($result, $i - 1, 'entitytype');
        $productname = $adb->query_result($result, $i - 1, 'productname');
        $productname = '<a href="index.php?action=DetailView&record=' . $productid . '&module=' . $entitytype . '">' . $productname . '</a>';
        if ($subprodname_str != '') {
            $productname .= "<br/><span style='color:#C0C0C0;font-style:italic;'>" . $subprodname_str . "</span>";
        }
        $comment = $adb->query_result($result, $i - 1, 'comment');
        $qtyinstock = $adb->query_result($result, $i - 1, 'qtyinstock');
        $qty = $adb->query_result($result, $i - 1, 'quantity');
        $qty = number_format($qty, 2, '.', '');
        //Convert to 2 decimals
        $unitprice = $adb->query_result($result, $i - 1, 'unit_price');
        $listprice = $adb->query_result($result, $i - 1, 'listprice');
        $total = $qty * $listprice;
        $listprice = number_format($listprice, 2, '.', '');
        //Convert to 2 decimals
        //Product wise Discount calculation - starts
        $discount_percent = $adb->query_result($result, $i - 1, 'discount_percent');
        $discount_amount = $adb->query_result($result, $i - 1, 'discount_amount');
        $totalAfterDiscount = $total;
        $productDiscount = '0.00';
        if ($discount_percent != 'NULL' && $discount_percent != '') {
            $productDiscount = $total * $discount_percent / 100;
            $productDiscount = number_format($productDiscount, 2, '.', '');
            $totalAfterDiscount = $total - $productDiscount;
            //if discount is percent then show the percentage
            $discount_info_message = "{$discount_percent} % of " . CurrencyField::convertToUserFormat($total, null, true) . " = " . CurrencyField::convertToUserFormat($productDiscount, null, true);
        } elseif ($discount_amount != 'NULL' && $discount_amount != '') {
            $productDiscount = $discount_amount;
            $productDiscount = number_format($productDiscount, 2, '.', '');
            $totalAfterDiscount = $total - $productDiscount;
            $discount_info_message = $app_strings['LBL_DIRECT_AMOUNT_DISCOUNT'] . " = " . CurrencyField::convertToUserFormat($productDiscount, null, true);
        } else {
            $discount_info_message = $app_strings['LBL_NO_DISCOUNT_FOR_THIS_LINE_ITEM'];
        }
        //Product wise Discount calculation - ends
        $totalAfterDiscount = number_format($totalAfterDiscount, 2, '.', '');
        //Convert to 2 decimals
        $netprice = $totalAfterDiscount;
        //Calculate the individual tax if taxtype is individual
        if ($taxtype == 'individual') {
            $taxtotal = '0.00';
            $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . " = " . CurrencyField::convertToUserFormat($totalAfterDiscount, null, true) . " \\n";
            $tax_details = getTaxDetailsForProduct($productid, 'all', $acvid);
            for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
                $tax_name = $tax_details[$tax_count]['taxname'];
                $tax_label = $tax_details[$tax_count]['taxlabel'];
                $tax_value = getInventoryProductTaxValue($focus->id, $productid, $tax_name);
                $individual_taxamount = $totalAfterDiscount * $tax_value / 100;
                $individual_taxamount = number_format($individual_taxamount, 2, '.', '');
                //Convert to 2 decimals
                $taxtotal = $taxtotal + $individual_taxamount;
                $taxtotal = number_format($taxtotal, 2, '.', '');
                //Convert to 2 decimals
                $tax_info_message .= "{$tax_label} : {$tax_value} % = " . CurrencyField::convertToUserFormat($individual_taxamount, null, true) . " \\n";
            }
            $tax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = " . CurrencyField::convertToUserFormat($taxtotal, null, true);
            $netprice = $netprice + $taxtotal;
            $netprice = number_format($netprice, 2, '.', '');
            //Convert to 2 decimals
        }
        $sc_image_tag = '';
        if ($module == 'Invoice') {
            switch ($entitytype) {
                case 'Services':
                    if (vtlib_isModuleActive('ServiceContracts')) {
                        $sc_image_tag = '<a href="index.php?module=ServiceContracts&action=EditView&service_id=' . $productid . '&sc_related_to=' . $focus->column_fields['account_id'] . '&start_date=' . DateTimeField::convertToUserFormat($focus->column_fields['invoicedate']) . '&return_module=' . $module . '&return_id=' . $focus->id . '">' . '<img border="0" src="' . vtiger_imageurl('handshake.gif', $theme) . '" title="' . getTranslatedString('LBL_ADD_NEW', $module) . " " . getTranslatedString('ServiceContracts', 'ServiceContracts') . '" style="cursor: pointer;" align="absmiddle" />' . '</a>';
                    }
                    break;
                case 'Products':
                    if (vtlib_isModuleActive('Assets')) {
                        $sc_image_tag = '<a href="index.php?module=Assets&action=EditView&invoiceid=' . $focus->id . '&product=' . $productid . '&account=' . $focus->column_fields['account_id'] . '&datesold=' . DateTimeField::convertToUserFormat($focus->column_fields['invoicedate']) . '&return_module=' . $module . '&return_id=' . $focus->id . '" onmouseout="vtlib_listview.trigger(\'invoiceasset.onmouseout\', $(this))" onmouseover="vtlib_listview.trigger(\'cell.onmouseover\', $(this))">' . '<img border="0" src="' . vtiger_imageurl('barcode.png', $theme) . '" title="' . getTranslatedString('LBL_ADD_NEW', $module) . " " . getTranslatedString('Assets', 'Assets') . '" style="cursor: pointer;" align="absmiddle" />' . '<span style="display:none;" vtmodule="Assets" vtfieldname="invoice_product" vtrecordid="' . $focus->id . '::' . $productid . '::' . $i . '" type="vtlib_metainfo"></span>' . '</a>';
                    }
                    break;
                default:
                    $sc_image_tag = '';
            }
        }
        //For Product Name
        $output .= '
			   <tr valign="top">
				<td class="crmTableRow small lineOnTop">
					' . $productname . '&nbsp;' . $sc_image_tag . '
					<br>' . $comment . '
				</td>';
        //Upto this added to display the Product name and comment
        if ($module != 'PurchaseOrder' && $hide_stock == 'no') {
            $output .= '<td class="crmTableRow small lineOnTop">' . $qtyinstock . '</td>';
        }
        $output .= '<td class="crmTableRow small lineOnTop">' . $qty . '</td>';
        $output .= '
			<td class="crmTableRow small lineOnTop" align="right">
				<table width="100%" border="0" cellpadding="5" cellspacing="0">
				   <tr>
				   	<td align="right">' . CurrencyField::convertToUserFormat($listprice, null, true) . '</td>
				   </tr>
				   <tr>
					   <td align="right">(-)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $discount_info_message . '\'); ">' . $app_strings['LBL_DISCOUNT'] . ' : </a></b></td>
				   </tr>
				   <tr>
				   	<td align="right" nowrap>' . $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . ' : </td>
				   </tr>';
        if ($taxtype == 'individual') {
            $output .= '
				   <tr>
					   <td align="right" nowrap>(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $tax_info_message . '\');">' . $app_strings['LBL_TAX'] . ' : </a></b></td>
				   </tr>';
        }
        $output .= '
				</table>
			</td>';
        $output .= '
			<td class="crmTableRow small lineOnTop" align="right">
				<table width="100%" border="0" cellpadding="5" cellspacing="0">
				   <tr><td align="right">' . CurrencyField::convertToUserFormat($total, null, true) . '</td></tr>
				   <tr><td align="right">' . CurrencyField::convertToUserFormat($productDiscount, null, true) . '</td></tr>
				   <tr><td align="right" nowrap>' . CurrencyField::convertToUserFormat($totalAfterDiscount, null, true) . '</td></tr>';
        if ($taxtype == 'individual') {
            $output .= '<tr><td align="right" nowrap>' . CurrencyField::convertToUserFormat($taxtotal, null, true) . '</td></tr>';
        }
        $output .= '
				</table>
			</td>';
        $output .= '<td class="crmTableRow small lineOnTop" valign="bottom" align="right">' . CurrencyField::convertToUserFormat($netprice, null, true) . '</td>';
        $output .= '</tr>';
        $netTotal = $netTotal + $netprice;
    }
    $output .= '</table>';
    //$netTotal should be equal to $focus->column_fields['hdnSubTotal']
    $netTotal = $focus->column_fields['hdnSubTotal'];
    $netTotal = number_format($netTotal, 2, '.', '');
    //Convert to 2 decimals
    //Display the total, adjustment, S&H details
    $output .= '<table width="100%" border="0" cellspacing="0" cellpadding="5" class="crmTable">';
    $output .= '<tr>';
    $output .= '<td width="88%" class="crmTableRow small" align="right"><b>' . $app_strings['LBL_NET_TOTAL'] . '</td>';
    $output .= '<td width="12%" class="crmTableRow small" align="right"><b>' . CurrencyField::convertToUserFormat($netTotal, null, true) . '</b></td>';
    $output .= '</tr>';
    //Decide discount
    $finalDiscount = '0.00';
    $final_discount_info = '0';
    //if($focus->column_fields['hdnDiscountPercent'] != '') - previously (before changing to prepared statement) the selected option (either percent or amount) will have value and the other remains empty. So we can find the non selected item by empty check. But now with prepared statement, the non selected option stored as 0
    if ($focus->column_fields['hdnDiscountPercent'] != '0') {
        $finalDiscount = $netTotal * $focus->column_fields['hdnDiscountPercent'] / 100;
        $finalDiscount = number_format($finalDiscount, 2, '.', '');
        $final_discount_info = $focus->column_fields['hdnDiscountPercent'] . " % of " . CurrencyField::convertToUserFormat($netTotal, null, true) . " = " . CurrencyField::convertToUserFormat($finalDiscount, null, true);
    } elseif ($focus->column_fields['hdnDiscountAmount'] != '0') {
        $finalDiscount = $focus->column_fields['hdnDiscountAmount'];
        $finalDiscount = number_format($finalDiscount, 2, '.', '');
        $final_discount_info = CurrencyField::convertToUserFormat($finalDiscount, null, true);
    }
    //Alert the Final Discount amount even it is zero
    $final_discount_info = $app_strings['LBL_FINAL_DISCOUNT_AMOUNT'] . " = {$final_discount_info}";
    $final_discount_info = 'onclick="alert(\'' . $final_discount_info . '\');"';
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">(-)&nbsp;<b><a href="javascript:;" ' . $final_discount_info . '>' . $app_strings['LBL_DISCOUNT'] . '</a></b></td>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">' . CurrencyField::convertToUserFormat($finalDiscount, null, true) . '</td>';
    $output .= '</tr>';
    if ($taxtype == 'group') {
        $taxtotal = '0.00';
        $final_totalAfterDiscount = $netTotal - $finalDiscount;
        $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . " = " . CurrencyField::convertToUserFormat($final_totalAfterDiscount, null, true) . " \\n";
        //First we should get all available taxes and then retrieve the corresponding tax values
        $tax_details = getAllTaxes('available', '', 'edit', $focus->id);
        $ipr_cols = $adb->getColumnNames('vtiger_inventoryproductrel');
        //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
        for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
            $tax_name = $tax_details[$tax_count]['taxname'];
            $tax_label = $tax_details[$tax_count]['taxlabel'];
            if (in_array($tax_name, $ipr_cols)) {
                $tax_value = $adb->query_result($result, 0, $tax_name);
            } else {
                $tax_value = $tax_details[$tax_count]['percentage'];
            }
            if ($tax_value == '' || $tax_value == 'NULL') {
                $tax_value = '0.00';
            }
            $taxamount = ($netTotal - $finalDiscount) * $tax_value / 100;
            $taxtotal = $taxtotal + $taxamount;
            $tax_info_message .= "{$tax_label} : {$tax_value} % = " . CurrencyField::convertToUserFormat($taxtotal, null, true) . " \\n";
        }
        $tax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = " . CurrencyField::convertToUserFormat($taxtotal, null, true);
        $output .= '<tr>';
        $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $tax_info_message . '\');">' . $app_strings['LBL_TAX'] . '</a></b></td>';
        $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($taxtotal, null, true) . '</td>';
        $output .= '</tr>';
    }
    $shAmount = $focus->column_fields['hdnS_H_Amount'] != '' ? $focus->column_fields['hdnS_H_Amount'] : '0.00';
    $shAmount = number_format($shAmount, 2, '.', '');
    //Convert to 2 decimals
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b>' . $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGES'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($shAmount, null, true) . '</td>';
    $output .= '</tr>';
    //calculate S&H tax
    $shtaxtotal = '0.00';
    //First we should get all available taxes and then retrieve the corresponding tax values
    $shtax_details = getAllTaxes('available', 'sh', 'edit', $focus->id);
    //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
    $shtax_info_message = $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGE'] . " = " . CurrencyField::convertToUserFormat($shAmount, null, true) . "\\n";
    for ($shtax_count = 0; $shtax_count < count($shtax_details); $shtax_count++) {
        $shtax_name = $shtax_details[$shtax_count]['taxname'];
        $shtax_label = $shtax_details[$shtax_count]['taxlabel'];
        $shtax_percent = getInventorySHTaxPercent($focus->id, $shtax_name);
        $shtaxamount = $shAmount * $shtax_percent / 100;
        $shtaxamount = number_format($shtaxamount, 2, '.', '');
        $shtaxtotal = $shtaxtotal + $shtaxamount;
        $shtax_info_message .= "{$shtax_label} : {$shtax_percent} % = " . CurrencyField::convertToUserFormat($shtaxamount, null, true) . " \\n";
    }
    $shtax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = " . CurrencyField::convertToUserFormat($shtaxtotal, null, true);
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $shtax_info_message . '\')">' . $app_strings['LBL_TAX_FOR_SHIPPING_AND_HANDLING'] . '</a></b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($shtaxtotal, null, true) . '</td>';
    $output .= '</tr>';
    $adjustment = $focus->column_fields['txtAdjustment'] != '' ? $focus->column_fields['txtAdjustment'] : '0.00';
    $adjustment = number_format($adjustment, 2, '.', '');
    //Convert to 2 decimals
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">&nbsp;<b>' . $app_strings['LBL_ADJUSTMENT'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($adjustment, null, true) . '</td>';
    $output .= '</tr>';
    $grandTotal = $focus->column_fields['hdnGrandTotal'] != '' ? $focus->column_fields['hdnGrandTotal'] : '0.00';
    $grandTotal = number_format($grandTotal, 2, '.', '');
    //Convert to 2 decimals
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop"><b>' . $app_strings['LBL_GRAND_TOTAL'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">' . CurrencyField::convertToUserFormat($grandTotal, null, true) . '</td>';
    $output .= '</tr>';
    $output .= '</table>';
    $log->debug("Exiting getDetailAssociatedProducts method ...");
    return $output;
}
Beispiel #28
0
    $tmp_file_name = $import_dir . "IMPORT_" . $focus->id;
    if (file_exists($tmp_file_name)) {
        unlink($tmp_file_name);
    }
    $arr = $_SESSION['lastpage'];
    if (isset($_SESSION['lastpage'])) {
        header("Location: index.php?" . $arr);
    } else {
        header("Location: index.php");
    }
} else {
    $sql = 'select failed_login_attempts from vtiger_users where user_name=?';
    $result = $adb->pquery($sql, array($focus->column_fields["user_name"]));
    $failed_login_attempts = 0;
    if ($result and $adb->num_rows($result) > 0) {
        $failed_login_attempts = $adb->query_result($result, 0, 0);
    }
    $maxFailedLoginAttempts = GlobalVariable::getVariable('Application_MaxFailedLoginAttempts', 5);
    // Increment number of failed login attempts
    $query = 'UPDATE vtiger_users SET failed_login_attempts=COALESCE(failed_login_attempts,0)+1 where user_name=?';
    $adb->pquery($query, array($focus->column_fields['user_name']));
    $_SESSION['login_user_name'] = $focus->column_fields["user_name"];
    $_SESSION['login_password'] = $user_password;
    if (empty($_SESSION['login_error'])) {
        $_SESSION['login_error'] = $failed_login_attempts >= $maxFailedLoginAttempts ? $mod_strings['ERR_MAXLOGINATTEMPTS'] : $mod_strings['ERR_INVALID_PASSWORD'];
    }
    cbEventHandler::do_action('corebos.audit.login.attempt', array(0, $focus->column_fields["user_name"], 'Login Attempt', 0, date('Y-m-d H:i:s')));
    // go back to the login screen.
    // create an error message for the user.
    header("Location: index.php");
}
Beispiel #29
0
    $tax_details = getAllTaxes('available');
    $sh_tax_details = getAllTaxes('available', 'sh');
} else {
    $tax_details = getAllTaxes('available', '', $focus->mode, $focus->id);
    $sh_tax_details = getAllTaxes('available', 'sh', 'edit', $focus->id);
}
$smarty->assign('GROUP_TAXES', $tax_details);
$smarty->assign('SH_TAXES', $sh_tax_details);
$smarty->assign("CURRENCIES_LIST", getAllCurrencies());
if ($focus->mode == 'edit') {
    $inventory_cur_info = getInventoryCurrencyInfo('PurchaseOrder', $focus->id);
    $smarty->assign("INV_CURRENCY_ID", $inventory_cur_info['currency_id']);
} else {
    $smarty->assign("INV_CURRENCY_ID", $currencyid);
}
$smarty->assign('CREATEMODE', vtlib_purify($_REQUEST['createmode']));
// Gather the help information associated with fields
$smarty->assign('FIELDHELPINFO', vtlib_getFieldHelpInfo($currentModule));
$picklistDependencyDatasource = Vtiger_DependencyPicklist::getPicklistDependencyDatasource($currentModule);
$smarty->assign("PICKIST_DEPENDENCY_DATASOURCE", Zend_Json::encode($picklistDependencyDatasource));
//Get Service or Product by default when create
$smarty->assign('PRODUCT_OR_SERVICE', GlobalVariable::getVariable('product_service_default', 'Products', $currentModule, $current_user->id));
//Set taxt type group or individual by default when create
$smarty->assign('TAX_TYPE', GlobalVariable::getVariable('Tax_Type_Default', 'individual', $currentModule, $current_user->id));
//Show or not the Header to copy address to left or right
$smarty->assign('SHOW_COPY_ADDRESS', GlobalVariable::getVariable('Show_Copy_Adress_Header', 'yes', $currentModule, $current_user->id));
if ($focus->mode == 'edit') {
    $smarty->display('Inventory/InventoryEditView.tpl');
} else {
    $smarty->display('Inventory/InventoryCreateView.tpl');
}
Beispiel #30
0
<?php

/*+**********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 ************************************************************************************/
global $app_strings, $mod_strings, $current_language, $currentModule, $current_user, $theme, $adb;
$selected_modules = array();
if (!empty($_SESSION['__UnifiedSearch_SelectedModules__']) && is_array($_SESSION['__UnifiedSearch_SelectedModules__'])) {
    $selected_modules = $_SESSION['__UnifiedSearch_SelectedModules__'];
} else {
    $appSearchModules = GlobalVariable::getVariable('Application_Global_Search_SelectedModules', '');
    if (!empty($appSearchModules)) {
        $selected_modules = explode(',', $appSearchModules);
        $_SESSION['__UnifiedSearch_SelectedModules__'] = $selected_modules;
    }
}
$allowed_modules = array();
$sql = 'select distinct vtiger_field.tabid,name from vtiger_field inner join vtiger_tab on vtiger_tab.tabid=vtiger_field.tabid where vtiger_tab.tabid not in (16,29) and vtiger_tab.presence != 1 and vtiger_field.presence in (0,2)';
$moduleres = $adb->query($sql);
while ($modulerow = $adb->fetch_array($moduleres)) {
    if (is_admin($current_user) || isPermitted($modulerow['name'], 'DetailView') == 'yes') {
        $modulename = $modulerow['name'];
        $allowed_modules[$modulename] = array('label' => getTranslatedString($modulename, $modulename), 'selected' => in_array($modulename, $selected_modules));
    }
}
uasort($allowed_modules, function ($a, $b) {