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

getEstimatedValue()   B

Complexity

Conditions 7
Paths 20

Size

Total Lines 30
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 30
ccs 0
cts 21
cp 0
rs 8.6186
c 0
b 0
f 0
cc 7
nc 20
nop 3
crap 56
1
<?php
2
3
/**
4
 * Widget show estimated value sale.
5
 *
6
 * @copyright YetiForce S.A.
7
 * @license YetiForce Public License 5.0 (licenses/LicenseEN.txt or yetiforce.com)
8
 * @author Radosław Skrzypczak <[email protected]>
9
 */
10
class SSalesProcesses_TeamsEstimatedSales_Dashboard extends Vtiger_IndexAjax_View
11
{
12
	/**
13
	 * Function to get search params in address listview.
14
	 *
15
	 * @param int   $owner number id of user
16
	 * @param array $time
17
	 *
18
	 * @return string
19
	 */
20
	public function getSearchParams($owner, $time)
21
	{
22
		$conditions = [];
23
		$listSearchParams = [];
24
		if (!empty($owner)) {
25
			array_push($conditions, ['assigned_user_id', 'e', $owner]);
26
		}
27
		if (!empty($time)) {
28
			array_push($conditions, ['estimated_date', 'bw', implode(',', $time)]);
29
		}
30
		$listSearchParams[] = $conditions;
31
		return '&viewname=All&search_params=' . urlencode(json_encode($listSearchParams));
32
	}
33
34
	/**
35
	 * Gets query.
36
	 *
37
	 * @param array $time
38
	 * @param bool  $owner
39
	 *
40
	 * @return App\QueryGenerator
41
	 */
42
	public function getQuery(array $time, $owner = false): App\QueryGenerator
43
	{
44
		$sum = new \yii\db\Expression('SUM(estimated)');
45
		$queryGenerator = new \App\QueryGenerator('SSalesProcesses');
46
		$queryGenerator->setFields(['assigned_user_id'])
47
			->setCustomColumn(['estimated' => $sum])
48
			->setGroup('assigned_user_id')
49
			->addCondition('estimated_date', implode(',', $time), 'bw');
50
		if ('all' !== $owner) {
0 ignored issues
show
introduced by
The condition 'all' !== $owner is always true.
Loading history...
51
			$queryGenerator->addNativeCondition(['smownerid' => $owner]);
52
		}
53
54
		return $queryGenerator;
55
	}
56
57
	/**
58
	 * Get raw data.
59
	 *
60
	 * @param array $time
61
	 * @param int   $owner
62
	 * @param bool  $compare
63
	 *
64
	 * @return array
65
	 */
66
	public function getDataForWidget(array $time, $owner, $compare): array
67
	{
68
		$data = [];
69
		$dim = implode(',', $time);
70
		$currentData = $this->getQuery($time, $owner)->createQuery()->createCommand()->queryAllByGroup();
0 ignored issues
show
Bug introduced by
$owner of type integer is incompatible with the type boolean expected by parameter $owner of SSalesProcesses_TeamsEst...s_Dashboard::getQuery(). ( Ignorable by Annotation )

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

70
		$currentData = $this->getQuery($time, /** @scrutinizer ignore-type */ $owner)->createQuery()->createCommand()->queryAllByGroup();
Loading history...
71
		if ($compare) {
72
			$start = new \DateTime($time[0]);
73
			$endPeriod = clone $start;
74
			$end = new \DateTime($time[1]);
75
			$interval = (int) $start->diff($end)->format('%r%a');
76
			if ($time[0] !== $time[1]) {
77
				++$interval;
78
			}
79
			$endPeriod->modify('-1 days');
80
			$start->modify("-{$interval} days");
81
			$previousTime = [$start->format('Y-m-d'), $endPeriod->format('Y-m-d')];
82
			$previousData = $this->getQuery($previousTime, $owner)->createQuery()->createCommand()->queryAllByGroup();
83
84
			$dim2 = implode(',', $previousTime);
85
86
			foreach ($currentData as $ownerId => $value) {
87
				$data[$ownerId][$dim2] = $previousData[$ownerId] ?? 0;
88
				$data[$ownerId][$dim] = $value;
89
			}
90
			foreach ($previousData as $ownerId => $value) {
91
				if (isset($data[$ownerId])) {
92
					$data[$ownerId][$dim2] = $value;
93
					$data[$ownerId][$dim] = $currentData[$ownerId] ?? 0;
94
				}
95
			}
96
		} else {
97
			foreach ($currentData as $ownerId => $value) {
98
				$data[$ownerId][$dim] = $value;
99
			}
100
		}
101
102
		return $data;
103
	}
104
105
	/**
106
	 * Function to get data to chart.
107
	 *
108
	 * @param array $time
109
	 * @param int   $owner
110
	 * @param bool  $compare
111
	 *
112
	 * @return array
113
	 */
114
	public function getEstimatedValue(array $time, $owner, $compare): array
115
	{
116
		$listViewUrl = Vtiger_Module_Model::getInstance('SSalesProcesses')->getListViewUrl();
117
		$data = $this->getDataForWidget($time, $owner, $compare);
118
		$xAxisData = array_keys($data);
119
		foreach ($data as $ownerId => $row) {
120
			$label = \App\Fields\Owner::getLabel($ownerId);
121
			$color = \App\Fields\Owner::getColor($ownerId);
122
			$seriesIndex = 0;
123
			foreach ($row as $dim => $value) {
124
				$setColor = \count($row) > 1 && 0 === $seriesIndex;
125
				$timeFormat = \App\Fields\Date::formatRangeToDisplay(explode(',', $dim));
126
				$chartData['series'][$seriesIndex]['name'] = implode(',', $timeFormat);
127
				$chartData['series'][$seriesIndex]['type'] = 'bar';
128
				$chartData['series'][$seriesIndex]['color'] = $setColor ? '#EDC240' : $color;
129
				$chartData['series'][$seriesIndex]['label'] = ['show' => true];
130
				$statusIndex = array_search($ownerId, $xAxisData);
131
				$chartData['series'][$seriesIndex]['data'][$statusIndex] = ['value' => round($value, 2), 'itemStyle' => ['color' => $setColor ? '#EDC240' : $color],
132
					'link' => $listViewUrl . '&viewname=All&entityState=Active' . $this->getSearchParams($ownerId, $timeFormat),
133
					'fullLabel' => $label];
134
				++$seriesIndex;
135
			}
136
		}
137
138
		foreach ($xAxisData as $ownerId) {
139
			$chartData['xAxis']['data'][] = \App\Utils::getInitials(\App\Fields\Owner::getLabel($ownerId));
140
		}
141
		$chartData['show_chart'] = !empty($xAxisData);
142
143
		return $chartData;
144
	}
145
146
	/**
147
	 * Main function.
148
	 *
149
	 * @param \App\Request $request
150
	 */
151
	public function process(App\Request $request)
152
	{
153
		$currentUserId = \App\User::getCurrentUserId();
154
		$viewer = $this->getViewer($request);
155
		$moduleName = $request->getModule();
156
		$time = $request->getDateRange('time');
157
		$compare = $request->getBoolean('compare');
158
		$widget = Vtiger_Widget_Model::getInstance($request->getInteger('linkid'), $currentUserId);
159
		if (empty($time)) {
160
			$time = Settings_WidgetsManagement_Module_Model::getDefaultDateRange($widget);
161
		}
162
		if (!$request->has('owner')) {
163
			$owner = Settings_WidgetsManagement_Module_Model::getDefaultUserId($widget, 'Accounts');
164
		} else {
165
			$owner = $request->getByType('owner', 2);
166
		}
167
168
		$data = $this->getEstimatedValue($time, $owner, $compare);
169
170
		$viewer->assign('WIDGET', $widget);
171
		$viewer->assign('MODULE_NAME', $moduleName);
172
		$viewer->assign('DATA', $data);
173
		$viewer->assign('DTIME', implode(',', \App\Fields\Date::formatRangeToDisplay($time)));
174
		$viewer->assign('COMPARE', $compare);
175
		$viewer->assign('ACCESSIBLE_USERS', \App\Fields\Owner::getInstance('Accounts', $currentUserId)->getAccessibleUsersForModule());
176
		$viewer->assign('ACCESSIBLE_GROUPS', \App\Fields\Owner::getInstance('Accounts', $currentUserId)->getAccessibleGroupForModule());
177
		if ($request->has('content')) {
178
			$viewer->view('dashboards/DashBoardWidgetContents.tpl', $moduleName);
179
		} else {
180
			$viewer->view('dashboards/TeamsEstimatedSales.tpl', $moduleName);
181
		}
182
	}
183
}
184