Passed
Push — developer ( a6dfc2...610d41 )
by Radosław
18:24
created

Vtiger_Inventory_Action::getCurrencyData()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 13
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 12
1
<?php
2
3
/**
4
 * Basic inventory action file.
5
 *
6
 * @package Action
7
 *
8
 * @copyright YetiForce S.A.
9
 * @license   YetiForce Public License 5.0 (licenses/LicenseEN.txt or yetiforce.com)
10
 * @author    Mariusz Krzaczkowski <[email protected]>
11
 * @author    Radosław Skrzypczak <[email protected]>
12
 */
13
14
/**
15
 * Basic inventory action class.
16
 */
17
class Vtiger_Inventory_Action extends \App\Controller\Action
18
{
19
	use \App\Controller\ExposeMethod;
20
21
	/** {@inheritdoc} */
22
	public function __construct()
23
	{
24
		parent::__construct();
25
		$this->exposeMethod('checkLimits');
26
		$this->exposeMethod('getDetails');
27
		$this->exposeMethod('getTableData');
28
		$this->exposeMethod('getCurrencyData');
29
	}
30
31
	/** {@inheritdoc} */
32
	public function checkPermission(App\Request $request)
33
	{
34
		$userPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
35
		if (!$userPrivilegesModel->hasModulePermission($request->getModule())) {
0 ignored issues
show
Bug introduced by
$request->getModule() of type string is incompatible with the type integer expected by parameter $mixed of Users_Privileges_Model::hasModulePermission(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

35
		if (!$userPrivilegesModel->hasModulePermission(/** @scrutinizer ignore-type */ $request->getModule())) {
Loading history...
36
			throw new \App\Exceptions\NoPermitted('LBL_PERMISSION_DENIED', 406);
37
		}
38
	}
39
40
	/**
41
	 * Function verifies whether the Account's credit limit has been reached.
42
	 *
43
	 * @param \App\Request $request
44
	 */
45
	public function checkLimits(App\Request $request)
46
	{
47
		$moduleName = $request->getModule();
48
		$record = $request->getInteger('record');
49
		if (!\App\Privilege::isPermitted($moduleName, 'EditView', $record)) {
50
			throw new \App\Exceptions\NoPermittedToRecord('ERR_NO_PERMISSIONS_FOR_THE_RECORD', 406);
51
		}
52
		$currency = $request->getInteger('currency');
53
		$price = $request->getByType('price', 'Double');
54
		$limitFieldName = 'creditlimit';
55
		$balanceFieldName = 'inventorybalance';
56
		$response = new Vtiger_Response();
57
58
		$moduleInstance = Vtiger_Module_Model::getInstance('Accounts');
59
		$limitField = Vtiger_Field_Model::getInstance($limitFieldName, $moduleInstance);
60
		$balanceField = Vtiger_Field_Model::getInstance($balanceFieldName, $moduleInstance);
61
		if (!$limitField->isActiveField() || !$balanceField->isActiveField()) {
62
			$response->setResult(['status' => true]);
63
			$response->emit();
64
65
			return;
66
		}
67
		$recordModel = Vtiger_Record_Model::getInstanceById($record, 'Accounts');
68
		$limitID = $recordModel->get($limitFieldName);
69
		$balance = $recordModel->get($balanceFieldName);
70
		if (!empty($limitID)) {
71
			$limit = Vtiger_InventoryLimit_UIType::getValues($limitID)['value'];
72
		} else {
73
			$response->setResult(['status' => true]);
74
			$response->emit();
75
76
			return;
77
		}
78
79
		$baseCurrency = Vtiger_Util_Helper::getBaseCurrency();
80
		$symbol = $baseCurrency['currency_symbol'];
81
		if ($baseCurrency['id'] != $currency) {
82
			$selectedCurrency = \App\Fields\Currency::getById($currency);
83
			$price = (float) $price * $selectedCurrency['conversion_rate'];
84
			$symbol = $selectedCurrency['currency_symbol'];
85
		}
86
		$totalPrice = $price + $balance;
87
88
		$status = $totalPrice > $limit ? false : true;
89
		if (!$status) {
90
			$viewer = new Vtiger_Viewer();
91
			$viewer->assign('PRICE', $price);
92
			$viewer->assign('BALANCE', $balance);
93
			$viewer->assign('SYMBOL', $symbol);
94
			$viewer->assign('LIMIT', $limit);
95
			$viewer->assign('TOTALS', $totalPrice);
96
			$html = $viewer->view('InventoryLimitAlert.tpl', $moduleName, true);
97
		}
98
		$response->setResult([
99
			'status' => $status,
100
			'html' => $html,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $html does not seem to be defined for all execution paths leading up to this point.
Loading history...
101
		]);
102
		$response->emit();
103
	}
104
105
	/**
106
	 * Get record details.
107
	 *
108
	 * @param App\Request $request
109
	 */
110
	public function getDetails(App\Request $request)
111
	{
112
		$currencyId = $request->getInteger('currency_id');
113
		$fieldName = $request->getByType('fieldname');
114
		$moduleName = $request->getModule();
115
		if ($request->isEmpty('idlist')) {
116
			$info = static::getRecordDetail($request->getInteger('record'), $currencyId, $moduleName, $fieldName);
117
		} else {
118
			foreach ($request->getArray('idlist', 'Integer') as $id) {
119
				$info[] = static::getRecordDetail($id, $currencyId, $moduleName, $fieldName);
120
			}
121
		}
122
		$response = new Vtiger_Response();
123
		$response->setResult($info);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $info does not seem to be defined for all execution paths leading up to this point.
Loading history...
124
		$response->emit();
125
	}
126
127
	/**
128
	 * Get record detail for inventory table.
129
	 *
130
	 * @param int      $recordId
131
	 * @param int|null $currencyId
132
	 * @param string   $moduleName
133
	 * @param string   $fieldName
134
	 *
135
	 * @throws \App\Exceptions\NoPermittedToRecord
136
	 *
137
	 * @return array
138
	 */
139
	public static function getRecordDetail(int $recordId, ?int $currencyId, string $moduleName, string $fieldName): array
140
	{
141
		$recordModel = Vtiger_Record_Model::getInstanceById($recordId);
142
		if (!$recordModel->isViewable()) {
143
			throw new \App\Exceptions\NoPermittedToRecord('ERR_NO_PERMISSIONS_FOR_THE_RECORD', 406);
144
		}
145
		$recordModuleName = $recordModel->getModuleName();
146
		$info = [
147
			'id' => $recordId,
148
			'name' => App\Purifier::decodeHtml($recordModel->getName()),
149
			'description' => $recordModel->get('description'),
150
		];
151
		$autoFields = [];
152
		$inventory = Vtiger_Inventory_Model::getInstance($moduleName);
153
		if ($autoCompleteField = ($inventory->getAutoCompleteFields()[$recordModuleName] ?? [])) {
154
			foreach ($autoCompleteField as $field) {
155
				$fieldModel = $recordModel->getField($field['field']);
156
				if ($fieldModel && ($fieldValue = $recordModel->get($field['field']))) {
157
					$autoFields[$field['tofield']] = $fieldModel->isReferenceField() ? $fieldValue : $fieldModel->getEditViewDisplayValue($fieldValue, $recordModel);
158
					$autoFields[$field['tofield'] . 'Text'] = $fieldModel->getDisplayValue($fieldValue, $recordId, $recordModel, true);
159
				}
160
			}
161
		}
162
		$info['autoFields'] = $autoFields;
163
		if (!$recordModel->isEmpty('taxes')) {
164
			if (false === strpos($recordModel->get('taxes'), ',')) {
165
				$taxModel = Settings_Inventory_Record_Model::getInstanceById($recordModel->get('taxes'), 'Taxes');
166
			} else {
167
				$productTaxes = explode(',', $recordModel->get('taxes'));
168
				$taxModel = Settings_Inventory_Record_Model::getInstanceById(reset($productTaxes), 'Taxes');
169
			}
170
			$info['taxes'] = [
171
				'type' => 'group',
172
				'value' => $taxModel->get('value'),
173
			];
174
		}
175
		$eventHandler = new App\EventHandler();
176
		$eventHandler->setRecordModel($recordModel);
177
		$eventHandler->setModuleName($recordModuleName);
178
		$eventHandler->setParams([
179
			'currencyId' => $currencyId,
180
			'moduleName' => $moduleName,
181
			'fieldName' => $fieldName,
182
			'info' => $info,
183
		]);
184
		$eventHandler->trigger('InventoryRecordDetails');
185
		$info = $eventHandler->getParam('info');
186
		return [$recordId => array_merge($info, $inventory->getCustomAutoComplete($fieldName, $recordModel))];
187
	}
188
189
	/**
190
	 * Get products and services from source invoice to display in correcting invoice before block.
191
	 *
192
	 * @param \App\Request $request
193
	 *
194
	 * @throws \App\Exceptions\IllegalValue
195
	 * @throws \App\Exceptions\NoPermittedToRecord
196
	 */
197
	public function getTableData(App\Request $request)
198
	{
199
		if ($request->isEmpty('src_record', true) || $request->isEmpty('src_module', true)) {
200
			throw new \App\Exceptions\NoPermittedToRecord('ERR_NO_PERMISSIONS_FOR_THE_RECORD', 406);
201
		}
202
		$srcModule = $request->getByType('src_module', \App\Purifier::ALNUM);
203
		$srcRecord = $request->getInteger('src_record');
204
		if (!\App\Privilege::isPermitted($srcModule, 'DetailView', $srcRecord)) {
205
			throw new \App\Exceptions\NoPermittedToRecord('ERR_NO_PERMISSIONS_FOR_THE_RECORD', 406);
206
		}
207
		$recordModel = Vtiger_Record_Model::getInstanceById($srcRecord, $srcModule);
208
		$inventoryModel = Vtiger_Inventory_Model::getInstance($srcModule);
209
		$data = $inventoryModel->transformData($recordModel->getInventoryData());
210
211
		foreach ($data as &$item) {
212
			$item['info'] = static::getRecordDetail($item['name'], $item['currency'] ?? 0, $request->getModule(), 'name')[$item['name']];
213
			$item['moduleName'] = \App\Record::getType($item['info']['id']);
214
			$item['basetableid'] = Vtiger_Module_Model::getInstance($item['moduleName'])->get('basetableid');
215
		}
216
217
		$response = new Vtiger_Response();
218
		$response->setResult(array_values($data));
219
		$response->emit();
220
	}
221
222
	/**
223
	 * Get cuurenct currency data with conversion rate and date.
224
	 *
225
	 * @param App\Request $request
226
	 */
227
	public function getCurrencyData(App\Request $request)
228
	{
229
		$currencies = [];
230
		$moduleName = $request->getModule();
231
		$fieldModel = \Vtiger_Inventory_Model::getInstance($moduleName)->getField('currency');
232
233
		if ($fieldModel && $fieldModel->getParamConfig('reset_currency')) {
234
			$currencies = $fieldModel->getCurrencyParam(\App\Fields\Currency::getAll(true));
0 ignored issues
show
Bug introduced by
The method getCurrencyParam() does not exist on Vtiger_Basic_InventoryField. It seems like you code against a sub-type of Vtiger_Basic_InventoryField such as Vtiger_Currency_InventoryField. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

234
			/** @scrutinizer ignore-call */ 
235
   $currencies = $fieldModel->getCurrencyParam(\App\Fields\Currency::getAll(true));
Loading history...
235
		}
236
237
		$response = new Vtiger_Response();
238
		$response->setResult($currencies);
239
		$response->emit();
240
	}
241
}
242