Passed
Push — master ( c9620c...0d5a04 )
by Brian
04:05
created
includes/class-wpinv-api.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@  discard block
 block discarded – undo
6 6
  * @since    1.0.19
7 7
  */
8 8
 
9
-defined( 'ABSPATH' ) || exit;
9
+defined('ABSPATH') || exit;
10 10
 
11 11
 /**
12 12
  * The main API class
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
         $this->sales     = new GetPaid_REST_Report_Sales_Controller();
73 73
 
74 74
         // Fires after loading the rest api.
75
-        do_action( 'getpaid_rest_api_loaded', $this );
75
+        do_action('getpaid_rest_api_loaded', $this);
76 76
     }
77 77
 
78 78
 }
Please login to merge, or discard this patch.
includes/api/class-getpaid-rest-reports-controller.php 2 patches
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -18,184 +18,184 @@
 block discarded – undo
18 18
  */
19 19
 class GetPaid_REST_Reports_Controller extends GetPaid_REST_Controller {
20 20
 
21
-	/**
22
-	 * Route base.
23
-	 *
24
-	 * @var string
25
-	 */
26
-	protected $rest_base = 'reports';
27
-
28
-	/**
29
-	 * Registers the routes for the objects of the controller.
30
-	 *
31
-	 * @since 2.0.0
32
-	 *
33
-	 * @see register_rest_route()
34
-	 */
35
-	public function register_namespace_routes( $namespace ) {
36
-
37
-		// List all available reports.
38
-		register_rest_route(
39
-			$namespace,
40
-			$this->rest_base,
41
-			array(
42
-				array(
43
-					'methods'             => WP_REST_Server::READABLE,
44
-					'callback'            => array( $this, 'get_items' ),
45
-					'permission_callback' => array( $this, 'get_items_permissions_check' ),
46
-					'args'                => $this->get_collection_params(),
47
-				),
48
-				'schema' => array( $this, 'get_public_item_schema' ),
49
-			)
50
-		);
51
-
52
-	}
53
-
54
-	/**
55
-	 * Makes sure the current user has access to READ the report APIs.
56
-	 *
57
-	 * @since  2.0.0
58
-	 * @param WP_REST_Request $request Full data about the request.
59
-	 * @return WP_Error|boolean
60
-	 */
61
-	public function get_items_permissions_check( $request ) {
62
-
63
-		if ( ! wpinv_current_user_can_manage_invoicing() ) {
64
-			return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
65
-		}
66
-
67
-		return true;
68
-	}
69
-
70
-	/**
71
-	 * Get reports list.
72
-	 *
73
-	 * @since 2.0.0
74
-	 * @return array
75
-	 */
76
-	protected function get_reports() {
77
-
78
-		$reports = array(
79
-			array(
80
-				'slug'        => 'sales',
81
-				'description' => __( 'List of sales reports.', 'invoicing' ),
82
-			),
83
-			array(
84
-				'slug'        => 'top_sellers',
85
-				'description' => __( 'List of top selling items.', 'invoicing' ),
86
-			),
87
-			array(
88
-				'slug'        => 'invoices/totals',
89
-				'description' => __( 'Invoice totals.', 'invoicing' ),
90
-			),
91
-			array(
92
-				'slug'        => 'items/totals',
93
-				'description' => __( 'Item totals.', 'invoicing' ),
94
-			),
95
-			array(
96
-				'slug'        => 'customers/totals',
97
-				'description' => __( 'Customer totals.', 'invoicing' ),
98
-			),
99
-			array(
100
-				'slug'        => 'discounts/totals',
101
-				'description' => __( 'Discount totals.', 'invoicing' ),
102
-			)
103
-		);
104
-
105
-		return apply_filters( 'getpaid_available_api_reports', $reports );
106
-
107
-	}
108
-
109
-	/**
110
-	 * Get all reports.
111
-	 *
112
-	 * @since 2.0.0
113
-	 * @param WP_REST_Request $request
114
-	 * @return array|WP_Error
115
-	 */
116
-	public function get_items( $request ) {
117
-		$data    = array();
118
-		$reports = $this->get_reports();
119
-
120
-		foreach ( $reports as $report ) {
121
-			$item   = $this->prepare_item_for_response( (object) $report, $request );
122
-			$data[] = $this->prepare_response_for_collection( $item );
123
-		}
124
-
125
-		return rest_ensure_response( $data );
126
-	}
127
-
128
-	/**
129
-	 * Prepare a report object for serialization.
130
-	 *
131
-	 * @since 2.0.0
132
-	 * @param stdClass $report Report data.
133
-	 * @param WP_REST_Request $request Request object.
134
-	 * @return WP_REST_Response $response Response data.
135
-	 */
136
-	public function prepare_item_for_response( $report, $request ) {
137
-		$data = array(
138
-			'slug'        => $report->slug,
139
-			'description' => $report->description,
140
-		);
141
-
142
-		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
143
-		$data = $this->add_additional_fields_to_object( $data, $request );
144
-		$data = $this->filter_response_by_context( $data, $context );
145
-
146
-		// Wrap the data in a response object.
147
-		$response = rest_ensure_response( $data );
148
-		$response->add_links( array(
149
-			'self' => array(
150
-				'href' => rest_url( sprintf( '/%s/%s/%s', $this->namespace, $this->rest_base, $report->slug ) ),
151
-			),
152
-			'collection' => array(
153
-				'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
154
-			),
155
-		) );
156
-
157
-		return apply_filters( 'getpaid_rest_prepare_report', $response, $report, $request );
158
-	}
159
-
160
-	/**
161
-	 * Get the Report's schema, conforming to JSON Schema.
162
-	 *
163
-	 * @since 2.0.0
164
-	 * @return array
165
-	 */
166
-	public function get_item_schema() {
167
-		$schema = array(
168
-			'$schema'    => 'http://json-schema.org/draft-04/schema#',
169
-			'title'      => 'report',
170
-			'type'       => 'object',
171
-			'properties' => array(
172
-				'slug' => array(
173
-					'description' => __( 'An alphanumeric identifier for the resource.', 'invoicing' ),
174
-					'type'        => 'string',
175
-					'context'     => array( 'view' ),
176
-					'readonly'    => true,
177
-				),
178
-				'description' => array(
179
-					'description' => __( 'A human-readable description of the resource.', 'invoicing' ),
180
-					'type'        => 'string',
181
-					'context'     => array( 'view' ),
182
-					'readonly'    => true,
183
-				),
184
-			),
185
-		);
186
-
187
-		return $this->add_additional_fields_schema( $schema );
188
-	}
189
-
190
-	/**
191
-	 * Get the query params for collections.
192
-	 *
193
-	 * @since 2.0.0
194
-	 * @return array
195
-	 */
196
-	public function get_collection_params() {
197
-		return array(
198
-			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
199
-		);
200
-	}
21
+    /**
22
+     * Route base.
23
+     *
24
+     * @var string
25
+     */
26
+    protected $rest_base = 'reports';
27
+
28
+    /**
29
+     * Registers the routes for the objects of the controller.
30
+     *
31
+     * @since 2.0.0
32
+     *
33
+     * @see register_rest_route()
34
+     */
35
+    public function register_namespace_routes( $namespace ) {
36
+
37
+        // List all available reports.
38
+        register_rest_route(
39
+            $namespace,
40
+            $this->rest_base,
41
+            array(
42
+                array(
43
+                    'methods'             => WP_REST_Server::READABLE,
44
+                    'callback'            => array( $this, 'get_items' ),
45
+                    'permission_callback' => array( $this, 'get_items_permissions_check' ),
46
+                    'args'                => $this->get_collection_params(),
47
+                ),
48
+                'schema' => array( $this, 'get_public_item_schema' ),
49
+            )
50
+        );
51
+
52
+    }
53
+
54
+    /**
55
+     * Makes sure the current user has access to READ the report APIs.
56
+     *
57
+     * @since  2.0.0
58
+     * @param WP_REST_Request $request Full data about the request.
59
+     * @return WP_Error|boolean
60
+     */
61
+    public function get_items_permissions_check( $request ) {
62
+
63
+        if ( ! wpinv_current_user_can_manage_invoicing() ) {
64
+            return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
65
+        }
66
+
67
+        return true;
68
+    }
69
+
70
+    /**
71
+     * Get reports list.
72
+     *
73
+     * @since 2.0.0
74
+     * @return array
75
+     */
76
+    protected function get_reports() {
77
+
78
+        $reports = array(
79
+            array(
80
+                'slug'        => 'sales',
81
+                'description' => __( 'List of sales reports.', 'invoicing' ),
82
+            ),
83
+            array(
84
+                'slug'        => 'top_sellers',
85
+                'description' => __( 'List of top selling items.', 'invoicing' ),
86
+            ),
87
+            array(
88
+                'slug'        => 'invoices/totals',
89
+                'description' => __( 'Invoice totals.', 'invoicing' ),
90
+            ),
91
+            array(
92
+                'slug'        => 'items/totals',
93
+                'description' => __( 'Item totals.', 'invoicing' ),
94
+            ),
95
+            array(
96
+                'slug'        => 'customers/totals',
97
+                'description' => __( 'Customer totals.', 'invoicing' ),
98
+            ),
99
+            array(
100
+                'slug'        => 'discounts/totals',
101
+                'description' => __( 'Discount totals.', 'invoicing' ),
102
+            )
103
+        );
104
+
105
+        return apply_filters( 'getpaid_available_api_reports', $reports );
106
+
107
+    }
108
+
109
+    /**
110
+     * Get all reports.
111
+     *
112
+     * @since 2.0.0
113
+     * @param WP_REST_Request $request
114
+     * @return array|WP_Error
115
+     */
116
+    public function get_items( $request ) {
117
+        $data    = array();
118
+        $reports = $this->get_reports();
119
+
120
+        foreach ( $reports as $report ) {
121
+            $item   = $this->prepare_item_for_response( (object) $report, $request );
122
+            $data[] = $this->prepare_response_for_collection( $item );
123
+        }
124
+
125
+        return rest_ensure_response( $data );
126
+    }
127
+
128
+    /**
129
+     * Prepare a report object for serialization.
130
+     *
131
+     * @since 2.0.0
132
+     * @param stdClass $report Report data.
133
+     * @param WP_REST_Request $request Request object.
134
+     * @return WP_REST_Response $response Response data.
135
+     */
136
+    public function prepare_item_for_response( $report, $request ) {
137
+        $data = array(
138
+            'slug'        => $report->slug,
139
+            'description' => $report->description,
140
+        );
141
+
142
+        $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
143
+        $data = $this->add_additional_fields_to_object( $data, $request );
144
+        $data = $this->filter_response_by_context( $data, $context );
145
+
146
+        // Wrap the data in a response object.
147
+        $response = rest_ensure_response( $data );
148
+        $response->add_links( array(
149
+            'self' => array(
150
+                'href' => rest_url( sprintf( '/%s/%s/%s', $this->namespace, $this->rest_base, $report->slug ) ),
151
+            ),
152
+            'collection' => array(
153
+                'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
154
+            ),
155
+        ) );
156
+
157
+        return apply_filters( 'getpaid_rest_prepare_report', $response, $report, $request );
158
+    }
159
+
160
+    /**
161
+     * Get the Report's schema, conforming to JSON Schema.
162
+     *
163
+     * @since 2.0.0
164
+     * @return array
165
+     */
166
+    public function get_item_schema() {
167
+        $schema = array(
168
+            '$schema'    => 'http://json-schema.org/draft-04/schema#',
169
+            'title'      => 'report',
170
+            'type'       => 'object',
171
+            'properties' => array(
172
+                'slug' => array(
173
+                    'description' => __( 'An alphanumeric identifier for the resource.', 'invoicing' ),
174
+                    'type'        => 'string',
175
+                    'context'     => array( 'view' ),
176
+                    'readonly'    => true,
177
+                ),
178
+                'description' => array(
179
+                    'description' => __( 'A human-readable description of the resource.', 'invoicing' ),
180
+                    'type'        => 'string',
181
+                    'context'     => array( 'view' ),
182
+                    'readonly'    => true,
183
+                ),
184
+            ),
185
+        );
186
+
187
+        return $this->add_additional_fields_schema( $schema );
188
+    }
189
+
190
+    /**
191
+     * Get the query params for collections.
192
+     *
193
+     * @since 2.0.0
194
+     * @return array
195
+     */
196
+    public function get_collection_params() {
197
+        return array(
198
+            'context' => $this->get_context_param( array( 'default' => 'view' ) ),
199
+        );
200
+    }
201 201
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
  * @since   2.0.0
10 10
  */
11 11
 
12
-defined( 'ABSPATH' ) || exit;
12
+defined('ABSPATH') || exit;
13 13
 
14 14
 /**
15 15
  * GetPaid REST reports controller class.
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
 	 *
33 33
 	 * @see register_rest_route()
34 34
 	 */
35
-	public function register_namespace_routes( $namespace ) {
35
+	public function register_namespace_routes($namespace) {
36 36
 
37 37
 		// List all available reports.
38 38
 		register_rest_route(
@@ -41,11 +41,11 @@  discard block
 block discarded – undo
41 41
 			array(
42 42
 				array(
43 43
 					'methods'             => WP_REST_Server::READABLE,
44
-					'callback'            => array( $this, 'get_items' ),
45
-					'permission_callback' => array( $this, 'get_items_permissions_check' ),
44
+					'callback'            => array($this, 'get_items'),
45
+					'permission_callback' => array($this, 'get_items_permissions_check'),
46 46
 					'args'                => $this->get_collection_params(),
47 47
 				),
48
-				'schema' => array( $this, 'get_public_item_schema' ),
48
+				'schema' => array($this, 'get_public_item_schema'),
49 49
 			)
50 50
 		);
51 51
 
@@ -58,10 +58,10 @@  discard block
 block discarded – undo
58 58
 	 * @param WP_REST_Request $request Full data about the request.
59 59
 	 * @return WP_Error|boolean
60 60
 	 */
61
-	public function get_items_permissions_check( $request ) {
61
+	public function get_items_permissions_check($request) {
62 62
 
63
-		if ( ! wpinv_current_user_can_manage_invoicing() ) {
64
-			return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
63
+		if (!wpinv_current_user_can_manage_invoicing()) {
64
+			return new WP_Error('rest_cannot_view', __('Sorry, you cannot list resources.', 'invoicing'), array('status' => rest_authorization_required_code()));
65 65
 		}
66 66
 
67 67
 		return true;
@@ -78,31 +78,31 @@  discard block
 block discarded – undo
78 78
 		$reports = array(
79 79
 			array(
80 80
 				'slug'        => 'sales',
81
-				'description' => __( 'List of sales reports.', 'invoicing' ),
81
+				'description' => __('List of sales reports.', 'invoicing'),
82 82
 			),
83 83
 			array(
84 84
 				'slug'        => 'top_sellers',
85
-				'description' => __( 'List of top selling items.', 'invoicing' ),
85
+				'description' => __('List of top selling items.', 'invoicing'),
86 86
 			),
87 87
 			array(
88 88
 				'slug'        => 'invoices/totals',
89
-				'description' => __( 'Invoice totals.', 'invoicing' ),
89
+				'description' => __('Invoice totals.', 'invoicing'),
90 90
 			),
91 91
 			array(
92 92
 				'slug'        => 'items/totals',
93
-				'description' => __( 'Item totals.', 'invoicing' ),
93
+				'description' => __('Item totals.', 'invoicing'),
94 94
 			),
95 95
 			array(
96 96
 				'slug'        => 'customers/totals',
97
-				'description' => __( 'Customer totals.', 'invoicing' ),
97
+				'description' => __('Customer totals.', 'invoicing'),
98 98
 			),
99 99
 			array(
100 100
 				'slug'        => 'discounts/totals',
101
-				'description' => __( 'Discount totals.', 'invoicing' ),
101
+				'description' => __('Discount totals.', 'invoicing'),
102 102
 			)
103 103
 		);
104 104
 
105
-		return apply_filters( 'getpaid_available_api_reports', $reports );
105
+		return apply_filters('getpaid_available_api_reports', $reports);
106 106
 
107 107
 	}
108 108
 
@@ -113,16 +113,16 @@  discard block
 block discarded – undo
113 113
 	 * @param WP_REST_Request $request
114 114
 	 * @return array|WP_Error
115 115
 	 */
116
-	public function get_items( $request ) {
116
+	public function get_items($request) {
117 117
 		$data    = array();
118 118
 		$reports = $this->get_reports();
119 119
 
120
-		foreach ( $reports as $report ) {
121
-			$item   = $this->prepare_item_for_response( (object) $report, $request );
122
-			$data[] = $this->prepare_response_for_collection( $item );
120
+		foreach ($reports as $report) {
121
+			$item   = $this->prepare_item_for_response((object) $report, $request);
122
+			$data[] = $this->prepare_response_for_collection($item);
123 123
 		}
124 124
 
125
-		return rest_ensure_response( $data );
125
+		return rest_ensure_response($data);
126 126
 	}
127 127
 
128 128
 	/**
@@ -133,28 +133,28 @@  discard block
 block discarded – undo
133 133
 	 * @param WP_REST_Request $request Request object.
134 134
 	 * @return WP_REST_Response $response Response data.
135 135
 	 */
136
-	public function prepare_item_for_response( $report, $request ) {
136
+	public function prepare_item_for_response($report, $request) {
137 137
 		$data = array(
138 138
 			'slug'        => $report->slug,
139 139
 			'description' => $report->description,
140 140
 		);
141 141
 
142
-		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
143
-		$data = $this->add_additional_fields_to_object( $data, $request );
144
-		$data = $this->filter_response_by_context( $data, $context );
142
+		$context = !empty($request['context']) ? $request['context'] : 'view';
143
+		$data = $this->add_additional_fields_to_object($data, $request);
144
+		$data = $this->filter_response_by_context($data, $context);
145 145
 
146 146
 		// Wrap the data in a response object.
147
-		$response = rest_ensure_response( $data );
148
-		$response->add_links( array(
147
+		$response = rest_ensure_response($data);
148
+		$response->add_links(array(
149 149
 			'self' => array(
150
-				'href' => rest_url( sprintf( '/%s/%s/%s', $this->namespace, $this->rest_base, $report->slug ) ),
150
+				'href' => rest_url(sprintf('/%s/%s/%s', $this->namespace, $this->rest_base, $report->slug)),
151 151
 			),
152 152
 			'collection' => array(
153
-				'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
153
+				'href' => rest_url(sprintf('%s/%s', $this->namespace, $this->rest_base)),
154 154
 			),
155
-		) );
155
+		));
156 156
 
157
-		return apply_filters( 'getpaid_rest_prepare_report', $response, $report, $request );
157
+		return apply_filters('getpaid_rest_prepare_report', $response, $report, $request);
158 158
 	}
159 159
 
160 160
 	/**
@@ -170,21 +170,21 @@  discard block
 block discarded – undo
170 170
 			'type'       => 'object',
171 171
 			'properties' => array(
172 172
 				'slug' => array(
173
-					'description' => __( 'An alphanumeric identifier for the resource.', 'invoicing' ),
173
+					'description' => __('An alphanumeric identifier for the resource.', 'invoicing'),
174 174
 					'type'        => 'string',
175
-					'context'     => array( 'view' ),
175
+					'context'     => array('view'),
176 176
 					'readonly'    => true,
177 177
 				),
178 178
 				'description' => array(
179
-					'description' => __( 'A human-readable description of the resource.', 'invoicing' ),
179
+					'description' => __('A human-readable description of the resource.', 'invoicing'),
180 180
 					'type'        => 'string',
181
-					'context'     => array( 'view' ),
181
+					'context'     => array('view'),
182 182
 					'readonly'    => true,
183 183
 				),
184 184
 			),
185 185
 		);
186 186
 
187
-		return $this->add_additional_fields_schema( $schema );
187
+		return $this->add_additional_fields_schema($schema);
188 188
 	}
189 189
 
190 190
 	/**
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 	 */
196 196
 	public function get_collection_params() {
197 197
 		return array(
198
-			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
198
+			'context' => $this->get_context_param(array('default' => 'view')),
199 199
 		);
200 200
 	}
201 201
 }
Please login to merge, or discard this patch.
includes/api/class-getpaid-rest-report-sales-controller.php 2 patches
Indentation   +646 added lines, -646 removed lines patch added patch discarded remove patch
@@ -18,651 +18,651 @@
 block discarded – undo
18 18
  */
19 19
 class GetPaid_REST_Report_Sales_Controller extends GetPaid_REST_Date_Based_Controller {
20 20
 
21
-	/**
22
-	 * Route base.
23
-	 *
24
-	 * @var string
25
-	 */
26
-	protected $rest_base = 'reports/sales';
27
-
28
-	/**
29
-	 * The report data.
30
-	 *
31
-	 * @var stdClass
32
-	 */
33
-	protected $report_data;
34
-
35
-	/**
36
-	 * The report range.
37
-	 *
38
-	 * @var array
39
-	 */
40
-	protected $report_range;
41
-
42
-	/**
43
-	 * Registers the routes for the objects of the controller.
44
-	 *
45
-	 * @since 2.0.0
46
-	 *
47
-	 * @see register_rest_route()
48
-	 */
49
-	public function register_namespace_routes( $namespace ) {
50
-
51
-		// Get sales report.
52
-		register_rest_route(
53
-			$namespace,
54
-			$this->rest_base,
55
-			array(
56
-				array(
57
-					'methods'             => WP_REST_Server::READABLE,
58
-					'callback'            => array( $this, 'get_items' ),
59
-					'permission_callback' => array( $this, 'get_items_permissions_check' ),
60
-					'args'                => $this->get_collection_params(),
61
-				),
62
-				'schema' => array( $this, 'get_public_item_schema' ),
63
-			)
64
-		);
65
-
66
-	}
67
-
68
-	/**
69
-	 * Makes sure the current user has access to READ the report APIs.
70
-	 *
71
-	 * @since  2.0.0
72
-	 * @param WP_REST_Request $request Full data about the request.
73
-	 * @return WP_Error|boolean
74
-	 */
75
-	public function get_items_permissions_check( $request ) {
76
-
77
-		if ( ! wpinv_current_user_can_manage_invoicing() ) {
78
-			return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
79
-		}
80
-
81
-		return true;
82
-	}
83
-
84
-	/**
85
-	 * Get sales reports.
86
-	 *
87
-	 * @param WP_REST_Request $request
88
-	 * @return array|WP_Error
89
-	 */
90
-	public function get_items( $request ) {
91
-		$data   = array();
92
-		$item   = $this->prepare_item_for_response( null, $request );
93
-		$data[] = $this->prepare_response_for_collection( $item );
94
-
95
-		return rest_ensure_response( $data );
96
-	}
97
-
98
-	/**
99
-	 * Prepare a report sales object for serialization.
100
-	 *
101
-	 * @param null $_
102
-	 * @param WP_REST_Request $request Request object.
103
-	 * @return WP_REST_Response $response Response data.
104
-	 */
105
-	public function prepare_item_for_response( $_, $request ) {
106
-
107
-		// Set report range.
108
-		$this->report_range = $this->get_date_range( $request );
109
-
110
-		$report_data     = $this->get_report_data();
111
-		$period_totals   = array();
112
-
113
-		// Setup period totals by ensuring each period in the interval has data.
114
-		$start_date      = strtotime( $this->report_range['after'] ) + DAY_IN_SECONDS;
115
-
116
-		if ( 'month' === $this->groupby ) {
117
-			$start_date      = strtotime( date( 'Y-m-01', $start_date ) );
118
-		}
119
-
120
-		for ( $i = 0; $i < $this->interval; $i++ ) {
121
-
122
-			switch ( $this->groupby ) {
123
-				case 'day' :
124
-					$time = date( 'Y-m-d', strtotime( "+{$i} DAY", $start_date ) );
125
-					break;
126
-				default :
127
-					$time = date( 'Y-m', strtotime( "+{$i} MONTH", $start_date ) );
128
-					break;
129
-			}
130
-
131
-			// Set the defaults for each period.
132
-			$period_totals[ $time ] = array(
133
-				'sales'             => wpinv_round_amount( 0.00 ),
134
-				'invoices'          => 0,
135
-				'refunds'           => wpinv_round_amount( 0.00 ),
136
-				'items'             => 0,
137
-				'refunded_items'    => 0,
138
-				'tax'               => wpinv_round_amount( 0.00 ),
139
-				'refunded_tax'      => wpinv_round_amount( 0.00 ),
140
-				'subtotal'          => wpinv_round_amount( 0.00 ),
141
-				'refunded_subtotal' => wpinv_round_amount( 0.00 ),
142
-				'fees'              => wpinv_round_amount( 0.00 ),
143
-				'refunded_fees'     => wpinv_round_amount( 0.00 ),
144
-				'discount'          => wpinv_round_amount( 0.00 ),
145
-			);
146
-
147
-		}
148
-
149
-		// add total sales, total invoice count, total tax for each period
150
-		$date_format = ( 'day' === $this->groupby ) ? 'Y-m-d' : 'Y-m';
151
-		foreach ( $report_data->invoices as $invoice ) {
152
-			$time = date( $date_format, strtotime( $invoice->post_date ) );
153
-
154
-			if ( ! isset( $period_totals[ $time ] ) ) {
155
-				continue;
156
-			}
157
-
158
-			$period_totals[ $time ]['sales']    = wpinv_round_amount( $invoice->total_sales );
159
-			$period_totals[ $time ]['tax']      = wpinv_round_amount( $invoice->total_tax );
160
-			$period_totals[ $time ]['subtotal'] = wpinv_round_amount( $invoice->subtotal );
161
-			$period_totals[ $time ]['fees']     = wpinv_round_amount( $invoice->total_fees );
162
-
163
-		}
164
-
165
-		foreach ( $report_data->refunds as $invoice ) {
166
-			$time = date( $date_format, strtotime( $invoice->post_date ) );
167
-
168
-			if ( ! isset( $period_totals[ $time ] ) ) {
169
-				continue;
170
-			}
171
-
172
-			$period_totals[ $time ]['refunds']           = wpinv_round_amount( $invoice->total_sales );
173
-			$period_totals[ $time ]['refunded_tax']      = wpinv_round_amount( $invoice->total_tax );
174
-			$period_totals[ $time ]['refunded_subtotal'] = wpinv_round_amount( $invoice->subtotal );
175
-			$period_totals[ $time ]['refunded_fees']     = wpinv_round_amount( $invoice->total_fees );
176
-
177
-		}
178
-
179
-		foreach ( $report_data->invoice_counts as $invoice ) {
180
-			$time = date( $date_format, strtotime( $invoice->post_date ) );
181
-
182
-			if ( isset( $period_totals[ $time ] ) ) {
183
-				$period_totals[ $time ]['invoices']   = (int) $invoice->count;
184
-			}
185
-
186
-		}
187
-
188
-		// Add total invoice items for each period.
189
-		foreach ( $report_data->invoice_items as $invoice_item ) {
190
-			$time = ( 'day' === $this->groupby ) ? date( 'Y-m-d', strtotime( $invoice_item->post_date ) ) : date( 'Y-m', strtotime( $invoice_item->post_date ) );
191
-
192
-			if ( isset( $period_totals[ $time ] ) ) {
193
-				$period_totals[ $time ]['items'] = (int) $invoice_item->invoice_item_count;
194
-			}
195
-
196
-		}
197
-
198
-		// Add total discount for each period.
199
-		foreach ( $report_data->coupons as $discount ) {
200
-			$time = ( 'day' === $this->groupby ) ? date( 'Y-m-d', strtotime( $discount->post_date ) ) : date( 'Y-m', strtotime( $discount->post_date ) );
201
-
202
-			if ( isset( $period_totals[ $time ] ) ) {
203
-				$period_totals[ $time ]['discount'] = wpinv_round_amount( $discount->discount_amount );
204
-			}
205
-
206
-		}
207
-
208
-		$report_data->totals            = $period_totals;
209
-		$report_data->grouped_by        = $this->groupby;
210
-		$report_data->interval          = max( $this->interval, 1 );
211
-		$report_data->currency          = wpinv_get_currency();
212
-		$report_data->currency_symbol   = wpinv_currency_symbol();
213
-		$report_data->currency_position = wpinv_currency_position();
214
-		$report_data->decimal_places    = wpinv_decimals();
215
-		$report_data->thousands_sep     = wpinv_thousands_separator();
216
-		$report_data->decimals_sep      = wpinv_decimal_separator();
217
-		$report_data->start_date        = getpaid_format_date( date( 'Y-m-d', strtotime( $this->report_range['after'] ) + DAY_IN_SECONDS ) );
218
-		$report_data->end_date          = getpaid_format_date( date( 'Y-m-d', strtotime( $this->report_range['before'] ) - DAY_IN_SECONDS ) );
219
-		$report_data->decimals_sep      = wpinv_decimal_separator();
220
-
221
-		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
222
-		$data    = $report_data;
223
-		unset( $data->invoice_counts, $data->invoices, $data->coupons, $data->refunds, $data->invoice_items );
224
-		$data    = $this->add_additional_fields_to_object( $data, $request );
225
-		$data    = $this->filter_response_by_context( $data, $context );
226
-
227
-		// Wrap the data in a response object.
228
-		$response = rest_ensure_response( $data );
229
-		$response->add_links( array(
230
-			'about' => array(
231
-				'href' => rest_url( sprintf( '%s/reports', $this->namespace ) ),
232
-			),
233
-		) );
234
-
235
-		return apply_filters( 'getpaid_rest_prepare_report_sales', $response, $report_data, $request );
236
-	}
237
-
238
-	/**
239
-	 * Get report data.
240
-	 *
241
-	 * @return stdClass
242
-	 */
243
-	public function get_report_data() {
244
-		if ( empty( $this->report_data ) ) {
245
-			$this->query_report_data();
246
-		}
247
-		return $this->report_data;
248
-	}
249
-
250
-	/**
251
-	 * Get all data needed for this report and store in the class.
252
-	 */
253
-	protected function query_report_data() {
254
-
255
-		// Prepare reports.
256
-		$this->report_data = (object) array(
257
-			'invoice_counts' => $this->query_invoice_counts(),//count, post_date
258
-			'coupons'        => $this->query_coupon_counts(), // discount_amount, post_date
259
-			'invoice_items'  => $this->query_item_counts(), // invoice_item_count, post_date
260
-			'refunded_items' => $this->count_refunded_items(), // invoice_item_count, post_date
261
-			'invoices'       => $this->query_invoice_totals(), // total_sales, total_tax, total_discount, total_fees, subtotal, post_date
262
-			'refunds'        => $this->query_refunded_totals(), // total_sales, total_tax, total_discount, total_fees, subtotal, post_date
263
-		);
264
-
265
-		// Calculated totals.
266
-		$this->report_data->total_tax          = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_tax' ) ) );
267
-		$this->report_data->total_sales        = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_sales' ) ) );
268
-		$this->report_data->total_discount     = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_discount' ) ) );
269
-		$this->report_data->total_fees         = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_fees' ) ) );
270
-		$this->report_data->subtotal           = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'subtotal' ) ) );
271
-		$this->report_data->net_sales          = wpinv_round_amount( $this->report_data->total_sales - max( 0, $this->report_data->total_tax ) );
272
-		$this->report_data->total_refunded_tax = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_tax' ) ) );
273
-		$this->report_data->total_refunds      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_sales' ) ) );
274
-		$this->report_data->refunded_discount  = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_discount' ) ) );
275
-		$this->report_data->refunded_fees      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_fees' ) ) );
276
-		$this->report_data->subtotal           = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'subtotal' ) ) );
277
-		$this->report_data->net_refunds        = wpinv_round_amount( $this->report_data->total_refunds + max( 0, $this->report_data->total_refunded_tax ) );
278
-
279
-
280
-		// Calculate average based on net.
281
-		$this->report_data->average_sales       = wpinv_round_amount( $this->report_data->net_sales / max( $this->interval, 1 ), 2 );
282
-		$this->report_data->average_total_sales = wpinv_round_amount( $this->report_data->total_sales / max( $this->interval, 1 ), 2 );
283
-
284
-		// Total invoices in this period, even if refunded.
285
-		$this->report_data->total_invoices = absint( array_sum( wp_list_pluck( $this->report_data->invoice_counts, 'count' ) ) );
286
-
287
-		// Items invoiced in this period, even if refunded.
288
-		$this->report_data->total_items = absint( array_sum( wp_list_pluck( $this->report_data->invoice_items, 'invoice_item_count' ) ) );
289
-
290
-		// 3rd party filtering of report data
291
-		$this->report_data = apply_filters( 'getpaid_rest_api_filter_report_data', $this->report_data );
292
-	}
293
-
294
-	/**
295
-	 * Prepares invoice counts.
296
-	 *
297
-	 * @return array.
298
-	 */
299
-	protected function query_invoice_counts() {
300
-
301
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
302
-			array(
303
-				'data'         => array(
304
-					'ID'        => array(
305
-						'type'     => 'post_data',
306
-						'function' => 'COUNT',
307
-						'name'     => 'count',
308
-						'distinct' => true,
309
-					),
310
-					'post_date' => array(
311
-						'type'     => 'post_data',
312
-						'function' => '',
313
-						'name'     => 'post_date',
314
-					),
315
-				),
316
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
317
-				'order_by'       => 'post_date ASC',
318
-				'query_type'     => 'get_results',
319
-				'filter_range'   => $this->report_range,
320
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded' ),
321
-			)
322
-		);
323
-
324
-	}
325
-
326
-	/**
327
-	 * Prepares coupon counts.
328
-	 *
329
-	 * @return array.
330
-	 */
331
-	protected function query_coupon_counts() {
332
-
333
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
334
-			array(
335
-				'data'         => array(
336
-					'discount' => array(
337
-						'type'     => 'invoice_data',
338
-						'function' => 'SUM',
339
-						'name'     => 'discount_amount',
340
-					),
341
-					'post_date'       => array(
342
-						'type'     => 'post_data',
343
-						'function' => '',
344
-						'name'     => 'post_date',
345
-					),
346
-				),
347
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
348
-				'order_by'       => 'post_date ASC',
349
-				'query_type'     => 'get_results',
350
-				'filter_range'   => $this->report_range,
351
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded' ),
352
-			)
353
-		);
354
-
355
-	}
356
-
357
-	/**
358
-	 * Prepares item counts.
359
-	 *
360
-	 * @return array.
361
-	 */
362
-	protected function query_item_counts() {
363
-
364
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
365
-			array(
366
-				'data'         => array(
367
-					'quantity'      => array(
368
-						'type'            => 'invoice_item',
369
-						'function'        => 'SUM',
370
-						'name'            => 'invoice_item_count',
371
-					),
372
-					'post_date' => array(
373
-						'type'     => 'post_data',
374
-						'function' => '',
375
-						'name'     => 'post_date',
376
-					),
377
-				),
378
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
379
-				'order_by'       => 'post_date ASC',
380
-				'query_type'     => 'get_results',
381
-				'filter_range'   => $this->report_range,
382
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded' ),
383
-			)
384
-		);
385
-
386
-	}
387
-
388
-	/**
389
-	 * Prepares refunded item counts.
390
-	 *
391
-	 * @return array.
392
-	 */
393
-	protected function count_refunded_items() {
394
-
395
-		return (int) GetPaid_Reports_Helper::get_invoice_report_data(
396
-			array(
397
-				'data'         => array(
398
-					'quantity'      => array(
399
-						'type'            => 'invoice_item',
400
-						'function'        => 'SUM',
401
-						'name'            => 'invoice_item_count',
402
-					),
403
-				),
404
-				'query_type'     => 'get_var',
405
-				'filter_range'   => $this->report_range,
406
-				'invoice_status' => array( 'wpi-refunded' ),
407
-			)
408
-		);
409
-
410
-	}
411
-
412
-	/**
413
-	 * Prepares daily invoice totals.
414
-	 *
415
-	 * @return array.
416
-	 */
417
-	protected function query_invoice_totals() {
418
-
419
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
420
-			array(
421
-				'data'         => array(
422
-					'total'      => array(
423
-						'type'            => 'invoice_data',
424
-						'function'        => 'SUM',
425
-						'name'            => 'total_sales',
426
-					),
427
-					'tax'      => array(
428
-						'type'            => 'invoice_data',
429
-						'function'        => 'SUM',
430
-						'name'            => 'total_tax',
431
-					),
432
-					'discount'      => array(
433
-						'type'            => 'invoice_data',
434
-						'function'        => 'SUM',
435
-						'name'            => 'total_discount',
436
-					),
437
-					'fees_total'      => array(
438
-						'type'            => 'invoice_data',
439
-						'function'        => 'SUM',
440
-						'name'            => 'total_fees',
441
-					),
442
-					'subtotal'      => array(
443
-						'type'            => 'invoice_data',
444
-						'function'        => 'SUM',
445
-						'name'            => 'subtotal',
446
-					),
447
-					'post_date' => array(
448
-						'type'     => 'post_data',
449
-						'function' => '',
450
-						'name'     => 'post_date',
451
-					),
452
-				),
453
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
454
-				'order_by'       => 'post_date ASC',
455
-				'query_type'     => 'get_results',
456
-				'filter_range'   => $this->report_range,
457
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
458
-			)
459
-		);
460
-
461
-	}
462
-
463
-	/**
464
-	 * Prepares daily invoice totals.
465
-	 *
466
-	 * @return array.
467
-	 */
468
-	protected function query_refunded_totals() {
469
-
470
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
471
-			array(
472
-				'data'         => array(
473
-					'total'      => array(
474
-						'type'            => 'invoice_data',
475
-						'function'        => 'SUM',
476
-						'name'            => 'total_sales',
477
-					),
478
-					'tax'      => array(
479
-						'type'            => 'invoice_data',
480
-						'function'        => 'SUM',
481
-						'name'            => 'total_tax',
482
-					),
483
-					'discount'      => array(
484
-						'type'            => 'invoice_data',
485
-						'function'        => 'SUM',
486
-						'name'            => 'total_discount',
487
-					),
488
-					'fees_total'      => array(
489
-						'type'            => 'invoice_data',
490
-						'function'        => 'SUM',
491
-						'name'            => 'total_fees',
492
-					),
493
-					'subtotal'      => array(
494
-						'type'            => 'invoice_data',
495
-						'function'        => 'SUM',
496
-						'name'            => 'subtotal',
497
-					),
498
-					'post_date' => array(
499
-						'type'     => 'post_data',
500
-						'function' => '',
501
-						'name'     => 'post_date',
502
-					),
503
-				),
504
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
505
-				'order_by'       => 'post_date ASC',
506
-				'query_type'     => 'get_results',
507
-				'filter_range'   => $this->report_range,
508
-				'invoice_status' => array( 'wpi-refunded' ),
509
-			)
510
-		);
511
-
512
-	}
513
-
514
-	/**
515
-	 * Get the Report's schema, conforming to JSON Schema.
516
-	 *
517
-	 * @return array
518
-	 */
519
-	public function get_item_schema() {
520
-
521
-		$schema = array(
522
-			'$schema'    => 'http://json-schema.org/draft-04/schema#',
523
-			'title'      => 'sales_report',
524
-			'type'       => 'object',
525
-			'properties' => array(
526
-				'total_sales' => array(
527
-					'description' => __( 'Gross sales in the period.', 'invoicing' ),
528
-					'type'        => 'string',
529
-					'context'     => array( 'view' ),
530
-					'readonly'    => true,
531
-				),
532
-				'net_sales' => array(
533
-					'description' => __( 'Net sales in the period.', 'invoicing' ),
534
-					'type'        => 'string',
535
-					'context'     => array( 'view' ),
536
-					'readonly'    => true,
537
-				),
538
-				'average_sales' => array(
539
-					'description' => __( 'Average net daily sales.', 'invoicing' ),
540
-					'type'        => 'string',
541
-					'context'     => array( 'view' ),
542
-					'readonly'    => true,
543
-				),
544
-				'average_total_sales' => array(
545
-					'description' => __( 'Average gross daily sales.', 'invoicing' ),
546
-					'type'        => 'string',
547
-					'context'     => array( 'view' ),
548
-					'readonly'    => true,
549
-				),
550
-				'total_invoices'  => array(
551
-					'description' => __( 'Number of paid invoices.', 'invoicing' ),
552
-					'type'        => 'integer',
553
-					'context'     => array( 'view' ),
554
-					'readonly'    => true,
555
-				),
556
-				'total_items' => array(
557
-					'description' => __( 'Number of items purchased.', 'invoicing' ),
558
-					'type'        => 'integer',
559
-					'context'     => array( 'view' ),
560
-					'readonly'    => true,
561
-				),
562
-				'refunded_items' => array(
563
-					'description' => __( 'Number of items refunded.', 'invoicing' ),
564
-					'type'        => 'integer',
565
-					'context'     => array( 'view' ),
566
-					'readonly'    => true,
567
-				),
568
-				'total_tax' => array(
569
-					'description' => __( 'Total charged for taxes.', 'invoicing' ),
570
-					'type'        => 'string',
571
-					'context'     => array( 'view' ),
572
-					'readonly'    => true,
573
-				),
574
-				'total_refunded_tax' => array(
575
-					'description' => __( 'Total refunded for taxes.', 'invoicing' ),
576
-					'type'        => 'string',
577
-					'context'     => array( 'view' ),
578
-					'readonly'    => true,
579
-				),
580
-				'total_fees' => array(
581
-					'description' => __( 'Total fees charged.', 'invoicing' ),
582
-					'type'        => 'string',
583
-					'context'     => array( 'view' ),
584
-					'readonly'    => true,
585
-				),
586
-				'total_refunds' => array(
587
-					'description' => __( 'Total of refunded invoices.', 'invoicing' ),
588
-					'type'        => 'integer',
589
-					'context'     => array( 'view' ),
590
-					'readonly'    => true,
591
-				),
592
-				'net_refunds' => array(
593
-					'description' => __( 'Net of refunded invoices.', 'invoicing' ),
594
-					'type'        => 'integer',
595
-					'context'     => array( 'view' ),
596
-					'readonly'    => true,
597
-				),
598
-				'total_discount' => array(
599
-					'description' => __( 'Total of discounts used.', 'invoicing' ),
600
-					'type'        => 'integer',
601
-					'context'     => array( 'view' ),
602
-					'readonly'    => true,
603
-				),
604
-				'totals' => array(
605
-					'description' => __( 'Totals.', 'invoicing' ),
606
-					'type'        => 'array',
607
-					'items'       => array(
608
-						'type'    => 'array',
609
-					),
610
-					'context'     => array( 'view' ),
611
-					'readonly'    => true,
612
-				),
613
-				'interval' => array(
614
-					'description' => __( 'Number of months/days in the report period.', 'invoicing' ),
615
-					'type'        => 'integer',
616
-					'context'     => array( 'view' ),
617
-					'readonly'    => true,
618
-				),
619
-				'grouped_by' => array(
620
-					'description' => __( 'The period used to group the totals.', 'invoicing' ),
621
-					'type'        => 'string',
622
-					'context'     => array( 'view' ),
623
-					'enum'        => array( 'day', 'month' ),
624
-					'readonly'    => true,
625
-				),
626
-				'currency' => array(
627
-					'description' => __( 'The default store currency.', 'invoicing' ),
628
-					'type'        => 'string',
629
-					'context'     => array( 'view' ),
630
-					'readonly'    => true,
631
-				),
632
-				'currency_symbol' => array(
633
-					'description' => __( 'The default store currency symbol.', 'invoicing' ),
634
-					'type'        => 'string',
635
-					'context'     => array( 'view' ),
636
-					'readonly'    => true,
637
-				),
638
-				'currency_position' => array(
639
-					'description' => __( 'The default store currency position.', 'invoicing' ),
640
-					'type'        => 'string',
641
-					'context'     => array( 'view' ),
642
-					'readonly'    => true,
643
-				),
644
-				'decimal_places' => array(
645
-					'description' => __( 'The default store decimal places.', 'invoicing' ),
646
-					'type'        => 'string',
647
-					'context'     => array( 'view' ),
648
-					'readonly'    => true,
649
-				),
650
-				'thousands_sep' => array(
651
-					'description' => __( 'The default store thousands separator.', 'invoicing' ),
652
-					'type'        => 'string',
653
-					'context'     => array( 'view' ),
654
-					'readonly'    => true,
655
-				),
656
-				'decimals_sep' => array(
657
-					'description' => __( 'The default store decimals separator.', 'invoicing' ),
658
-					'type'        => 'string',
659
-					'context'     => array( 'view' ),
660
-					'readonly'    => true,
661
-				),
662
-			),
663
-		);
664
-
665
-		return $this->add_additional_fields_schema( $schema );
666
-	}
21
+    /**
22
+     * Route base.
23
+     *
24
+     * @var string
25
+     */
26
+    protected $rest_base = 'reports/sales';
27
+
28
+    /**
29
+     * The report data.
30
+     *
31
+     * @var stdClass
32
+     */
33
+    protected $report_data;
34
+
35
+    /**
36
+     * The report range.
37
+     *
38
+     * @var array
39
+     */
40
+    protected $report_range;
41
+
42
+    /**
43
+     * Registers the routes for the objects of the controller.
44
+     *
45
+     * @since 2.0.0
46
+     *
47
+     * @see register_rest_route()
48
+     */
49
+    public function register_namespace_routes( $namespace ) {
50
+
51
+        // Get sales report.
52
+        register_rest_route(
53
+            $namespace,
54
+            $this->rest_base,
55
+            array(
56
+                array(
57
+                    'methods'             => WP_REST_Server::READABLE,
58
+                    'callback'            => array( $this, 'get_items' ),
59
+                    'permission_callback' => array( $this, 'get_items_permissions_check' ),
60
+                    'args'                => $this->get_collection_params(),
61
+                ),
62
+                'schema' => array( $this, 'get_public_item_schema' ),
63
+            )
64
+        );
65
+
66
+    }
67
+
68
+    /**
69
+     * Makes sure the current user has access to READ the report APIs.
70
+     *
71
+     * @since  2.0.0
72
+     * @param WP_REST_Request $request Full data about the request.
73
+     * @return WP_Error|boolean
74
+     */
75
+    public function get_items_permissions_check( $request ) {
76
+
77
+        if ( ! wpinv_current_user_can_manage_invoicing() ) {
78
+            return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
79
+        }
80
+
81
+        return true;
82
+    }
83
+
84
+    /**
85
+     * Get sales reports.
86
+     *
87
+     * @param WP_REST_Request $request
88
+     * @return array|WP_Error
89
+     */
90
+    public function get_items( $request ) {
91
+        $data   = array();
92
+        $item   = $this->prepare_item_for_response( null, $request );
93
+        $data[] = $this->prepare_response_for_collection( $item );
94
+
95
+        return rest_ensure_response( $data );
96
+    }
97
+
98
+    /**
99
+     * Prepare a report sales object for serialization.
100
+     *
101
+     * @param null $_
102
+     * @param WP_REST_Request $request Request object.
103
+     * @return WP_REST_Response $response Response data.
104
+     */
105
+    public function prepare_item_for_response( $_, $request ) {
106
+
107
+        // Set report range.
108
+        $this->report_range = $this->get_date_range( $request );
109
+
110
+        $report_data     = $this->get_report_data();
111
+        $period_totals   = array();
112
+
113
+        // Setup period totals by ensuring each period in the interval has data.
114
+        $start_date      = strtotime( $this->report_range['after'] ) + DAY_IN_SECONDS;
115
+
116
+        if ( 'month' === $this->groupby ) {
117
+            $start_date      = strtotime( date( 'Y-m-01', $start_date ) );
118
+        }
119
+
120
+        for ( $i = 0; $i < $this->interval; $i++ ) {
121
+
122
+            switch ( $this->groupby ) {
123
+                case 'day' :
124
+                    $time = date( 'Y-m-d', strtotime( "+{$i} DAY", $start_date ) );
125
+                    break;
126
+                default :
127
+                    $time = date( 'Y-m', strtotime( "+{$i} MONTH", $start_date ) );
128
+                    break;
129
+            }
130
+
131
+            // Set the defaults for each period.
132
+            $period_totals[ $time ] = array(
133
+                'sales'             => wpinv_round_amount( 0.00 ),
134
+                'invoices'          => 0,
135
+                'refunds'           => wpinv_round_amount( 0.00 ),
136
+                'items'             => 0,
137
+                'refunded_items'    => 0,
138
+                'tax'               => wpinv_round_amount( 0.00 ),
139
+                'refunded_tax'      => wpinv_round_amount( 0.00 ),
140
+                'subtotal'          => wpinv_round_amount( 0.00 ),
141
+                'refunded_subtotal' => wpinv_round_amount( 0.00 ),
142
+                'fees'              => wpinv_round_amount( 0.00 ),
143
+                'refunded_fees'     => wpinv_round_amount( 0.00 ),
144
+                'discount'          => wpinv_round_amount( 0.00 ),
145
+            );
146
+
147
+        }
148
+
149
+        // add total sales, total invoice count, total tax for each period
150
+        $date_format = ( 'day' === $this->groupby ) ? 'Y-m-d' : 'Y-m';
151
+        foreach ( $report_data->invoices as $invoice ) {
152
+            $time = date( $date_format, strtotime( $invoice->post_date ) );
153
+
154
+            if ( ! isset( $period_totals[ $time ] ) ) {
155
+                continue;
156
+            }
157
+
158
+            $period_totals[ $time ]['sales']    = wpinv_round_amount( $invoice->total_sales );
159
+            $period_totals[ $time ]['tax']      = wpinv_round_amount( $invoice->total_tax );
160
+            $period_totals[ $time ]['subtotal'] = wpinv_round_amount( $invoice->subtotal );
161
+            $period_totals[ $time ]['fees']     = wpinv_round_amount( $invoice->total_fees );
162
+
163
+        }
164
+
165
+        foreach ( $report_data->refunds as $invoice ) {
166
+            $time = date( $date_format, strtotime( $invoice->post_date ) );
167
+
168
+            if ( ! isset( $period_totals[ $time ] ) ) {
169
+                continue;
170
+            }
171
+
172
+            $period_totals[ $time ]['refunds']           = wpinv_round_amount( $invoice->total_sales );
173
+            $period_totals[ $time ]['refunded_tax']      = wpinv_round_amount( $invoice->total_tax );
174
+            $period_totals[ $time ]['refunded_subtotal'] = wpinv_round_amount( $invoice->subtotal );
175
+            $period_totals[ $time ]['refunded_fees']     = wpinv_round_amount( $invoice->total_fees );
176
+
177
+        }
178
+
179
+        foreach ( $report_data->invoice_counts as $invoice ) {
180
+            $time = date( $date_format, strtotime( $invoice->post_date ) );
181
+
182
+            if ( isset( $period_totals[ $time ] ) ) {
183
+                $period_totals[ $time ]['invoices']   = (int) $invoice->count;
184
+            }
185
+
186
+        }
187
+
188
+        // Add total invoice items for each period.
189
+        foreach ( $report_data->invoice_items as $invoice_item ) {
190
+            $time = ( 'day' === $this->groupby ) ? date( 'Y-m-d', strtotime( $invoice_item->post_date ) ) : date( 'Y-m', strtotime( $invoice_item->post_date ) );
191
+
192
+            if ( isset( $period_totals[ $time ] ) ) {
193
+                $period_totals[ $time ]['items'] = (int) $invoice_item->invoice_item_count;
194
+            }
195
+
196
+        }
197
+
198
+        // Add total discount for each period.
199
+        foreach ( $report_data->coupons as $discount ) {
200
+            $time = ( 'day' === $this->groupby ) ? date( 'Y-m-d', strtotime( $discount->post_date ) ) : date( 'Y-m', strtotime( $discount->post_date ) );
201
+
202
+            if ( isset( $period_totals[ $time ] ) ) {
203
+                $period_totals[ $time ]['discount'] = wpinv_round_amount( $discount->discount_amount );
204
+            }
205
+
206
+        }
207
+
208
+        $report_data->totals            = $period_totals;
209
+        $report_data->grouped_by        = $this->groupby;
210
+        $report_data->interval          = max( $this->interval, 1 );
211
+        $report_data->currency          = wpinv_get_currency();
212
+        $report_data->currency_symbol   = wpinv_currency_symbol();
213
+        $report_data->currency_position = wpinv_currency_position();
214
+        $report_data->decimal_places    = wpinv_decimals();
215
+        $report_data->thousands_sep     = wpinv_thousands_separator();
216
+        $report_data->decimals_sep      = wpinv_decimal_separator();
217
+        $report_data->start_date        = getpaid_format_date( date( 'Y-m-d', strtotime( $this->report_range['after'] ) + DAY_IN_SECONDS ) );
218
+        $report_data->end_date          = getpaid_format_date( date( 'Y-m-d', strtotime( $this->report_range['before'] ) - DAY_IN_SECONDS ) );
219
+        $report_data->decimals_sep      = wpinv_decimal_separator();
220
+
221
+        $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
222
+        $data    = $report_data;
223
+        unset( $data->invoice_counts, $data->invoices, $data->coupons, $data->refunds, $data->invoice_items );
224
+        $data    = $this->add_additional_fields_to_object( $data, $request );
225
+        $data    = $this->filter_response_by_context( $data, $context );
226
+
227
+        // Wrap the data in a response object.
228
+        $response = rest_ensure_response( $data );
229
+        $response->add_links( array(
230
+            'about' => array(
231
+                'href' => rest_url( sprintf( '%s/reports', $this->namespace ) ),
232
+            ),
233
+        ) );
234
+
235
+        return apply_filters( 'getpaid_rest_prepare_report_sales', $response, $report_data, $request );
236
+    }
237
+
238
+    /**
239
+     * Get report data.
240
+     *
241
+     * @return stdClass
242
+     */
243
+    public function get_report_data() {
244
+        if ( empty( $this->report_data ) ) {
245
+            $this->query_report_data();
246
+        }
247
+        return $this->report_data;
248
+    }
249
+
250
+    /**
251
+     * Get all data needed for this report and store in the class.
252
+     */
253
+    protected function query_report_data() {
254
+
255
+        // Prepare reports.
256
+        $this->report_data = (object) array(
257
+            'invoice_counts' => $this->query_invoice_counts(),//count, post_date
258
+            'coupons'        => $this->query_coupon_counts(), // discount_amount, post_date
259
+            'invoice_items'  => $this->query_item_counts(), // invoice_item_count, post_date
260
+            'refunded_items' => $this->count_refunded_items(), // invoice_item_count, post_date
261
+            'invoices'       => $this->query_invoice_totals(), // total_sales, total_tax, total_discount, total_fees, subtotal, post_date
262
+            'refunds'        => $this->query_refunded_totals(), // total_sales, total_tax, total_discount, total_fees, subtotal, post_date
263
+        );
264
+
265
+        // Calculated totals.
266
+        $this->report_data->total_tax          = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_tax' ) ) );
267
+        $this->report_data->total_sales        = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_sales' ) ) );
268
+        $this->report_data->total_discount     = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_discount' ) ) );
269
+        $this->report_data->total_fees         = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_fees' ) ) );
270
+        $this->report_data->subtotal           = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'subtotal' ) ) );
271
+        $this->report_data->net_sales          = wpinv_round_amount( $this->report_data->total_sales - max( 0, $this->report_data->total_tax ) );
272
+        $this->report_data->total_refunded_tax = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_tax' ) ) );
273
+        $this->report_data->total_refunds      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_sales' ) ) );
274
+        $this->report_data->refunded_discount  = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_discount' ) ) );
275
+        $this->report_data->refunded_fees      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_fees' ) ) );
276
+        $this->report_data->subtotal           = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'subtotal' ) ) );
277
+        $this->report_data->net_refunds        = wpinv_round_amount( $this->report_data->total_refunds + max( 0, $this->report_data->total_refunded_tax ) );
278
+
279
+
280
+        // Calculate average based on net.
281
+        $this->report_data->average_sales       = wpinv_round_amount( $this->report_data->net_sales / max( $this->interval, 1 ), 2 );
282
+        $this->report_data->average_total_sales = wpinv_round_amount( $this->report_data->total_sales / max( $this->interval, 1 ), 2 );
283
+
284
+        // Total invoices in this period, even if refunded.
285
+        $this->report_data->total_invoices = absint( array_sum( wp_list_pluck( $this->report_data->invoice_counts, 'count' ) ) );
286
+
287
+        // Items invoiced in this period, even if refunded.
288
+        $this->report_data->total_items = absint( array_sum( wp_list_pluck( $this->report_data->invoice_items, 'invoice_item_count' ) ) );
289
+
290
+        // 3rd party filtering of report data
291
+        $this->report_data = apply_filters( 'getpaid_rest_api_filter_report_data', $this->report_data );
292
+    }
293
+
294
+    /**
295
+     * Prepares invoice counts.
296
+     *
297
+     * @return array.
298
+     */
299
+    protected function query_invoice_counts() {
300
+
301
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
302
+            array(
303
+                'data'         => array(
304
+                    'ID'        => array(
305
+                        'type'     => 'post_data',
306
+                        'function' => 'COUNT',
307
+                        'name'     => 'count',
308
+                        'distinct' => true,
309
+                    ),
310
+                    'post_date' => array(
311
+                        'type'     => 'post_data',
312
+                        'function' => '',
313
+                        'name'     => 'post_date',
314
+                    ),
315
+                ),
316
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
317
+                'order_by'       => 'post_date ASC',
318
+                'query_type'     => 'get_results',
319
+                'filter_range'   => $this->report_range,
320
+                'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded' ),
321
+            )
322
+        );
323
+
324
+    }
325
+
326
+    /**
327
+     * Prepares coupon counts.
328
+     *
329
+     * @return array.
330
+     */
331
+    protected function query_coupon_counts() {
332
+
333
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
334
+            array(
335
+                'data'         => array(
336
+                    'discount' => array(
337
+                        'type'     => 'invoice_data',
338
+                        'function' => 'SUM',
339
+                        'name'     => 'discount_amount',
340
+                    ),
341
+                    'post_date'       => array(
342
+                        'type'     => 'post_data',
343
+                        'function' => '',
344
+                        'name'     => 'post_date',
345
+                    ),
346
+                ),
347
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
348
+                'order_by'       => 'post_date ASC',
349
+                'query_type'     => 'get_results',
350
+                'filter_range'   => $this->report_range,
351
+                'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded' ),
352
+            )
353
+        );
354
+
355
+    }
356
+
357
+    /**
358
+     * Prepares item counts.
359
+     *
360
+     * @return array.
361
+     */
362
+    protected function query_item_counts() {
363
+
364
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
365
+            array(
366
+                'data'         => array(
367
+                    'quantity'      => array(
368
+                        'type'            => 'invoice_item',
369
+                        'function'        => 'SUM',
370
+                        'name'            => 'invoice_item_count',
371
+                    ),
372
+                    'post_date' => array(
373
+                        'type'     => 'post_data',
374
+                        'function' => '',
375
+                        'name'     => 'post_date',
376
+                    ),
377
+                ),
378
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
379
+                'order_by'       => 'post_date ASC',
380
+                'query_type'     => 'get_results',
381
+                'filter_range'   => $this->report_range,
382
+                'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded' ),
383
+            )
384
+        );
385
+
386
+    }
387
+
388
+    /**
389
+     * Prepares refunded item counts.
390
+     *
391
+     * @return array.
392
+     */
393
+    protected function count_refunded_items() {
394
+
395
+        return (int) GetPaid_Reports_Helper::get_invoice_report_data(
396
+            array(
397
+                'data'         => array(
398
+                    'quantity'      => array(
399
+                        'type'            => 'invoice_item',
400
+                        'function'        => 'SUM',
401
+                        'name'            => 'invoice_item_count',
402
+                    ),
403
+                ),
404
+                'query_type'     => 'get_var',
405
+                'filter_range'   => $this->report_range,
406
+                'invoice_status' => array( 'wpi-refunded' ),
407
+            )
408
+        );
409
+
410
+    }
411
+
412
+    /**
413
+     * Prepares daily invoice totals.
414
+     *
415
+     * @return array.
416
+     */
417
+    protected function query_invoice_totals() {
418
+
419
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
420
+            array(
421
+                'data'         => array(
422
+                    'total'      => array(
423
+                        'type'            => 'invoice_data',
424
+                        'function'        => 'SUM',
425
+                        'name'            => 'total_sales',
426
+                    ),
427
+                    'tax'      => array(
428
+                        'type'            => 'invoice_data',
429
+                        'function'        => 'SUM',
430
+                        'name'            => 'total_tax',
431
+                    ),
432
+                    'discount'      => array(
433
+                        'type'            => 'invoice_data',
434
+                        'function'        => 'SUM',
435
+                        'name'            => 'total_discount',
436
+                    ),
437
+                    'fees_total'      => array(
438
+                        'type'            => 'invoice_data',
439
+                        'function'        => 'SUM',
440
+                        'name'            => 'total_fees',
441
+                    ),
442
+                    'subtotal'      => array(
443
+                        'type'            => 'invoice_data',
444
+                        'function'        => 'SUM',
445
+                        'name'            => 'subtotal',
446
+                    ),
447
+                    'post_date' => array(
448
+                        'type'     => 'post_data',
449
+                        'function' => '',
450
+                        'name'     => 'post_date',
451
+                    ),
452
+                ),
453
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
454
+                'order_by'       => 'post_date ASC',
455
+                'query_type'     => 'get_results',
456
+                'filter_range'   => $this->report_range,
457
+                'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
458
+            )
459
+        );
460
+
461
+    }
462
+
463
+    /**
464
+     * Prepares daily invoice totals.
465
+     *
466
+     * @return array.
467
+     */
468
+    protected function query_refunded_totals() {
469
+
470
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
471
+            array(
472
+                'data'         => array(
473
+                    'total'      => array(
474
+                        'type'            => 'invoice_data',
475
+                        'function'        => 'SUM',
476
+                        'name'            => 'total_sales',
477
+                    ),
478
+                    'tax'      => array(
479
+                        'type'            => 'invoice_data',
480
+                        'function'        => 'SUM',
481
+                        'name'            => 'total_tax',
482
+                    ),
483
+                    'discount'      => array(
484
+                        'type'            => 'invoice_data',
485
+                        'function'        => 'SUM',
486
+                        'name'            => 'total_discount',
487
+                    ),
488
+                    'fees_total'      => array(
489
+                        'type'            => 'invoice_data',
490
+                        'function'        => 'SUM',
491
+                        'name'            => 'total_fees',
492
+                    ),
493
+                    'subtotal'      => array(
494
+                        'type'            => 'invoice_data',
495
+                        'function'        => 'SUM',
496
+                        'name'            => 'subtotal',
497
+                    ),
498
+                    'post_date' => array(
499
+                        'type'     => 'post_data',
500
+                        'function' => '',
501
+                        'name'     => 'post_date',
502
+                    ),
503
+                ),
504
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
505
+                'order_by'       => 'post_date ASC',
506
+                'query_type'     => 'get_results',
507
+                'filter_range'   => $this->report_range,
508
+                'invoice_status' => array( 'wpi-refunded' ),
509
+            )
510
+        );
511
+
512
+    }
513
+
514
+    /**
515
+     * Get the Report's schema, conforming to JSON Schema.
516
+     *
517
+     * @return array
518
+     */
519
+    public function get_item_schema() {
520
+
521
+        $schema = array(
522
+            '$schema'    => 'http://json-schema.org/draft-04/schema#',
523
+            'title'      => 'sales_report',
524
+            'type'       => 'object',
525
+            'properties' => array(
526
+                'total_sales' => array(
527
+                    'description' => __( 'Gross sales in the period.', 'invoicing' ),
528
+                    'type'        => 'string',
529
+                    'context'     => array( 'view' ),
530
+                    'readonly'    => true,
531
+                ),
532
+                'net_sales' => array(
533
+                    'description' => __( 'Net sales in the period.', 'invoicing' ),
534
+                    'type'        => 'string',
535
+                    'context'     => array( 'view' ),
536
+                    'readonly'    => true,
537
+                ),
538
+                'average_sales' => array(
539
+                    'description' => __( 'Average net daily sales.', 'invoicing' ),
540
+                    'type'        => 'string',
541
+                    'context'     => array( 'view' ),
542
+                    'readonly'    => true,
543
+                ),
544
+                'average_total_sales' => array(
545
+                    'description' => __( 'Average gross daily sales.', 'invoicing' ),
546
+                    'type'        => 'string',
547
+                    'context'     => array( 'view' ),
548
+                    'readonly'    => true,
549
+                ),
550
+                'total_invoices'  => array(
551
+                    'description' => __( 'Number of paid invoices.', 'invoicing' ),
552
+                    'type'        => 'integer',
553
+                    'context'     => array( 'view' ),
554
+                    'readonly'    => true,
555
+                ),
556
+                'total_items' => array(
557
+                    'description' => __( 'Number of items purchased.', 'invoicing' ),
558
+                    'type'        => 'integer',
559
+                    'context'     => array( 'view' ),
560
+                    'readonly'    => true,
561
+                ),
562
+                'refunded_items' => array(
563
+                    'description' => __( 'Number of items refunded.', 'invoicing' ),
564
+                    'type'        => 'integer',
565
+                    'context'     => array( 'view' ),
566
+                    'readonly'    => true,
567
+                ),
568
+                'total_tax' => array(
569
+                    'description' => __( 'Total charged for taxes.', 'invoicing' ),
570
+                    'type'        => 'string',
571
+                    'context'     => array( 'view' ),
572
+                    'readonly'    => true,
573
+                ),
574
+                'total_refunded_tax' => array(
575
+                    'description' => __( 'Total refunded for taxes.', 'invoicing' ),
576
+                    'type'        => 'string',
577
+                    'context'     => array( 'view' ),
578
+                    'readonly'    => true,
579
+                ),
580
+                'total_fees' => array(
581
+                    'description' => __( 'Total fees charged.', 'invoicing' ),
582
+                    'type'        => 'string',
583
+                    'context'     => array( 'view' ),
584
+                    'readonly'    => true,
585
+                ),
586
+                'total_refunds' => array(
587
+                    'description' => __( 'Total of refunded invoices.', 'invoicing' ),
588
+                    'type'        => 'integer',
589
+                    'context'     => array( 'view' ),
590
+                    'readonly'    => true,
591
+                ),
592
+                'net_refunds' => array(
593
+                    'description' => __( 'Net of refunded invoices.', 'invoicing' ),
594
+                    'type'        => 'integer',
595
+                    'context'     => array( 'view' ),
596
+                    'readonly'    => true,
597
+                ),
598
+                'total_discount' => array(
599
+                    'description' => __( 'Total of discounts used.', 'invoicing' ),
600
+                    'type'        => 'integer',
601
+                    'context'     => array( 'view' ),
602
+                    'readonly'    => true,
603
+                ),
604
+                'totals' => array(
605
+                    'description' => __( 'Totals.', 'invoicing' ),
606
+                    'type'        => 'array',
607
+                    'items'       => array(
608
+                        'type'    => 'array',
609
+                    ),
610
+                    'context'     => array( 'view' ),
611
+                    'readonly'    => true,
612
+                ),
613
+                'interval' => array(
614
+                    'description' => __( 'Number of months/days in the report period.', 'invoicing' ),
615
+                    'type'        => 'integer',
616
+                    'context'     => array( 'view' ),
617
+                    'readonly'    => true,
618
+                ),
619
+                'grouped_by' => array(
620
+                    'description' => __( 'The period used to group the totals.', 'invoicing' ),
621
+                    'type'        => 'string',
622
+                    'context'     => array( 'view' ),
623
+                    'enum'        => array( 'day', 'month' ),
624
+                    'readonly'    => true,
625
+                ),
626
+                'currency' => array(
627
+                    'description' => __( 'The default store currency.', 'invoicing' ),
628
+                    'type'        => 'string',
629
+                    'context'     => array( 'view' ),
630
+                    'readonly'    => true,
631
+                ),
632
+                'currency_symbol' => array(
633
+                    'description' => __( 'The default store currency symbol.', 'invoicing' ),
634
+                    'type'        => 'string',
635
+                    'context'     => array( 'view' ),
636
+                    'readonly'    => true,
637
+                ),
638
+                'currency_position' => array(
639
+                    'description' => __( 'The default store currency position.', 'invoicing' ),
640
+                    'type'        => 'string',
641
+                    'context'     => array( 'view' ),
642
+                    'readonly'    => true,
643
+                ),
644
+                'decimal_places' => array(
645
+                    'description' => __( 'The default store decimal places.', 'invoicing' ),
646
+                    'type'        => 'string',
647
+                    'context'     => array( 'view' ),
648
+                    'readonly'    => true,
649
+                ),
650
+                'thousands_sep' => array(
651
+                    'description' => __( 'The default store thousands separator.', 'invoicing' ),
652
+                    'type'        => 'string',
653
+                    'context'     => array( 'view' ),
654
+                    'readonly'    => true,
655
+                ),
656
+                'decimals_sep' => array(
657
+                    'description' => __( 'The default store decimals separator.', 'invoicing' ),
658
+                    'type'        => 'string',
659
+                    'context'     => array( 'view' ),
660
+                    'readonly'    => true,
661
+                ),
662
+            ),
663
+        );
664
+
665
+        return $this->add_additional_fields_schema( $schema );
666
+    }
667 667
 
