Newer
Older

madhu sr
committed
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
$log->debug("Exit from function getInventorySHTaxPercent($id, $taxname)");
return $taxpercentage;
}
/** Function used to get the list of all Currencies as a array
* @param string available - if 'all' returns all the currencies, default value 'available' returns only the currencies which are available for use.
* return array $currency_details - return details of all the currencies as a array
*/
function getAllCurrencies($available='available') {
global $adb, $log;
$log->debug("Entering into function getAllCurrencies($available)");
$sql = "select * from vtiger_currency_info";
if ($available != 'all') {
$sql .= " where currency_status='Active' and deleted=0";
}
$res=$adb->pquery($sql, array());
$noofrows = $adb->num_rows($res);
for($i=0;$i<$noofrows;$i++)
{
$currency_details[$i]['currencylabel'] = $adb->query_result($res,$i,'currency_name');
$currency_details[$i]['currencycode'] = $adb->query_result($res,$i,'currency_code');
$currency_details[$i]['currencysymbol'] = $adb->query_result($res,$i,'currency_symbol');
$currency_details[$i]['curid'] = $adb->query_result($res,$i,'id');
/* alias key added to be consistent with result of InventoryUtils::getInventoryCurrencyInfo */
$currency_details[$i]['currency_id'] = $adb->query_result($res,$i,'id');
$currency_details[$i]['conversionrate'] = $adb->query_result($res,$i,'conversion_rate');
$currency_details[$i]['curname'] = 'curname' . $adb->query_result($res,$i,'id');
}
$log->debug("Entering into function getAllCurrencies($available)");
return $currency_details;
}
/** Function used to get all the price details for different currencies which are associated to the given product
* @param int $productid - product id to which we want to get all the associated prices
* @param decimal $unit_price - Unit price of the product
* @param string $available - available or available_associated where as default is available, if available then the prices in the currencies which are available now will be returned, otherwise if the value is available_associated then prices of all the associated currencies will be retruned
* @return array $price_details - price details as a array with productid, curid, curname
*/
function getPriceDetailsForProduct($productid, $unit_price, $available='available', $itemtype='Products')
{
global $log, $adb;
$log->debug("Entering into function getPriceDetailsForProduct($productid)");
if($productid != '')
{
$product_currency_id = getProductBaseCurrency($productid, $itemtype);
$product_base_conv_rate = getBaseConversionRateForProduct($productid,'edit',$itemtype);
// Detail View
if ($available == 'available_associated') {
$query = "select vtiger_currency_info.*, vtiger_productcurrencyrel.converted_price, vtiger_productcurrencyrel.actual_price
from vtiger_currency_info
inner join vtiger_productcurrencyrel on vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid
where vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0
and vtiger_productcurrencyrel.productid = ? and vtiger_currency_info.id != ?";
$params = array($productid, $product_currency_id);
} else { // Edit View
$query = "select vtiger_currency_info.*, vtiger_productcurrencyrel.converted_price, vtiger_productcurrencyrel.actual_price
from vtiger_currency_info
left join vtiger_productcurrencyrel
on vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid and vtiger_productcurrencyrel.productid = ?
where vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0";
$params = array($productid);
}
//Postgres 8 fixes
if( $adb->dbType == "pgsql")
$query = fixPostgresQuery( $query, $log, 0);
$res = $adb->pquery($query, $params);
for($i=0;$i<$adb->num_rows($res);$i++)
{
$price_details[$i]['productid'] = $productid;
$price_details[$i]['currencylabel'] = $adb->query_result($res,$i,'currency_name');
$price_details[$i]['currencycode'] = $adb->query_result($res,$i,'currency_code');
$price_details[$i]['currencysymbol'] = $adb->query_result($res,$i,'currency_symbol');
$currency_id = $adb->query_result($res,$i,'id');
$price_details[$i]['curid'] = $currency_id;
$price_details[$i]['curname'] = 'curname' . $adb->query_result($res,$i,'id');
$cur_value = $adb->query_result($res,$i,'actual_price');
// Get the conversion rate for the given currency, get the conversion rate of the product currency to base currency.
// Both together will be the actual conversion rate for the given currency.
$conversion_rate = $adb->query_result($res,$i,'conversion_rate');
$actual_conversion_rate = $product_base_conv_rate * $conversion_rate;
$is_basecurrency = false;
if ($currency_id == $product_currency_id) {
$is_basecurrency = true;
}
$price_details[$i]['check_value'] = false;
if ($unit_price != null) {
$cur_value = CurrencyField::convertFromMasterCurrency($unit_price, $actual_conversion_rate);
} else {
$cur_value = '0';
}
}
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
$price_details[$i]['curvalue'] = CurrencyField::convertToUserFormat($cur_value, null, true);
$price_details[$i]['conversionrate'] = $actual_conversion_rate;
$price_details[$i]['is_basecurrency'] = $is_basecurrency;
}
}
else
{
if($available == 'available') { // Create View
global $current_user;
$user_currency_id = fetchCurrency($current_user->id);
$query = "select vtiger_currency_info.* from vtiger_currency_info
where vtiger_currency_info.currency_status = 'Active' and vtiger_currency_info.deleted=0";
$params = array();
$res = $adb->pquery($query, $params);
for($i=0;$i<$adb->num_rows($res);$i++)
{
$price_details[$i]['currencylabel'] = $adb->query_result($res,$i,'currency_name');
$price_details[$i]['currencycode'] = $adb->query_result($res,$i,'currency_code');
$price_details[$i]['currencysymbol'] = $adb->query_result($res,$i,'currency_symbol');
$currency_id = $adb->query_result($res,$i,'id');
$price_details[$i]['curid'] = $currency_id;
$price_details[$i]['curname'] = 'curname' . $adb->query_result($res,$i,'id');
// Get the conversion rate for the given currency, get the conversion rate of the product currency(logged in user's currency) to base currency.
// Both together will be the actual conversion rate for the given currency.
$conversion_rate = $adb->query_result($res,$i,'conversion_rate');
$user_cursym_convrate = getCurrencySymbolandCRate($user_currency_id);
$product_base_conv_rate = 1 / $user_cursym_convrate['rate'];
$actual_conversion_rate = $product_base_conv_rate * $conversion_rate;
$price_details[$i]['check_value'] = false;
$price_details[$i]['curvalue'] = '0';
$price_details[$i]['conversionrate'] = $actual_conversion_rate;
$is_basecurrency = false;
if ($currency_id == $user_currency_id) {
$is_basecurrency = true;
}
$price_details[$i]['is_basecurrency'] = $is_basecurrency;
}
} else {
$log->debug("Product id is empty. we cannot retrieve the associated prices.");
}
}
$log->debug("Exit from function getPriceDetailsForProduct($productid)");
return $price_details;
}
/** Function used to get the base currency used for the given Product
* @param int $productid - product id for which we want to get the id of the base currency
* @return int $currencyid - id of the base currency for the given product
*/
function getProductBaseCurrency($productid,$module='Products') {
global $adb, $log;
if ($module == 'Services') {
$sql = "select currency_id from vtiger_service where serviceid=?";
} else {
$sql = "select currency_id from vtiger_products where productid=?";
}
$params = array($productid);
$res = $adb->pquery($sql, $params);
$currencyid = $adb->query_result($res, 0, 'currency_id');
return $currencyid;
}
/** Function used to get the conversion rate for the product base currency with respect to the CRM base currency
* @param int $productid - product id for which we want to get the conversion rate of the base currency
* @param string $mode - Mode in which the function is called
* @return number $conversion_rate - conversion rate of the base currency for the given product based on the CRM base currency
*/
function getBaseConversionRateForProduct($productid, $mode='edit', $module='Products') {
global $adb, $log, $current_user;
if ($mode == 'edit') {
if ($module == 'Services') {
$sql = "select conversion_rate from vtiger_service inner join vtiger_currency_info
on vtiger_service.currency_id = vtiger_currency_info.id where vtiger_service.serviceid=?";
} else {
$sql = "select conversion_rate from vtiger_products inner join vtiger_currency_info
on vtiger_products.currency_id = vtiger_currency_info.id where vtiger_products.productid=?";
}
$params = array($productid);
} else {
$sql = "select conversion_rate from vtiger_currency_info where id=?";
$params = array(fetchCurrency($current_user->id));
}
$res = $adb->pquery($sql, $params);
$conv_rate = $adb->query_result($res, 0, 'conversion_rate');
return $conv_rate ? (1 / $conv_rate) : 1;
}
/** Function used to get the prices for the given list of products based in the specified currency
* @param int $currencyid - currency id based on which the prices have to be provided
* @param array $product_ids - List of product id's for which we want to get the price based on given currency
* @return array $prices_list - List of prices for the given list of products based on the given currency in the form of 'product id' mapped to 'price value'
*/
function getPricesForProducts($currencyid, $product_ids, $module='Products', $skipActualPrice = false) {
global $adb,$log,$current_user;
$price_list = array();
if (php7_count($product_ids) > 0) {
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
if ($module == 'Services') {
$query = "SELECT vtiger_currency_info.id, vtiger_currency_info.conversion_rate, " .
"vtiger_service.serviceid AS productid, vtiger_service.unit_price, " .
"vtiger_productcurrencyrel.actual_price " .
"FROM (vtiger_currency_info, vtiger_service) " .
"left join vtiger_productcurrencyrel on vtiger_service.serviceid = vtiger_productcurrencyrel.productid " .
"and vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid " .
"where vtiger_service.serviceid in (". generateQuestionMarks($product_ids) .") and vtiger_currency_info.id = ?";
} else {
$query = "SELECT vtiger_currency_info.id, vtiger_currency_info.conversion_rate, " .
"vtiger_products.productid, vtiger_products.unit_price, " .
"vtiger_productcurrencyrel.actual_price " .
"FROM (vtiger_currency_info, vtiger_products) " .
"left join vtiger_productcurrencyrel on vtiger_products.productid = vtiger_productcurrencyrel.productid " .
"and vtiger_currency_info.id = vtiger_productcurrencyrel.currencyid " .
"where vtiger_products.productid in (". generateQuestionMarks($product_ids) .") and vtiger_currency_info.id = ?";
}
$params = array($product_ids, $currencyid);
$result = $adb->pquery($query, $params);
for($i=0;$i<$adb->num_rows($result);$i++)
{
$product_id = $adb->query_result($result, $i, 'productid');
if(getFieldVisibilityPermission($module,$current_user->id,'unit_price') == '0') {
$actual_price = (float)$adb->query_result($result, $i, 'actual_price');
if ($actual_price == null || $actual_price == '' || $skipActualPrice) {
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
$unit_price = $adb->query_result($result, $i, 'unit_price');
$product_conv_rate = $adb->query_result($result, $i, 'conversion_rate');
$product_base_conv_rate = getBaseConversionRateForProduct($product_id,'edit',$module);
$conversion_rate = $product_conv_rate * $product_base_conv_rate;
$actual_price = $unit_price * $conversion_rate;
}
$price_list[$product_id] = $actual_price;
} else {
$price_list[$product_id] = '';
}
}
}
return $price_list;
}
/** Function used to get the currency used for the given Price book
* @param int $pricebook_id - pricebook id for which we want to get the id of the currency used
* @return int $currencyid - id of the currency used for the given pricebook
*/
function getPriceBookCurrency($pricebook_id) {
global $adb;
$result = $adb->pquery("select currency_id from vtiger_pricebook where pricebookid=?", array($pricebook_id));
$currency_id = $adb->query_result($result,0,'currency_id');
return $currency_id;
}
// deduct products from stock - if status will be changed from cancel to other status.
function deductProductsFromStock($recordId) {
global $adb;
$adb->pquery("UPDATE vtiger_inventoryproductrel SET incrementondel=1 WHERE id=?",array($recordId));
$product_info = $adb->pquery("SELECT productid,sequence_no, quantity from vtiger_inventoryproductrel WHERE id=?",array($recordId));
$numrows = $adb->num_rows($product_info);
for($index = 0;$index <$numrows;$index++) {
$productid = $adb->query_result($product_info,$index,'productid');
$qty = $adb->query_result($product_info,$index,'quantity');
$sequence_no = $adb->query_result($product_info,$index,'sequence_no');
$upd_qty = $qtyinstk-$qty;
updateProductQty($productid, $upd_qty);
$sub_prod_query = $adb->pquery("SELECT productid, quantity FROM vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($recordId,$sequence_no));
if($adb->num_rows($sub_prod_query)>0) {
for($j=0;$j<$adb->num_rows($sub_prod_query);$j++) {
$sub_prod_id = $adb->query_result($sub_prod_query,$j,"productid");
$subProductQty = $adb->query_result($sub_prod_query, $j, 'quantity');
$sqtyinstk= getProductQtyInStock($sub_prod_id);
$supd_qty = $sqtyinstk - ($qty * $subProductQty);
updateProductQty($sub_prod_id, $supd_qty);
}
}
}
}
// Add Products to stock - status changed to cancel or delete the invoice
function addProductsToStock($recordId) {
global $adb;
$product_info = $adb->pquery("SELECT productid,sequence_no, quantity from vtiger_inventoryproductrel WHERE id=?",array($recordId));
$numrows = $adb->num_rows($product_info);
for($index = 0;$index <$numrows;$index++) {
$productid = $adb->query_result($product_info,$index,'productid');
$qty = $adb->query_result($product_info,$index,'quantity');
$sequence_no = $adb->query_result($product_info,$index,'sequence_no');
$upd_qty = $qtyinstk+$qty;
updateProductQty($productid, $upd_qty);
$sub_prod_query = $adb->pquery("SELECT productid, quantity FROM vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?",array($recordId,$sequence_no));
if($adb->num_rows($sub_prod_query)>0) {
for($j=0;$j<$adb->num_rows($sub_prod_query);$j++) {
$sub_prod_id = $adb->query_result($sub_prod_query,$j,"productid");
$subProductQty = $adb->query_result($sub_prod_query, $j, 'quantity');
$sqtyinstk= getProductQtyInStock($sub_prod_id);
$supd_qty = $sqtyinstk + ($qty * $subProductQty);
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
updateProductQty($sub_prod_id, $supd_qty);
}
}
}
}
function getImportBatchLimit() {
$importBatchLimit = 100;
return $importBatchLimit;
}
function createRecords($obj) {
global $adb;
$moduleName = $obj->module;
$moduleHandler = vtws_getModuleHandlerFromName($moduleName, $obj->user);
$moduleMeta = $moduleHandler->getMeta();
$moduleObjectId = $moduleMeta->getEntityId();
$moduleFields = $moduleMeta->getModuleFields();
$focus = CRMEntity::getInstance($moduleName);
$tableName = Import_Utils_Helper::getDbTableName($obj->user);
$sql = 'SELECT * FROM ' . $tableName . ' WHERE status = ? GROUP BY subject';
$params[] = Import_Data_Action::$IMPORT_RECORD_NONE;
if($obj->batchImport) {
$importBatchLimit = getImportBatchLimit();
$sql .= ' LIMIT '. $importBatchLimit;
} else if ($obj->paging) {
$configReader = new Import_Config_Model();
$pagingLimit = $configReader->get('importPagingLimit');
$sql .= ' LIMIT '.$pagingLimit;
$result = $adb->pquery($sql, $params);
$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'];
$subject = str_replace("\\", "\\\\", $subject);
$subject = str_replace('"', '""', $subject);
$sql = "SELECT * FROM $tableName WHERE status = ? AND subject = ?";
$params = array();
array_push($params, Import_Data_Action::$IMPORT_RECORD_NONE, $subject);
$subjectResult = $adb->pquery($sql, $params);
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
$count = $adb->num_rows($subjectResult);
$subjectRowIDs = array();
for ($j = 0; $j < $count; ++$j) {
$subjectRow = $adb->raw_query_result_rowdata($subjectResult, $j);
array_push($subjectRowIDs, $subjectRow['id']);
if ($subjectRow['productid'] == '' || $subjectRow['quantity'] == '' || $subjectRow['listprice'] == '') {
continue;
} else {
$lineItemData = array();
foreach ($fieldMapping as $fieldName => $index) {
if($moduleFields[$fieldName]->getTableName() == 'vtiger_inventoryproductrel') {
$lineItemData[$fieldName] = $subjectRow[$fieldName];
}
}
array_push($lineItems,$lineItemData);
}
}
foreach ($fieldMapping as $fieldName => $index) {
$fieldData[$fieldName] = $row[strtolower($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'));
} else {
$entityIdComponents = vtws_getIdComponents($entityInfo['id']);
$createdRecords[] = $entityIdComponents[1];
}
foreach ($subjectRowIDs as $id) {
$obj->importedRecordInfo[$id] = $entityInfo;
$obj->updateImportStatus($id, $entityInfo);
}
}
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
//Creating entity data of created records to trigger inventory workflow supporting product quantity update
require_once 'modules/com_vtiger_workflow/VTEventHandler.inc';
if ($createdRecords) {
$inventoryModules = getInventoryModules();
$recordModels = Vtiger_Record_Model::getInstancesFromIds($createdRecords, $moduleName);
foreach ($recordModels as $recordModel) {
$keyLabel[$recordModel->get("id")]=$recordModel->get("subject");
$focus = $recordModel->getEntity();
$entityData = VTEntityData::fromCRMEntity($focus);
$moduleName = $entityData->getModuleName();
if (in_array($moduleName, $inventoryModules)) {
$workflowManger = new VTWorkflowManager($adb);
$workflowHandler = new VTWorkflowEventHandler();
$workflowHandler->workflows = $workflowManger->getInventoryWorkflowsSupportingProductQtyUpdate($moduleName);
$workflowHandler->handleEvent($eventName, $entityData);
}
}
$query = "UPDATE vtiger_crmentity SET label= CASE crmid";
foreach ($keyLabel as $id => $value) {
$query .= " WHEN '$id' THEN '$value' ";
}
$query .= ' ELSE label END';
$adb->pquery($query,array());
}
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
unset($result);
return true;
}
function isRecordExistInDB($fieldData, $moduleMeta, $user) {
global $adb, $log;
$moduleFields = $moduleMeta->getModuleFields();
$isRecordExist = false;
if (array_key_exists('productid', $fieldData)) {
$fieldName = 'productid';
$fieldValue = $fieldData[$fieldName];
$fieldInstance = $moduleFields[$fieldName];
if ($fieldInstance->getFieldDataType() == 'reference') {
$entityId = false;
if (!empty($fieldValue)) {
if(strpos($fieldValue, '::::') > 0) {
$fieldValueDetails = explode('::::', $fieldValue);
} else if (strpos($fieldValue, ':::') > 0) {
$fieldValueDetails = explode(':::', $fieldValue);
} else {
$fieldValueDetails = $fieldValue;
}
if (php7_count($fieldValueDetails) > 1) {
$referenceModuleName = trim($fieldValueDetails[0]);
$entityLabel = trim($fieldValueDetails[1]);
$entityId = getEntityId($referenceModuleName, decode_html($entityLabel));
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
} else {
$referencedModules = $fieldInstance->getReferenceList();
$entityLabel = $fieldValue;
foreach ($referencedModules as $referenceModule) {
$referenceModuleName = $referenceModule;
$referenceEntityId = getEntityId($referenceModule, $entityLabel);
if ($referenceEntityId != 0) {
$entityId = $referenceEntityId;
break;
}
}
}
if (!empty($entityId) && $entityId != 0) {
$types = vtws_listtypes(null, $user);
$accessibleModules = $types['types'];
if (in_array($referenceModuleName, $accessibleModules)) {
$isRecordExist = true;
}
}
}
}
}
return $isRecordExist;
}
function importRecord($obj, $inventoryFieldData, $lineItemDetails) {
global $adb, $log;
$moduleName = $obj->module;
$fieldMapping = $obj->fieldMapping;
$inventoryHandler = vtws_getModuleHandlerFromName($moduleName, $obj->user);
$inventoryMeta = $inventoryHandler->getMeta();
$moduleFields = $inventoryMeta->getModuleFields();
$isRecordExist = isRecordExistInDB($inventoryFieldData, $inventoryMeta, $obj->user);
$lineItemHandler = vtws_getModuleHandlerFromName('LineItem', $obj->user);
$lineItemMeta = $lineItemHandler->getMeta();
$lineItems = array();
foreach ($lineItemDetails as $index => $lineItemFieldData) {
$isLineItemExist = isRecordExistInDB($lineItemFieldData, $lineItemMeta, $obj->user);
if($isLineItemExist) {
$count = $index;
$lineItemData = array();
$lineItemFieldData = $obj->transformForImport($lineItemFieldData, $lineItemMeta);
foreach ($fieldMapping as $fieldName => $index) {
if($moduleFields[$fieldName]->getTableName() == 'vtiger_inventoryproductrel') {
$lineItemData[$fieldName] = $lineItemFieldData[$fieldName];
if($fieldName != 'productid')
$inventoryFieldData[$fieldName] = '';
}
}
array_push($lineItems,$lineItemData);
}
}
if (empty ($lineItems)) {
return null;
} elseif ($isRecordExist == false) {
foreach ($lineItemDetails[$count] as $key => $value) {
$inventoryFieldData[$key] = $value;
}
}
$fieldData = $obj->transformForImport($inventoryFieldData, $inventoryMeta);
if(empty($fieldData) || empty($lineItemDetails)) {
return null;
}
if ($fieldData['currency_id'] == ' ') {
$fieldData['currency_id'] = '1';
}
$fieldData['LineItems'] = $lineItems;
$webserviceObject = VtigerWebserviceObject::fromName($adb, $moduleName);
$inventoryOperation = new VtigerInventoryOperation($webserviceObject, $obj->user, $adb, $log);
$entityInfo = $inventoryOperation->create($moduleName, $fieldData);
$entityInfo['status'] = $obj->getImportRecordStatus('created');
return $entityInfo;
}
function getImportStatusCount($obj) {
global $adb;
$tableName = Import_Utils_Helper::getDbTableName($obj->user);
$result = $adb->pquery('SELECT status FROM '.$tableName. ' GROUP BY subject', array());
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
$statusCount = array('TOTAL' => 0, 'IMPORTED' => 0, 'FAILED' => 0, 'PENDING' => 0,
'CREATED' => 0, 'SKIPPED' => 0, 'UPDATED' => 0, 'MERGED' => 0);
if($result) {
$noOfRows = $adb->num_rows($result);
$statusCount['TOTAL'] = $noOfRows;
for($i=0; $i<$noOfRows; ++$i) {
$status = $adb->query_result($result, $i, 'status');
if($obj->getImportRecordStatus('none') == $status) {
$statusCount['PENDING']++;
} elseif($obj->getImportRecordStatus('failed') == $status) {
$statusCount['FAILED']++;
} else {
$statusCount['IMPORTED']++;
switch($status) {
case $obj->getImportRecordStatus('created') : $statusCount['CREATED']++;
break;
case $obj->getImportRecordStatus('skipped') : $statusCount['SKIPPED']++;
break;
case $obj->getImportRecordStatus('updated') : $statusCount['UPDATED']++;
break;
case $obj->getImportRecordStatus('merged') : $statusCount['MERGED']++;
break;
}
}
}
}
return $statusCount;
}
function undoLastImport($obj, $user) {
global $adb;
$moduleName = $obj->get('module');
$ownerId = $obj->get('foruser');
$owner = new Users();
$owner->id = $ownerId;
$owner->retrieve_entity_info($ownerId, 'Users');
if(!is_admin($user) && $user->id != $owner->id) {
$viewer = new Vtiger_Viewer();
$viewer->view('OperationNotPermitted.tpl', 'Vtiger');
exit;
}
$result = $adb->pquery("SELECT recordid FROM $dbTableName WHERE status = ? AND recordid IS NOT NULL GROUP BY subject", array(Import_Data_Controller::$IMPORT_RECORD_CREATED));
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
$noOfRecords = $adb->num_rows($result);
$noOfRecordsDeleted = 0;
for($i=0; $i<$noOfRecords; ++$i) {
$recordId = $adb->query_result($result, $i, 'recordid');
if(isRecordExists($recordId) && isPermitted($moduleName, 'Delete', $recordId) == 'yes') {
$focus = CRMEntity::getInstance($moduleName);
$focus->id = $recordId;
$focus->trash($moduleName, $recordId);
$noOfRecordsDeleted++;
}
}
$viewer = new Vtiger_Viewer();
$viewer->assign('FOR_MODULE', $moduleName);
$viewer->assign('TOTAL_RECORDS', $noOfRecords);
$viewer->assign('DELETED_RECORDS_COUNT', $noOfRecordsDeleted);
$viewer->view('ImportUndoResult.tpl');
}
function getInventoryFieldsForExport($tableName) {
$sql = ','.$tableName.'.adjustment AS "Adjustment", '.$tableName.'.total AS "Total", '.$tableName.'.subtotal AS "Sub Total", ';
$sql .= $tableName.'.taxtype AS "Tax Type", '.$tableName.'.discount_amount AS "Discount Amount", ';
$sql .= $tableName.'.discount_percent AS "Discount Percent", '.$tableName.'.s_h_amount AS "S&H Amount", ';
$sql .= 'vtiger_currency_info.currency_name as "Currency" ';
return $sql;
}
function getCurrencyId($fieldValue) {
global $adb;
$sql = 'SELECT id FROM vtiger_currency_info WHERE currency_name = ? AND deleted = 0';
$result = $adb->pquery($sql, array($fieldValue));
$currencyId = 1;
if ($adb->num_rows($result) > 0) {
$currencyId = $adb->query_result($result, 0, 'id');
}
return $currencyId;
}
/**
* Function used to get the lineitems fields
* @global type $adb
* @return type <array> - list of lineitem fields
*/
function getLineItemFields(){
global $adb;
$sql = 'SELECT DISTINCT columnname FROM vtiger_field WHERE tablename=?';
$result = $adb->pquery($sql, array('vtiger_inventoryproductrel'));
$lineItemdFields = array();
$num_rows = $adb->num_rows($result);
for($i=0; $i<$num_rows; $i++){
$lineItemdFields[] = $adb->query_result($result,$i, 'columnname');
}
return $lineItemdFields;
}
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
/**
* Function to get mandatory importable fields for Inventory modules.
* By default some fields like Quantity, List Price is not mandaroty for Invertory modules but
* import fails if those fields are not mapped during import.
*/
function getInventoryImportableMandatoryFeilds($module) {
$moduleModel = Vtiger_Module_Model::getInstance($module);
$moduleMeta = $moduleModel->getModuleMeta();
$moduleFields = $moduleMeta->getAccessibleFields($module);
$mandatoryFields = array();
foreach($moduleFields as $fieldName => $fieldInstance) {
if($fieldInstance->isMandatory() && $fieldInstance->getFieldDataType() != 'owner' && $moduleMeta->isEditableField($fieldInstance)) {
$mandatoryFields[$fieldName] = vtranslate($fieldInstance->getFieldLabelKey(), $module);
}
}
$defaultMandatoryFields = array('quantity', 'listprice');
foreach($defaultMandatoryFields as $fieldName) {
$fieldInstance = $moduleFields[$fieldName];
$mandatoryFields[$fieldName] = vtranslate($fieldInstance->getFieldLabelKey(), $module);
}
return $mandatoryFields;
}
/**
* Function to get all charges
* @return <Array>
*/
function getAllCharges() {
$db = PearDatabase::getInstance();
$allChargesInfo = array();
$result = $db->pquery('SELECT * FROM vtiger_inventorycharges WHERE deleted = 0', array());
while($rowData = $db->fetch_array($result)) {
$chargeInfo = array();
$chargeInfo['id'] = $rowData['chargeid'];
$chargeInfo['chargeid'] = $rowData['chargeid'];
$chargeInfo['name'] = $rowData['name'];
$chargeInfo['format'] = $rowData['format'];
$chargeInfo['type'] = $rowData['type'];
$chargeInfo['value'] = $rowData['value'];
$chargeInfo['istaxable']= $rowData['istaxable'];
$chargeInfo['deleted'] = $rowData['deleted'];
$chargeInfo['regions'] = Zend_Json::decode(html_entity_decode($rowData['regions']));
$chargeInfo['taxes'] = Zend_Json::decode(html_entity_decode($rowData['taxes']));
$allChargesInfo[$chargeInfo['id']] = $chargeInfo;
}
return $allChargesInfo;
}
/**
* Function to get all regions
* @return <Array>
*/
function getAllRegions() {
$db = PearDatabase::getInstance();
$allRegionsInfo = array();
$result = $db->pquery('SELECT * FROM vtiger_taxregions', array());
while($rowData = $db->fetch_array($result)) {
$allRegionsInfo[$rowData['regionid']] = array('id' => $rowData['regionid'], 'name' => $rowData['name']);
}
return $allRegionsInfo;
}
/**
* Function to get existing compound taxes for an inventory record
* @param <Number> $recordId
* @param <String> $moduleName
* @return <Array>
*/
function getCompoundTaxesInfoForInventoryRecord($recordId, $moduleName) {
$compoundTaxesInfo = array();
$tableName = '';
switch($moduleName) {
case 'Quotes' : $tableName = 'vtiger_quotes'; $index = 'quoteid'; break;
case 'Invoice' : $tableName = 'vtiger_invoice'; $index = 'invoiceid'; break;
case 'SalesOrder' : $tableName = 'vtiger_salesorder'; $index = 'salesorderid'; break;
case 'PurchaseOrder': $tableName = 'vtiger_purchaseorder'; $index = 'purchaseorderid'; break;
}
if ($recordId && $tableName) {
$db = PearDatabase::getInstance();
$result = $db->pquery("SELECT compound_taxes_info FROM $tableName WHERE $index = ?", array($recordId));
while($rowData = $db->fetch_array($result)) {
$info = $rowData['compound_taxes_info'];
if ($info !== NULL) {
$compoundTaxesInfo = Zend_Json::decode(html_entity_decode($info));
}
}
}
return $compoundTaxesInfo;
}