Completed
Push — master ( 6ba699...b594a8 )
by Andreas
17:55
created

get_cycle_identifier()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.0342

Importance

Changes 0
Metric Value
cc 5
eloc 18
nc 5
nop 1
dl 0
loc 27
ccs 16
cts 18
cp 0.8889
crap 5.0342
rs 9.3554
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package org.openpsa.invoices
4
 * @author CONTENT CONTROL http://www.contentcontrol-berlin.de/
5
 * @copyright CONTENT CONTROL http://www.contentcontrol-berlin.de/
6
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License
7
 */
8
9
/**
10
 * Helper class to process subscription invoicing
11
 *
12
 * @package org.openpsa.invoices
13
 */
14
class org_openpsa_invoices_scheduler extends midcom_baseclasses_components_purecode
15
{
16
    /**
17
     * The deliverable we're processing
18
     *
19
     * @var org_openpsa_sales_salesproject_deliverable_dba
20
     */
21
    private $_deliverable;
22
23
    /**
24
     * The day of month on which subscriptions are invoiced (if none is set, they are invoiced continuously)
25
     *
26
     * @var int
27
     */
28
    private $subscription_day;
29
30 32
    public function __construct(org_openpsa_sales_salesproject_deliverable_dba $deliverable)
31
    {
32 32
        parent::__construct();
33 32
        $this->_deliverable = $deliverable;
34 32
        $this->subscription_day = midcom_baseclasses_components_configuration::get('org.openpsa.sales', 'config')->get('subscription_invoice_day_of_month');
35 32
    }
36
37
    /**
38
     * Initiates a new subscription cycle and registers a midcom.services.at call for the next cycle.
39
     *
40
     * The subscription cycles rely on midcom.services.at. I'm not sure if it is wise to rely on it for such
41
     * a totally mission critical part of OpenPSA. Some safeguards might be wise to add.
42
     */
43 8
    public function run_cycle($cycle_number, $send_invoice = true)
44
    {
45 8
        if (time() < $this->_deliverable->start) {
46 1
            debug_add('Subscription hasn\'t started yet, register the start-up event to $start');
47 1
            return $this->_create_at_entry($cycle_number, $this->_deliverable->start);
48
        }
49
50 7
        debug_add('Running cycle ' . $cycle_number . ' for deliverable "' . $this->_deliverable->title . '"');
51
52 7
        $this_cycle_start = $this->get_cycle_start($cycle_number, time());
53 7
        if ($this->subscription_day && $cycle_number == 1) {
54
            // If there's a fixed day for invoicing, get_cycle_start already picked a future date for cycle 1
55
            $next_cycle_start = $this_cycle_start + 2; // +2 so we don't get overlaps in task
56
        } else {
57 7
            $next_cycle_start = $this->calculate_cycle_next($this_cycle_start);
58
        }
59 7
        $product = org_openpsa_products_product_dba::get_cached($this->_deliverable->product);
60
61 7
        if ($this->_deliverable->state < org_openpsa_sales_salesproject_deliverable_dba::STATE_STARTED) {
62 2
            $this->_deliverable->state = org_openpsa_sales_salesproject_deliverable_dba::STATE_STARTED;
63 2
            $this->_deliverable->update();
64
        }
65
66 7
        if ($send_invoice) {
67 7
            $calculator = new org_openpsa_invoices_calculator();
68 7
            $this_cycle_amount = $calculator->process_deliverable($this->_deliverable, $cycle_number);
69
        }
70
71 7
        $tasks_completed = [];
72 7
        $tasks_not_completed = [];
73 7
        $new_task = null;
74
75 7
        if ($product->orgOpenpsaObtype == org_openpsa_products_product_dba::TYPE_SERVICE) {
0 ignored issues
show
Bug Best Practice introduced by
The property orgOpenpsaObtype does not exist on midcom_core_dbaobject. Since you implemented __get, consider adding a @property annotation.
Loading history...
76
            // Close previous task(s)
77 2
            $last_task = null;
78
79 2
            $qb = org_openpsa_projects_task_dba::new_query_builder();
80 2
            $qb->add_constraint('agreement', '=', $this->_deliverable->id);
81 2
            $qb->add_constraint('status', '<', org_openpsa_projects_task_status_dba::COMPLETED);
82
83 2
            foreach ($qb->execute() as $task) {
84 2
                if (org_openpsa_projects_workflow::complete($task, sprintf($this->_i18n->get_string('completed by subscription %s', 'org.openpsa.sales'), $cycle_number))) {
85 2
                    $tasks_completed[] = $task;
86
                } else {
87
                    $tasks_not_completed[] = $task;
88
                }
89 2
                $last_task = $task;
90
            }
91
92
            // Create task for the duration of this cycle
93 2
            $task_title = sprintf('%s %s', $this->_deliverable->title, $this->get_cycle_identifier($this_cycle_start));
0 ignored issues
show
Bug introduced by
It seems like $this->get_cycle_identifier($this_cycle_start) can also be of type false; however, parameter $args of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

93
            $task_title = sprintf('%s %s', $this->_deliverable->title, /** @scrutinizer ignore-type */ $this->get_cycle_identifier($this_cycle_start));
Loading history...
94 2
            $new_task = $this->create_task($this_cycle_start, $next_cycle_start - 1, $task_title, $last_task);
95
        }
96
97
        // TODO: Warehouse management: create new order
98 7
        if (   $this->_deliverable->end < $next_cycle_start
99 7
            && $this->_deliverable->end != 0) {
100 1
            debug_add('Do not register next cycle, the contract ends before');
101 1
            return $this->_deliverable->end_subscription();
102
        }
103
104 7
        if (!$this->_create_at_entry($cycle_number + 1, $next_cycle_start)) {
105
            return false;
106
        }
107 7
        if ($send_invoice) {
108 7
            $this->_notify_owner($calculator, $cycle_number, $next_cycle_start, $this_cycle_amount, $tasks_completed, $tasks_not_completed, $new_task);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $calculator does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $this_cycle_amount does not seem to be defined for all execution paths leading up to this point.
Loading history...
109
        }
110 7
        return true;
111
    }
112
113 8
    private function _create_at_entry($cycle_number, $start)
114
    {
115
        $args = [
116 8
            'deliverable' => $this->_deliverable->guid,
117 8
            'cycle'       => $cycle_number,
118
        ];
119 8
        $at_entry = new midcom_services_at_entry_dba();
120 8
        $at_entry->start = $start;
121 8
        $at_entry->component = 'org.openpsa.sales';
122 8
        $at_entry->method = 'new_subscription_cycle';
123 8
        $at_entry->arguments = $args;
124
125 8
        if (!$at_entry->create()) {
126
            debug_add('AT registration failed, last midgard error was: ' . midcom_connection::get_error_string(), MIDCOM_LOG_WARN);
127
            return false;
128
        }
129 8
        debug_add('AT entry for cycle ' . $cycle_number . ' created');
130 8
        org_openpsa_relatedto_plugin::create($at_entry, 'midcom.services.at', $this->_deliverable, 'org.openpsa.sales');
131 8
        return true;
132
    }
133
134 7
    private function _notify_owner($calculator, $cycle_number, $next_run, $invoiced_sum, $tasks_completed, $tasks_not_completed, $new_task)
135
    {
136 7
        $siteconfig = org_openpsa_core_siteconfig::get_instance();
137 7
        $message = [];
138 7
        $salesproject = org_openpsa_sales_salesproject_dba::get_cached($this->_deliverable->salesproject);
139
        try {
140 7
            $owner = midcom_db_person::get_cached($salesproject->owner);
0 ignored issues
show
Bug Best Practice introduced by
The property owner does not exist on midcom_core_dbaobject. Since you implemented __get, consider adding a @property annotation.
Loading history...
141
        } catch (midcom_error $e) {
142
            $e->log();
143
            return;
144
        }
145 7
        $customer = $salesproject->get_customer();
0 ignored issues
show
Bug introduced by
The method get_customer() does not exist on midcom_core_dbaobject. It seems like you code against a sub-type of midcom_core_dbaobject such as org_openpsa_invoices_invoice_dba or org_openpsa_sales_salesproject_dba. ( Ignorable by Annotation )

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

145
        /** @scrutinizer ignore-call */ 
146
        $customer = $salesproject->get_customer();
Loading history...
146 7
        $l10n = $this->_i18n->get_l10n('org.openpsa.sales');
147 7
        if ($next_run === null) {
148
            $next_run_label = $l10n->get('no more cycles');
149
        } else {
150 7
            $next_run_label = $l10n->get_formatter()->date($next_run);
151
        }
152
153
        // Title for long notifications
154 7
        $message['title'] = sprintf($l10n->get('subscription cycle %d closed for agreement %s (%s)'), $cycle_number, $this->_deliverable->title, $customer->get_label());
155
156
        // Content for long notifications
157 7
        $message['content'] = "{$message['title']}\n\n";
158 7
        $message['content'] .= $l10n->get('invoiced') . ": {$invoiced_sum}\n\n";
159
160 7
        if ($invoiced_sum > 0) {
161 4
            $invoice = $calculator->get_invoice();
162 4
            $message['content'] .= $this->_l10n->get('invoice') . " {$invoice->number}:\n";
163 4
            $url = $siteconfig->get_node_full_url('org.openpsa.invoices');
164 4
            $message['content'] .= $url . 'invoice/' . $invoice->guid . "/\n\n";
0 ignored issues
show
Bug introduced by
Are you sure $url of type false|mixed|null can be used in concatenation? ( Ignorable by Annotation )

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

164
            $message['content'] .= /** @scrutinizer ignore-type */ $url . 'invoice/' . $invoice->guid . "/\n\n";
Loading history...
165
        }
166
167 7
        if (!empty($tasks_completed)) {
168 2
            $message['content'] .= "\n" . $l10n->get('tasks completed') . ":\n";
169
170 2
            foreach ($tasks_completed as $task) {
171 2
                $message['content'] .= "{$task->title}: {$task->reportedHours}h\n";
172
            }
173
        }
174
175 7
        if (!empty($tasks_not_completed)) {
176
            $message['content'] .= "\n" . $l10n->get('tasks not completed') . ":\n";
177
178
            foreach ($tasks_not_completed as $task) {
179
                $message['content'] .= "{$task->title}: {$task->reportedHours}h\n";
180
            }
181
        }
182
183 7
        if ($new_task) {
184 2
            $message['content'] .= "\n" . $l10n->get('created new task') . ":\n";
185 2
            $message['content'] .= "{$new_task->title}\n";
186
        }
187
188 7
        $message['content'] .= "\n" . $l10n->get('next run') . ": {$next_run_label}\n\n";
189 7
        $message['content'] .= $this->_i18n->get_string('agreement', 'org.openpsa.projects') . ":\n";
190
191 7
        $url = $siteconfig->get_node_full_url('org.openpsa.sales');
192 7
        $message['content'] .= $url . 'deliverable/' . $this->_deliverable->guid . '/';
193
194
        // Content for short notifications
195 7
        $message['abstract'] = sprintf($l10n->get('%s: closed subscription cycle %d for agreement %s. invoiced %d. next cycle %s'), $customer->get_label(), $cycle_number, $this->_deliverable->title, $invoiced_sum, $next_run_label);
196
197
        // Send the message out
198 7
        org_openpsa_notifications::notify('org.openpsa.sales:new_subscription_cycle', $owner->guid, $message);
199 7
    }
200
201
    /**
202
     * @todo Check if we already have an open task for this delivery?
203
     */
204 3
    public function create_task($start, $end, $title, $source_task = null)
205
    {
206 3
        $salesproject = org_openpsa_sales_salesproject_dba::get_cached($this->_deliverable->salesproject);
207
208
        // Check if we already have a project for the sales project
209 3
        $project = $salesproject->get_project();
0 ignored issues
show
Bug introduced by
The method get_project() does not exist on midcom_core_dbaobject. Did you maybe mean get_parent()? ( Ignorable by Annotation )

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

209
        /** @scrutinizer ignore-call */ 
210
        $project = $salesproject->get_project();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
210
211
        // Create the task
212 3
        $task = new org_openpsa_projects_task_dba();
213 3
        $task->agreement = $this->_deliverable->id;
214 3
        $task->customer = $salesproject->customer;
0 ignored issues
show
Bug Best Practice introduced by
The property customer does not exist on midcom_core_dbaobject. Since you implemented __get, consider adding a @property annotation.
Loading history...
215 3
        $task->title = $title;
216 3
        $task->description = $this->_deliverable->description;
217 3
        $task->start = $start;
218 3
        $task->end = $end;
219 3
        $task->plannedHours = $this->_deliverable->plannedUnits;
220
221 3
        $task->manager = $salesproject->owner;
0 ignored issues
show
Bug Best Practice introduced by
The property owner does not exist on midcom_core_dbaobject. Since you implemented __get, consider adding a @property annotation.
Loading history...
222 3
        if ($project) {
223 3
            $task->project = $project->id;
224 3
            $task->orgOpenpsaAccesstype = $project->orgOpenpsaAccesstype;
225 3
            $task->orgOpenpsaOwnerWg = $project->orgOpenpsaOwnerWg;
226
        }
227
228 3
        if (!empty($source_task)) {
229 3
            $task->priority = $source_task->priority;
230 3
            $task->manager = $source_task->manager;
231
        }
232
233
        // TODO: Figure out if we really want to keep this
234 3
        $task->hoursInvoiceableDefault = true;
235 3
        if (!$task->create()) {
236
            throw new midcom_error("The task for this cycle could not be created. Last Midgard error was: " . midcom_connection::get_error_string());
237
        }
238 3
        $task->add_members('contacts', array_keys($salesproject->contacts));
0 ignored issues
show
Bug introduced by
It seems like $salesproject->contacts can also be of type null; however, parameter $input of array_keys() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

238
        $task->add_members('contacts', array_keys(/** @scrutinizer ignore-type */ $salesproject->contacts));
Loading history...
Bug Best Practice introduced by
The property contacts does not exist on midcom_core_dbaobject. Since you implemented __get, consider adding a @property annotation.
Loading history...
239 3
        if (!empty($source_task)) {
240 3
            $source_task->get_members();
241 3
            $task->add_members('resources', array_keys($source_task->resources));
242
        }
243
244
        // Copy tags from deliverable so we can seek resources
245 3
        $tagger = new net_nemein_tag_handler();
246 3
        $tagger->copy_tags($this->_deliverable, $task);
247
248 3
        midcom::get()->uimessages->add($this->_i18n->get_string('org.openpsa.sales', 'org.openpsa.sales'), sprintf($this->_i18n->get_string('created task "%s"', 'org.openpsa.sales'), $task->title));
249 3
        return $task;
250
    }
251
252
    /**
253
     * Calculcate remaining cycles until salesproject's end or the specified number of months passes
254
     *
255
     * @param integer $months The maximum number of months to look forward
256
     * @param integer $start The timestamp from which to begin
257
     * @return integer
258
     */
259 13
    public function calculate_cycles($months = null, $start = null)
260
    {
261 13
        if ($start === null) {
262 9
            $start = time();
263
        }
264 13
        $cycles = 0;
265 13
        $cycle_time = $this->_deliverable->start;
266 13
        $end_time = $this->_deliverable->end;
267
268
        // This takes care of invalid/unsupported unit configs
269 13
        if ($this->calculate_cycle_next($cycle_time) === false) {
270
            return $cycles;
271
        }
272
273 13
        while ($cycle_time < $start) {
274 8
            $cycle_time = $this->calculate_cycle_next($cycle_time);
275
        }
276
277 13
        if ($months !== null) {
278 9
            $end_time = mktime(date('H', $cycle_time), date('m', $cycle_time), date('i', $cycle_time), date('m', $cycle_time) + $months, date('d', $cycle_time), date('Y', $cycle_time));
0 ignored issues
show
Bug introduced by
date('i', $cycle_time) of type string is incompatible with the type integer expected by parameter $second of mktime(). ( Ignorable by Annotation )

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

278
            $end_time = mktime(date('H', $cycle_time), date('m', $cycle_time), /** @scrutinizer ignore-type */ date('i', $cycle_time), date('m', $cycle_time) + $months, date('d', $cycle_time), date('Y', $cycle_time));
Loading history...
Bug introduced by
date('Y', $cycle_time) of type string is incompatible with the type integer expected by parameter $year of mktime(). ( Ignorable by Annotation )

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

278
            $end_time = mktime(date('H', $cycle_time), date('m', $cycle_time), date('i', $cycle_time), date('m', $cycle_time) + $months, date('d', $cycle_time), /** @scrutinizer ignore-type */ date('Y', $cycle_time));
Loading history...
Bug introduced by
date('d', $cycle_time) of type string is incompatible with the type integer expected by parameter $day of mktime(). ( Ignorable by Annotation )

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

278
            $end_time = mktime(date('H', $cycle_time), date('m', $cycle_time), date('i', $cycle_time), date('m', $cycle_time) + $months, /** @scrutinizer ignore-type */ date('d', $cycle_time), date('Y', $cycle_time));
Loading history...
Bug introduced by
date('H', $cycle_time) of type string is incompatible with the type integer expected by parameter $hour of mktime(). ( Ignorable by Annotation )

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

278
            $end_time = mktime(/** @scrutinizer ignore-type */ date('H', $cycle_time), date('m', $cycle_time), date('i', $cycle_time), date('m', $cycle_time) + $months, date('d', $cycle_time), date('Y', $cycle_time));
Loading history...
Bug introduced by
It seems like $cycle_time can also be of type false; however, parameter $timestamp of date() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

278
            $end_time = mktime(date('H', /** @scrutinizer ignore-type */ $cycle_time), date('m', $cycle_time), date('i', $cycle_time), date('m', $cycle_time) + $months, date('d', $cycle_time), date('Y', $cycle_time));
Loading history...
Bug introduced by
date('m', $cycle_time) of type string is incompatible with the type integer expected by parameter $minute of mktime(). ( Ignorable by Annotation )

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

278
            $end_time = mktime(date('H', $cycle_time), /** @scrutinizer ignore-type */ date('m', $cycle_time), date('i', $cycle_time), date('m', $cycle_time) + $months, date('d', $cycle_time), date('Y', $cycle_time));
Loading history...
279
        }
280
281 13
        $cycles = 0;
282 13
        while ($cycle_time < $end_time) {
283 13
            $cycle_time = $this->calculate_cycle_next($cycle_time);
284 13
            if ($cycle_time <= $end_time) {
285 13
                $cycles++;
286
            }
287
        }
288 13
        return $cycles;
289
    }
290
291 21
    public function calculate_cycle_next($time)
292
    {
293 21
        switch ($this->_deliverable->unit) {
294 21
            case 'm':
295
                // Monthly recurring subscription
296 14
                $new_date = $this->_add_month($time, 1);
297 14
                break;
298 7
            case 'q':
299
                // Quarterly recurring subscription
300 3
                $new_date = $this->_add_month($time, 3);
301 3
                break;
302 4
            case 'hy':
303
                // Half-yearly recurring subscription
304 1
                $new_date = $this->_add_month($time, 6);
305 1
                break;
306 3
            case 'y':
307
                // Yearly recurring subscription
308 2
                $new_date = new DateTime('+1 year ' . gmdate('Y-m-d', $time), new DateTimeZone('GMT'));
309 2
                break;
310
            default:
311 1
                debug_add('Unrecognized unit value "' . $this->_deliverable->unit . '" for deliverable ' . $this->_deliverable->guid . ", returning false", MIDCOM_LOG_WARN);
312 1
                return false;
313
        }
314
315
        //If previous cycle was run at the end of the month, the new one should be at the end of the month as well
316 20
        $date = new DateTime(gmdate('Y-m-d', $time), new DateTimeZone('GMT'));
317 20
        if (   $date->format('t') == $date->format('j')
318 20
            && $new_date->format('t') != $new_date->format('j')) {
319 5
            $new_date->setDate((int) $new_date->format('Y'), (int) $new_date->format('m'), (int) $new_date->format('t'));
320
        }
321 20
        return (int) $new_date->format('U');
322
    }
323
324
    /**
325
     * Workaround for odd PHP DateTime behavior where for example
326
     * 2012-10-31 + 1 month would return 2012-12-01. This function makes
327
     * sure the new date is always in the expected month (so in the example above
328
     * it would return 2012-11-30)
329
     *
330
     * @param integer $time Original timestamp
331
     * @param integer $offset number of months to add
332
     * @return DateTime The new date object
333
     */
334 18
    private function _add_month($time, $offset)
335
    {
336 18
        $orig = new DateTime(gmdate('Y-m-d', $time), new DateTimeZone('GMT'));
337 18
        $new_date = clone $orig;
338 18
        $new_date->modify('+' . $offset . ' months');
339 18
        $control = clone $new_date;
340 18
        $control->modify('-' . $offset . ' months');
341
342 18
        while ($orig->format('m') !== $control->format('m')) {
343 6
            $new_date->modify('-1 day');
344 6
            $control = clone $new_date;
345 6
            $control->modify('-' . $offset . ' months');
346
        }
347
348 18
        return $new_date;
349
    }
350
351 10
    public function get_cycle_start($cycle_number, $time)
352
    {
353 10
        if ($cycle_number == 1) {
354 7
            if ($this->subscription_day) {
355 3
                return gmmktime(0, 0, 0, date('n', $time) + 1, $this->subscription_day, date('Y', $time));
0 ignored issues
show
Bug introduced by
date('Y', $time) of type string is incompatible with the type integer expected by parameter $year of gmmktime(). ( Ignorable by Annotation )

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

355
                return gmmktime(0, 0, 0, date('n', $time) + 1, $this->subscription_day, /** @scrutinizer ignore-type */ date('Y', $time));
Loading history...
356
            }
357
358
            // no explicit day of month set for invoicing, use the deliverable start date
359 4
            return $this->_deliverable->start;
360
        }
361
362
        // cycle number > 1
363 4
        return $time;
364
    }
365
366 6
    public function get_cycle_identifier($time)
367
    {
368 6
        $date = new DateTime(gmdate('Y-m-d', $time), new DateTimeZone('GMT'));
369
370 6
        switch ($this->_deliverable->unit) {
371 6
            case 'm':
372
                // Monthly recurring subscription
373 3
                $identifier = $date->format('Y-m');
374 3
                break;
375 3
            case 'q':
376
                // Quarterly recurring subscription
377 1
                $identifier = ceil(((int)$date->format('n')) / 4) . 'Q' . $date->format('y');
378 1
                break;
379 2
            case 'hy':
380
                // Half-yearly recurring subscription
381 1
                $identifier = ceil(((int)$date->format('n')) / 6) . '/' . $date->format('Y');
382 1
                break;
383 1
            case 'y':
384
                // Yearly recurring subscription
385 1
                $identifier = $date->format('Y');
386 1
                break;
387
            default:
388
                debug_add('Unrecognized unit value "' . $this->_deliverable->unit . '" for deliverable ' . $this->_deliverable->guid . ", returning false", MIDCOM_LOG_WARN);
389
                return false;
390
        }
391
392 6
        return $identifier;
393
    }
394
}
395