668 668
 }
Please login to merge, or discard this patch.
Spacing   +146 added lines, -146 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
  * @since   2.0.0
10 10
  */
11 11
 
12
-defined( 'ABSPATH' ) || exit;
12
+defined('ABSPATH') || exit;
13 13
 
14 14
 /**
15 15
  * GetPaid REST reports controller class.
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 	 *
47 47
 	 * @see register_rest_route()
48 48
 	 */
49
-	public function register_namespace_routes( $namespace ) {
49
+	public function register_namespace_routes($namespace) {
50 50
 
51 51
 		// Get sales report.
52 52
 		register_rest_route(
@@ -55,11 +55,11 @@  discard block
 block discarded – undo
55 55
 			array(
56 56
 				array(
57 57
 					'methods'             => WP_REST_Server::READABLE,
58
-					'callback'            => array( $this, 'get_items' ),
59
-					'permission_callback' => array( $this, 'get_items_permissions_check' ),
58
+					'callback'            => array($this, 'get_items'),
59
+					'permission_callback' => array($this, 'get_items_permissions_check'),
60 60
 					'args'                => $this->get_collection_params(),
61 61
 				),
62
-				'schema' => array( $this, 'get_public_item_schema' ),
62
+				'schema' => array($this, 'get_public_item_schema'),
63 63
 			)
64 64
 		);
65 65
 
@@ -72,10 +72,10 @@  discard block
 block discarded – undo
72 72
 	 * @param WP_REST_Request $request Full data about the request.
73 73
 	 * @return WP_Error|boolean
74 74
 	 */
75
-	public function get_items_permissions_check( $request ) {
75
+	public function get_items_permissions_check($request) {
76 76
 
77
-		if ( ! wpinv_current_user_can_manage_invoicing() ) {
78
-			return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
77
+		if (!wpinv_current_user_can_manage_invoicing()) {
78
+			return new WP_Error('rest_cannot_view', __('Sorry, you cannot list resources.', 'invoicing'), array('status' => rest_authorization_required_code()));
79 79
 		}
80 80
 
81 81
 		return true;
@@ -87,12 +87,12 @@  discard block
 block discarded – undo
87 87
 	 * @param WP_REST_Request $request
88 88
 	 * @return array|WP_Error
89 89
 	 */
90
-	public function get_items( $request ) {
90
+	public function get_items($request) {
91 91
 		$data   = array();
92
-		$item   = $this->prepare_item_for_response( null, $request );
93
-		$data[] = $this->prepare_response_for_collection( $item );
92
+		$item   = $this->prepare_item_for_response(null, $request);
93
+		$data[] = $this->prepare_response_for_collection($item);
94 94
 
95
-		return rest_ensure_response( $data );
95
+		return rest_ensure_response($data);
96 96
 	}
97 97
 
98 98
 	/**
@@ -102,137 +102,137 @@  discard block
 block discarded – undo
102 102
 	 * @param WP_REST_Request $request Request object.
103 103
 	 * @return WP_REST_Response $response Response data.
104 104
 	 */
105
-	public function prepare_item_for_response( $_, $request ) {
105
+	public function prepare_item_for_response($_, $request) {
106 106
 
107 107
 		// Set report range.
108
-		$this->report_range = $this->get_date_range( $request );
108
+		$this->report_range = $this->get_date_range($request);
109 109
 
110 110
 		$report_data     = $this->get_report_data();
111 111
 		$period_totals   = array();
112 112
 
113 113
 		// Setup period totals by ensuring each period in the interval has data.
114
-		$start_date      = strtotime( $this->report_range['after'] ) + DAY_IN_SECONDS;
114
+		$start_date      = strtotime($this->report_range['after']) + DAY_IN_SECONDS;
115 115
 
116
-		if ( 'month' === $this->groupby ) {
117
-			$start_date      = strtotime( date( 'Y-m-01', $start_date ) );
116
+		if ('month' === $this->groupby) {
117
+			$start_date = strtotime(date('Y-m-01', $start_date));
118 118
 		}
119 119
 
120
-		for ( $i = 0; $i < $this->interval; $i++ ) {
120
+		for ($i = 0; $i < $this->interval; $i++) {
121 121
 
122
-			switch ( $this->groupby ) {
122
+			switch ($this->groupby) {
123 123
 				case 'day' :
124
-					$time = date( 'Y-m-d', strtotime( "+{$i} DAY", $start_date ) );
124
+					$time = date('Y-m-d', strtotime("+{$i} DAY", $start_date));
125 125
 					break;
126 126
 				default :
127
-					$time = date( 'Y-m', strtotime( "+{$i} MONTH", $start_date ) );
127
+					$time = date('Y-m', strtotime("+{$i} MONTH", $start_date));
128 128
 					break;
129 129
 			}
130 130
 
131 131
 			// Set the defaults for each period.
132
-			$period_totals[ $time ] = array(
133
-				'sales'             => wpinv_round_amount( 0.00 ),
132
+			$period_totals[$time] = array(
133
+				'sales'             => wpinv_round_amount(0.00),
134 134
 				'invoices'          => 0,
135
-				'refunds'           => wpinv_round_amount( 0.00 ),
135
+				'refunds'           => wpinv_round_amount(0.00),
136 136
 				'items'             => 0,
137 137
 				'refunded_items'    => 0,
138
-				'tax'               => wpinv_round_amount( 0.00 ),
139
-				'refunded_tax'      => wpinv_round_amount( 0.00 ),
140
-				'subtotal'          => wpinv_round_amount( 0.00 ),
141
-				'refunded_subtotal' => wpinv_round_amount( 0.00 ),
142
-				'fees'              => wpinv_round_amount( 0.00 ),
143
-				'refunded_fees'     => wpinv_round_amount( 0.00 ),
144
-				'discount'          => wpinv_round_amount( 0.00 ),
138
+				'tax'               => wpinv_round_amount(0.00),
139
+				'refunded_tax'      => wpinv_round_amount(0.00),
140
+				'subtotal'          => wpinv_round_amount(0.00),
141
+				'refunded_subtotal' => wpinv_round_amount(0.00),
142
+				'fees'              => wpinv_round_amount(0.00),
143
+				'refunded_fees'     => wpinv_round_amount(0.00),
144
+				'discount'          => wpinv_round_amount(0.00),
145 145
 			);
146 146
 
147 147
 		}
148 148
 
149 149
 		// add total sales, total invoice count, total tax for each period
150
-		$date_format = ( 'day' === $this->groupby ) ? 'Y-m-d' : 'Y-m';
151
-		foreach ( $report_data->invoices as $invoice ) {
152
-			$time = date( $date_format, strtotime( $invoice->post_date ) );
150
+		$date_format = ('day' === $this->groupby) ? 'Y-m-d' : 'Y-m';
151
+		foreach ($report_data->invoices as $invoice) {
152
+			$time = date($date_format, strtotime($invoice->post_date));
153 153
 
154
-			if ( ! isset( $period_totals[ $time ] ) ) {
154
+			if (!isset($period_totals[$time])) {
155 155
 				continue;
156 156
 			}
157 157
 
158
-			$period_totals[ $time ]['sales']    = wpinv_round_amount( $invoice->total_sales );
159
-			$period_totals[ $time ]['tax']      = wpinv_round_amount( $invoice->total_tax );
160
-			$period_totals[ $time ]['subtotal'] = wpinv_round_amount( $invoice->subtotal );
161
-			$period_totals[ $time ]['fees']     = wpinv_round_amount( $invoice->total_fees );
158
+			$period_totals[$time]['sales']    = wpinv_round_amount($invoice->total_sales);
159
+			$period_totals[$time]['tax']      = wpinv_round_amount($invoice->total_tax);
160
+			$period_totals[$time]['subtotal'] = wpinv_round_amount($invoice->subtotal);
161
+			$period_totals[$time]['fees']     = wpinv_round_amount($invoice->total_fees);
162 162
 
163 163
 		}
164 164
 
165
-		foreach ( $report_data->refunds as $invoice ) {
166
-			$time = date( $date_format, strtotime( $invoice->post_date ) );
165
+		foreach ($report_data->refunds as $invoice) {
166
+			$time = date($date_format, strtotime($invoice->post_date));
167 167
 
168
-			if ( ! isset( $period_totals[ $time ] ) ) {
168
+			if (!isset($period_totals[$time])) {
169 169
 				continue;
170 170
 			}
171 171
 
172
-			$period_totals[ $time ]['refunds']           = wpinv_round_amount( $invoice->total_sales );
173
-			$period_totals[ $time ]['refunded_tax']      = wpinv_round_amount( $invoice->total_tax );
174
-			$period_totals[ $time ]['refunded_subtotal'] = wpinv_round_amount( $invoice->subtotal );
175
-			$period_totals[ $time ]['refunded_fees']     = wpinv_round_amount( $invoice->total_fees );
172
+			$period_totals[$time]['refunds']           = wpinv_round_amount($invoice->total_sales);
173
+			$period_totals[$time]['refunded_tax']      = wpinv_round_amount($invoice->total_tax);
174
+			$period_totals[$time]['refunded_subtotal'] = wpinv_round_amount($invoice->subtotal);
175
+			$period_totals[$time]['refunded_fees']     = wpinv_round_amount($invoice->total_fees);
176 176
 
177 177
 		}
178 178
 
179
-		foreach ( $report_data->invoice_counts as $invoice ) {
180
-			$time = date( $date_format, strtotime( $invoice->post_date ) );
179
+		foreach ($report_data->invoice_counts as $invoice) {
180
+			$time = date($date_format, strtotime($invoice->post_date));
181 181
 
182
-			if ( isset( $period_totals[ $time ] ) ) {
183
-				$period_totals[ $time ]['invoices']   = (int) $invoice->count;
182
+			if (isset($period_totals[$time])) {
183
+				$period_totals[$time]['invoices'] = (int) $invoice->count;
184 184
 			}
185 185
 
186 186
 		}
187 187
 
188 188
 		// Add total invoice items for each period.
189
-		foreach ( $report_data->invoice_items as $invoice_item ) {
190
-			$time = ( 'day' === $this->groupby ) ? date( 'Y-m-d', strtotime( $invoice_item->post_date ) ) : date( 'Y-m', strtotime( $invoice_item->post_date ) );
189
+		foreach ($report_data->invoice_items as $invoice_item) {
190
+			$time = ('day' === $this->groupby) ? date('Y-m-d', strtotime($invoice_item->post_date)) : date('Y-m', strtotime($invoice_item->post_date));
191 191
 
192
-			if ( isset( $period_totals[ $time ] ) ) {
193
-				$period_totals[ $time ]['items'] = (int) $invoice_item->invoice_item_count;
192
+			if (isset($period_totals[$time])) {
193
+				$period_totals[$time]['items'] = (int) $invoice_item->invoice_item_count;
194 194
 			}
195 195
 
196 196
 		}
197 197
 
198 198
 		// Add total discount for each period.
199
-		foreach ( $report_data->coupons as $discount ) {
200
-			$time = ( 'day' === $this->groupby ) ? date( 'Y-m-d', strtotime( $discount->post_date ) ) : date( 'Y-m', strtotime( $discount->post_date ) );
199
+		foreach ($report_data->coupons as $discount) {
200
+			$time = ('day' === $this->groupby) ? date('Y-m-d', strtotime($discount->post_date)) : date('Y-m', strtotime($discount->post_date));
201 201
 
202
-			if ( isset( $period_totals[ $time ] ) ) {
203
-				$period_totals[ $time ]['discount'] = wpinv_round_amount( $discount->discount_amount );
202
+			if (isset($period_totals[$time])) {
203
+				$period_totals[$time]['discount'] = wpinv_round_amount($discount->discount_amount);
204 204
 			}
205 205
 
206 206
 		}
207 207
 
208 208
 		$report_data->totals            = $period_totals;
209 209
 		$report_data->grouped_by        = $this->groupby;
210
-		$report_data->interval          = max( $this->interval, 1 );
210
+		$report_data->interval          = max($this->interval, 1);
211 211
 		$report_data->currency          = wpinv_get_currency();
212 212
 		$report_data->currency_symbol   = wpinv_currency_symbol();
213 213
 		$report_data->currency_position = wpinv_currency_position();
214 214
 		$report_data->decimal_places    = wpinv_decimals();
215 215
 		$report_data->thousands_sep     = wpinv_thousands_separator();
216 216
 		$report_data->decimals_sep      = wpinv_decimal_separator();
217
-		$report_data->start_date        = getpaid_format_date( date( 'Y-m-d', strtotime( $this->report_range['after'] ) + DAY_IN_SECONDS ) );
218
-		$report_data->end_date          = getpaid_format_date( date( 'Y-m-d', strtotime( $this->report_range['before'] ) - DAY_IN_SECONDS ) );
217
+		$report_data->start_date        = getpaid_format_date(date('Y-m-d', strtotime($this->report_range['after']) + DAY_IN_SECONDS));
218
+		$report_data->end_date          = getpaid_format_date(date('Y-m-d', strtotime($this->report_range['before']) - DAY_IN_SECONDS));
219 219
 		$report_data->decimals_sep      = wpinv_decimal_separator();
220 220
 
221
-		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
221
+		$context = !empty($request['context']) ? $request['context'] : 'view';
222 222
 		$data    = $report_data;
223
-		unset( $data->invoice_counts, $data->invoices, $data->coupons, $data->refunds, $data->invoice_items );
224
-		$data    = $this->add_additional_fields_to_object( $data, $request );
225
-		$data    = $this->filter_response_by_context( $data, $context );
223
+		unset($data->invoice_counts, $data->invoices, $data->coupons, $data->refunds, $data->invoice_items);
224
+		$data    = $this->add_additional_fields_to_object($data, $request);
225
+		$data    = $this->filter_response_by_context($data, $context);
226 226
 
227 227
 		// Wrap the data in a response object.
228
-		$response = rest_ensure_response( $data );
229
-		$response->add_links( array(
228
+		$response = rest_ensure_response($data);
229
+		$response->add_links(array(
230 230
 			'about' => array(
231
-				'href' => rest_url( sprintf( '%s/reports', $this->namespace ) ),
231
+				'href' => rest_url(sprintf('%s/reports', $this->namespace)),
232 232
 			),
233
-		) );
233
+		));
234 234
 
235
-		return apply_filters( 'getpaid_rest_prepare_report_sales', $response, $report_data, $request );
235
+		return apply_filters('getpaid_rest_prepare_report_sales', $response, $report_data, $request);
236 236
 	}
237 237
 
238 238
 	/**
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 	 * @return stdClass
242 242
 	 */
243 243
 	public function get_report_data() {
244
-		if ( empty( $this->report_data ) ) {
244
+		if (empty($this->report_data)) {
245 245
 			$this->query_report_data();
246 246
 		}
247 247
 		return $this->report_data;
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 
255 255
 		// Prepare reports.
256 256
 		$this->report_data = (object) array(
257
-			'invoice_counts' => $this->query_invoice_counts(),//count, post_date
257
+			'invoice_counts' => $this->query_invoice_counts(), //count, post_date
258 258
 			'coupons'        => $this->query_coupon_counts(), // discount_amount, post_date
259 259
 			'invoice_items'  => $this->query_item_counts(), // invoice_item_count, post_date
260 260
 			'refunded_items' => $this->count_refunded_items(), // invoice_item_count, post_date
@@ -263,32 +263,32 @@  discard block
 block discarded – undo
263 263
 		);
264 264
 
265 265
 		// Calculated totals.
266
-		$this->report_data->total_tax          = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_tax' ) ) );
267
-		$this->report_data->total_sales        = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_sales' ) ) );
268
-		$this->report_data->total_discount     = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_discount' ) ) );
269
-		$this->report_data->total_fees         = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_fees' ) ) );
270
-		$this->report_data->subtotal           = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'subtotal' ) ) );
271
-		$this->report_data->net_sales          = wpinv_round_amount( $this->report_data->total_sales - max( 0, $this->report_data->total_tax ) );
272
-		$this->report_data->total_refunded_tax = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_tax' ) ) );
273
-		$this->report_data->total_refunds      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_sales' ) ) );
274
-		$this->report_data->refunded_discount  = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_discount' ) ) );
275
-		$this->report_data->refunded_fees      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_fees' ) ) );
276
-		$this->report_data->subtotal           = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'subtotal' ) ) );
277
-		$this->report_data->net_refunds        = wpinv_round_amount( $this->report_data->total_refunds + max( 0, $this->report_data->total_refunded_tax ) );
266
+		$this->report_data->total_tax          = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'total_tax')));
267
+		$this->report_data->total_sales        = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'total_sales')));
268
+		$this->report_data->total_discount     = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'total_discount')));
269
+		$this->report_data->total_fees         = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'total_fees')));
270
+		$this->report_data->subtotal           = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'subtotal')));
271
+		$this->report_data->net_sales          = wpinv_round_amount($this->report_data->total_sales - max(0, $this->report_data->total_tax));
272
+		$this->report_data->total_refunded_tax = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'total_tax')));
273
+		$this->report_data->total_refunds      = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'total_sales')));
274
+		$this->report_data->refunded_discount  = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'total_discount')));
275
+		$this->report_data->refunded_fees      = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'total_fees')));
276
+		$this->report_data->subtotal           = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'subtotal')));
277
+		$this->report_data->net_refunds        = wpinv_round_amount($this->report_data->total_refunds + max(0, $this->report_data->total_refunded_tax));
278 278
 
