Passed
Push — developer ( 884b36...3fc379 )
by Radosław
32:13 queued 16:24
created

FInvoice_SummationByMonths_Dashboard::process()   B

Complexity

Conditions 8
Paths 24

Size

Total Lines 32
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 32
ccs 0
cts 22
cp 0
rs 8.4444
c 0
b 0
f 0
cc 8
nc 24
nop 1
crap 72
1
<?php
2
3
/**
4
 * FInvoice Summation By Months Dashboard Class.
5
 *
6
 * @copyright YetiForce S.A.
7
 * @license   YetiForce Public License 5.0 (licenses/LicenseEN.txt or yetiforce.com)
8
 * @author    Mariusz Krzaczkowski <[email protected]>
9
 * @author    Radosław Skrzypczak <[email protected]>
10
 */
11
class FInvoice_SummationByMonths_Dashboard extends Vtiger_IndexAjax_View
12
{
13
	private $conditions = false;
14
15
	/**
16
	 * Process.
17
	 *
18
	 * @param \App\Request $request
19
	 */
20
	public function process(App\Request $request)
21
	{
22
		$currentUserId = \App\User::getCurrentUserId();
23
		$viewer = $this->getViewer($request);
24
		$moduleName = $request->getModule();
25
		$widget = Vtiger_Widget_Model::getInstance($request->getInteger('linkid'), $currentUserId);
26
		if (!$request->has('owner')) {
27
			$owner = Settings_WidgetsManagement_Module_Model::getDefaultUserId($widget);
28
		} else {
29
			$owner = $request->getByType('owner', \App\Purifier::TEXT);
30
		}
31
		$fields = $this->getFilterFields($moduleName);
32
		foreach ($fields as $fieldModel) {
33
			if ($request->has($fieldModel->getName()) && '' !== ($value = $request->getForSql($fieldModel->getName())) && isset($fieldModel->getPicklistValues()[$value])) {
34
				$fieldModel->set('fieldvalue', $value);
35
			}
36
		}
37
		$data = $fields ? $this->getWidgetData($moduleName, $owner) : [];
38
		$viewer->assign('OWNER', $owner);
39
		$viewer->assign('DATA', $data);
40
		$viewer->assign('WIDGET', $widget);
41
		$viewer->assign('MODULE_NAME', $moduleName);
42
		$accessibleUsers = \App\Fields\Owner::getInstance($moduleName, $currentUserId)->getAccessibleUsersForModule();
43
		$accessibleGroups = \App\Fields\Owner::getInstance($moduleName, $currentUserId)->getAccessibleGroupForModule();
44
		$viewer->assign('ACCESSIBLE_USERS', $accessibleUsers);
45
		$viewer->assign('ACCESSIBLE_GROUPS', $accessibleGroups);
46
		$viewer->assign('USER_CONDITIONS', $this->conditions);
47
		$viewer->assign('FILTER_FIELDS', $fields);
48
		if ($request->has('content')) {
49
			$viewer->view('dashboards/SummationByMonthsContents.tpl', $moduleName);
50
		} else {
51
			$viewer->view('dashboards/SummationByMonths.tpl', $moduleName);
52
		}
53
	}
54
55
	/**
56
	 * Gets filter fields.
57
	 *
58
	 * @param string $moduleName
59
	 *
60
	 * @return \Vtiger_Field_Model[]
61
	 */
62
	public function getFilterFields($moduleName): array
63
	{
64
		if (!isset($this->filterFields)) {
65
			$this->filterFields = [];
0 ignored issues
show
Bug Best Practice introduced by
The property filterFields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
66
			$moduleModel = Vtiger_Module_Model::getInstance($moduleName);
67
			$fieldModel = $moduleModel->getFieldByName('sum_total');
68
			$fieldModelGross = $moduleModel->getFieldByName('sum_gross');
69
			$field = new \Vtiger_Field_Model();
70
			$field->set('name', 'sum_field')
71
				->set('column', 'sum_field')
72
				->set('label', 'DW_SUM_FIELD')
73
				->set('fromOutsideList', true)
74
				->set('uitype', 16)
75
				->set('icon', 'mdi mdi-sigma')
76
				->setModule($moduleModel);
77
			$picklistValues = [];
78
			if ($fieldModel && $fieldModel->isActiveField()) {
79
				$picklistValues[$fieldModel->getColumnName()] = \App\Language::translate($fieldModel->getFieldLabel(), $fieldModel->getModuleName());
0 ignored issues
show
Deprecated Code introduced by
The function Vtiger_Field_Model::getFieldLabel() has been deprecated: 7.0 Use $this->getLabel() ( Ignorable by Annotation )

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

79
				$picklistValues[$fieldModel->getColumnName()] = \App\Language::translate(/** @scrutinizer ignore-deprecated */ $fieldModel->getFieldLabel(), $fieldModel->getModuleName());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
80
				$field->set('fieldvalue', $fieldModel->getColumnName());
81
			}
82
			if ($fieldModelGross && $fieldModelGross->isActiveField()) {
83
				$picklistValues[$fieldModelGross->getColumnName()] = \App\Language::translate($fieldModelGross->getFieldLabel(), $fieldModelGross->getModuleName());
0 ignored issues
show
Deprecated Code introduced by
The function Vtiger_Field_Model::getFieldLabel() has been deprecated: 7.0 Use $this->getLabel() ( Ignorable by Annotation )

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

83
				$picklistValues[$fieldModelGross->getColumnName()] = \App\Language::translate(/** @scrutinizer ignore-deprecated */ $fieldModelGross->getFieldLabel(), $fieldModelGross->getModuleName());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
84
				$field->set('fieldvalue', $fieldModelGross->getColumnName());
85
			}
86
			if ($picklistValues) {
87
				$field->set('picklistValues', $picklistValues);
88
				$this->filterFields[$field->getName()] = $field;
89
			}
90
		}
91
		return $this->filterFields;
92
	}
93
94
	/**
95
	 * Get widget data.
96
	 *
97
	 * @param string     $moduleName
98
	 * @param int|string $owner
99
	 *
100
	 * @return array
101
	 */
102
	public function getWidgetData($moduleName, $owner)
103
	{
104
		$rawData = $years = [];
105
		$dateStart = ((int) date('Y') - 2) . '-01-01';
106
		$dateEnd = date('Y-m-d', strtotime('last day of december'));
107
		$date = "{$dateStart},{$dateEnd}";
108
		$queryGenerator = new \App\QueryGenerator($moduleName);
109
		$sumColumnName = $this->getFilterFields($moduleName)['sum_field']->get('fieldvalue') ?: 'sum_gross';
110
		$y = new \yii\db\Expression('extract(year FROM saledate)');
111
		$m = new \yii\db\Expression('extract(month FROM saledate)');
112
		$s = new \yii\db\Expression("SUM({$sumColumnName})");
113
		$fieldList = ['y' => $y, 'm' => $m, 's' => $s];
114
		$queryGenerator->setCustomColumn($fieldList);
115
		$queryGenerator->addCondition('saledate', $date, 'bw');
116
		if ('all' !== $owner) {
117
			$queryGenerator->addCondition('assigned_user_id', $owner, 'e');
118
		}
119
		$queryGenerator->setCustomGroup([new \yii\db\Expression('y'), new \yii\db\Expression('m')]);
120
		$query = $queryGenerator->createQuery();
121
		$dataReader = $query->createCommand()->query();
122
		while ($row = $dataReader->read()) {
123
			$rawData[$row['y']][$row['m']] = [round((float) $row['s'], 2)];
124
		}
125
		$dataReader->close();
126
127
		$chartData = [
128
			'dataset' => [],
129
			'show_chart' => (bool) \count($rawData),
130
		];
131
		$this->conditions = ['condition' => ['between', 'saledate', $dateStart, $dateEnd]];
132
		$yearsData = [];
133
		$chartData['show_chart'] = (bool) \count($rawData);
134
		$shortMonth = ['LBL_Jan', 'LBL_Feb', 'LBL_Mar', 'LBL_Apr', 'LBL_May', 'LBL_Jun',
135
			'LBL_Jul', 'LBL_Aug', 'LBL_Sep', 'LBL_Oct', 'LBL_Nov', 'LBL_Dec', ];
136
137
		$chartData['dataset']['dimensions'][] = 'months';
138
		for ($i = 0; $i < 12; ++$i) {
139
			$chartData['dataset']['source'][$i] = ['months' => App\Language::translate($shortMonth[$i])];
140
		}
141
		foreach ($rawData as $y => $raw) {
142
			$years[] = $y;
143
			if (!isset($yearsData[$y])) {
144
				$chartData['dataset']['dimensions'][] = "{$y}";
145
				$chartData['series'][] = ['type' => 'bar'];
146
				for ($m = 0; $m < 12; ++$m) {
147
					$chartData['dataset']['source'][$m]["{$y}"] = null;
148
				}
149
			}
150
			foreach ($raw as $m => $value) {
151
				$chartData['dataset']['source'][$m - 1][$y] = $value[0];
152
			}
153
		}
154
155
		return $chartData;
156
	}
157
}
158