[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/modules/Invoice/ -> Invoice.php (source)

   1  <?php
   2  /*********************************************************************************
   3   * The contents of this file are subject to the SugarCRM Public License Version 1.1.2
   4   * ("License"); You may not use this file except in compliance with the
   5   * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
   6   * Software distributed under the License is distributed on an  "AS IS"  basis,
   7   * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
   8   * the specific language governing rights and limitations under the License.
   9   * The Original Code is:  SugarCRM Open Source
  10   * The Initial Developer of the Original Code is SugarCRM, Inc.
  11   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.;
  12   * All Rights Reserved.
  13   * Contributor(s): ______________________________________.
  14   ********************************************************************************/
  15  /*********************************************************************************
  16   * $Header$
  17   * Description:  Defines the Account SugarBean Account entity with the necessary
  18   * methods and variables.
  19   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  20   * All Rights Reserved.
  21   * Contributor(s): ______________________________________..
  22   ********************************************************************************/
  23  
  24  class Invoice extends CRMEntity {
  25      var $log;
  26      var $db;
  27  
  28      var $table_name = "vtiger_invoice";
  29      var $table_index= 'invoiceid';
  30      var $tab_name = Array('vtiger_crmentity','vtiger_invoice','vtiger_invoicebillads','vtiger_invoiceshipads','vtiger_invoicecf', 'vtiger_inventoryproductrel');
  31      var $tab_name_index = Array('vtiger_crmentity'=>'crmid','vtiger_invoice'=>'invoiceid','vtiger_invoicebillads'=>'invoicebilladdressid','vtiger_invoiceshipads'=>'invoiceshipaddressid','vtiger_invoicecf'=>'invoiceid','vtiger_inventoryproductrel'=>'id');
  32      /**
  33       * Mandatory table for supporting custom fields.
  34       */
  35      var $customFieldTable = Array('vtiger_invoicecf', 'invoiceid');
  36  
  37      var $column_fields = Array();
  38  
  39      var $update_product_array = Array();
  40  
  41      var $sortby_fields = Array('subject','invoice_no','invoicestatus','smownerid','accountname','lastname');
  42  
  43      // This is used to retrieve related vtiger_fields from form posts.
  44      var $additional_column_fields = Array('assigned_user_name', 'smownerid', 'opportunity_id', 'case_id', 'contact_id', 'task_id', 'note_id', 'meeting_id', 'call_id', 'email_id', 'parent_name', 'member_id' );
  45  
  46      // This is the list of vtiger_fields that are in the lists.
  47      var $list_fields = Array(
  48                  //'Invoice No'=>Array('crmentity'=>'crmid'),
  49                  'Invoice No'=>Array('invoice'=>'invoice_no'),
  50                  'Subject'=>Array('invoice'=>'subject'),
  51                  'Sales Order'=>Array('invoice'=>'salesorderid'),
  52                  'Status'=>Array('invoice'=>'invoicestatus'),
  53                  'Total'=>Array('invoice'=>'total'),
  54                  'Assigned To'=>Array('crmentity'=>'smownerid')
  55                  );
  56  
  57      var $list_fields_name = Array(
  58                          'Invoice No'=>'invoice_no',
  59                          'Subject'=>'subject',
  60                          'Sales Order'=>'salesorder_id',
  61                          'Status'=>'invoicestatus',
  62                          'Total'=>'hdnGrandTotal',
  63                          'Assigned To'=>'assigned_user_id'
  64                        );
  65      var $list_link_field= 'subject';
  66  
  67      var $search_fields = Array(
  68                  //'Invoice No'=>Array('crmentity'=>'crmid'),
  69                  'Invoice No'=>Array('invoice'=>'invoice_no'),
  70                  'Subject'=>Array('purchaseorder'=>'subject'),
  71                  'Account Name'=>Array('contactdetails'=>'account_id'),
  72                  'Created Date' => Array('crmentity'=>'createdtime'),
  73                  'Assigned To'=>Array('crmentity'=>'smownerid'),
  74                  );
  75  
  76      var $search_fields_name = Array(
  77                          'Invoice No'          => 'invoice_no',
  78                          'Subject'             => 'subject',
  79                          'Account Name'        => 'account_id',
  80                          'Created Time'        => 'createdtime',
  81                          'Assigned To'         => 'assigned_user_id'
  82                        );
  83  
  84      // This is the list of vtiger_fields that are required.
  85      var $required_fields =  array("accountname"=>1);
  86  
  87      //Added these variables which are used as default order by and sortorder in ListView
  88      var $default_order_by = 'crmid';
  89      var $default_sort_order = 'ASC';
  90  
  91      //var $groupTable = Array('vtiger_invoicegrouprelation','invoiceid');
  92  
  93      var $mandatory_fields = Array('subject','createdtime' ,'modifiedtime', 'assigned_user_id');
  94      var $_salesorderid;
  95      var $_recurring_mode;
  96  
  97      // For Alphabetical search
  98      var $def_basicsearch_col = 'subject';
  99  
 100      var $entity_table = "vtiger_crmentity";
 101  
 102      // For workflows update field tasks is deleted all the lineitems.
 103      var $isLineItemUpdate = true;
 104  
 105      /**    Constructor which will set the column_fields in this object
 106       */
 107  	function Invoice() {
 108          $this->log =LoggerManager::getLogger('Invoice');
 109          $this->log->debug("Entering Invoice() method ...");
 110          $this->db = PearDatabase::getInstance();
 111          $this->column_fields = getColumnFields('Invoice');
 112          $this->log->debug("Exiting Invoice method ...");
 113      }
 114  
 115  
 116      /** Function to handle the module specific save operations
 117  
 118      */
 119  
 120  	function save_module($module) {
 121          global $updateInventoryProductRel_deduct_stock;
 122          $updateInventoryProductRel_deduct_stock = true;
 123  
 124          //in ajax save we should not call this function, because this will delete all the existing product values
 125          if(isset($this->_recurring_mode) && $this->_recurring_mode == 'recurringinvoice_from_so' && isset($this->_salesorderid) && $this->_salesorderid!='') {
 126              // We are getting called from the RecurringInvoice cron service!
 127              $this->createRecurringInvoiceFromSO();
 128  
 129          } else if(isset($_REQUEST)) {
 130              if($_REQUEST['action'] != 'InvoiceAjax' && $_REQUEST['ajxaction'] != 'DETAILVIEW'
 131                      && $_REQUEST['action'] != 'MassEditSave' && $_REQUEST['action'] != 'ProcessDuplicates'
 132                      && $_REQUEST['action'] != 'SaveAjax' && $this->isLineItemUpdate != false && $_REQUEST['action'] != 'FROM_WS') {
 133                  //Based on the total Number of rows we will save the product relationship with this entity
 134                  saveInventoryProductDetails($this, 'Invoice');
 135              } else if($_REQUEST['action'] == 'InvoiceAjax' || $_REQUEST['action'] == 'MassEditSave' || $_REQUEST['action'] == 'FROM_WS') {
 136                  $updateInventoryProductRel_deduct_stock = false;
 137              }
 138          }
 139          // Update the currency id and the conversion rate for the invoice
 140          $update_query = "update vtiger_invoice set currency_id=?, conversion_rate=? where invoiceid=?";
 141  
 142          $update_params = array($this->column_fields['currency_id'], $this->column_fields['conversion_rate'], $this->id);
 143          $this->db->pquery($update_query, $update_params);
 144      }
 145  
 146      /**
 147       * Customizing the restore procedure.
 148       */
 149  	function restore($module, $id) {
 150          global $updateInventoryProductRel_deduct_stock;
 151          $status = getInvoiceStatus($id);
 152          if($status != 'Cancel') {
 153              $updateInventoryProductRel_deduct_stock = true;
 154          }
 155          parent::restore($module, $id);
 156      }
 157  
 158      /**
 159       * Customizing the Delete procedure.
 160       */
 161  	function trash($module, $recordId) {
 162          $status = getInvoiceStatus($recordId);
 163          if($status != 'Cancel') {
 164              addProductsToStock($recordId);
 165          }
 166          parent::trash($module, $recordId);
 167      }
 168  
 169      /**    function used to get the name of the current object
 170       *    @return string $this->name - name of the current object
 171       */
 172  	function get_summary_text()
 173      {
 174          global $log;
 175          $log->debug("Entering get_summary_text() method ...");
 176          $log->debug("Exiting get_summary_text method ...");
 177          return $this->name;
 178      }
 179  
 180  
 181      /**    function used to get the list of activities which are related to the invoice
 182       *    @param int $id - invoice id
 183       *    @return array - return an array which will be returned from the function GetRelatedList
 184       */
 185  	function get_activities($id, $cur_tab_id, $rel_tab_id, $actions=false) {
 186          global $log, $singlepane_view,$currentModule,$current_user;
 187          $log->debug("Entering get_activities(".$id.") method ...");
 188          $this_module = $currentModule;
 189  
 190          $related_module = vtlib_getModuleNameById($rel_tab_id);
 191          require_once("modules/$related_module/Activity.php");
 192          $other = new Activity();
 193          vtlib_setup_modulevars($related_module, $other);
 194          $singular_modname = vtlib_toSingular($related_module);
 195  
 196          $parenttab = getParentTab();
 197  
 198          if($singlepane_view == 'true')
 199              $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
 200          else
 201              $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;
 202  
 203          $button = '';
 204  
 205          $button .= '<input type="hidden" name="activity_mode">';
 206  
 207          if($actions) {
 208              if(is_string($actions)) $actions = explode(',', strtoupper($actions));
 209              if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
 210                  if(getFieldVisibilityPermission('Calendar',$current_user->id,'parent_id', 'readwrite') == '0') {
 211                      $button .= "<input title='".getTranslatedString('LBL_NEW'). " ". getTranslatedString('LBL_TODO', $related_module) ."' class='crmbutton small create'" .
 212                          " onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\";this.form.return_module.value=\"$this_module\";this.form.activity_mode.value=\"Task\";' type='submit' name='button'" .
 213                          " value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString('LBL_TODO', $related_module) ."'>&nbsp;";
 214                  }
 215              }
 216          }
 217  
 218          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>
 219                              'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 220          $query = "SELECT case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name,
 221                  vtiger_contactdetails.lastname, vtiger_contactdetails.firstname, vtiger_contactdetails.contactid,
 222                  vtiger_activity.*,vtiger_seactivityrel.crmid as parent_id,vtiger_crmentity.crmid, vtiger_crmentity.smownerid,
 223                  vtiger_crmentity.modifiedtime
 224                  from vtiger_activity
 225                  inner join vtiger_seactivityrel on vtiger_seactivityrel.activityid=vtiger_activity.activityid
 226                  inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid
 227                  left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid= vtiger_activity.activityid
 228                  left join vtiger_contactdetails on vtiger_contactdetails.contactid = vtiger_cntactivityrel.contactid
 229                  left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid
 230                  left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid
 231                  where vtiger_seactivityrel.crmid=".$id." and activitytype='Task' and vtiger_crmentity.deleted=0
 232                          and (vtiger_activity.status is not NULL and vtiger_activity.status != 'Completed')
 233                          and (vtiger_activity.status is not NULL and vtiger_activity.status != 'Deferred')";
 234  
 235          $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);
 236  
 237          if($return_value == null) $return_value = Array();
 238          $return_value['CUSTOM_BUTTON'] = $button;
 239  
 240          $log->debug("Exiting get_activities method ...");
 241          return $return_value;
 242      }
 243  
 244      /**    function used to get the the activity history related to the quote
 245       *    @param int $id - invoice id
 246       *    @return array - return an array which will be returned from the function GetHistory
 247       */
 248  	function get_history($id)
 249      {
 250          global $log;
 251          $log->debug("Entering get_history(".$id.") method ...");
 252          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>
 253                              'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 254          $query = "SELECT vtiger_contactdetails.lastname, vtiger_contactdetails.firstname,
 255                  vtiger_contactdetails.contactid,vtiger_activity.*,vtiger_seactivityrel.*,
 256                  vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_crmentity.modifiedtime,
 257                  vtiger_crmentity.createdtime, vtiger_crmentity.description,
 258                  case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name
 259                  from vtiger_activity
 260                  inner join vtiger_seactivityrel on vtiger_seactivityrel.activityid=vtiger_activity.activityid
 261                  inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid
 262                  left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid= vtiger_activity.activityid
 263                  left join vtiger_contactdetails on vtiger_contactdetails.contactid = vtiger_cntactivityrel.contactid
 264                  left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid
 265                  left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid
 266                  where vtiger_activity.activitytype='Task'
 267                      and (vtiger_activity.status = 'Completed' or vtiger_activity.status = 'Deferred')
 268                      and vtiger_seactivityrel.crmid=".$id."
 269                      and vtiger_crmentity.deleted = 0";
 270          //Don't add order by, because, for security, one more condition will be added with this query in include/RelatedListView.php
 271  
 272          $log->debug("Exiting get_history method ...");
 273          return getHistory('Invoice',$query,$id);
 274      }
 275  
 276  
 277  
 278      /**    Function used to get the Status history of the Invoice
 279       *    @param $id - invoice id
 280       *    @return $return_data - array with header and the entries in format Array('header'=>$header,'entries'=>$entries_list) where as $header and $entries_list are arrays which contains header values and all column values of all entries
 281       */
 282  	function get_invoicestatushistory($id)
 283      {
 284          global $log;
 285          $log->debug("Entering get_invoicestatushistory(".$id.") method ...");
 286  
 287          global $adb;
 288          global $mod_strings;
 289          global $app_strings;
 290  
 291          $query = 'select vtiger_invoicestatushistory.*, vtiger_invoice.invoice_no from vtiger_invoicestatushistory inner join vtiger_invoice on vtiger_invoice.invoiceid = vtiger_invoicestatushistory.invoiceid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_invoice.invoiceid where vtiger_crmentity.deleted = 0 and vtiger_invoice.invoiceid = ?';
 292          $result=$adb->pquery($query, array($id));
 293          $noofrows = $adb->num_rows($result);
 294  
 295          $header[] = $app_strings['Invoice No'];
 296          $header[] = $app_strings['LBL_ACCOUNT_NAME'];
 297          $header[] = $app_strings['LBL_AMOUNT'];
 298          $header[] = $app_strings['LBL_INVOICE_STATUS'];
 299          $header[] = $app_strings['LBL_LAST_MODIFIED'];
 300  
 301          //Getting the field permission for the current user. 1 - Not Accessible, 0 - Accessible
 302          //Account Name , Amount are mandatory fields. So no need to do security check to these fields.
 303          global $current_user;
 304  
 305          //If field is accessible then getFieldVisibilityPermission function will return 0 else return 1
 306          $invoicestatus_access = (getFieldVisibilityPermission('Invoice', $current_user->id, 'invoicestatus') != '0')? 1 : 0;
 307          $picklistarray = getAccessPickListValues('Invoice');
 308  
 309          $invoicestatus_array = ($invoicestatus_access != 1)? $picklistarray['invoicestatus']: array();
 310          //- ==> picklist field is not permitted in profile
 311          //Not Accessible - picklist is permitted in profile but picklist value is not permitted
 312          $error_msg = ($invoicestatus_access != 1)? 'Not Accessible': '-';
 313  
 314          while($row = $adb->fetch_array($result))
 315          {
 316              $entries = Array();
 317  
 318              // Module Sequence Numbering
 319              //$entries[] = $row['invoiceid'];
 320              $entries[] = $row['invoice_no'];
 321              // END
 322              $entries[] = $row['accountname'];
 323              $entries[] = $row['total'];
 324              $entries[] = (in_array($row['invoicestatus'], $invoicestatus_array))? $row['invoicestatus']: $error_msg;
 325              $entries[] = DateTimeField::convertToUserFormat($row['lastmodified']);
 326  
 327              $entries_list[] = $entries;
 328          }
 329  
 330          $return_data = Array('header'=>$header,'entries'=>$entries_list);
 331  
 332           $log->debug("Exiting get_invoicestatushistory method ...");
 333  
 334          return $return_data;
 335      }
 336  
 337      // Function to get column name - Overriding function of base class
 338  	function get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype = '') {
 339          if ($columname == 'salesorderid') {
 340              if ($fldvalue == '') return null;
 341          }
 342          return parent::get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype);
 343      }
 344  
 345      /*
 346       * Function to get the secondary query part of a report
 347       * @param - $module primary module name
 348       * @param - $secmodule secondary module name
 349       * returns the query string formed on fetching the related data for report for secondary module
 350       */
 351  	function generateReportsSecQuery($module,$secmodule,$queryPlanner){
 352  
 353          // Define the dependency matrix ahead
 354          $matrix = $queryPlanner->newDependencyMatrix();
 355          $matrix->setDependency('vtiger_crmentityInvoice', array('vtiger_usersInvoice', 'vtiger_groupsInvoice', 'vtiger_lastModifiedByInvoice'));
 356          $matrix->setDependency('vtiger_inventoryproductrelInvoice', array('vtiger_productsInvoice', 'vtiger_serviceInvoice'));
 357          $matrix->setDependency('vtiger_invoice',array('vtiger_crmentityInvoice', "vtiger_currency_info$secmodule",
 358                  'vtiger_invoicecf', 'vtiger_salesorderInvoice', 'vtiger_invoicebillads',
 359                  'vtiger_invoiceshipads', 'vtiger_inventoryproductrelInvoice', 'vtiger_contactdetailsInvoice', 'vtiger_accountInvoice'));
 360  
 361          if (!$queryPlanner->requireTable('vtiger_invoice', $matrix)) {
 362              return '';
 363          }
 364  
 365          $query = $this->getRelationQuery($module,$secmodule,"vtiger_invoice","invoiceid", $queryPlanner);
 366  
 367          if ($queryPlanner->requireTable('vtiger_crmentityInvoice', $matrix)) {
 368              $query .= " left join vtiger_crmentity as vtiger_crmentityInvoice on vtiger_crmentityInvoice.crmid=vtiger_invoice.invoiceid and vtiger_crmentityInvoice.deleted=0";
 369          }
 370          if ($queryPlanner->requireTable('vtiger_invoicecf')) {
 371              $query .= " left join vtiger_invoicecf on vtiger_invoice.invoiceid = vtiger_invoicecf.invoiceid";
 372          }
 373          if ($queryPlanner->requireTable("vtiger_currency_info$secmodule")) {
 374              $query .= " left join vtiger_currency_info as vtiger_currency_info$secmodule on vtiger_currency_info$secmodule.id = vtiger_invoice.currency_id";
 375          }
 376          if ($queryPlanner->requireTable('vtiger_salesorderInvoice')) {
 377              $query .= " left join vtiger_salesorder as vtiger_salesorderInvoice on vtiger_salesorderInvoice.salesorderid=vtiger_invoice.salesorderid";
 378          }
 379          if ($queryPlanner->requireTable('vtiger_invoicebillads')) {
 380              $query .= " left join vtiger_invoicebillads on vtiger_invoice.invoiceid=vtiger_invoicebillads.invoicebilladdressid";
 381          }
 382          if ($queryPlanner->requireTable('vtiger_invoiceshipads')) {
 383              $query .= " left join vtiger_invoiceshipads on vtiger_invoice.invoiceid=vtiger_invoiceshipads.invoiceshipaddressid";
 384          }
 385          if ($queryPlanner->requireTable('vtiger_inventoryproductrelInvoice', $matrix)) {
 386              $query .= " left join vtiger_inventoryproductrel as vtiger_inventoryproductrelInvoice on vtiger_invoice.invoiceid = vtiger_inventoryproductrelInvoice.id";
 387              // To Eliminate duplicates in reports
 388              if(($module == 'Products' || $module == 'Services') && $secmodule == "Invoice"){
 389                  if($module == 'Products'){
 390                      $query .= " and vtiger_inventoryproductrelInvoice.productid = vtiger_products.productid ";    
 391                  }else if($module == 'Services'){
 392                      $query .= " and vtiger_inventoryproductrelInvoice.productid = vtiger_service.serviceid "; 
 393                  }
 394              }
 395          }
 396          if ($queryPlanner->requireTable('vtiger_productsInvoice')) {
 397              $query .= " left join vtiger_products as vtiger_productsInvoice on vtiger_productsInvoice.productid = vtiger_inventoryproductrelInvoice.productid";
 398          }
 399          if ($queryPlanner->requireTable('vtiger_serviceInvoice')) {
 400              $query .= " left join vtiger_service as vtiger_serviceInvoice on vtiger_serviceInvoice.serviceid = vtiger_inventoryproductrelInvoice.productid";
 401          }
 402          if ($queryPlanner->requireTable('vtiger_groupsInvoice')) {
 403              $query .= " left join vtiger_groups as vtiger_groupsInvoice on vtiger_groupsInvoice.groupid = vtiger_crmentityInvoice.smownerid";
 404          }
 405          if ($queryPlanner->requireTable('vtiger_usersInvoice')) {
 406              $query .= " left join vtiger_users as vtiger_usersInvoice on vtiger_usersInvoice.id = vtiger_crmentityInvoice.smownerid";
 407          }
 408          if ($queryPlanner->requireTable('vtiger_contactdetailsInvoice')) {
 409              $query .= " left join vtiger_contactdetails as vtiger_contactdetailsInvoice on vtiger_invoice.contactid = vtiger_contactdetailsInvoice.contactid";
 410          }
 411          if ($queryPlanner->requireTable('vtiger_accountInvoice')) {
 412              $query .= " left join vtiger_account as vtiger_accountInvoice on vtiger_accountInvoice.accountid = vtiger_invoice.accountid";
 413          }
 414          if ($queryPlanner->requireTable('vtiger_lastModifiedByInvoice')) {
 415              $query .= " left join vtiger_users as vtiger_lastModifiedByInvoice on vtiger_lastModifiedByInvoice.id = vtiger_crmentityInvoice.modifiedby ";
 416          }
 417          if ($queryPlanner->requireTable("vtiger_createdbyInvoice")){
 418              $query .= " left join vtiger_users as vtiger_createdbyInvoice on vtiger_createdbyInvoice.id = vtiger_crmentityInvoice.smcreatorid ";
 419          }
 420          return $query;
 421      }
 422  
 423      /*
 424       * Function to get the relation tables for related modules
 425       * @param - $secmodule secondary module name
 426       * returns the array with table names and fieldnames storing relations between module and this module
 427       */
 428  	function setRelationTables($secmodule){
 429          $rel_tables = array (
 430              "Calendar" =>array("vtiger_seactivityrel"=>array("crmid","activityid"),"vtiger_invoice"=>"invoiceid"),
 431              "Documents" => array("vtiger_senotesrel"=>array("crmid","notesid"),"vtiger_invoice"=>"invoiceid"),
 432              "Accounts" => array("vtiger_invoice"=>array("invoiceid","accountid")),
 433          );
 434          return $rel_tables[$secmodule];
 435      }
 436  
 437      // Function to unlink an entity with given Id from another entity
 438  	function unlinkRelationship($id, $return_module, $return_id) {
 439          global $log;
 440          if(empty($return_module) || empty($return_id)) return;
 441  
 442          if($return_module == 'Accounts' || $return_module == 'Contacts') {
 443              $this->trash('Invoice',$id);
 444          } elseif($return_module=='SalesOrder') {
 445              $relation_query = 'UPDATE vtiger_invoice set salesorderid=? where invoiceid=?';
 446              $this->db->pquery($relation_query, array(null,$id));
 447          } else {
 448              $sql = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)';
 449              $params = array($id, $return_module, $return_id, $id, $return_module, $return_id);
 450              $this->db->pquery($sql, $params);
 451          }
 452      }
 453  
 454      /*
 455       * Function to get the relations of salesorder to invoice for recurring invoice procedure
 456       * @param - $salesorder_id Salesorder ID
 457       */
 458  	function createRecurringInvoiceFromSO(){
 459          global $adb;
 460          $salesorder_id = $this->_salesorderid;
 461          $query1 = "SELECT * FROM vtiger_inventoryproductrel WHERE id=?";
 462          $res = $adb->pquery($query1, array($salesorder_id));
 463          $no_of_products = $adb->num_rows($res);
 464          $fieldsList = $adb->getFieldsArray($res);
 465          $update_stock = array();
 466          for($j=0; $j<$no_of_products; $j++) {
 467              $row = $adb->query_result_rowdata($res, $j);
 468              $col_value = array();
 469              for($k=0; $k<count($fieldsList); $k++) {
 470                  if($fieldsList[$k]!='lineitem_id'){
 471                      $col_value[$fieldsList[$k]] = $row[$fieldsList[$k]];
 472                  }
 473              }
 474              if(count($col_value) > 0) {
 475                  $col_value['id'] = $this->id;
 476                  $columns = array_keys($col_value);
 477                  $values = array_values($col_value);
 478                  $query2 = "INSERT INTO vtiger_inventoryproductrel(". implode(",",$columns) .") VALUES (". generateQuestionMarks($values) .")";
 479                  $adb->pquery($query2, array($values));
 480                  $prod_id = $col_value['productid'];
 481                  $qty = $col_value['quantity'];
 482                  $update_stock[$col_value['sequence_no']] = $qty;
 483                  updateStk($prod_id,$qty,'',array(),'Invoice');
 484              }
 485          }
 486  
 487          $query1 = "SELECT * FROM vtiger_inventorysubproductrel WHERE id=?";
 488          $res = $adb->pquery($query1, array($salesorder_id));
 489          $no_of_products = $adb->num_rows($res);
 490          $fieldsList = $adb->getFieldsArray($res);
 491          for($j=0; $j<$no_of_products; $j++) {
 492              $row = $adb->query_result_rowdata($res, $j);
 493              $col_value = array();
 494              for($k=0; $k<count($fieldsList); $k++) {
 495                      $col_value[$fieldsList[$k]] = $row[$fieldsList[$k]];
 496              }
 497              if(count($col_value) > 0) {
 498                  $col_value['id'] = $this->id;
 499                  $columns = array_keys($col_value);
 500                  $values = array_values($col_value);
 501                  $query2 = "INSERT INTO vtiger_inventorysubproductrel(". implode(",",$columns) .") VALUES (". generateQuestionMarks($values) .")";
 502                  $adb->pquery($query2, array($values));
 503                  $prod_id = $col_value['productid'];
 504                  $qty = $update_stock[$col_value['sequence_no']];
 505                  updateStk($prod_id,$qty,'',array(),'Invoice');
 506              }
 507          }
 508  
 509          // Add the Shipping taxes for the Invoice
 510          $query3 = "SELECT * FROM vtiger_inventoryshippingrel WHERE id=?";
 511          $res = $adb->pquery($query3, array($salesorder_id));
 512          $no_of_shippingtax = $adb->num_rows($res);
 513          $fieldsList = $adb->getFieldsArray($res);
 514          for($j=0; $j<$no_of_shippingtax; $j++) {
 515              $row = $adb->query_result_rowdata($res, $j);
 516              $col_value = array();
 517              for($k=0; $k<count($fieldsList); $k++) {
 518                  $col_value[$fieldsList[$k]] = $row[$fieldsList[$k]];
 519              }
 520              if(count($col_value) > 0) {
 521                  $col_value['id'] = $this->id;
 522                  $columns = array_keys($col_value);
 523                  $values = array_values($col_value);
 524                  $query4 = "INSERT INTO vtiger_inventoryshippingrel(". implode(",",$columns) .") VALUES (". generateQuestionMarks($values) .")";
 525                  $adb->pquery($query4, array($values));
 526              }
 527          }
 528  
 529          //Update the netprice (subtotal), taxtype, discount, S&H charge, adjustment and total for the Invoice
 530  
 531          $updatequery  = " UPDATE vtiger_invoice SET ";
 532          $updateparams = array();
 533          // Remaining column values to be updated -> column name to field name mapping
 534          $invoice_column_field = Array (
 535              'adjustment' => 'txtAdjustment',
 536              'subtotal' => 'hdnSubTotal',
 537              'total' => 'hdnGrandTotal',
 538              'taxtype' => 'hdnTaxType',
 539              'discount_percent' => 'hdnDiscountPercent',
 540              'discount_amount' => 'hdnDiscountAmount',
 541              's_h_amount' => 'hdnS_H_Amount',
 542          );
 543          $updatecols = array();
 544          foreach($invoice_column_field as $col => $field) {
 545              $updatecols[] = "$col=?";
 546              $updateparams[] = $this->column_fields[$field];
 547          }
 548          if (count($updatecols) > 0) {
 549              $updatequery .= implode(",", $updatecols);
 550  
 551              $updatequery .= " WHERE invoiceid=?";
 552              array_push($updateparams, $this->id);
 553  
 554              $adb->pquery($updatequery, $updateparams);
 555          }
 556      }
 557  
 558  	function insertIntoEntityTable($table_name, $module, $fileid = '')  {
 559          //Ignore relation table insertions while saving of the record
 560          if($table_name == 'vtiger_inventoryproductrel') {
 561              return;
 562          }
 563          parent::insertIntoEntityTable($table_name, $module, $fileid);
 564      }
 565  
 566      /*Function to create records in current module.
 567      **This function called while importing records to this module*/
 568  	function createRecords($obj) {
 569          $createRecords = createRecords($obj);
 570          return $createRecords;
 571      }
 572  
 573      /*Function returns the record information which means whether the record is imported or not
 574      **This function called while importing records to this module*/
 575  	function importRecord($obj, $inventoryFieldData, $lineItemDetails) {
 576          $entityInfo = importRecord($obj, $inventoryFieldData, $lineItemDetails);
 577          return $entityInfo;
 578      }
 579  
 580      /*Function to return the status count of imported records in current module.
 581      **This function called while importing records to this module*/
 582  	function getImportStatusCount($obj) {
 583          $statusCount = getImportStatusCount($obj);
 584          return $statusCount;
 585      }
 586  
 587  	function undoLastImport($obj, $user) {
 588          $undoLastImport = undoLastImport($obj, $user);
 589      }
 590  
 591      /** Function to export the lead records in CSV Format
 592      * @param reference variable - where condition is passed when the query is executed
 593      * Returns Export Invoice Query.
 594      */
 595  	function create_export_query($where)
 596      {
 597          global $log;
 598          global $current_user;
 599          $log->debug("Entering create_export_query(".$where.") method ...");
 600  
 601          include ("include/utils/ExportUtils.php");
 602  
 603          //To get the Permitted fields query and the permitted fields list
 604          $sql = getPermittedFieldsQuery("Invoice", "detail_view");
 605          $fields_list = getFieldsListFromQuery($sql);
 606          $fields_list .= getInventoryFieldsForExport($this->table_name);
 607          $userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
 608  
 609          $query = "SELECT $fields_list FROM ".$this->entity_table."
 610                  INNER JOIN vtiger_invoice ON vtiger_invoice.invoiceid = vtiger_crmentity.crmid
 611                  LEFT JOIN vtiger_invoicecf ON vtiger_invoicecf.invoiceid = vtiger_invoice.invoiceid
 612                  LEFT JOIN vtiger_salesorder ON vtiger_salesorder.salesorderid = vtiger_invoice.salesorderid
 613                  LEFT JOIN vtiger_invoicebillads ON vtiger_invoicebillads.invoicebilladdressid = vtiger_invoice.invoiceid
 614                  LEFT JOIN vtiger_invoiceshipads ON vtiger_invoiceshipads.invoiceshipaddressid = vtiger_invoice.invoiceid
 615                  LEFT JOIN vtiger_inventoryproductrel ON vtiger_inventoryproductrel.id = vtiger_invoice.invoiceid
 616                  LEFT JOIN vtiger_products ON vtiger_products.productid = vtiger_inventoryproductrel.productid
 617                  LEFT JOIN vtiger_service ON vtiger_service.serviceid = vtiger_inventoryproductrel.productid
 618                  LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_invoice.contactid
 619                  LEFT JOIN vtiger_account ON vtiger_account.accountid = vtiger_invoice.accountid
 620                  LEFT JOIN vtiger_currency_info ON vtiger_currency_info.id = vtiger_invoice.currency_id
 621                  LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
 622                  LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid";
 623  
 624          $query .= $this->getNonAdminAccessControlQuery('Invoice',$current_user);
 625          $where_auto = " vtiger_crmentity.deleted=0";
 626  
 627          if($where != "") {
 628              $query .= " where ($where) AND ".$where_auto;
 629          } else {
 630              $query .= " where ".$where_auto;
 631          }
 632  
 633          $log->debug("Exiting create_export_query method ...");
 634          return $query;
 635      }
 636  
 637  }
 638  
 639  ?>


Generated: Fri Nov 28 20:08:37 2014 Cross-referenced by PHPXref 0.7.1