279 279
 
280 280
 		// Calculate average based on net.
281
-		$this->report_data->average_sales       = wpinv_round_amount( $this->report_data->net_sales / max( $this->interval, 1 ), 2 );
282
-		$this->report_data->average_total_sales = wpinv_round_amount( $this->report_data->total_sales / max( $this->interval, 1 ), 2 );
281
+		$this->report_data->average_sales       = wpinv_round_amount($this->report_data->net_sales / max($this->interval, 1), 2);
282
+		$this->report_data->average_total_sales = wpinv_round_amount($this->report_data->total_sales / max($this->interval, 1), 2);
283 283
 
284 284
 		// Total invoices in this period, even if refunded.
285
-		$this->report_data->total_invoices = absint( array_sum( wp_list_pluck( $this->report_data->invoice_counts, 'count' ) ) );
285
+		$this->report_data->total_invoices = absint(array_sum(wp_list_pluck($this->report_data->invoice_counts, 'count')));
286 286
 
287 287
 		// Items invoiced in this period, even if refunded.
288
-		$this->report_data->total_items = absint( array_sum( wp_list_pluck( $this->report_data->invoice_items, 'invoice_item_count' ) ) );
288
+		$this->report_data->total_items = absint(array_sum(wp_list_pluck($this->report_data->invoice_items, 'invoice_item_count')));
289 289
 
