Passed
Pull Request — master (#444)
by Brian
10:32
created

GetPaid_Reports_Report_Earnings::display_graph()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 20
rs 9.9666
1
<?php
2
/**
3
 * Contains the class that displays the earnings report.
4
 *
5
 *
6
 */
7
8
defined( 'ABSPATH' ) || exit;
9
10
/**
11
 * GetPaid_Reports_Report_Earnings Class.
12
 */
13
class GetPaid_Reports_Report_Earnings extends GetPaid_Reports_Abstract_Report {
14
15
	/**
16
	 * Retrieves the earning graphs.
17
	 *
18
	 */
19
	public function get_graphs() {
20
21
		$graphs = array(
22
23
            'total'      => __( 'Earnings', 'invoicing' ),
24
            'discount'   => __( 'Discount', 'invoicing' ),
25
			'fees_total' => __( 'Fees', 'invoicing' ),
26
			'tax'        => __( 'Tax', 'invoicing' ),
27
28
		);
29
30
		return apply_filters( 'getpaid_earning_graphs', $graphs );
31
32
	}
33
34
	/**
35
	 * Retrieves the earning sql.
36
	 *
37
	 */
38
	public function get_sql( $range ) {
39
		global $wpdb;
40
41
		$table      = $wpdb->prefix . 'getpaid_invoices';
42
		$clauses    = $this->get_range_sql( $range );
43
		$graphs     = array_keys( $this->get_graphs() );
44
		$graphs_sql = array();
45
46
		foreach ( $graphs as $graph ) {
47
			$graphs_sql[] = "SUM( meta.$graph ) AS $graph";
48
		}
49
50
		$graphs_sql = implode( ', ', $graphs_sql );
51
		$sql        = "SELECT {$clauses[0]} AS completed_date, $graphs_sql
52
            FROM $wpdb->posts
53
            LEFT JOIN $table as meta ON meta.post_id = $wpdb->posts.ID
54
            WHERE meta.post_id IS NOT NULL
55
                AND $wpdb->posts.post_type = 'wpi_invoice'
56
                AND ( $wpdb->posts.post_status = 'publish' OR $wpdb->posts.post_status = 'wpi-renewal' )
57
                AND {$clauses[1]}
58
            GROUP BY {$clauses[0]}
59
        ";
60
61
		return apply_filters( 'getpaid_earning_graphs_get_sql', $sql, $range );
62
63
	}
64
65
	/**
66
	 * Prepares the report stats.
67
	 *
68
	 */
69
	public function prepare_stats() {
70
		global $wpdb;
71
		$this->stats = $wpdb->get_results( $this->get_sql( $this->get_range() ) );
72
	}
73
74
	/**
75
	 * Retrieves report labels.
76
	 *
77
	 */
78
	public function get_labels( $range ) {
79
80
		$labels = array(
81
			'today'     => $this->get_hours_in_a_day(),
82
			'yesterday' => $this->get_hours_in_a_day(),
83
			'7_days'    => $this->get_days_in_period( 7 ),
84
			'30_days'   => $this->get_days_in_period( 30 ),
85
			'60_days'   => $this->get_days_in_period( 60 ),
86
			'90_days'   => $this->get_weeks_in_period( 90 ),
87
			'180_days'  => $this->get_weeks_in_period( 180 ),
88
			'360_days'  => $this->get_weeks_in_period( 360 ),
89
		);
90
91
		$label = isset( $labels[ $range ] ) ? $labels[ $range ] : $labels[ '7_days' ];
92
		return apply_filters( 'getpaid_earning_graphs_get_labels', $label, $range );
93
	}
94
95
	/**
96
	 * Retrieves report datasets.
97
	 *
98
	 */
99
	public function get_datasets( $labels ) {
100
101
		$datasets = array();
102
103
		foreach ( $this->get_graphs() as $key => $label ) {
104
			$datasets[ $key ] = array(
105
				'label' => $label,
106
				'data'  => $this->get_data( $key, $labels )
107
			);
108
		}
109
110
		return apply_filters( 'getpaid_earning_graphs_get_datasets', $datasets, $key, $labels );
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $key seems to be defined by a foreach iteration on line 103. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
111
	}
112
113
	/**
114
	 * Retrieves report data.
115
	 *
116
	 */
117
	public function get_data( $key, $labels ) {
118
119
		$data     = wp_list_pluck( $this->stats, $key, 'completed_date' );
120
		$prepared = array();
121
122
		foreach ( $labels as $label ) {
123
124
			$value = 0;
125
			if ( isset( $data[ $label ] ) ) {
126
				$value = wpinv_round_amount( wpinv_sanitize_amount( $data[ $label ] ) );
127
			}
128
129
			$prepared[] = $value;
130
		}
131
132
		return apply_filters( 'getpaid_earning_graphs_get_data', $prepared, $key, $labels );
133
134
	}
135
136
	/**
137
	 * Displays the report card.
138
	 *
139
	 */
140
	public function display() {
141
142
		$labels     = $this->get_labels( $this->get_range() );
143
		$chart_data = array(
144
			'labels'   => array_values( $labels ),
145
			'datasets' => $this->get_datasets( array_keys( $labels ) ),
146
		);
147
148
		?>
149
150
			<?php foreach ( $chart_data['datasets'] as $key => $dataset ) : ?>
151
				<div class="row mb-4">
152
					<div class="col-12">
153
						<div class="card m-0 p-0" style="max-width:100%">
154
							<div class="card-header d-flex align-items-center">
155
								<strong class="flex-grow-1"><?php echo $dataset['label']; ?></strong>
156
								<?php $this->display_range_selector(); ?>
157
							</div>
158
							<div class="card-body">
159
								<?php $this->display_graph( $key, $dataset, $chart_data['labels'] ); ?>
160
							</div>
161
						</div>
162
					</div>
163
				</div>
164
			<?php endforeach; ?>
165
166
		<?php
167
168
	}
169
170
	/**
171
	 * Displays the actual report.
172
	 *
173
	 */
174
	public function display_graph( $key, $dataset, $labels ) {
175
176
		?>
177
178
		<canvas id="getpaid-chartjs-earnings-<?php echo sanitize_key( $key ); ?>"></canvas>
179
180
		<script>
181
			window.addEventListener( 'DOMContentLoaded', function() {
182
183
				var ctx = document.getElementById( 'getpaid-chartjs-earnings-<?php echo sanitize_key( $key ); ?>' ).getContext('2d');
184
				new Chart(
185
					ctx,
186
					{
187
						type: 'line',
188
						data: {
189
							'labels': <?php echo wp_json_encode( $labels ); ?>,
0 ignored issues
show
Bug introduced by
Are you sure wp_json_encode($labels) of type false|string can be used in echo? ( Ignorable by Annotation )

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

189
							'labels': <?php echo /** @scrutinizer ignore-type */ wp_json_encode( $labels ); ?>,
Loading history...
190
							'datasets': [
191
								{
192
									label: '<?php echo esc_attr( $dataset['label'] ); ?>',
193
									data: <?php echo wp_json_encode( $dataset['data'] ); ?>,
0 ignored issues
show
Bug introduced by
Are you sure wp_json_encode($dataset['data']) of type false|string can be used in echo? ( Ignorable by Annotation )

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

193
									data: <?php echo /** @scrutinizer ignore-type */ wp_json_encode( $dataset['data'] ); ?>,
Loading history...
194
									backgroundColor: 'rgba(54, 162, 235, 0.1)',
195
									borderColor: 'rgb(54, 162, 235)',
196
									borderWidth: 4,
197
									pointBackgroundColor: 'rgb(54, 162, 235)'
198
								}
199
							]
200
						},
201
						options: {
202
							scales: {
203
								yAxes: [{
204
									ticks: {
205
										beginAtZero: true
206
									}
207
								}],
208
								xAxes: [{
209
									ticks: {
210
										maxTicksLimit: 15
211
									}
212
                    			}]
213
							},
214
							legend: {
215
    							display: false
216
    						}
217
						}
218
					}
219
				);
220
221
			})
222
223
		</script>
224
225
		<?php
226
	}
227
228
	/**
229
	 * Displays the actual report.
230
	 *
231
	 */
232
	public function display_stats() {}
233
234
	/**
235
	 * Displays the range selector.
236
	 *
237
	 */
238
	public function display_range_selector() {
239
240
		?>
241
242
			<form method="get" class="getpaid-filter-earnings">
243
				<?php
244
245
					getpaid_hidden_field( 'page', 'wpinv-reports' );
246
					getpaid_hidden_field( 'tab', 'reports' );
247
248
					$html = aui()->select(
249
						array(
250
							'name'        => 'date_range',
251
							'id'          => 'view' . uniqid( '_' ),
252
							'placeholder' => __( 'Select a date range', 'invoicing' ),
253
							'label'       => __( 'Date Range', 'invoicing' ),
254
							'options'     => $this->get_periods(),
255
							'value'       => $this->get_range(),
256
							'no_wrap'     => true,
257
							'extra_attributes' => array(
258
								'onChange'        => 'this.form.submit()',
259
							),
260
						)
261
					);
262
263
					echo str_replace( 'custom-select', '', $html );
264
				?>
265
266
			</form>
267
268
		<?php
269
	}
270
271
}
272