Files
crm.twinpol.com/modules/EcmProducts/EcmProduct.php

1161 lines
44 KiB
PHP
Raw Normal View History

2025-05-12 15:44:39 +00:00
<?php
if (!defined('sugarEntry') || !sugarEntry)
die('Not A Valid Entry Point');
/* * ***************************************************************************
* The contents of this file are subject to the RECIPROCAL PUBLIC LICENSE
* Version 1.1 ("License"); You may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/rpl.php. Software distributed under the
* License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
* either express or implied.
*
* You may:
* a) Use and distribute this code exactly as you received without payment or
* a royalty or other fee.
* b) Create extensions for this code, provided that you make the extensions
* publicly available and document your modifications clearly.
* c) Charge for a fee for warranty or support or for accepting liability
* obligations for your customers.
*
* You may NOT:
* a) Charge for the use of the original code or extensions, including in
* electronic distribution models, such as ASP (Application Service
* Provider).
* b) Charge for the original source code or your extensions other than a
* nominal fee to cover distribution costs where such distribution
* involves PHYSICAL media.
* c) Modify or delete any pre-existing copyright notices, change notices,
* or License text in the Licensed Software
* d) Assert any patent claims against the Licensor or Contributors, or
* which would in any way restrict the ability of any third party to use the
* Licensed Software.
*
* You must:
* a) Document any modifications you make to this code including the nature of
* the change, the authors of the change, and the date of the change.
* b) Make the source code for any extensions you deploy available via an
* Electronic Distribution Mechanism such as FTP or HTTP download.
* c) Notify the licensor of the availability of source code to your extensions
* and include instructions on how to acquire the source code and updates.
* d) Grant Licensor a world-wide, non-exclusive, royalty-free license to use,
* reproduce, perform, modify, sublicense, and distribute your extensions.
*
* The Original Code is: CommuniCore
* Olavo Farias
* 2006-04-7 olavo.farias@gmail.com
*
* The Initial Developer of the Original Code is CommuniCore.
* Portions created by CommuniCore are Copyright (C) 2005 CommuniCore Ltda
* All Rights Reserved.
* ****************************************************************************** */
require_once('data/SugarBean.php');
require_once('include/utils.php');
include_once("modules/EcmStockOperations/EcmStockOperation.php");
include_once("modules/EcmPaymentStates/helper.php");
// SHOULD INCLUDE SELECTIVELY
class EcmProduct extends SugarBean {
var $field_name_map = array();
// STANDARD FIELDS
var $id;
var $date_entered;
var $date_modified;
var $modified_user_id;
var $assigned_user_id;
var $name;
//TABLE COLUMNS
var $code;
var $product_category_id;
var $product_category_name;
var $product_subcategory_id;
var $product_subcategory_name;
var $product_line_id;
var $product_line_name;
var $manufacturer_id;
var $manufacturer_name;
var $contact_id;
var $contact_name;
var $vendor_id;
var $vendor_name;
var $vendor_part_no;
var $product_active;
var $flag;
var $sales_start_date;
var $sales_end_date;
var $parent_type;
var $parent_id;
var $parent_name;
var $website;
var $part_no;
var $serial_no;
var $exchange_rate_id;
var $exchange_rate_name;
var $fob_price;
var $purchase_price;
var $ems_price;
var $commission_rate;
var $custom_duty_rate;
var $srp_price;
var $srp_price_eur;
var $srp_promo_price;
var $tax_class_id;
var $tax_class_name;
var $usage_unit_id;
var $usage_unit_name;
var $qty_in_stock;
var $qty_in_demand;
var $ems_qty_in_stock;
var $reorder_level;
var $sales_last_month_1;
var $sales_last_month;
var $sales_this_month;
var $qty_per_unit;
var $average_sale_3_months;
var $sales_plus_1;
var $sales_plus_2;
var $sales_plus_3;
var $product_picture;
var $packing_front_picture;
var $driver_1;
var $driver_2;
var $moq;
var $fob_basis_id;
var $fob_basis_name;
var $delivery_time_fob;
var $pieces_per_carton;
var $product_netto_weight;
var $product_brutto_weight;
var $packing_type_id;
var $packing_type_name;
var $packing_dimensions_1;
var $packing_dimensions_2;
var $packing_dimensions_3;
var $rma;
var $carton_dimensions_1;
var $carton_dimensions_2;
var $carton_dimensions_3;
var $carton_netto_weight;
var $carton_brutto_weight;
var $carton_volume_meter;
var $carton_volume_feet;
var $country_of_origin;
var $certificate_of_origin;
var $form_a;
var $vat_id;
var $vat_name;
var $vat_value;
var $selling_price;
var $ems_ordered;
var $graduated_prices;
var $unit_id;
var $ordered;
var $lead_time;
var $production;
var $description_card;
var $characteristic_card;
var $specification_card;
var $used_to_card;
var $image_card;
var $end_of_line;
var $status;
var $add_status;
var $models;
var $position_list;
var $th;
var $ean;
// RELATED FIELDS
var $created_by;
var $created_by_name;
var $modified_by_name;
var $assigned_user_name;
// SUBPANELS RELATED
// MODULE OBJECT DETAILS
var $module_dir = 'EcmProducts';
var $table_name = "ecmproducts";
var $object_name = "EcmProduct";
//RELATED TABLE NAMES
// USED TO RETRIEVE RELATED FIELDS FROM FORM POSTS.
var $additional_column_fields = Array(
'assigned_user_name',
'assigned_user_id',
'modified_user_id',
'created_by',
);
var $relationship_fields = Array(
//RELATIONSHIP FIELDS
);
function EcmProduct() {
parent::SugarBean();
$this->setupCustomFields('EcmProducts');
foreach ($this->field_defs as $field) {
$this->field_name_map[$field['name']] = $field;
}
}
var $new_schema = true;
function get_summary_text() {
return "$this->name";
}
function create_list_query($order_by, $where, $show_deleted = 0) {
// Fill in the assigned_user_name
$custom_join = $this->custom_fields->getJOIN();
$query = "SELECT ";
$query .= "
ecmproducts.*
,users.user_name as assigned_user_name";
if ($custom_join) {
$query .= $custom_join['select'];
}
$query .= " FROM ecmproducts
LEFT JOIN users
ON ecmproducts.assigned_user_id=users.id";
$query .= " ";
if ($custom_join) {
$query .= $custom_join['join'];
}
$where_auto = '1=1';
if ($show_deleted == 0) {
$where_auto = " $this->table_name.deleted=0 ";
} else if ($show_deleted == 1) {
$where_auto = " $this->table_name.deleted=1 ";
}
if ($where != "")
$query .= "where $where AND " . $where_auto;
else
$query .= "where " . $where_auto;
if (substr_count($order_by, '.') > 0) {
$query .= " ORDER BY $order_by";
} else if ($order_by != "")
$query .= " ORDER BY $order_by";
else
$query .= " ORDER BY ecmproducts.name";
return $query;
}
function create_export_query($order_by, $where) {
$custom_join = $this->custom_fields->getJOIN();
$query = "SELECT
ecmproducts.*,
users.user_name assigned_user_name";
if ($custom_join) {
$query .= $custom_join['select'];
}
$query .= " FROM ecmproducts ";
$query .= " LEFT JOIN users
ON ecmproducts.assigned_user_id=users.id";
if ($custom_join) {
$query .= $custom_join['join'];
}
$query .= "";
$where_auto = " ecmproducts.deleted=0
";
if ($where != "")
$query .= " where $where AND " . $where_auto;
else
$query .= " where " . $where_auto;
if ($order_by != "")
$query .= " ORDER BY $order_by";
else
$query .= " ORDER BY ecmproducts.name";
return $query;
}
function fill_in_additional_list_fields() {
}
function fill_in_additional_detail_fields() {
// FILL IN THE ASSIGNED_USER_NAME
$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
$this->created_by_name = get_assigned_user_name($this->created_by);
$this->modified_by_name = get_assigned_user_name($this->modified_user_id);
$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT SUM(quantity) as qty FROM ecmstockstates WHERE product_id='" . $this->id . "'"));
$this->ems_qty_in_stock = $r['qty'];
}
function getSale($date) {
foreach ($date as $d) {
$z = "select
sum(
CASE WHEN e.type!='correct'
THEN
CASE WHEN e.currency_value is null or e.currency_value=''
THEN
i.price*i.quantity
ELSE
i.price*i.quantity*e.currency_value
END
ELSE
CASE WHEN ci.price is null or ci.quantity is null
THEN
0
ELSE
i.price*i.quantity-ci.price*ci.quantity
END
END
) as sales,
sum(
CASE WHEN e.type!='correct'
THEN
i.purchase_price*i.quantity
ELSE
CASE WHEN ci.quantity is null
THEN
0
ELSE
ci.purchase_price*i.quantity-ci.purchase_price*ci.quantity
END
END
) as purchase,
sum(
CASE WHEN e.type!='correct'
THEN
i.quantity
ELSE
CASE WHEN ci.quantity is null
THEN
0
ELSE
i.quantity-ci.quantity
END
END
) as quantity
from ecminvoiceoutitems as i
left join ecminvoiceoutitems as ci on i.ecminvoiceoutitem_id=ci.id
inner join ecminvoiceouts as e on e.id=i.ecminvoiceout_id
left join ecmstockdocouts as w on e.wz_id=w.id
left join ecmproducts as p on p.id=i.ecmproduct_id
where
e.register_date like '" . $d . "%' and e.status='accepted' and i.ecmproduct_id='" . $this->id . "'";
$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query($z));
$total_s+=$r['sales'];
$total_p+=$r['purchase'];
$total_q+=$r['quantity'];
/* $r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(i.quantity) as q,sum(i.quantity*i.price) as s,sum(i.quantity*i.purchase_price) as p from ecminvoiceouts as e inner join ecminvoiceoutitems as i on i.ecminvoiceout_id=e.id where e.register_date like '".$d."%' and e.status='accepted' and i.ecmproduct_id='".$this->id."'"));
$total_s+=$r['s'];
$total_p+=$r['p'];
$total_q+=$r['q'];
$w=$GLOBALS['db']->query("select i.quantity,i.price,i.purchase_price,i.ecminvoiceoutitem_id from ecminvoiceouts as e inner join ecminvoiceoutitems as i on i.ecminvoiceout_id=e.id where e.register_date like '".$d."%' and e.status='accepted' and e.type='correct' and i.ecmproduct_id='".$this->id."'");
while($r=$GLOBALS['db']->fetchByAssoc($w)){
$total_s+=$r['price']*$r['quantity'];
$total_q+=$r['quantity'];
$rr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select price,quantity,purchase_price from ecminvoiceoutitems where id='".$r['ecminvoiceoutitem_id']."'"));
$totat_s-=$rr['price']*$rr['quantity'];
$totat_p-=$rr['purchase_price']*$rr['quantity'];
$total_p+=$rr['purchase_price']*$r['quantity'];
$totat_q-=$rr['quantity'];
} */
}
//echo $total_s." ".$total_p." ".$total_q."<br>";
return array("sale" => $total_s, "purchase" => $total_p, "quantity" => $total_q);
}
function get_list_view_data() {
global $current_language, $current_user, $app_list_strings, $mod_strings;
global $numerek;
$record=$this->record_id;
$record_type=$this->record_type;
$this->retrieve($this->id);
$numerek = $this->id;
$i = 0;
$i++;
$the_array = parent::get_list_view_data();
if($record!=''){
$tmp=$this->getQuantityPrice($record,$record_type);
$the_array['QUANTITY'] = number_format($tmp['quantity'], $app_list_strings['ecmproducts_unit_dom_precision'][$this->unit_id], ",",".");
$the_array['TOTAL_NETTO'] = number_format($tmp['total_netto'], 2, ',', '.');
$the_array['PRICE_NETTO'] = number_format($tmp['price_netto'], 2, ',', '.');
$the_array['DOCUMENT_NO']=$tmp['document_no'];
$the_array['DOCUMENT_TYPE']=$tmp['DOCUMENT_TYPE'];
$the_array['REGISTER_DATE']=date('d.m.Y',strtotime($tmp['register_date']));
$the_array['CODE']=$tmp['code'];
}
global $current_user_id;
$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT SUM(quantity) as qty FROM ecmstockstates WHERE product_id='" . $this->id . "'"));
$this->ems_qty_in_stock = $r['qty'];
// THE NEW LISTVIEW CODE ONLY FETCHES COLUMNS THAT WE'RE DISPLAYING AND NOT ALL
// THE COLUMNS SO WE NEED THESE CHECKS.
$the_array['NAME'] = (($this->name == "") ? "<em>brak</em>" : $this->name);
//chmod('modules/EcmProducts/upload/images/'.$this->product_picture,777);
$op = new EcmStockOperation();
$value = $op->getAllQuantity($this->id);
if ($value != null) {
$the_array['STOCK_QTY'] = number_format($r['qty'], $app_list_strings['ecmproducts_unit_dom_precision'][$this->unit_id], ",",".");
} else {
$the_array['STOCK_QTY'] = number_format(0, $app_list_strings['ecmproducts_unit_dom_precision'][$this->unit_id], ",",".");
}
$the_array['ENCODED_NAME'] = $this->name;
$lolek = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(pp.product_quantity) as l from ecmproducts_ecmpurchaseorders as pp inner join ecmpurchaseorders as p on p.id=pp.ecmpurchaseorder_id where pp.ecmproduct_id='" . $this->id . "' and p.status='accepted'"));
$the_array['ORDERED'] = $lolek['l'];
if ($the_array['SRP_PRICE'] != '') {
$the_array['SRP_PRICE'] = number_format($this->srp_price, 2, $GLOBALS['sugar_config']['default_decimal_seperator'], $GLOBALS['sugar_config']['default_number_grouping_seperator']);
}
if ($the_array['PURCHASE_PRICE'] != '') {
$the_array['PURCHASE_PRICE'] = number_format($this->purchase_price, 2, $GLOBALS['sugar_config']['default_decimal_seperator'], $GLOBALS['sugar_config']['default_number_grouping_seperator']);
}
$the_array['EDIT_BTN'] = '<img src="themes/Sugar5/images/edit_inline.gif" onclick="javascript:window.location=\'index.php?module=EcmProducts&action=EditView&record=' . $this->id . '&return_module=EcmProducts&return_action=index\';" style="cursor: pointer;" border="0">';
if ($the_array['COMMISSION_RATE'] != '') {
$the_array['COMMISSION_RATE'] = number_format($this->commission_rate, 2, $GLOBALS['sugar_config']['default_decimal_seperator'], $GLOBALS['sugar_config']['default_number_grouping_seperator']);
}
if ($_SESSION[$current_user->user_name . '_PREFERENCES']['global']['EcmProductsQ']['stock_id_basic']) {
$sid = $_SESSION[$current_user->user_name . '_PREFERENCES']['global']['EcmProductsQ']['stock_id_basic'];
$st = " and stock_id='" . $sid . "'";
} elseif ($_SESSION[$current_user->user_name . '_PREFERENCES']['global']['EcmProductsQ']['stock_id_advanced']) {
$sid = $_SESSION[$current_user->user_name . '_PREFERENCES']['global']['EcmProductsQ']['stock_id_advanced'];
$st = " and stock_id='" . $sid . "'";
} else
$st = "";
$r2 = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select round(price,2) as price from ecmstockdocinitems where ecmproduct_id='" . $this->id . "' order by date_entered desc LIMIT 1"));
$the_array['LAST_PURCHASE_PRICE'] = number_format($r2['price'], 2, ",", ".");
$the_array['UNIT_NAME'] = $app_list_strings['ecmproducts_unit_dom'][$this->unit_id];
if (!$this->code)
$this->code = '--';
if ($_REQUEST['action'] == 'ListView' || $_REQUEST['action'] == 'index') {
if ($this->product_active) {
if ($this->status == 'active') {
$the_array['CODE'] = '<div style="background:green;font-weight:bold;padding:3px;color:white;text-align:left">' . $this->code . '</div>';
}
if ($this->status == 'new') {
$the_array['CODE'] = '<div style="background:blue;font-weight:bold;padding:3px;color:white;text-align:left">' . $this->code . '</div>';
}
if ($this->status == 'end_of_line') {
$the_array['CODE'] = '<div style="background:yellow;font-weight:bold;padding:3px;color:red;text-align:left">' . $this->code . '</div>';
}
if (!$this->status) {
$the_array['CODE'] = '<div style="background:grey;font-weight:bold;padding:3px;color:red;text-align:left">' . $this->code . '</div>';
}
} else
$the_array['CODE'] = '<div style="background:red;font-weight:bold;padding:3px;color:white;text-align:left">' . $this->code . '</div>';
}
/* $z="select sum(quantity) as q from ecmstockstates where product_id='".$this->id."' and deleted='0'".$st;
$w=$GLOBALS['db']->query($z);
$qq=0;
$r=$GLOBALS['db']->fetchByAssoc($w);
$qq+=$r['q']; */
$the_array['EMS_QTY_IN_STOCK'] = number_format($this->ems_qty_in_stock, 0, "", "");
/*
include_once("modules/EcmProductReports/vtigerConnector.php");
$vc=new vtigerConnector();
$vc->where="poproductrel.productcode like '".$this->code."'";
$vc->limit="0,999";
$vc->getData();
$vc->getCount();
$data=$vc->data;
for($i=0;$i<$vc->count;$i++){
$ord+=$data[$i]['quantity'];
}
*/
if (file_exists('modules/EcmProducts/upload/images/' . $this->product_picture) && $this->product_picture) {
$the_array['IMAGE'] = '<img src="modules/EcmProducts/upload/images/'
. $this->product_picture .
'" width="50px" border="0" onclick="window.open(\'modules/EcmProducts/upload/images/big/' . $this->product_picture.'\',\'' . $this->product_picture .'\')">';
}
$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select * from ecmproducts where id='" . $this->id . "'"));
$rp_sum = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(p.product_quantity) as s from ecmproducts_ecmpurchaseorders as p inner join ecmpurchaseorders as e on e.id=p.ecmpurchaseorder_id where p.ecmproduct_id='" . $this->id . "' and p.deleted='0' and e.deleted='0'"));
$rp_app = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(p.product_quantity) as s from ecmproducts_ecmpurchaseorders as p inner join ecmpurchaseorders as e on e.id=p.ecmpurchaseorder_id where p.ecmproduct_id='" . $this->id . "' and p.deleted='0' and (e.status='accepted' or e.status='mailed') and e.deleted='0'"));
$rp_cr = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(p.product_quantity) as s from ecmproducts_ecmpurchaseorders as p inner join ecmpurchaseorders as e on e.id=p.ecmpurchaseorder_id where p.ecmproduct_id='" . $this->id . "' and p.deleted='0' and e.status='not_accepted' and e.deleted='0'"));
$the_array['ORD_CREATED'] = $rp_cr['s'];
$the_array['ORD_APPROVED'] = $rp_app['s'];
//$the_array['ORDERED']=$rp_app['s']+$rp_cr['s'];
//$the_array['ORD_DELIVERED']=$r['ord_delivered'];
$stock_value = ($this->ems_price * $this->ems_qty_in_stock);
$the_array['STOCK_VALUE'] = number_format($stock_value, $app_list_strings['ecmproducts_unit_dom_precision'][$this->unit_id], ",", ".");
if (round(($r['s3'])) != 0)
$stock_month = (($this->ems_qty_in_stock + $this->ordered) / round(($r['s3'])));
else
$stock_month = 0;
$the_array['STOCK_MONTH'] = number_format($stock_month, $app_list_strings['ecmproducts_unit_dom_precision'][$this->unit_id], ",", ".");
$the_array['EMS_PRICE'] = number_format($this->ems_price, 2, ",", ".");
$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select flag from ecmproducts where id='" . $this->id . "'"));
if ($this->flag) {
$flag = 0;
$color = "red";
} else {
$flag = 1;
$color = "#cccccc";
}
$the_array['FLAGS'] = '<a href="index.php?module=EcmProducts&action=setFlag&flag=' . $flag . '&record=' . $this->id . '" style="color:' . $color . ';font-weight:bold;text-decoration:none;font-size:16px;">!</a>';
$the_array['HINT'] = HintProduct($this->id, $this->description, $this->add_status);
// $the_array['TO_ORDER'] = $r['to']
//$GLOBALS['db']->query("update ecmproducts set q0='".$s0['quantity']."',p0='".($s0['sale']-$s0['purchase'])."',s0='".$s0['sale']."',q3='".($s3['quantity']/3)."',p3='".(($s3['sale']-$s3['purchase'])/3)."',s3='".($s3['sale']/3)."',stock_month='".$stock_month."',stock_value='".$stock_value."' where id='".$this->id."'");
//echo mysql_error();
// echo $i;
/*
* zmiena globalna z include / utils.php funkcja get_unlinked_product_query do pobierania produktów z faktur kontrahenta
*/
global $parent_to_product, $seach_quantity,$invoices_id;
return $the_array;
}
function getQuantityPrice($parent_id,$parent_type) {
if($parent_type=='EcmInvoiceOuts'){
$tmp = $this->db->fetchByAssoc($this->db->query("select i.quantity,i.price_netto,i.total_netto,ii.document_no,i.code,ii.register_date from ecminvoiceoutitems i
inner join ecminvoiceouts ii on ii.id=i.ecminvoiceout_id where i.ecmproduct_id='".$this->id."' and i.ecminvoiceout_id='".$parent_id."'"));
$tmp['document_no']='<a target="_blank" href="index.php?module='.$parent_type.'&action=DetailView&record='.$parent_id.'">'.$tmp['document_no'].'</a>';
$tmp['DOCUMENT_TYPE']='Faktura';
} else {
$tmp = $this->db->fetchByAssoc($this->db->query("select i.quantity,i.price_netto,i.total_netto,ii.document_no,i.code,ii.register_date from ecmreceiptitems i
inner join ecmreceipts ii on ii.id=i.ecmreceipt_id where i.ecmproduct_id='".$this->id."' and i.ecmreceipt_id='".$parent_id."'"));
$tmp['document_no']='<a target="_blank" href="index.php?module='.$parent_type.'&action=DetailView&record='.$parent_id.'">'.$tmp['document_no'].'</a>';
$tmp['DOCUMENT_TYPE']='Paragon';
}
return $tmp;
}
/**
BUILDS A GENERIC SEARCH BASED ON THE QUERY STRING USING OR.
DO NOT INCLUDE ANY $THIS-> BECAUSE THIS IS CALLED ON WITHOUT HAVING THE CLASS INSTANTIATED.
*/
function build_generic_where_clause($the_query_string) {
$where_clauses = Array();
$the_query_string = PearDatabase::quote(from_html($the_query_string));
array_push($where_clauses, "ecmproducts.name like '$the_query_string%'");
$the_where = "";
foreach ($where_clauses as $clause) {
if ($the_where != "")
$the_where .= " or ";
$the_where .= $clause;
}
return $the_where;
}
function set_notification_body($xtpl, $simplemodule) {
global $mod_strings, $app_list_strings;
$xtpl->assign("NAME", $simplemodule->name);
$xtpl->assign("ECMPRODUCTS_DESCRIPTION", $ecmproducts->description);
return $xtpl;
}
function bean_implements($interface) {
switch ($interface) {
case 'ACL':return true;
}
return false;
}
function r($t) {
$t = str_replace(".", "", $t);
$t = str_replace(",", ".", $t);
$t = floatval($t);
return $t;
}
function save($check_notify = FALSE) {
include_once("modules/EcmProducts/generateEAN.php");
if ($_REQUEST['newEan'] == '1')
$_REQUEST['ean'] = generateEan(1);
if ($_REQUEST['newEan2'] == '1')
$this->ean2 = generateEAN(2);
//$_REQUEST['ean2'] = generateEan(1);
if ($_REQUEST['massupdate']) {
foreach ($_REQUEST['mass'] as $m)
$mm[] = "id='" . $m . "'";
if ($_REQUEST['production'])
$set[] = "production='" . $_REQUEST['production'] . "'";
if ($_REQUEST['product_active'])
$set[] = "product_active='" . $_REQUEST['product_active'] . "'";
if ($_REQUEST['end_of_line'])
$set[] = "end_of_line='" . $_REQUEST['end_of_line'] . "'";
if ($_REQUEST['sales_start_date'])
$set[] = "sales_start_date='" . date("Y-m-d", strtotime($GLOBALS['timedate']->to_db_date($_REQUEST['sales_start_date'])) + 24 * 3600) . "'";
if ($_REQUEST['sales_end_date'])
$set[] = "sales_end_date='" . date("Y-m-d", strtotime($GLOBALS['timedate']->to_db_date($_REQUEST['sales_end_date'])) + 24 * 3600) . "'";
if (count($set) > 0)
$z = "update ecmproducts set " . implode(",", $set) . " where " . implode(" or ", $mm);
//echo $z;
$GLOBALS['db']->query($z);
header("Location: index.php?module=EcmProducts&action=index");
}
else {
$return_id = parent::save($check_notify);
$components = self::ParseComponentsFromPOST();
if (!(!is_array($components) && $components == false))
$this->position_list = $components;
$this->savePositions($return_id);
//save categories
$this->savePositions3($_POST['position_list3']);
$this->savePrices($_POST['position_list4']);
$actionTmpid = explode(',', $_POST ['tableTimeEdit_rowOrder']);
$action_array = array();
foreach ($actionTmpid as $value) {
if ($_POST ['tableTimeEdit_ecmactionid_' . $value] != '') {
$action_array [$value] ['quantity'] = unformat_number($_POST ['tableTimeEdit_quantity_' . $value]);
$action_array [$value] ['ecmaction_id'] = $_POST ['tableTimeEdit_ecmactionid_' . $value];
$action_array [$value] ['single_price'] = unformat_number($_POST ['tableTimeEdit_price_' . $value . '_Single']);
$action_array [$value] ['quantity_recipe'] = unformat_number($_POST ['tableTimeEdit_quantity_recipe_' . $value . '']);
$action_array [$value] ['divider'] = unformat_number($_POST ['tableTimeEdit_divider_' . $value . '']);
$action_array [$value] ['unit_id'] = $_POST ['tableTimeEdit_unit_id_' . $value];
}
}
$this->saveActionList($action_array);
$componentsTmpid = explode(',', $_POST ['tableComponents_rowOrder']);
$components_array = array();
foreach ($componentsTmpid as $value) {
if ($_POST ['tableComponents_ecmcomponent_id_' . $value] != '') {
$components_array [$value] ['quantity'] = ($_POST ['tableComponents_quantity_' . $value]);
$components_array [$value] ['divider'] = unformat_number($_POST ['tableComponents_divider_' . $value]);
$components_array [$value] ['quantity_recipe'] = ($_POST ['tableComponents_quantity_recipe_' . $value]);
$components_array [$value] ['ecmcomponent_id'] = $_POST ['tableComponents_ecmcomponent_id_' . $value];
$components_array [$value] ['code'] = $_POST ['tableComponents_code_' . $value];
$components_array [$value] ['name'] = $_POST ['tableComponents_name_' . $value];
$components_array [$value] ['single_price'] = unformat_number($_POST ['tableComponents_price_' . $value . '_Single']);
$components_array [$value] ['unit_id'] = $_POST ['tableComponents_unit_id_' . $value];
}
}
$this->saveComponentsList($components_array);
if($_REQUEST['srp_price_replace']=='1'){
$query="update ecmproductcomponents set single_price='".$this->srp_price."' where ecmcomponent_id='".$this->id."'";
$this->db->query($query);
}
return $return_id;
}
}
static function ParseComponentsFromPOST() {
if (isset($_POST['position_list'])) {
$c_ = $_POST['position_list'];
$json = getJSONobj();
$c = $json->decode(htmlspecialchars_decode($c_));
return $c;
}
return false;
}
//***************************Start Managing Positions*************************//
function constructInsertQuery($data, $table = '') {
if ($table == '' && isset($this->object_name) && $this->object_name != '') {
$table = strtolower($this->object_name) . "components";
} else
return "";
$keys = array();
$values = array();
foreach ($data as $key => $value) {
$keys[] = $key;
if (is_array($value))
$values[] = $value[1] . str_replace("'", "\'", $value[0]) . $value[1];
else
$values[] = "'" . str_replace("'", "\'", $value) . "'";
}
$q = "insert into `$table` (`";
$q .= implode('`, `', $keys);
$q .= "`) values (";
$q .= implode(", ", $values);
$q .= ");";
return $q;
}
function getAmount($money)
{
$cleanString = preg_replace('/([^0-9\.,])/i', '', $money);
$onlyNumbersString = preg_replace('/([^0-9])/i', '', $money);
$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
$stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
$removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);
return (float) str_replace(',', '.', $removedThousendSeparator);
}
function savePrices($prices) {
if (!is_array($prices))
return null;
$fields = array('id', 'ecmprice_id', 'ecmproduct_id', 'price');
$new = array();
$db = $GLOBALS['db'];
$db->query("insert into log (msg) VALUES ('tu')");
foreach ($prices as $p) {
$db->query("insert into log (msg) VALUES ('tam2')");
if (!isset($p['price']) || !isset($p['ecmpricebook_id']) || floatval($p['price']) == 0)
continue;
$db->query("insert into log (msg) VALUES ('tam')");
$id = create_guid();
$new[] = $id;
$tmp = array();
$tmp[] = $id;
$tmp[] = $p['ecmpricebook_id'];
$tmp[] = $this->id;
$tmp[] = $p['price'];
$query = "INSERT INTO ecmprices_ecmproducts (" . implode(",", $fields) . ") VALUES ('" . implode("','", $tmp) . "')";
$db->query($query);
}
$db->query("delete from ecmprices_ecmproducts where ecmproduct_id='" . $this->id . "' AND id NOT IN ('" . implode("','", $new) . "')");
}
function showPrices() {
$arr = $this->getPricesList(true);
if (count($arr) > 0) {
$table = '
<table cellpadding="0" cellspacing="0" border="0" class="list view">
<tr class="oddListRowS1">
<th width="15%"><b>Nazwa</b></td>
<th><b>Wartość</b></td>
<th><b>Waluta</b></td>
</tr>
';
foreach ($arr as $a) {
$table.='
<tr class="oddListRowS1">
<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">
' . $a['pricebook_name'] . '</td>
<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;text-align:right;">
' . format_number($a['price']) . '</td>
<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">
' . $a['currency'] . '</td>
';
}
$table.='</table>';
}
return $table;
}
function savePositions($id = null, $position_list = null) {
global $current_user, $timedate;
if ($position_list == null)
$position_list = $this->position_list;
if ($id == null)
$id = $this->id;
if (count($position_list) > 0)
$this->deleteAssignedPositions($id);
$arr = array();
$position = 0;
for ($i = 0; $i < count($position_list); $i ++) {
if ($position_list[$i]['name'] == '')
continue;
$p = $position_list[$i];
/* Not Nessesary
require_once("modules/EcmVats/EcmVat.php");
$vats = new EcmVat();
$vats->retrieve($p['vat_id']);
$p['vat_name'] = $vats->name;
require_once("modules/Currencies/Currency.php");
$curr = new Currency();
$curr->retrieve($p['currency_id']);
$p['currency_name'] = $curr->name;
if(!empty($p['category_id']) || $p['category_id'] == '') {
require_once("modules/EcmProducts/EcmProduct.php");
$pr = new EcmProduct();
$pr->retrieve($p['id']);
$p['category_id'] = $pr->product_category_id;
}
*/
$arr = array(
'id' => create_guid(),
'date_entered' => array('NOW()', ''),
'date_modified' => array('NOW()', ''),
'modified_user_id' => $current_user->id,
'assigned_user_id' => $current_user->id,
'created_by' => $current_user->id,
'deleted' => '0',
strtolower($this->object_name) . '_id' => $id,
'ecmcomponent_id' => $p['id'],
'position' => $position,
'code' => $p['code'],
'name' => $p['name'],
'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
'ecmusageunit_id' => $p['unit_id'],
/* Not Nessesary
'price' => ((empty($p['price']) || $p['price'] == '') ? 0 : $p['price']),
'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
'total' => ((empty($p['total']) || $p['total'] == '') ? 0 : $p['total']),
'dd_unit_id' => $p['unit_id'],
'dd_unit_name' => '',
'ecmvat_id' => $p['vat_id'],
'ecmvat_name' => $p['vat_name'],
'ecmvat_value' => $p['vat_value'],
'ecmproductcategory_id' => $p['category_id'],
'currency_id' => $p['currency_id'],
'currency_name' => $p['currency_name'],
'recipient_code' => $p['recipient_code'],
*/
);
$this->db->query($this->constructInsertQuery($arr));
$position ++;
}
}
function getPosition($position) {
if (!is_array($position))
return '';
global $timedate;
$return_array = array();
$return_array['id'] = $position['ecmcomponent_id'];
$return_array['position'] = $position['position'];
$return_array['code'] = $position['code'];
$return_array['name'] = str_replace('&quot;', '', $position['name']);
$return_array['quantity'] = $position['quantity'];
$return_array['price'] = $position['price'];
$return_array['discount'] = $position['discount'];
$return_array['total'] = $position['total'];
$return_array['unit_id'] = $position['ecmusageunit_id'];
$return_array['unit_name'] = $position['dd_unit_name'];
$return_array['vat_id'] = $position['ecmvat_id'];
$return_array['vat_name'] = $position['ecmvat_name'];
$return_array['vat_value'] = $position['ecmvat_value'];
$return_array['category_id'] = $position['ecmproductcategory_id'];
$return_array['currency_id'] = $position['currency_id'];
$return_array['currency_name'] = $position['currency_name'];
$return_array['recipient_code'] = $position['recipient_code'];
//get ems price
$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT ems_price FROM ecmproducts WHERE id='" . $position['ecmcomponent_id'] . "'"));
$return_array['ems_price'] = $position['quantity'] * $r['ems_price'];
if (!$r || $r['ems_price'] == 0)
$return_array['ems_price'] = 0;
global $db;
$c = $db->fetchByAssoc($db->query("SELECT product_category_id as c, purchase_price as p FROM ecmproducts WHERE id='" . $position['ecmcomponent_id'] . "'"));
if ($c['c'] == 'd7f876b0-1a3d-43a1-7c9b-511ba40df3d1')
$return_array['ems_price'] = $c['p'];
return $return_array;
}
function getPositionList($array = false) {
if (isset($this->id) && $this->id != '') {
$query = "SELECT * FROM `ecmproductcomponents` WHERE `ecmproduct_id`='" . $this->id . "' order by position asc";
$r = $this->db->query($query);
$return_array = array();
if ($r) {
while ($w = $this->db->fetchByAssoc($r)) {
$return_array [] = $this->getPosition($w);
}
$json = getJSONobj();
return $array ? $return_array : $json->encode($return_array);
}
}
return $array ? false : '[]';
}
function deleteAssignedPositions() {
if (isset($this->id) && $this->id != '') {
$query = "DELETE FROM `" . strtolower($this->object_name) . "components` WHERE `" . strtolower($this->object_name) . "_id`='" . $this->id . "'";
$r = $this->db->query($query);
if ($r)
return true;
}
return false;
}
//***************************End Managing Positions*************************//
//start managing categories
function savePositions3($pl) {
global $current_user;
$exists = array();
$first = true;
if($pl==''){
$pl=$this->position_list3;
}
foreach ($pl as $p) {
if (!isset($p['ecmproductcategory_id']) || $p['ecmproductcategory_id'] == '')
continue;
//first position save into main category
if ($first) {
$q = "UPDATE ecmproducts set product_category_id='" . $p['ecmproductcategory_id'] . "', product_category_name='" . $p['ecmproductcategory_name'] . "' WHERE id='" . $this->id . "'";
$GLOBALS['db']->query($q);
$first = false;
}
if (isset($p['id']) && $p['id'] != '') {
//update exists
$q = "
UPDATE ecmproductcategories_bean set
date_modified = '" . date("Y-m-d H:i:s") . "',
modified_user_id = '" . $current_user->id . "',
bean_id = '" . addslashes($this->id) . "',
ecmproductcategory_id = '" . addslashes($p['ecmproductcategory_id']) . "',
position = '".$p['position']."'
WHERE id = '" . $p['id'] . "'
";
$GLOBALS['db']->query($q);
$exists[] = $p['id'];
} else {
//insert new record
$id = create_guid();
$t = array(
$id,
addslashes($p['ecmproductcategory_id']),
$this->id,
"EcmProducts",
date("Y-m-d H:i:s"),
date("Y-m-d H:i:s"),
$current_user->id,
$current_user->id,
'0',
$p['position'],
);
$q = "INSERT INTO ecmproductcategories_bean VALUES ('" . implode("','", $t) . "')";
$GLOBALS['db']->query($q);
$exists[] = $id;
}
}
//delete old
$GLOBALS['db']->query("UPDATE ecmproductcategories_bean SET deleted='1', modified_user_id='" . $current_user->id . "',date_modified = '" . date("Y-m-d H:i:s") . "' WHERE bean_id='" . $this->id . "' AND id NOT IN ('" . implode("','", $exists) . "')");
}
function getPositionList3($array = false) {
if (isset($this->id) && $this->id != '') {
$query = "SELECT * FROM ecmproductcategories_bean WHERE bean_id='" . $this->id . "' AND deleted='0' AND bean_name='EcmProducts'";
$r = $this->db->query($query);
$return_array = array();
if ($r) {
while ($w = $this->db->fetchByAssoc($r)) {
//get category name && assigned_file
$n = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT name, assigned_file FROM ecmproductcategories WHERE id='" . $w['ecmproductcategory_id'] . "'"));
$w['ecmproductcategory_name'] = $n['name'];
$w['assigned_file'] = $n['assigned_file'];
$return_array [] = $w;
}
$json = getJSONobj();
return $array ? $return_array : $json->encode($return_array);
}
}
return $array ? false : '[]';
}
function showPositions3() {
$arr = $this->getPositionList3(true);
global $mod_strings;
if (count($arr) > 0) {
$table = '
<table cellpadding="0" cellspacing="0" border="0" class="list view" width="40%">
<tr class="oddListRowS1">
<th><b>' . $mod_strings['LBL_CATEGORY_NAME'] . '</b></td>
<th><b>' . $mod_strings['LBL_CATEGORY_ASSIGNED_FILE'] . '</b></td>
</tr>
';
$i == 0;
foreach ($arr as $a) {
$i++;
//assigned file
if ($a['assigned_file'] != "" && $a['assigned_file']) {
$tmp = explode(".", $a['assigned_file']);
if (end($tmp) == 'jpeg' || end($tmp) == 'jpg' || end($tmp) == 'png' || end($tmp) == 'bmp')
$af = '<img src="modules/EcmProductCategories/files/' . $a['assigned_file'] . '"/>';
else
$af = '<a href="modules/EcmProductCategories/files/' . $a['assigned_file'] . '" target="new">' . $a['assigned_file'] . '</a>';
}
$table.='
<tr class="oddListRowS1">
<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;"><a href="index.php?module=EcmProductCategories&action=DetailView&record=' . $a['ecmproductcategory_id'] . '">' . $a['ecmproductcategory_name'] . '</a></td>
<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">' . $af . '</td>
';
}
$table.='</table>';
}
return $table;
}
//end managing categories
function getProductResInfo($product_id, $stock_id) {
$info = array();
global $db;
require_once('modules/EcmStockOperations/EcmStockOperation.php');
$op = new EcmStockOperation();
$info['stock'] = $op->getRealStock($product_id, $stock_id);
//temp reserwations
$rr = $db->fetchByAssoc($db->query("SELECT sum(quantity) as s FROM ecmreservations WHERE product_id='$product_id' AND doc_id IS NULL"));
if (!$rr['s'])
$rr['s'] = 0;
$info['res'] = $rr['s'];
//doc reservations
$res = $db->query("SELECT quantity, doc_id, doc_type FROM ecmreservations WHERE product_id='$product_id' AND doc_id IS NOT NULL");
if (!is_array($res) == 0)
return $info;
while ($row = $db->fetchByAssoc($res)) {
$tmp = array();
$type = '';
if ($row['doc_type'] == 'EcmSales')
$type = 'ZS';
if ($row['doc_type'] == 'EcmInsideOrders')
$type = 'ZW';
//get document name
$doc = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT document_no, parent_name FROM " . strtolower($row['doc_type']) . " WHERE id='" . $row['doc_id'] . "'"));
$tmp[] = '<a target="new" href="index.php?module=' . $row['doc_type'] . '&action=DetailView&record=' . $row['doc_id'] . '">' . $type . ' ' . $doc['document_no'] . '</a> - ' . $row['quantity'] . '&nbsp&nbsp' . $doc['parent_name'];
}
$info['docs'] = $tmp;
return $info;
}
function getPricesList($array = false) {
$query = "SELECT p.id as id, p.name as name, pp.price as price,p.exchange_rate_id as currency FROM ecmprices as p
LEFT JOIN ecmprices_ecmproducts as pp
ON pp.ecmprice_id=p.id AND pp.ecmproduct_id='" . $this->id . "'
WHERE p.deleted='0'";
$r = $this->db->query($query);
$return_array = array();
$c = new Currency ();
if ($r) {
while ($w = $this->db->fetchByAssoc($r)) {
$tmp = array();
$tmp['pricebook_id'] = $w['id'];
$tmp['pricebook_name'] = $w['name'];
$tmp['price'] = $w['price'];
$c->retrieve($w['currency']);
$tmp['currency'] = $c->name;
$return_array [] = $tmp;
}
$json = getJSONobj();
return $array ? $return_array : $json->encode($return_array);
}
return $array ? false : '[]';
}
function retrieve($id = -1, $encode = true, $deleted = true) {
parent::retrieve($id, $encode, $deleted);
$json = getJSONobj();
$this->action_list = $json->decode($this->getActionList());
$this->component_list = $this->getComponentsList();
}
function saveActionList($pl) {
global $current_user;
$exists = array();
if ($this->id != '') {
$GLOBALS ['db']->query("DELETE FROM ecmproductactions WHERE ecmproduct_id='" . $this->id . "'");
}
$i = 0;
foreach ($pl as $p) {
$id = create_guid();
$i++;
$t = array(
$id,
$current_user->id,
date("Y-m-d H:i:s"),
$this->id,
addslashes($p ['ecmaction_id']),
addslashes($p ['quantity']),
$i,
addslashes($p ['single_price']),
addslashes($p ['unit_id'])
);
$q = "INSERT INTO ecmproductactions VALUES ('" . implode("','", $t) . "')";
$GLOBALS ['db']->query($q);
$exists [] = $id;
}
}
function getActionList($array = false) {
global $app_list_strings;
if (isset($this->id) && $this->id != '') {
$query = "SELECT a.id, a.name, a.indeks, pa.single_price,pa.unit_id, a.cost_hour, a.category, pa.quantity FROM ecmactions a, ecmproductactions pa WHERE a.id = pa.ecmaction_id AND pa.ecmproduct_id='" . $this->id . "' AND a.deleted=0 ORDER BY a.indeks";
$r = $this->db->query($query);
$return_array = array();
if ($r) {
while ($row = $this->db->fetchByAssoc($r)) {
$a_json_row ['ecmactionid'] = $row ['id'];
$a_json_row ['name'] = $row ['name'];
$a_json_row ['indeks'] = $row ['indeks'];
$a_json_row ['price']['Single'] = $row ['single_price'];
$a_json_row ['price']['Summary'] = $row ['single_price'] * $row['quantity'];
$a_json_row ['category'] = $app_list_strings ['ecmactions_category_dom'] [$row ['category']];
$a_json_row ['quantity'] = $row['quantity'];
$a_json_row ['unit_id'] = $row['unit_id'];
$return_array [] = $a_json_row;
}
$json = getJSONobj();
return $array ? $return_array : $json->encode($return_array);
}
}
return $array ? false : '[]';
}
function saveComponentsList($pl) {
global $current_user;
$exists = array();
if ($this->id != '') {
$GLOBALS ['db']->query("DELETE FROM ecmproductcomponents WHERE ecmproduct_id='" . $this->id . "'");
}
$i = 0;
foreach ($pl as $p) {
$id = create_guid();
$i++;
$t = array(
$id, //id
date("Y-m-d H:i:s"), //date_entered
date("Y-m-d H:i:s"), //date_modified
$current_user->id, //modified_user_id
$current_user->id, //assigned_user_id
$current_user->id, //created_by
'0', //deleted
$this->id, //ecmproduct_id
addslashes($p['ecmcomponent_id']), //ecmcomponent_id
$i, //position
addslashes($p ['code']), //code
addslashes($p ['name']), //name
addslashes($p ['quantity']), //quantity
addslashes($p ['unit_id']), //ecmusageunit_id
addslashes($p ['single_price']), //single price,
addslashes($p ['divider']), //single price
addslashes($p ['quantity_recipe']) //single price
);
$q = "INSERT INTO ecmproductcomponents VALUES ('" . implode("','", $t) . "')";
$GLOBALS ['db']->query($q);
$exists [] = $id;
}
}
function getComponentsList() {
global $app_list_strings;
if (isset($this->id) && $this->id != '') {
$query = "SELECT a.ecmcomponent_id, a.quantity,a.divider,a.quantity_recipe, a.ecmusageunit_id, a.single_price, b.name, b.code, b.product_category_name FROM ecmproductcomponents a, ecmproducts b WHERE b.id = a.ecmcomponent_id AND a.ecmproduct_id='" . $this->id . "' AND a.deleted=0 ORDER BY a.position, a.code";
$r = $this->db->query($query);
$return_array = array();
if ($r) {
while ($row = $this->db->fetchByAssoc($r)) {
$a_json_row ['ecmcomponent_id'] = $row ['ecmcomponent_id'];
$a_json_row ['ecmproduct_id'] = $row ['ecmcomponent_id'];
$a_json_row ['name'] = $row ['name'];
$a_json_row ['code'] = $row ['code'];
$a_json_row ['price']['Single'] = $row ['single_price'];
$a_json_row ['price']['Summary'] = $row ['single_price'] * $row['quantity'];
$a_json_row ['quantity'] = $row['quantity'];
$a_json_row ['unit_id'] = $row['ecmusageunit_id'];
$a_json_row ['product_category_name'] = $row ['product_category_name'];
$a_json_row ['divider'] = $row ['divider'];
$a_json_row ['quantity_recipe'] = $row ['quantity_recipe'];
$return_array [] = $a_json_row;
}
return $return_array;
}
return null;
}else{
return null;
}
}
}
?>