290 290
 		// 3rd party filtering of report data
291
-		$this->report_data = apply_filters( 'getpaid_rest_api_filter_report_data', $this->report_data );
291
+		$this->report_data = apply_filters('getpaid_rest_api_filter_report_data', $this->report_data);
292 292
 	}
293 293
 
294 294
 	/**
@@ -313,11 +313,11 @@  discard block
 block discarded – undo
313 313
 						'name'     => 'post_date',
314 314
 					),
315 315
 				),
316
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
316
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
317 317
 				'order_by'       => 'post_date ASC',
318 318
 				'query_type'     => 'get_results',
319 319
 				'filter_range'   => $this->report_range,
320
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded' ),
320
+				'invoice_status' => array('publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded'),
321 321
 			)
322 322
 		);
323 323
 
@@ -344,11 +344,11 @@  discard block
 block discarded – undo
344 344
 						'name'     => 'post_date',
345 345
 					),
346 346
 				),
347
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
347
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
348 348
 				'order_by'       => 'post_date ASC',
349 349
 				'query_type'     => 'get_results',
350 350
 				'filter_range'   => $this->report_range,
351
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded' ),
351
+				'invoice_status' => array('publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded'),
352 352
 			)
353 353
 		);
354 354
 
@@ -375,11 +375,11 @@  discard block
 block discarded – undo
375 375
 						'name'     => 'post_date',
376 376
 					),
377 377
 				),
378
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
378
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
379 379
 				'order_by'       => 'post_date ASC',
380 380
 				'query_type'     => 'get_results',
381 381
 				'filter_range'   => $this->report_range,
382
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded' ),
382
+				'invoice_status' => array('publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded'),
383 383
 			)
384 384
 		);
385 385
 
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
 				),
404 404
 				'query_type'     => 'get_var',
405 405
 				'filter_range'   => $this->report_range,
406
-				'invoice_status' => array( 'wpi-refunded' ),
406
+				'invoice_status' => array('wpi-refunded'),
407 407
 			)
408 408
 		);
409 409
 
@@ -450,11 +450,11 @@  discard block
 block discarded – undo
450 450
 						'name'     => 'post_date',
451 451
 					),
452 452
 				),
453
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
453
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
454 454
 				'order_by'       => 'post_date ASC',
455 455
 				'query_type'     => 'get_results',
456 456
 				'filter_range'   => $this->report_range,
457
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
457
+				'invoice_status' => array('publish', 'wpi-processing', 'wpi-onhold'),
458 458
 			)
459 459
 		);
460 460
 
@@ -501,11 +501,11 @@  discard block
 block discarded – undo
501 501
 						'name'     => 'post_date',
502 502
 					),
503 503
 				),
504
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
504
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
505 505
 				'order_by'       => 'post_date ASC',
506 506
 				'query_type'     => 'get_results',
507 507
 				'filter_range'   => $this->report_range,
508
-				'invoice_status' => array( 'wpi-refunded' ),
508
+				'invoice_status' => array('wpi-refunded'),
509 509
 			)
510 510
 		);
511 511
 
@@ -524,145 +524,145 @@  discard block
 block discarded – undo
524 524
 			'type'       => 'object',
525 525
 			'properties' => array(
526 526
 				'total_sales' => array(
527
-					'description' => __( 'Gross sales in the period.', 'invoicing' ),
527
+					'description' => __('Gross sales in the period.', 'invoicing'),
528 528
 					'type'        => 'string',
529
-					'context'     => array( 'view' ),
529
+					'context'     => array('view'),
530 530
 					'readonly'    => true,
531 531
 				),
532 532
 				'net_sales' => array(
533
-					'description' => __( 'Net sales in the period.', 'invoicing' ),
533
+					'description' => __('Net sales in the period.', 'invoicing'),
534 534
 					'type'        => 'string',
535
-					'context'     => array( 'view' ),
535
+					'context'     => array('view'),
536 536
 					'readonly'    => true,
537 537
 				),
538 538
 				'average_sales' => array(
539
-					'description' => __( 'Average net daily sales.', 'invoicing' ),
539
+					'description' => __('Average net daily sales.', 'invoicing'),
540 540
 					'type'        => 'string',
541
-					'context'     => array( 'view' ),
541
+					'context'     => array('view'),
542 542
 					'readonly'    => true,
543 543
 				),
544 544
 				'average_total_sales' => array(
545
-					'description' => __( 'Average gross daily sales.', 'invoicing' ),
545
+					'description' => __('Average gross daily sales.', 'invoicing'),
546 546
 					'type'        => 'string',
547
-					'context'     => array( 'view' ),
547
+					'context'     => array('view'),
548 548
 					'readonly'    => true,
549 549
 				),
550 550
 				'total_invoices'  => array(
551
-					'description' => __( 'Number of paid invoices.', 'invoicing' ),
551
+					'description' => __('Number of paid invoices.', 'invoicing'),
552 552
 					'type'        => 'integer',
553
-					'context'     => array( 'view' ),
553
+					'context'     => array('view'),
554 554
 					'readonly'    => true,
555 555
 				),
556 556
 				'total_items' => array(
557
-					'description' => __( 'Number of items purchased.', 'invoicing' ),
557
+					'description' => __('Number of items purchased.', 'invoicing'),
558 558
 					'type'        => 'integer',
559
-					'context'     => array( 'view' ),
559
+					'context'     => array('view'),
560 560
 					'readonly'    => true,
561 561
 				),
562 562
 				'refunded_items' => array(
563
-					'description' => __( 'Number of items refunded.', 'invoicing' ),
563
+					'description' => __('Number of items refunded.', 'invoicing'),
564 564
 					'type'        => 'integer',
565
-					'context'     => array( 'view' ),
565
+					'context'     => array('view'),
566 566
 					'readonly'    => true,
567 567
 				),
568 568
 				'total_tax' => array(
569
-					'description' => __( 'Total charged for taxes.', 'invoicing' ),
569
+					'description' => __('Total charged for taxes.', 'invoicing'),
570 570
 					'type'        => 'string',
571
-					'context'     => array( 'view' ),
571
+					'context'     => array('view'),
572 572
 					'readonly'    => true,
573 573
 				),
574 574
 				'total_refunded_tax' => array(
575
-					'description' => __( 'Total refunded for taxes.', 'invoicing' ),
575
+					'description' => __('Total refunded for taxes.', 'invoicing'),
576 576
 					'type'        => 'string',
577
-					'context'     => array( 'view' ),
577
+					'context'     => array('view'),
578 578
 					'readonly'    => true,
579 579
 				),
580 580
 				'total_fees' => array(
581
-					'description' => __( 'Total fees charged.', 'invoicing' ),
581
+					'description' => __('Total fees charged.', 'invoicing'),
582 582
 					'type'        => 'string',
583
-					'context'     => array( 'view' ),
583
+					'context'     => array('view'),
584 584
 					'readonly'    => true,
585 585
 				),
586 586
 				'total_refunds' => array(
587
-					'description' => __( 'Total of refunded invoices.', 'invoicing' ),
587
+					'description' => __('Total of refunded invoices.', 'invoicing'),
588 588
 					'type'        => 'integer',
589
-					'context'     => array( 'view' ),
589
+					'context'     => array('view'),
590 590
 					'readonly'    => true,
591 591
 				),
592 592
 				'net_refunds' => array(
593
-					'description' => __( 'Net of refunded invoices.', 'invoicing' ),
593
+					'description' => __('Net of refunded invoices.', 'invoicing'),
594 594
 					'type'        => 'integer',
595
-					'context'     => array( 'view' ),
595
+					'context'     => array('view'),
596 596
 					'readonly'    => true,
597 597
 				),
598 598
 				'total_discount' => array(
599
-					'description' => __( 'Total of discounts used.', 'invoicing' ),
599
+					'description' => __('Total of discounts used.', 'invoicing'),
600 600
 					'type'        => 'integer',
601
-					'context'     => array( 'view' ),
601
+					'context'     => array('view'),
602 602
 					'readonly'    => true,
603 603
 				),
604 604
 				'totals' => array(
605
-					'description' => __( 'Totals.', 'invoicing' ),
605
+					'description' => __('Totals.', 'invoicing'),
606 606
 					'type'        => 'array',
607 607
 					'items'       => array(
608 608
 						'type'    => 'array',
609 609
 					),
610
-					'context'     => array( 'view' ),
610
+					'context'     => array('view'),
611 611
 					'readonly'    => true,
612 612
 				),
613 613
 				'interval' => array(
614
-					'description' => __( 'Number of months/days in the report period.', 'invoicing' ),
614
+					'description' => __('Number of months/days in the report period.', 'invoicing'),
615 615
 					'type'        => 'integer',
616
-					'context'     => array( 'view' ),
616
+					'context'     => array('view'),
617 617
 					'readonly'    => true,
618 618
 				),
619 619
 				'grouped_by' => array(
620
-					'description' => __( 'The period used to group the totals.', 'invoicing' ),
620
+					'description' => __('The period used to group the totals.', 'invoicing'),
621 621
 					'type'        => 'string',
622
-					'context'     => array( 'view' ),
623
-					'enum'        => array( 'day', 'month' ),
622
+					'context'     => array('view'),
623
+					'enum'        => array('day', 'month'),
624 624
 					'readonly'    => true,
625 625
 				),
626 626
 				'currency' => array(
627
-					'description' => __( 'The default store currency.', 'invoicing' ),
627
+					'description' => __('The default store currency.', 'invoicing'),
628 628
 					'type'        => 'string',
629
-					'context'     => array( 'view' ),
629
+					'context'     => array('view'),
630 630
 					'readonly'    => true,
631 631
 				),
632 632
 				'currency_symbol' => array(
633
-					'description' => __( 'The default store currency symbol.', 'invoicing' ),
633
+					'description' => __('The default store currency symbol.', 'invoicing'),
634 634
 					'type'        => 'string',
635
-					'context'     => array( 'view' ),
635
+					'context'     => array('view'),
636 636
 					'readonly'    => true,
637 637
 				),
638 638
 				'currency_position' => array(
639
-					'description' => __( 'The default store currency position.', 'invoicing' ),
639
+					'description' => __('The default store currency position.', 'invoicing'),
640 640
 					'type'        => 'string',
641
-					'context'     => array( 'view' ),
641
+					'context'     => array('view'),
642 642
 					'readonly'    => true,
643 643
 				),
644 644
 				'decimal_places' => array(
645
-					'description' => __( 'The default store decimal places.', 'invoicing' ),
645
+					'description' => __('The default store decimal places.', 'invoicing'),
646 646
 					'type'        => 'string',
647
-					'context'     => array( 'view' ),
647
+					'context'     => array('view'),
648 648
 					'readonly'    => true,
649 649
 				),
650 650
 				'thousands_sep' => array(
651
-					'description' => __( 'The default store thousands separator.', 'invoicing' ),
651
+					'description' => __('The default store thousands separator.', 'invoicing'),
652 652
 					'type'        => 'string',
653
-					'context'     => array( 'view' ),
653
+					'context'     => array('view'),
654 654
 					'readonly'    => true,
655 655
 				),
656 656
 				'decimals_sep' => array(
657
-					'description' => __( 'The default store decimals separator.', 'invoicing' ),
657
+					'description' => __('The default store decimals separator.', 'invoicing'),
658 658
 					'type'        => 'string',
659
-					'context'     => array( 'view' ),
659
+					'context'     => array('view'),
660 660
 					'readonly'    => true,
661 661
 				),
662 662
 			),
663 663
 		);
664 664
 
665
-		return $this->add_additional_fields_schema( $schema );
665
+		return $this->add_additional_fields_schema($schema);
666 666
 	}
667 667
 
668 668
 }
Please login to merge, or discard this patch.
includes/api/class-getpaid-rest-date-based-controller.php 2 patches
Indentation   +330 added lines, -330 removed lines patch added patch discarded remove patch
@@ -16,334 +16,334 @@
 block discarded – undo
16 16
  */
17 17
 class GetPaid_REST_Date_Based_Controller extends GetPaid_REST_Controller {
18 18
 
19
-	/**
20
-	 * Group response items by day or month.
21
-	 *
22
-	 * @var string
23
-	 */
24
-	public $groupby = 'day';
25
-
26
-	/**
27
-	 * The period interval.
28
-	 *
29
-	 * @var int
30
-	 */
31
-	public $interval;
32
-
33
-	/**
34
-	 * Retrieves the before and after dates.
35
-	 *
36
-	 * @param WP_REST_Request $request Request object.
37
-	 * @return array The appropriate date range.
38
-	 */
39
-	public function get_date_range( $request ) {
40
-
41
-		// If not supported, assume all time.
42
-		if ( ! in_array( $request['period'], array( 'custom', 'today', 'yesterday', '7_days', '30_days', '60_days', '90_days', '180_days', 'month', 'last_month', 'year', 'last_year' ) ) ) {
43
-			$request['period'] = '7_days';
44
-		}
45
-
46
-		$date_range = call_user_func( array( $this, 'get_' . $request['period'] . '_date_range' ), $request );
47
-		$this->prepare_interval( $date_range );
48
-
49
-		return $date_range;
50
-
51
-	}
52
-
53
-	/**
54
-	 * Groups by month or days.
55
-	 *
56
-	 * @param array $range Date range.
57
-	 * @return array The appropriate date range.
58
-	 */
59
-	public function prepare_interval( $range ) {
60
-
61
-		$before = strtotime( $range['before'] ) - DAY_IN_SECONDS;
62
-		$after  = strtotime( $range['after'] ) + DAY_IN_SECONDS;
63
-		if ( 'day' === $this->groupby ) {
64
-			$difference     = max( DAY_IN_SECONDS, ( DAY_IN_SECONDS + $before - $after ) ); // Prevent division by 0;
65
-			$this->interval = absint( ceil( max( 1, $difference / DAY_IN_SECONDS ) ) );
66
-			return;
67
-		}
68
-
69
-		$this->interval = 0;
70
-		$min_date       = strtotime( date( 'Y-m-01', $after ) );
71
-
72
-		while ( $min_date <= $before ) {
73
-			$this->interval ++;
74
-			$min_date = strtotime( '+1 MONTH', $min_date );
75
-		}
76
-
77
-		$this->interval = max( 1, $this->interval );
78
-
79
-	}
80
-
81
-	/**
82
-	 * Retrieves a custom date range.
83
-	 *
84
-	 * @param WP_REST_Request $request Request object.
85
-	 * @return array The appropriate date range.
86
-	 */
87
-	public function get_custom_date_range( $request ) {
88
-
89
-		$after  = max( strtotime( '-20 years' ), strtotime( sanitize_text_field( $request['after'] ) ) );
90
-		$before = strtotime( '+1 day', current_time( 'timestamp' ) );
91
-
92
-		if ( ! empty( $request['before'] ) ) {
93
-			$before  = min( $before, strtotime( sanitize_text_field( $request['before'] ) ) );
94
-		}
95
-
96
-		// 3 months max for day view
97
-		if ( ( $before - $after ) / MONTH_IN_SECONDS > 3 ) {
98
-			$this->groupby = 'month';
99
-		}
100
-
101
-		return array(
102
-			'before' => date( 'Y-m-d', $before ),
103
-			'after' => date( 'Y-m-d', $after ),
104
-		);
105
-
106
-	}
107
-
108
-	/**
109
-	 * Retrieves todays date range.
110
-	 *
111
-	 * @return array The appropriate date range.
112
-	 */
113
-	public function get_today_date_range() {
114
-
115
-		return array(
116
-			'before' => date( 'Y-m-d', strtotime( '+1 day', current_time( 'timestamp' ) ) ),
117
-			'after'  => date( 'Y-m-d', strtotime( '-1 day', current_time( 'timestamp' ) ) ),
118
-		);
119
-
120
-	}
121
-
122
-	/**
123
-	 * Retrieves yesterdays date range.
124
-	 *
125
-	 * @return array The appropriate date range.
126
-	 */
127
-	public function get_yesterday_date_range() {
128
-
129
-		return array(
130
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
131
-			'after'  => date( 'Y-m-d', strtotime( '-2 days', current_time( 'timestamp' ) ) ),
132
-		);
133
-
134
-	}
135
-
136
-	/**
137
-	 * Retrieves last 7 days date range.
138
-	 *
139
-	 * @return array The appropriate date range.
140
-	 */
141
-	public function get_7_days_date_range() {
142
-
143
-		return array(
144
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
145
-			'after'  => date( 'Y-m-d', strtotime( '-8 days', current_time( 'timestamp' ) ) ),
146
-		);
147
-
148
-	}
149
-
150
-	/**
151
-	 * Retrieves last 30 days date range.
152
-	 *
153
-	 * @return array The appropriate date range.
154
-	 */
155
-	public function get_30_days_date_range() {
156
-
157
-		return array(
158
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
159
-			'after'  => date( 'Y-m-d', strtotime( '-31 days', current_time( 'timestamp' ) ) ),
160
-		);
161
-
162
-	}
163
-
164
-	/**
165
-	 * Retrieves last 90 days date range.
166
-	 *
167
-	 * @return array The appropriate date range.
168
-	 */
169
-	public function get_90_days_date_range() {
170
-
171
-		$this->groupby = 'month';
172
-		return array(
173
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
174
-			'after'  => date( 'Y-m-d', strtotime( '-91 days', current_time( 'timestamp' ) ) ),
175
-		);
176
-
177
-	}
178
-
179
-	/**
180
-	 * Retrieves last 180 days date range.
181
-	 *
182
-	 * @return array The appropriate date range.
183
-	 */
184
-	public function get_180_days_date_range() {
185
-
186
-		$this->groupby = 'month';
187
-		return array(
188
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
189
-			'after'  => date( 'Y-m-d', strtotime( '-181 days', current_time( 'timestamp' ) ) ),
190
-		);
191
-
192
-	}
193
-
194
-	/**
195
-	 * Retrieves last 60 days date range.
196
-	 *
197
-	 * @return array The appropriate date range.
198
-	 */
199
-	public function get_60_days_date_range() {
200
-
201
-		return array(
202
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
203
-			'after'  => date( 'Y-m-d', strtotime( '-61 days', current_time( 'timestamp' ) ) ),
204
-		);
205
-
206
-	}
207
-
208
-	/**
209
-	 * Retrieves this month date range.
210
-	 *
211
-	 * @return array The appropriate date range.
212
-	 */
213
-	public function get_month_date_range() {
214
-
215
-		return array(
216
-			'before' => date( 'Y-m-d', strtotime( '+1 day', current_time( 'timestamp' ) ) ),
217
-			'after'  => date( 'Y-m-t', strtotime( 'last month', current_time( 'timestamp' ) ) ),
218
-		);
219
-
220
-	}
221
-
222
-	/**
223
-	 * Retrieves last month's date range.
224
-	 *
225
-	 * @return array The appropriate date range.
226
-	 */
227
-	public function get_last_month_date_range() {
228
-
229
-		return array(
230
-			'before' => date( 'Y-m-1', current_time( 'timestamp' ) ),
231
-			'after'  => date( 'Y-m-t', strtotime( "-2 months", current_time( 'timestamp' ) ) ),
232
-		);
233
-
234
-	}
235
-
236
-	/**
237
-	 * Retrieves this year date range.
238
-	 *
239
-	 * @return array The appropriate date range.
240
-	 */
241
-	public function get_year_date_range() {
242
-
243
-		$this->groupby = 'month';
244
-		return array(
245
-			'before' => date( 'Y-m-d', strtotime( '+1 day', current_time( 'timestamp' ) ) ),
246
-			'after'  => date( 'Y-m-d', strtotime( 'last year December 31st', current_time( 'timestamp' ) ) ),
247
-		);
248
-
249
-	}
250
-
251
-	/**
252
-	 * Retrieves last year date range.
253
-	 *
254
-	 * @return array The appropriate date range.
255
-	 */
256
-	public function get_last_year_date_range() {
257
-
258
-		$this->groupby = 'month';
259
-		$year          = (int) date('Y') - 2;
260
-		return array(
261
-			'after'  => "$year-12-31",
262
-			'before' => date( 'Y-m-d', strtotime( 'first day of january this year', current_time( 'timestamp' ) ) ),
263
-		);
264
-
265
-	}
266
-
267
-	/**
268
-	 * Prepare a the request date for SQL usage.
269
-	 *
270
-	 * @param WP_REST_Request $request Request object.
271
-	 * @param string $date_field The date field.
272
-	 * @return string The appropriate SQL.
273
-	 */
274
-	public function get_date_range_sql( $request, $date_field ) {
275
-		global $wpdb;
276
-
277
-		$sql = '1=1';
278
-		$range = $this->get_date_range( $request );
279
-
280
-		if ( ! empty( $range['after'] ) ) {
281
-			$sql .= ' AND ' .  $wpdb->prepare(
282
-				"$date_field > %s",
283
-				$range['after']
284
-			);
285
-		}
286
-
287
-		if ( ! empty( $range['before'] ) ) {
288
-			$sql .= ' AND ' .  $wpdb->prepare(
289
-				"$date_field < %s",
290
-				$range['before']
291
-			);
292
-		}
293
-
294
-		return $sql;
295
-
296
-	}
297
-
298
-	/**
299
-	 * Prepares a group by query.
300
-	 *
301
-	 * @param string $date_field The date field.
302
-	 * @return string The appropriate SQL.
303
-	 */
304
-	public function get_group_by_sql( $date_field ) {
305
-
306
-		if ( 'day' === $this->groupby ) {
307
-			return "YEAR($date_field), MONTH($date_field), DAY($date_field)";
308
-		}
309
-
310
-		return "YEAR($date_field), MONTH($date_field)";
311
-	}
312
-
313
-	/**
314
-	 * Get the query params for collections.
315
-	 *
316
-	 * @return array
317
-	 */
318
-	public function get_collection_params() {
319
-		return array(
320
-			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
321
-			'period' => array(
322
-				'description'       => __( 'Limit to results of a specific period.', 'invoicing' ),
323
-				'type'              => 'string',
324
-				'enum'              => array( 'custom', 'today', 'yesterday', '7_days', '30_days', '60_days' , '90_days', '180_days', 'month', 'last_month', 'year', 'last_year' ),
325
-				'validate_callback' => 'rest_validate_request_arg',
326
-				'sanitize_callback' => 'sanitize_text_field',
327
-				'default'           => '7_days',
328
-			),
329
-			'after' => array(
330
-				/* translators: %s: date format */
331
-				'description'       => sprintf( __( 'Limit to results after a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
332
-				'type'              => 'string',
333
-				'format'            => 'date',
334
-				'validate_callback' => 'rest_validate_request_arg',
335
-				'sanitize_callback' => 'sanitize_text_field',
336
-				'default'           => date( 'Y-m-d', strtotime( '-8 days', current_time( 'timestamp' ) ) ),
337
-			),
338
-			'before' => array(
339
-				/* translators: %s: date format */
340
-				'description'       => sprintf( __( 'Limit to results before a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
341
-				'type'              => 'string',
342
-				'format'            => 'date',
343
-				'validate_callback' => 'rest_validate_request_arg',
344
-				'sanitize_callback' => 'sanitize_text_field',
345
-				'default'           => date( 'Y-m-d', current_time( 'timestamp' ) ),
346
-			),
347
-		);
348
-	}
19
+    /**
20
+     * Group response items by day or month.
21
+     *
22
+     * @var string
23
+     */
24
+    public $groupby = 'day';
25
+
26
+    /**
27
+     * The period interval.
28
+     *
29
+     * @var int
30
+     */
31
+    public $interval;
32
+
33
+    /**
34
+     * Retrieves the before and after dates.
35
+     *
36
+     * @param WP_REST_Request $request Request object.
37
+     * @return array The appropriate date range.
38
+     */
39
+    public function get_date_range( $request ) {
40
+
41
+        // If not supported, assume all time.
42
+        if ( ! in_array( $request['period'], array( 'custom', 'today', 'yesterday', '7_days', '30_days', '60_days', '90_days', '180_days', 'month', 'last_month', 'year', 'last_year' ) ) ) {
43
+            $request['period'] = '7_days';
44
+        }
45
+
46
+        $date_range = call_user_func( array( $this, 'get_' . $request['period'] . '_date_range' ), $request );
47
+        $this->prepare_interval( $date_range );
48
+
49
+        return $date_range;
50
+
51
+    }
52
+
53
+    /**
54
+     * Groups by month or days.
55
+     *
56
+     * @param array $range Date range.
57
+     * @return array The appropriate date range.
58
+     */
59
+    public function prepare_interval( $range ) {
60
+
61
+        $before = strtotime( $range['before'] ) - DAY_IN_SECONDS;
62
+        $after  = strtotime( $range['after'] ) + DAY_IN_SECONDS;
63
+        if ( 'day' === $this->groupby ) {
64
+            $difference     = max( DAY_IN_SECONDS, ( DAY_IN_SECONDS + $before - $after ) ); // Prevent division by 0;
65
+            $this->interval = absint( ceil( max( 1, $difference / DAY_IN_SECONDS ) ) );
66
+            return;
67
+        }
68
+
69
+        $this->interval = 0;
70
+        $min_date       = strtotime( date( 'Y-m-01', $after ) );
71
+
72
+        while ( $min_date <= $before ) {
73
+            $this->interval ++;
74
+            $min_date = strtotime( '+1 MONTH', $min_date );
75
+        }
76
+
77
+        $this->interval = max( 1, $this->interval );
78
+
79
+    }
80
+
81
+    /**
82
+     * Retrieves a custom date range.
83
+     *
84
+     * @param WP_REST_Request $request Request object.
85
+     * @return array The appropriate date range.
86
+     */
87
+    public function get_custom_date_range( $request ) {
88
+
89
+        $after  = max( strtotime( '-20 years' ), strtotime( sanitize_text_field( $request['after'] ) ) );
90
+        $before = strtotime( '+1 day', current_time( 'timestamp' ) );
91
+
92
+        if ( ! empty( $request['before'] ) ) {
93
+            $before  = min( $before, strtotime( sanitize_text_field( $request['before'] ) ) );
94
+        }
95
+
96
+        // 3 months max for day view
97
+        if ( ( $before - $after ) / MONTH_IN_SECONDS > 3 ) {
98
+            $this->groupby = 'month';
99
+        }
100
+
101
+        return array(
102
+            'before' => date( 'Y-m-d', $before ),
103
+            'after' => date( 'Y-m-d', $after ),
104
+        );
105
+
106
+    }
107
+
108
+    /**
109
+     * Retrieves todays date range.
110
+     *
111
+     * @return array The appropriate date range.
112
+     */
113
+    public function get_today_date_range() {
114
+
115
+        return array(
116
+            'before' => date( 'Y-m-d', strtotime( '+1 day', current_time( 'timestamp' ) ) ),
117
+            'after'  => date( 'Y-m-d', strtotime( '-1 day', current_time( 'timestamp' ) ) ),
118
+        );
119
+
120
+    }
121
+
122
+    /**
123
+     * Retrieves yesterdays date range.
124
+     *
125
+     * @return array The appropriate date range.
126
+     */
127
+    public function get_yesterday_date_range() {
128
+
129
+        return array(
130
+            'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
131
+            'after'  => date( 'Y-m-d', strtotime( '-2 days', current_time( 'timestamp' ) ) ),
132
+        );
133
+
134
+    }
135
+
136
+    /**
137
+     * Retrieves last 7 days date range.
138
+     *
139
+     * @return array The appropriate date range.
140
+     */
141
+    public function get_7_days_date_range() {
142
+
143
+        return array(
144
+            'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
145
+            'after'  => date( 'Y-m-d', strtotime( '-8 days', current_time( 'timestamp' ) ) ),
146
+        );
147
+
148
+    }
149
+
150
+    /**
151
+     * Retrieves last 30 days date range.
152
+     *
153
+     * @return array The appropriate date range.
154
+     */
155
+    public function get_30_days_date_range() {
156
+
157
+        return array(
158
+            'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
159
+            'after'  => date( 'Y-m-d', strtotime( '-31 days', current_time( 'timestamp' ) ) ),
160
+        );
161
+
162
+    }
163
+
164
+    /**
165
+     * Retrieves last 90 days date range.
166
+     *
167
+     * @return array The appropriate date range.
168
+     */
169
+    public function get_90_days_date_range() {
170
+
171
+        $this->groupby = 'month';
172
+        return array(
173
+            'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
174
+            'after'  => date( 'Y-m-d', strtotime( '-91 days', current_time( 'timestamp' ) ) ),
175
+        );
176
+
177
+    }
178
+
179
+    /**
180
+     * Retrieves last 180 days date range.
181
+     *
182
+     * @return array The appropriate date range.
183
+     */
184
+    public function get_180_days_date_range() {
185
+
186
+        $this->groupby = 'month';
187
+        return array(
188
+            'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
189
+            'after'  => date( 'Y-m-d', strtotime( '-181 days', current_time( 'timestamp' ) ) ),
190
+        );
191
+
192
+    }
193
+
194
+    /**
195
+     * Retrieves last 60 days date range.
196
+     *
197
+     * @return array The appropriate date range.
198
+     */
199
+    public function get_60_days_date_range() {
200
+
201
+        return array(
202
+            'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
203
+            'after'  => date( 'Y-m-d', strtotime( '-61 days', current_time( 'timestamp' ) ) ),
204
+        );
205
+
206
+    }
207
+
208
+    /**
209
+     * Retrieves this month date range.
210
+     *
211
+     * @return array The appropriate date range.
212
+     */
213
+    public function get_month_date_range() {
214
+
215
+        return array(
216
+            'before' => date( 'Y-m-d', strtotime( '+1 day', current_time( 'timestamp' ) ) ),
217
+            'after'  => date( 'Y-m-t', strtotime( 'last month', current_time( 'timestamp' ) ) ),
218
+        );
219
+
220
+    }
221
+
222
+    /**
223
+     * Retrieves last month's date range.
224
+     *
225
+     * @return array The appropriate date range.
226
+     */
227
+    public function get_last_month_date_range() {
228
+
229
+        return array(
230
+            'before' => date( 'Y-m-1', current_time( 'timestamp' ) ),
231
+            'after'  => date( 'Y-m-t', strtotime( "-2 months", current_time( 'timestamp' ) ) ),
232
+        );
233
+
234
+    }
235
+
236
+    /**
237
+     * Retrieves this year date range.
238
+     *
239
+     * @return array The appropriate date range.
240
+     */
241
+    public function get_year_date_range() {
242
+
243
+        $this->groupby = 'month';
244
+        return array(
245
+            'before' => date( 'Y-m-d', strtotime( '+1 day', current_time( 'timestamp' ) ) ),
246
+            'after'  => date( 'Y-m-d', strtotime( 'last year December 31st', current_time( 'timestamp' ) ) ),
247
+        );
248
+
249
+    }
250
+
251
+    /**
252
+     * Retrieves last year date range.
253
+     *
254
+     * @return array The appropriate date range.
255
+     */
256
+    public function get_last_year_date_range() {
257
+
258
+        $this->groupby = 'month';
259
+        $year          = (int) date('Y') - 2;
260
+        return array(
261
+            'after'  => "$year-12-31",
262
+            'before' => date( 'Y-m-d', strtotime( 'first day of january this year', current_time( 'timestamp' ) ) ),
263
+        );
264
+
265
+    }
266
+
267
+    /**
268
+     * Prepare a the request date for SQL usage.
269
+     *
270
+     * @param WP_REST_Request $request Request object.
271
+     * @param string $date_field The date field.
272
+     * @return string The appropriate SQL.
273
+     */
274
+    public function get_date_range_sql( $request, $date_field ) {
275
+        global $wpdb;
276
+
277
+        $sql = '1=1';
278
+        $range = $this->get_date_range( $request );
279
+
280
+        if ( ! empty( $range['after'] ) ) {
281
+            $sql .= ' AND ' .  $wpdb->prepare(
282
+                "$date_field > %s",
283
+                $range['after']
284
+            );
285
+        }
286
+
287
+        if ( ! empty( $range['before'] ) ) {
288
+            $sql .= ' AND ' .  $wpdb->prepare(
289
+                "$date_field < %s",
290
+                $range['before']
291
+            );
292
+        }
293
+
294
+        return $sql;
295
+
296
+    }
297
+
298
+    /**
299
+     * Prepares a group by query.
300
+     *
301
+     * @param string $date_field The date field.
302
+     * @return string The appropriate SQL.
303
+     */
304
+    public function get_group_by_sql( $date_field ) {
305
+
306
+        if ( 'day' === $this->groupby ) {
307
+            return "YEAR($date_field), MONTH($date_field), DAY($date_field)";
308
+        }
309
+
310
+        return "YEAR($date_field), MONTH($date_field)";
311
+    }
312
+
313
+    /**
314
+     * Get the query params for collections.
315
+     *
316
+     * @return array
317
+     */
318
+    public function get_collection_params() {
319
+        return array(
320
+            'context' => $this->get_context_param( array( 'default' => 'view' ) ),
321
+            'period' => array(
322
+                'description'       => __( 'Limit to results of a specific period.', 'invoicing' ),
323
+                'type'              => 'string',
324
+                'enum'              => array( 'custom', 'today', 'yesterday', '7_days', '30_days', '60_days' , '90_days', '180_days', 'month', 'last_month', 'year', 'last_year' ),
325
+                'validate_callback' => 'rest_validate_request_arg',
326
+                'sanitize_callback' => 'sanitize_text_field',
327
+                'default'           => '7_days',
328
+            ),
329
+            'after' => array(
330
+                /* translators: %s: date format */
331
+                'description'       => sprintf( __( 'Limit to results after a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
332
+                'type'              => 'string',
333
+                'format'            => 'date',
334
+                'validate_callback' => 'rest_validate_request_arg',
335
+                'sanitize_callback' => 'sanitize_text_field',
336
+                'default'           => date( 'Y-m-d', strtotime( '-8 days', current_time( 'timestamp' ) ) ),
337
+            ),
338
+            'before' => array(
339
+                /* translators: %s: date format */
340
+                'description'       => sprintf( __( 'Limit to results before a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
341
+                'type'              => 'string',
342
+                'format'            => 'date',
343
+                'validate_callback' => 'rest_validate_request_arg',
344
+                'sanitize_callback' => 'sanitize_text_field',
345
+                'default'           => date( 'Y-m-d', current_time( 'timestamp' ) ),
346
+            ),
347
+        );
348
+    }
349 349
 }
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@  discard block
 block discarded – undo
7 7
  * @since   2.0.0
8 8
  */
9 9
 
10
-defined( 'ABSPATH' ) || exit;
10
+defined('ABSPATH') || exit;
11 11
 
12 12
 /**
13 13
  * GetPaid REST date based controller class.
@@ -36,15 +36,15 @@  discard block
 block discarded – undo
36 36
 	 * @param WP_REST_Request $request Request object.
37 37
 	 * @return array The appropriate date range.
38 38
 	 */
39
-	public function get_date_range( $request ) {
39
+	public function get_date_range($request) {
40 40
 
41 41
 		// If not supported, assume all time.
42
-		if ( ! in_array( $request['period'], array( 'custom', 'today', 'yesterday', '7_days', '30_days', '60_days', '90_days', '180_days', 'month', 'last_month', 'year', 'last_year' ) ) ) {
42
+		if (!in_array($request['period'], array('custom', 'today', 'yesterday', '7_days', '30_days', '60_days', '90_days', '180_days', 'month', 'last_month', 'year', 'last_year'))) {
43 43
 			$request['period'] = '7_days';
44 44
 		}
45 45
 
46
-		$date_range = call_user_func( array( $this, 'get_' . $request['period'] . '_date_range' ), $request );
47
-		$this->prepare_interval( $date_range );
46
+		$date_range = call_user_func(array($this, 'get_' . $request['period'] . '_date_range'), $request);
47
+		$this->prepare_interval($date_range);
48 48
 
49 49
 		return $date_range;
50 50
 
@@ -56,25 +56,25 @@  discard block
 block discarded – undo
56 56
 	 * @param array $range Date range.
57 57
 	 * @return array The appropriate date range.
58 58
 	 */
59
-	public function prepare_interval( $range ) {
59
+	public function prepare_interval($range) {
60 60
 
61
-		$before = strtotime( $range['before'] ) - DAY_IN_SECONDS;
62
-		$after  = strtotime( $range['after'] ) + DAY_IN_SECONDS;
63
-		if ( 'day' === $this->groupby ) {
64
-			$difference     = max( DAY_IN_SECONDS, ( DAY_IN_SECONDS + $before - $after ) ); // Prevent division by 0;
65
-			$this->interval = absint( ceil( max( 1, $difference / DAY_IN_SECONDS ) ) );
61
+		$before = strtotime($range['before']) - DAY_IN_SECONDS;
62
+		$after  = strtotime($range['after']) + DAY_IN_SECONDS;
63
+		if ('day' === $this->groupby) {
64
+			$difference     = max(DAY_IN_SECONDS, (DAY_IN_SECONDS + $before - $after)); // Prevent division by 0;
65
+			$this->interval = absint(ceil(max(1, $difference / DAY_IN_SECONDS)));
66 66
 			return;
67 67
 		}
68 68
 
69 69
 		$this->interval = 0;
70
-		$min_date       = strtotime( date( 'Y-m-01', $after ) );
70
+		$min_date       = strtotime(date('Y-m-01', $after));
71 71
 
72
-		while ( $min_date <= $before ) {
73
-			$this->interval ++;
74
-			$min_date = strtotime( '+1 MONTH', $min_date );
72
+		while ($min_date <= $before) {
73
+			$this->interval++;
74
+			$min_date = strtotime('+1 MONTH', $min_date);
75 75
 		}
76 76
 
77
-		$this->interval = max( 1, $this->interval );
77
+		$this->interval = max(1, $this->interval);
78 78
 
79 79
 	}
80 80
 
@@ -84,23 +84,23 @@  discard block
 block discarded – undo
84 84
 	 * @param WP_REST_Request $request Request object.
85 85
 	 * @return array The appropriate date range.
86 86
 	 */
87
-	public function get_custom_date_range( $request ) {
87
+	public function get_custom_date_range($request) {
88 88
 
89
-		$after  = max( strtotime( '-20 years' ), strtotime( sanitize_text_field( $request['after'] ) ) );
90
-		$before = strtotime( '+1 day', current_time( 'timestamp' ) );
89
+		$after  = max(strtotime('-20 years'), strtotime(sanitize_text_field($request['after'])));
90
+		$before = strtotime('+1 day', current_time('timestamp'));
91 91
 
92
-		if ( ! empty( $request['before'] ) ) {
93
-			$before  = min( $before, strtotime( sanitize_text_field( $request['before'] ) ) );
92
+		if (!empty($request['before'])) {
93
+			$before = min($before, strtotime(sanitize_text_field($request['before'])));
94 94
 		}
95 95
 
96 96
 		// 3 months max for day view
97
-		if ( ( $before - $after ) / MONTH_IN_SECONDS > 3 ) {
97
+		if (($before - $after) / MONTH_IN_SECONDS > 3) {
98 98
 			$this->groupby = 'month';
99 99
 		}
100 100
 
101 101
 		return array(
102
-			'before' => date( 'Y-m-d', $before ),
103
-			'after' => date( 'Y-m-d', $after ),
102
+			'before' => date('Y-m-d', $before),
103
+			'after' => date('Y-m-d', $after),
104 104
 		);
105 105
 
106 106
 	}
@@ -113,8 +113,8 @@  discard block
 block discarded – undo
113 113
 	public function get_today_date_range() {
114 114
 
115 115
 		return array(
116
-			'before' => date( 'Y-m-d', strtotime( '+1 day', current_time( 'timestamp' ) ) ),
117
-			'after'  => date( 'Y-m-d', strtotime( '-1 day', current_time( 'timestamp' ) ) ),
116
+			'before' => date('Y-m-d', strtotime('+1 day', current_time('timestamp'))),
117
+			'after'  => date('Y-m-d', strtotime('-1 day', current_time('timestamp'))),
118 118
 		);
119 119
 
120 120
 	}
@@ -127,8 +127,8 @@  discard block
 block discarded – undo
127 127
 	public function get_yesterday_date_range() {
128 128
 
129 129
 		return array(
130
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
131
-			'after'  => date( 'Y-m-d', strtotime( '-2 days', current_time( 'timestamp' ) ) ),
130
+			'before' => date('Y-m-d', current_time('timestamp')),
131
+			'after'  => date('Y-m-d', strtotime('-2 days', current_time('timestamp'))),
132 132
 		);
133 133
 
134 134
 	}
@@ -141,8 +141,8 @@  discard block
 block discarded – undo
141 141
 	public function get_7_days_date_range() {
142 142
 
143 143
 		return array(
144
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
145
-			'after'  => date( 'Y-m-d', strtotime( '-8 days', current_time( 'timestamp' ) ) ),
144
+			'before' => date('Y-m-d', current_time('timestamp')),
145
+			'after'  => date('Y-m-d', strtotime('-8 days', current_time('timestamp'))),
146 146
 		);
147 147
 
148 148
 	}
@@ -155,8 +155,8 @@  discard block
 block discarded – undo
155 155
 	public function get_30_days_date_range() {
156 156
 
157 157
 		return array(
158
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
159
-			'after'  => date( 'Y-m-d', strtotime( '-31 days', current_time( 'timestamp' ) ) ),
158
+			'before' => date('Y-m-d', current_time('timestamp')),
159
+			'after'  => date('Y-m-d', strtotime('-31 days', current_time('timestamp'))),
160 160
 		);
161 161
 
162 162
 	}
@@ -170,8 +170,8 @@  discard block
 block discarded – undo
170 170
 
171 171
 		$this->groupby = 'month';
172 172
 		return array(
173
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
174
-			'after'  => date( 'Y-m-d', strtotime( '-91 days', current_time( 'timestamp' ) ) ),
173
+			'before' => date('Y-m-d', current_time('timestamp')),
174
+			'after'  => date('Y-m-d', strtotime('-91 days', current_time('timestamp'))),
175 175
 		);
176 176
 
177 177
 	}
@@ -185,8 +185,8 @@  discard block
 block discarded – undo
185 185
 
186 186
 		$this->groupby = 'month';
187 187
 		return array(
188
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
189
-			'after'  => date( 'Y-m-d', strtotime( '-181 days', current_time( 'timestamp' ) ) ),
188
+			'before' => date('Y-m-d', current_time('timestamp')),
189
+			'after'  => date('Y-m-d', strtotime('-181 days', current_time('timestamp'))),
190 190
 		);
191 191
 
192 192
 	}
@@ -199,8 +199,8 @@  discard block
 block discarded – undo
199 199
 	public function get_60_days_date_range() {
200 200
 
201 201
 		return array(
202
-			'before' => date( 'Y-m-d', current_time( 'timestamp' ) ),
203
-			'after'  => date( 'Y-m-d', strtotime( '-61 days', current_time( 'timestamp' ) ) ),
202
+			'before' => date('Y-m-d', current_time('timestamp')),
203
+			'after'  => date('Y-m-d', strtotime('-61 days', current_time('timestamp'))),
204 204
 		);
205 205
 
206 206
 	}
@@ -213,8 +213,8 @@  discard block
 block discarded – undo
213 213
 	public function get_month_date_range() {
214 214
 
215 215
 		return array(
216
-			'before' => date( 'Y-m-d', strtotime( '+1 day', current_time( 'timestamp' ) ) ),
217
-			'after'  => date( 'Y-m-t', strtotime( 'last month', current_time( 'timestamp' ) ) ),
216
+			'before' => date('Y-m-d', strtotime('+1 day', current_time('timestamp'))),
217
+			'after'  => date('Y-m-t', strtotime('last month', current_time('timestamp'))),
218 218
 		);
219 219
 
220 220
 	}
@@ -227,8 +227,8 @@  discard block
 block discarded – undo
227 227
 	public function get_last_month_date_range() {
228 228
 
229 229
 		return array(
230
-			'before' => date( 'Y-m-1', current_time( 'timestamp' ) ),
231
-			'after'  => date( 'Y-m-t', strtotime( "-2 months", current_time( 'timestamp' ) ) ),
230
+			'before' => date('Y-m-1', current_time('timestamp')),
231
+			'after'  => date('Y-m-t', strtotime("-2 months", current_time('timestamp'))),
232 232
 		);
233 233
 
234 234
 	}
@@ -242,8 +242,8 @@  discard block
 block discarded – undo
242 242
 
243 243
 		$this->groupby = 'month';
244 244
 		return array(
245
-			'before' => date( 'Y-m-d', strtotime( '+1 day', current_time( 'timestamp' ) ) ),
246
-			'after'  => date( 'Y-m-d', strtotime( 'last year December 31st', current_time( 'timestamp' ) ) ),
245
+			'before' => date('Y-m-d', strtotime('+1 day', current_time('timestamp'))),
246
+			'after'  => date('Y-m-d', strtotime('last year December 31st', current_time('timestamp'))),
247 247
 		);
248 248
 
249 249
 	}
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 		$year          = (int) date('Y') - 2;
260 260
 		return array(
261 261
 			'after'  => "$year-12-31",
262
-			'before' => date( 'Y-m-d', strtotime( 'first day of january this year', current_time( 'timestamp' ) ) ),
262
+			'before' => date('Y-m-d', strtotime('first day of january this year', current_time('timestamp'))),
263 263
 		);
264 264
 
265 265
 	}
@@ -271,21 +271,21 @@  discard block
 block discarded – undo
271 271
 	 * @param string $date_field The date field.
272 272
 	 * @return string The appropriate SQL.
273 273
 	 */
274
-	public function get_date_range_sql( $request, $date_field ) {
274
+	public function get_date_range_sql($request, $date_field) {
275 275
 		global $wpdb;
276 276
 
277 277
 		$sql = '1=1';
278
-		$range = $this->get_date_range( $request );
278
+		$range = $this->get_date_range($request);
279 279
 
280
-		if ( ! empty( $range['after'] ) ) {
281
-			$sql .= ' AND ' .  $wpdb->prepare(
280
+		if (!empty($range['after'])) {
281
+			$sql .= ' AND ' . $wpdb->prepare(
282 282
 				"$date_field > %s",
283 283
 				$range['after']
284 284
 			);
285 285
 		}
286 286
 
287
-		if ( ! empty( $range['before'] ) ) {
288
-			$sql .= ' AND ' .  $wpdb->prepare(
287
+		if (!empty($range['before'])) {
288
+			$sql .= ' AND ' . $wpdb->prepare(
289 289
 				"$date_field < %s",
290 290
 				$range['before']
291 291
 			);
@@ -301,9 +301,9 @@  discard block
 block discarded – undo
301 301
 	 * @param string $date_field The date field.
302 302
 	 * @return string The appropriate SQL.
303 303
 	 */
304
-	public function get_group_by_sql( $date_field ) {
304
+	public function get_group_by_sql($date_field) {
305 305
 
306
-		if ( 'day' === $this->groupby ) {
306
+		if ('day' === $this->groupby) {
307 307
 			return "YEAR($date_field), MONTH($date_field), DAY($date_field)";
308 308
 		}
309 309
 
@@ -317,32 +317,32 @@  discard block
 block discarded – undo
317 317
 	 */
318 318
 	public function get_collection_params() {
319 319
 		return array(
320
-			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
320
+			'context' => $this->get_context_param(array('default' => 'view')),
321 321
 			'period' => array(
322
-				'description'       => __( 'Limit to results of a specific period.', 'invoicing' ),
322
+				'description'       => __('Limit to results of a specific period.', 'invoicing'),
323 323
 				'type'              => 'string',
324
-				'enum'              => array( 'custom', 'today', 'yesterday', '7_days', '30_days', '60_days' , '90_days', '180_days', 'month', 'last_month', 'year', 'last_year' ),
324
+				'enum'              => array('custom', 'today', 'yesterday', '7_days', '30_days', '60_days', '90_days', '180_days', 'month', 'last_month', 'year', 'last_year'),
325 325
 				'validate_callback' => 'rest_validate_request_arg',
326 326
 				'sanitize_callback' => 'sanitize_text_field',
327 327
 				'default'           => '7_days',
328 328
 			),
329 329
 			'after' => array(
330 330
 				/* translators: %s: date format */
331
-				'description'       => sprintf( __( 'Limit to results after a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
331
+				'description'       => sprintf(__('Limit to results after a specific date, the date needs to be in the %s format.', 'invoicing'), 'YYYY-MM-DD'),
332 332
 				'type'              => 'string',
333 333
 				'format'            => 'date',
334 334
 				'validate_callback' => 'rest_validate_request_arg',
335 335
 				'sanitize_callback' => 'sanitize_text_field',
336
-				'default'           => date( 'Y-m-d', strtotime( '-8 days', current_time( 'timestamp' ) ) ),
336
+				'default'           => date('Y-m-d', strtotime('-8 days', current_time('timestamp'))),
337 337
 			),
338 338
 			'before' => array(
339 339
 				/* translators: %s: date format */
340
-				'description'       => sprintf( __( 'Limit to results before a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
340
+				'description'       => sprintf(__('Limit to results before a specific date, the date needs to be in the %s format.', 'invoicing'), 'YYYY-MM-DD'),
341 341
 				'type'              => 'string',
342 342
 				'format'            => 'date',
343 343
 				'validate_callback' => 'rest_validate_request_arg',
344 344
 				'sanitize_callback' => 'sanitize_text_field',
345
-				'default'           => date( 'Y-m-d', current_time( 'timestamp' ) ),
345
+				'default'           => date('Y-m-d', current_time('timestamp')),
346 346
 			),
347 347
 		);
348 348
 	}
Please login to merge, or discard this patch.
includes/reports/class-getpaid-reports-helper.php 2 patches
Indentation   +276 added lines, -276 removed lines patch added patch discarded remove patch
@@ -12,294 +12,294 @@
 block discarded – undo
12 12
  */
13 13
 class GetPaid_Reports_Helper {
14 14
 
15
-	/**
16
-	 * Get report totals such as invoice totals and discount amounts.
17
-	 *
18
-	 * Data example:
19
-	 *
20
-	 * 'subtotal' => array(
21
-	 *     'type'     => 'invoice_data',
22
-	 *     'function' => 'SUM',
23
-	 *     'name'     => 'subtotal'
24
-	 * )
25
-	 *
26
-	 * @param  array $args
27
-	 * @return mixed depending on query_type
28
-	 */
29
-	public static function get_invoice_report_data( $args = array() ) {
30
-		global $wpdb;
31
-
32
-		$default_args = array(
33
-			'data'                  => array(), // The data to retrieve.
34
-			'where'                 => array(), // An array of where queries.
35
-			'query_type'            => 'get_row', // wpdb query to run.
36
-			'group_by'              => '', // What to group results by.
37
-			'order_by'              => '', // What to order by.
38
-			'limit'                 => '', // Results limit.
39
-			'filter_range'          => array(), // An array of before and after dates to limit results by.
40
-			'invoice_types'         => array( 'wpi_invoice' ), // An array of post types to retrieve.
41
-			'invoice_status'        => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
42
-			'parent_invoice_status' => false, // Optionally filter by parent invoice status.
43
-		);
44
-
45
-		$args         = apply_filters( 'getpaid_reports_get_invoice_report_data_args', $args );
46
-		$args         = wp_parse_args( $args, $default_args );
47
-
48
-		extract( $args );
49
-
50
-		if ( empty( $data ) ) {
51
-			return '';
52
-		}
53
-
54
-		$query           = array();
55
-		$query['select'] = 'SELECT ' . implode( ',', self::prepare_invoice_data( $data ) );
56
-		$query['from']   = "FROM {$wpdb->posts} AS posts";
57
-		$query['join']   = implode( ' ', self::prepare_invoice_joins( $data + $where, ! empty( $parent_invoice_status ) ) );
58
-
59
-		$query['where']  = "
15
+    /**
16
+     * Get report totals such as invoice totals and discount amounts.
17
+     *
18
+     * Data example:
19
+     *
20
+     * 'subtotal' => array(
21
+     *     'type'     => 'invoice_data',
22
+     *     'function' => 'SUM',
23
+     *     'name'     => 'subtotal'
24
+     * )
25
+     *
26
+     * @param  array $args
27
+     * @return mixed depending on query_type
28
+     */
29
+    public static function get_invoice_report_data( $args = array() ) {
30
+        global $wpdb;
31
+
32
+        $default_args = array(
33
+            'data'                  => array(), // The data to retrieve.
34
+            'where'                 => array(), // An array of where queries.
35
+            'query_type'            => 'get_row', // wpdb query to run.
36
+            'group_by'              => '', // What to group results by.
37
+            'order_by'              => '', // What to order by.
38
+            'limit'                 => '', // Results limit.
39
+            'filter_range'          => array(), // An array of before and after dates to limit results by.
40
+            'invoice_types'         => array( 'wpi_invoice' ), // An array of post types to retrieve.
41
+            'invoice_status'        => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
42
+            'parent_invoice_status' => false, // Optionally filter by parent invoice status.
43
+        );
44
+
45
+        $args         = apply_filters( 'getpaid_reports_get_invoice_report_data_args', $args );
46
+        $args         = wp_parse_args( $args, $default_args );
47
+
48
+        extract( $args );
49
+
50
+        if ( empty( $data ) ) {
51
+            return '';
52
+        }
53
+
54
+        $query           = array();
55
+        $query['select'] = 'SELECT ' . implode( ',', self::prepare_invoice_data( $data ) );
56
+        $query['from']   = "FROM {$wpdb->posts} AS posts";
57
+        $query['join']   = implode( ' ', self::prepare_invoice_joins( $data + $where, ! empty( $parent_invoice_status ) ) );
58
+
59
+        $query['where']  = "
60 60
 			WHERE 	posts.post_type 	IN ( '" . implode( "','", $invoice_types ) . "' )
61 61
 			";
62 62
 
63
-		if ( ! empty( $invoice_status ) ) {
64
-			$query['where'] .= "
63
+        if ( ! empty( $invoice_status ) ) {
64
+            $query['where'] .= "
65 65
 				AND 	posts.post_status 	IN ( '" . implode( "','", $invoice_status ) . "' )
66 66
 			";
67
-		}
68
-
69
-		if ( ! empty( $parent_invoice_status ) ) {
70
-			if ( ! empty( $invoice_status ) ) {
71
-				$query['where'] .= " AND ( parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) OR parent.ID IS NULL ) ";
72
-			} else {
73
-				$query['where'] .= " AND parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) ";
74
-			}
75
-		}
76
-
77
-		if ( ! empty( $filter_range['before'] ) ) {
78
-			$query['where'] .= "
67
+        }
68
+
69
+        if ( ! empty( $parent_invoice_status ) ) {
70
+            if ( ! empty( $invoice_status ) ) {
71
+                $query['where'] .= " AND ( parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) OR parent.ID IS NULL ) ";
72
+            } else {
73
+                $query['where'] .= " AND parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) ";
74
+            }
75
+        }
76
+
77
+        if ( ! empty( $filter_range['before'] ) ) {
78
+            $query['where'] .= "
79 79
 				AND 	posts.post_date < '" . date( 'Y-m-d H:i:s', strtotime( $filter_range['before'] ) ) . "'
80 80
 			";
81
-		}
81
+        }
82 82
 
83
-		if ( ! empty( $filter_range['after'] ) ) {
84
-			$query['where'] .= "
83
+        if ( ! empty( $filter_range['after'] ) ) {
84
+            $query['where'] .= "
85 85
 				AND 	posts.post_date > '" . date( 'Y-m-d H:i:s', strtotime( $filter_range['after'] ) ) . "'
86 86
 			";
87
-		}
87
+        }
88 88
 
89
-		if ( ! empty( $where ) ) {
89
+        if ( ! empty( $where ) ) {
90 90
 
91
-			foreach ( $where as $value ) {
91
+            foreach ( $where as $value ) {
92 92
 
93
-				if ( strtolower( $value['operator'] ) == 'in' || strtolower( $value['operator'] ) == 'not in' ) {
94
-
95
-					if ( is_array( $value['value'] ) ) {
96
-						$value['value'] = implode( "','", $value['value'] );
97
-					}
98
-
99
-					if ( ! empty( $value['value'] ) ) {
100
-						$where_value = "{$value['operator']} ('{$value['value']}')";
101
-					}
102
-				} else {
103
-					$where_value = "{$value['operator']} '{$value['value']}'";
104
-				}
105
-
106
-				if ( ! empty( $where_value ) ) {
107
-					$query['where'] .= " AND {$value['key']} {$where_value}";
108
-				}
109
-			}
110
-		}
111
-
112
-		if ( $group_by ) {
113
-			$query['group_by'] = "GROUP BY {$group_by}";
114
-		}
115
-
116
-		if ( $order_by ) {
117
-			$query['order_by'] = "ORDER BY {$order_by}";
118
-		}
119
-
120
-		if ( $limit ) {
121
-			$query['limit'] = "LIMIT {$limit}";
122
-		}
123
-
124
-		$query = apply_filters( 'getpaid_reports_get_invoice_report_query', $query, $data );
125
-		$query = implode( ' ', $query );
126
-
127
-		return self::execute( $query_type, $query );
128
-
129
-	}
130
-
131
-	/**
132
-	 * Prepares the data to select.
133
-	 *
134
-	 *
135
-	 * @param  array $data
136
-	 * @return array
137
-	 */
138
-	public static function prepare_invoice_data( $data ) {
139
-
140
-		$prepared = array();
141
-
142
-		foreach ( $data as $raw_key => $value ) {
143
-			$key      = sanitize_key( $raw_key );
144
-			$distinct = '';
145
-
146
-			if ( isset( $value['distinct'] ) ) {
147
-				$distinct = 'DISTINCT';
148
-			}
149
-
150
-			$get_key = self::get_invoice_table_key( $key, $value['type'] );
151
-
152
-			if ( false === $get_key ) {
153
-				// Skip to the next foreach iteration else the query will be invalid.
154
-				continue;
155
-			}
156
-
157
-			if ( ! empty( $value['function'] ) ) {
158
-				$get = "{$value['function']}({$distinct} {$get_key})";
159
-			} else {
160
-				$get = "{$distinct} {$get_key}";
161
-			}
162
-
163
-			$prepared[] = "{$get} as {$value['name']}";
164
-		}
165
-
166
-		return $prepared;
167
-
168
-	}
169
-
170
-	/**
171
-	 * Prepares the joins to use.
172
-	 *
173
-	 *
174
-	 * @param  array $data
175
-	 * @param  bool $with_parent
176
-	 * @return array
177
-	 */
178
-	public static function prepare_invoice_joins( $data, $with_parent ) {
179
-		global $wpdb;
180
-
181
-		$prepared = array();
182
-
183
-		foreach ( $data as $raw_key => $value ) {
184
-			$join_type = isset( $value['join_type'] ) ? $value['join_type'] : 'INNER';
185
-			$type      = isset( $value['type'] ) ? $value['type'] : false;
186
-			$key       = sanitize_key( $raw_key );
187
-
188
-			switch ( $type ) {
189
-				case 'meta':
190
-					$prepared[ "meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
191
-					break;
192
-				case 'parent_meta':
193
-					$prepared[ "parent_meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
194
-					break;
195
-				case 'invoice_data':
196
-					$prepared['invoices'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoices AS invoices ON posts.ID = invoices.post_id";
197
-					break;
198
-				case 'invoice_item':
199
-					$prepared['invoice_items'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoice_items AS invoice_items ON posts.ID = invoices.post_id";
200
-					break;
201
-			}
202
-		}
203
-
204
-		if ( $with_parent ) {
205
-			$prepared['parent'] = "LEFT JOIN {$wpdb->posts} AS parent ON posts.post_parent = parent.ID";
206
-		}
207
-
208
-		return $prepared;
209
-
210
-	}
211
-
212
-	/**
213
-	 * Retrieves the appropriate table key to use.
214
-	 *
215
-	 *
216
-	 * @param  string $key
217
-	 * @param  string $table
218
-	 * @return string|false
219
-	 */
220
-	public static function get_invoice_table_key( $key, $table ) {
221
-
222
-		$keys = array(
223
-			'meta'         => "meta_{$key}.meta_value",
224
-			'parent_meta'  => "parent_meta_{$key}.meta_value",
225
-			'post_data'    => "posts.{$key}",
226
-			'invoice_data' => "invoices.{$key}",
227
-			'invoice_item' => "invoice_items.{$key}",
228
-		);
229
-
230
-		return isset( $keys[ $table ] ) ? $keys[ $table ] : false;
231
-
232
-	}
233
-
234
-	/**
235
-	 * Executes a query and caches the result for a minute.
236
-	 *
237
-	 *
238
-	 * @param  string $query_type
239
-	 * @param  string $query
240
-	 * @return mixed depending on query_type
241
-	 */
242
-	public static function execute( $query_type, $query ) {
243
-		global $wpdb;
244
-
245
-		$query_hash = md5( $query_type . $query );
246
-		$result     = self::get_cached_query( $query_hash );
247
-		if ( $result === false ) {
248
-			self::enable_big_selects();
249
-
250
-			$result = $wpdb->$query_type( $query );
251
-			self::set_cached_query( $query_hash, $result );
252
-		}
253
-
254
-		return $result;
255
-
256
-	}
257
-
258
-	/**
259
-	 * Enables big mysql selects for reports, just once for this session.
260
-	 */
261
-	protected static function enable_big_selects() {
262
-		static $big_selects = false;
263
-
264
-		global $wpdb;
265
-
266
-		if ( ! $big_selects ) {
267
-			$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
268
-			$big_selects = true;
269
-		}
270
-	}
271
-
272
-	/**
273
-	 * Get the cached query result or null if it's not in the cache.
274
-	 *
275
-	 * @param string $query_hash The query hash.
276
-	 *
277
-	 * @return mixed|false The cache contents on success, false on failure to retrieve contents.
278
-	 */
279
-	protected static function get_cached_query( $query_hash ) {
280
-
281
-		return wp_cache_get(
282
-			$query_hash,
283
-			strtolower( __CLASS__ )
284
-		);
285
-
286
-	}
287
-
288
-	/**
289
-	 * Set the cached query result.
290
-	 *
291
-	 * @param string $query_hash The query hash.
292
-	 * @param mixed  $data The data to cache.
293
-	 */
294
-	protected static function set_cached_query( $query_hash, $data ) {
295
-
296
-		wp_cache_set(
297
-			$query_hash,
298
-			$data,
299
-			strtolower( __CLASS__ ),
300
-			5 * MINUTE_IN_SECONDS
301
-		);
302
-
303
-	}
93
+                if ( strtolower( $value['operator'] ) == 'in' || strtolower( $value['operator'] ) == 'not in' ) {
94
+
95
+                    if ( is_array( $value['value'] ) ) {
96
+                        $value['value'] = implode( "','", $value['value'] );
97
+                    }
98
+
99
+                    if ( ! empty( $value['value'] ) ) {
100
+                        $where_value = "{$value['operator']} ('{$value['value']}')";
101
+                    }
102
+                } else {
103
+                    $where_value = "{$value['operator']} '{$value['value']}'";
104
+                }
105
+
106
+                if ( ! empty( $where_value ) ) {
107
+                    $query['where'] .= " AND {$value['key']} {$where_value}";
108
+                }
109
+            }
110
+        }
111
+
112
+        if ( $group_by ) {
113
+            $query['group_by'] = "GROUP BY {$group_by}";
114
+        }
115
+
116
+        if ( $order_by ) {
117
+            $query['order_by'] = "ORDER BY {$order_by}";
118
+        }
119
+
120
+        if ( $limit ) {
121
+            $query['limit'] = "LIMIT {$limit}";
122
+        }
123
+
124
+        $query = apply_filters( 'getpaid_reports_get_invoice_report_query', $query, $data );
125
+        $query = implode( ' ', $query );
126
+
127
+        return self::execute( $query_type, $query );
128
+
129
+    }
130
+
131
+    /**
132
+     * Prepares the data to select.
133
+     *
134
+     *
135
+     * @param  array $data
136
+     * @return array
137
+     */
138
+    public static function prepare_invoice_data( $data ) {
139
+
140
+        $prepared = array();
141
+
142
+        foreach ( $data as $raw_key => $value ) {
143
+            $key      = sanitize_key( $raw_key );
144
+            $distinct = '';
145
+
146
+            if ( isset( $value['distinct'] ) ) {
147
+                $distinct = 'DISTINCT';
148
+            }
149
+
150
+            $get_key = self::get_invoice_table_key( $key, $value['type'] );
151
+
152
+            if ( false === $get_key ) {
153
+                // Skip to the next foreach iteration else the query will be invalid.
154
+                continue;
155
+            }
156
+
157
+            if ( ! empty( $value['function'] ) ) {
158
+                $get = "{$value['function']}({$distinct} {$get_key})";
159
+            } else {
160
+                $get = "{$distinct} {$get_key}";
161
+            }
162
+
163
+            $prepared[] = "{$get} as {$value['name']}";
164
+        }
165
+
166
+        return $prepared;
167
+
168
+    }
169
+
170
+    /**
171
+     * Prepares the joins to use.
172
+     *
173
+     *
174
+     * @param  array $data
175
+     * @param  bool $with_parent
176
+     * @return array
177
+     */
178
+    public static function prepare_invoice_joins( $data, $with_parent ) {
179
+        global $wpdb;
180
+
181
+        $prepared = array();
182
+
183
+        foreach ( $data as $raw_key => $value ) {
184
+            $join_type = isset( $value['join_type'] ) ? $value['join_type'] : 'INNER';
185
+            $type      = isset( $value['type'] ) ? $value['type'] : false;
186
+            $key       = sanitize_key( $raw_key );
187
+
188
+            switch ( $type ) {
189
+                case 'meta':
190
+                    $prepared[ "meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
191
+                    break;
192
+                case 'parent_meta':
193
+                    $prepared[ "parent_meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
194
+                    break;
195
+                case 'invoice_data':
196
+                    $prepared['invoices'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoices AS invoices ON posts.ID = invoices.post_id";
197
+                    break;
198
+                case 'invoice_item':
199
+                    $prepared['invoice_items'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoice_items AS invoice_items ON posts.ID = invoices.post_id";
200
+                    break;
201
+            }
202
+        }
203
+
204
+        if ( $with_parent ) {
205
+            $prepared['parent'] = "LEFT JOIN {$wpdb->posts} AS parent ON posts.post_parent = parent.ID";
206
+        }
207
+
208
+        return $prepared;
209
+
210
+    }
211
+
212
+    /**
213
+     * Retrieves the appropriate table key to use.
214
+     *
215
+     *
216
+     * @param  string $key
217
+     * @param  string $table
218
+     * @return string|false
219
+     */
220
+    public static function get_invoice_table_key( $key, $table ) {
221
+
222
+        $keys = array(
223
+            'meta'         => "meta_{$key}.meta_value",
224
+            'parent_meta'  => "parent_meta_{$key}.meta_value",
225
+            'post_data'    => "posts.{$key}",
226
+            'invoice_data' => "invoices.{$key}",
227
+            'invoice_item' => "invoice_items.{$key}",
228
+        );
229
+
230
+        return isset( $keys[ $table ] ) ? $keys[ $table ] : false;
231
+
232
+    }
233
+
234
+    /**
235
+     * Executes a query and caches the result for a minute.
236
+     *
237
+     *
238
+     * @param  string $query_type
239
+     * @param  string $query
240
+     * @return mixed depending on query_type
241
+     */
242
+    public static function execute( $query_type, $query ) {
243
+        global $wpdb;
244
+
245
+        $query_hash = md5( $query_type . $query );
246
+        $result     = self::get_cached_query( $query_hash );
247
+        if ( $result === false ) {
248
+            self::enable_big_selects();
249
+
250
+            $result = $wpdb->$query_type( $query );
251
+            self::set_cached_query( $query_hash, $result );
252
+        }
253
+
254
+        return $result;
255
+
256
+    }
257
+
258
+    /**
259
+     * Enables big mysql selects for reports, just once for this session.
260
+     */
261
+    protected static function enable_big_selects() {
262
+        static $big_selects = false;
263
+
264
+        global $wpdb;
265
+
266
+        if ( ! $big_selects ) {
267
+            $wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
268
+            $big_selects = true;
269
+        }
270
+    }
271
+
272
+    /**
273
+     * Get the cached query result or null if it's not in the cache.
274
+     *
275
+     * @param string $query_hash The query hash.
276
+     *
277
+     * @return mixed|false The cache contents on success, false on failure to retrieve contents.
278
+     */
279
+    protected static function get_cached_query( $query_hash ) {
280
+
281
+        return wp_cache_get(
282
+            $query_hash,
283
+            strtolower( __CLASS__ )
284
+        );
285
+
286
+    }
287
+
288
+    /**
289
+     * Set the cached query result.
290
+     *
291
+     * @param string $query_hash The query hash.
292
+     * @param mixed  $data The data to cache.
293
+     */
294
+    protected static function set_cached_query( $query_hash, $data ) {
295
+
296
+        wp_cache_set(
297
+            $query_hash,
298
+            $data,
299
+            strtolower( __CLASS__ ),
300
+            5 * MINUTE_IN_SECONDS
301
+        );
302
+
303
+    }
304 304
 
305 305
 }
Please login to merge, or discard this patch.
Spacing   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
  *
6 6
  */
7 7
 
8
-defined( 'ABSPATH' ) || exit;
8
+defined('ABSPATH') || exit;
9 9
 
10 10
 /**
11 11
  * GetPaid_Reports_Helper Class.
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 	 * @param  array $args
27 27
 	 * @return mixed depending on query_type
28 28
 	 */
29
-	public static function get_invoice_report_data( $args = array() ) {
29
+	public static function get_invoice_report_data($args = array()) {
30 30
 		global $wpdb;
31 31
 
32 32
 		$default_args = array(
@@ -37,94 +37,94 @@  discard block
 block discarded – undo
37 37
 			'order_by'              => '', // What to order by.
38 38
 			'limit'                 => '', // Results limit.
39 39
 			'filter_range'          => array(), // An array of before and after dates to limit results by.
40
-			'invoice_types'         => array( 'wpi_invoice' ), // An array of post types to retrieve.
41
-			'invoice_status'        => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
40
+			'invoice_types'         => array('wpi_invoice'), // An array of post types to retrieve.
41
+			'invoice_status'        => array('publish', 'wpi-processing', 'wpi-onhold'),
42 42
 			'parent_invoice_status' => false, // Optionally filter by parent invoice status.
43 43
 		);
44 44
 
45
-		$args         = apply_filters( 'getpaid_reports_get_invoice_report_data_args', $args );
46
-		$args         = wp_parse_args( $args, $default_args );
45
+		$args         = apply_filters('getpaid_reports_get_invoice_report_data_args', $args);
46
+		$args         = wp_parse_args($args, $default_args);
47 47
 
48
-		extract( $args );
48
+		extract($args);
49 49
 
50
-		if ( empty( $data ) ) {
50
+		if (empty($data)) {
51 51
 			return '';
52 52
 		}
53 53
 
54 54
 		$query           = array();
55
-		$query['select'] = 'SELECT ' . implode( ',', self::prepare_invoice_data( $data ) );
55
+		$query['select'] = 'SELECT ' . implode(',', self::prepare_invoice_data($data));
56 56
 		$query['from']   = "FROM {$wpdb->posts} AS posts";
57
-		$query['join']   = implode( ' ', self::prepare_invoice_joins( $data + $where, ! empty( $parent_invoice_status ) ) );
57
+		$query['join']   = implode(' ', self::prepare_invoice_joins($data + $where, !empty($parent_invoice_status)));
58 58
 
59 59
 		$query['where']  = "
60
-			WHERE 	posts.post_type 	IN ( '" . implode( "','", $invoice_types ) . "' )
60
+			WHERE 	posts.post_type 	IN ( '" . implode("','", $invoice_types) . "' )
61 61
 			";
62 62
 
63
-		if ( ! empty( $invoice_status ) ) {
63
+		if (!empty($invoice_status)) {
64 64
 			$query['where'] .= "
65
-				AND 	posts.post_status 	IN ( '" . implode( "','", $invoice_status ) . "' )
65
+				AND 	posts.post_status 	IN ( '" . implode("','", $invoice_status) . "' )
66 66
 			";
67 67
 		}
68 68
 
69
-		if ( ! empty( $parent_invoice_status ) ) {
70
-			if ( ! empty( $invoice_status ) ) {
71
-				$query['where'] .= " AND ( parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) OR parent.ID IS NULL ) ";
69
+		if (!empty($parent_invoice_status)) {
70
+			if (!empty($invoice_status)) {
71
+				$query['where'] .= " AND ( parent.post_status IN ( '" . implode("','", $parent_invoice_status) . "' ) OR parent.ID IS NULL ) ";
72 72
 			} else {
73
-				$query['where'] .= " AND parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) ";
73
+				$query['where'] .= " AND parent.post_status IN ( '" . implode("','", $parent_invoice_status) . "' ) ";
74 74
 			}
75 75
 		}
76 76
 
77
-		if ( ! empty( $filter_range['before'] ) ) {
77
+		if (!empty($filter_range['before'])) {
78 78
 			$query['where'] .= "
79
-				AND 	posts.post_date < '" . date( 'Y-m-d H:i:s', strtotime( $filter_range['before'] ) ) . "'
79
+				AND 	posts.post_date < '" . date('Y-m-d H:i:s', strtotime($filter_range['before'])) . "'
80 80
 			";
81 81
 		}
82 82
 
83
-		if ( ! empty( $filter_range['after'] ) ) {
83
+		if (!empty($filter_range['after'])) {
84 84
 			$query['where'] .= "
85
-				AND 	posts.post_date > '" . date( 'Y-m-d H:i:s', strtotime( $filter_range['after'] ) ) . "'
85
+				AND 	posts.post_date > '" . date('Y-m-d H:i:s', strtotime($filter_range['after'])) . "'
86 86
 			";
87 87
 		}
88 88
 
89
-		if ( ! empty( $where ) ) {
89
+		if (!empty($where)) {
90 90
 
91
-			foreach ( $where as $value ) {
91
+			foreach ($where as $value) {
92 92
 
93
-				if ( strtolower( $value['operator'] ) == 'in' || strtolower( $value['operator'] ) == 'not in' ) {
93
+				if (strtolower($value['operator']) == 'in' || strtolower($value['operator']) == 'not in') {
94 94
 
95
-					if ( is_array( $value['value'] ) ) {
96
-						$value['value'] = implode( "','", $value['value'] );
95
+					if (is_array($value['value'])) {
96
+						$value['value'] = implode("','", $value['value']);
97 97
 					}
98 98
 
99
-					if ( ! empty( $value['value'] ) ) {
99
+					if (!empty($value['value'])) {
100 100
 						$where_value = "{$value['operator']} ('{$value['value']}')";
101 101
 					}
102 102
 				} else {
103 103
 					$where_value = "{$value['operator']} '{$value['value']}'";
104 104
 				}
105 105
 
106
-				if ( ! empty( $where_value ) ) {
106
+				if (!empty($where_value)) {
107 107
 					$query['where'] .= " AND {$value['key']} {$where_value}";
108 108
 				}
109 109
 			}
110 110
 		}
111 111
 
112
-		if ( $group_by ) {
112
+		if ($group_by) {
113 113
 			$query['group_by'] = "GROUP BY {$group_by}";
114 114
 		}
115 115
 
116
-		if ( $order_by ) {
116
+		if ($order_by) {
117 117
 			$query['order_by'] = "ORDER BY {$order_by}";
118 118
 		}
119 119
 
120
-		if ( $limit ) {
120
+		if ($limit) {
121 121
 			$query['limit'] = "LIMIT {$limit}";
122 122
 		}
123 123
 
124
-		$query = apply_filters( 'getpaid_reports_get_invoice_report_query', $query, $data );
125
-		$query = implode( ' ', $query );
124
+		$query = apply_filters('getpaid_reports_get_invoice_report_query', $query, $data);
125
+		$query = implode(' ', $query);
126 126
 
127
-		return self::execute( $query_type, $query );
127
+		return self::execute($query_type, $query);
128 128
 
129 129
 	}
130 130
 
@@ -135,26 +135,26 @@  discard block
 block discarded – undo
135 135
 	 * @param  array $data
136 136
 	 * @return array
137 137
 	 */
138
-	public static function prepare_invoice_data( $data ) {
138
+	public static function prepare_invoice_data($data) {
139 139
 
140 140
 		$prepared = array();
141 141
 
142
-		foreach ( $data as $raw_key => $value ) {
143
-			$key      = sanitize_key( $raw_key );
142
+		foreach ($data as $raw_key => $value) {
143
+			$key      = sanitize_key($raw_key);
144 144
 			$distinct = '';
145 145
 
146
-			if ( isset( $value['distinct'] ) ) {
146
+			if (isset($value['distinct'])) {
147 147
 				$distinct = 'DISTINCT';
148 148
 			}
149 149
 
150
-			$get_key = self::get_invoice_table_key( $key, $value['type'] );
150
+			$get_key = self::get_invoice_table_key($key, $value['type']);
151 151
 
152
-			if ( false === $get_key ) {
152
+			if (false === $get_key) {
153 153
 				// Skip to the next foreach iteration else the query will be invalid.
154 154
 				continue;
155 155
 			}
156 156
 
157
-			if ( ! empty( $value['function'] ) ) {
157
+			if (!empty($value['function'])) {
158 158
 				$get = "{$value['function']}({$distinct} {$get_key})";
159 159
 			} else {
160 160
 				$get = "{$distinct} {$get_key}";
@@ -175,22 +175,22 @@  discard block
 block discarded – undo
175 175
 	 * @param  bool $with_parent
176 176
 	 * @return array
177 177
 	 */
178
-	public static function prepare_invoice_joins( $data, $with_parent ) {
178
+	public static function prepare_invoice_joins($data, $with_parent) {
179 179
 		global $wpdb;
180 180
 
181 181
 		$prepared = array();
182 182
 
183
-		foreach ( $data as $raw_key => $value ) {
184
-			$join_type = isset( $value['join_type'] ) ? $value['join_type'] : 'INNER';
185
-			$type      = isset( $value['type'] ) ? $value['type'] : false;
186
-			$key       = sanitize_key( $raw_key );
183
+		foreach ($data as $raw_key => $value) {
184
+			$join_type = isset($value['join_type']) ? $value['join_type'] : 'INNER';
185
+			$type      = isset($value['type']) ? $value['type'] : false;
186
+			$key       = sanitize_key($raw_key);
187 187
 
188
-			switch ( $type ) {
188
+			switch ($type) {
189 189
 				case 'meta':
190
-					$prepared[ "meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
190
+					$prepared["meta_{$key}"] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
191 191
 					break;
192 192
 				case 'parent_meta':
193
-					$prepared[ "parent_meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
193
+					$prepared["parent_meta_{$key}"] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
194 194
 					break;
195 195
 				case 'invoice_data':
196 196
 					$prepared['invoices'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoices AS invoices ON posts.ID = invoices.post_id";
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
 			}
202 202
 		}
203 203
 
204
-		if ( $with_parent ) {
204
+		if ($with_parent) {
205 205
 			$prepared['parent'] = "LEFT JOIN {$wpdb->posts} AS parent ON posts.post_parent = parent.ID";
206 206
 		}
207 207
 
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 	 * @param  string $table
218 218
 	 * @return string|false
219 219
 	 */
220
-	public static function get_invoice_table_key( $key, $table ) {
220
+	public static function get_invoice_table_key($key, $table) {
221 221
 
222 222
 		$keys = array(
223 223
 			'meta'         => "meta_{$key}.meta_value",
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 			'invoice_item' => "invoice_items.{$key}",
228 228
 		);
229 229
 
230
-		return isset( $keys[ $table ] ) ? $keys[ $table ] : false;
230
+		return isset($keys[$table]) ? $keys[$table] : false;
231 231
 
232 232
 	}
233 233
 
@@ -239,16 +239,16 @@  discard block
 block discarded – undo
239 239
 	 * @param  string $query
240 240
 	 * @return mixed depending on query_type
241 241
 	 */
242
-	public static function execute( $query_type, $query ) {
242
+	public static function execute($query_type, $query) {
243 243
 		global $wpdb;
244 244
 
245
-		$query_hash = md5( $query_type . $query );
246
-		$result     = self::get_cached_query( $query_hash );
247
-		if ( $result === false ) {
245
+		$query_hash = md5($query_type . $query);
246
+		$result     = self::get_cached_query($query_hash);
247
+		if ($result === false) {
248 248
 			self::enable_big_selects();
249 249
 
250
-			$result = $wpdb->$query_type( $query );
251
-			self::set_cached_query( $query_hash, $result );
250
+			$result = $wpdb->$query_type($query);
251
+			self::set_cached_query($query_hash, $result);
252 252
 		}
253 253
 
254 254
 		return $result;
@@ -263,8 +263,8 @@  discard block
 block discarded – undo
263 263
 
264 264
 		global $wpdb;
265 265
 
266
-		if ( ! $big_selects ) {
267
-			$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
266
+		if (!$big_selects) {
267
+			$wpdb->query('SET SESSION SQL_BIG_SELECTS=1');
268 268
 			$big_selects = true;
269 269
 		}
270 270
 	}
@@ -276,11 +276,11 @@  discard block
 block discarded – undo
276 276
 	 *
277 277
 	 * @return mixed|false The cache contents on success, false on failure to retrieve contents.
278 278
 	 */
279
-	protected static function get_cached_query( $query_hash ) {
279
+	protected static function get_cached_query($query_hash) {
280 280
 
281 281
 		return wp_cache_get(
282 282
 			$query_hash,
283
-			strtolower( __CLASS__ )
283
+			strtolower(__CLASS__)
284 284
 		);
285 285
 
286 286
 	}
@@ -291,12 +291,12 @@  discard block
 block discarded – undo
291 291
 	 * @param string $query_hash The query hash.
292 292
 	 * @param mixed  $data The data to cache.
293 293
 	 */
294
-	protected static function set_cached_query( $query_hash, $data ) {
294
+	protected static function set_cached_query($query_hash, $data) {
295 295
 
296 296
 		wp_cache_set(
297 297
 			$query_hash,
298 298
 			$data,
299
-			strtolower( __CLASS__ ),
299
+			strtolower(__CLASS__),
300 300
 			5 * MINUTE_IN_SECONDS
301 301
 		);
302 302
 
Please login to merge, or discard this patch.