Test Failed
Push — master ( dd0813...14557d )
by Antony
06:13
created

UnleashedUpdateOrderTask   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 118
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 69
dl 0
loc 118
rs 10
c 0
b 0
f 0
wmc 17

1 Method

Rating   Name   Duplication   Size   Complexity  
D run() 0 85 17
1
<?php
2
3
namespace AntonyThorpe\SilverShopUnleashed;
4
5
use Psr\Http\Message\ResponseInterface;
6
use GuzzleHttp\Exception\RequestException;
7
use DateTime;
8
use SilverStripe\Dev\Debug;
9
use SilverStripe\Control\Email\Email;
10
use SilverShop\Extension\ShopConfigExtension;
11
use AntonyThorpe\Consumer\Consumer;
12
use AntonyThorpe\SilvershopUnleashed\Defaults;
13
14
/**
15
 * Update Order with fresh data from Unleashed's Sales Orders
16
 *
17
 * @package silvershop-unleashed
18
 * @subpackage tasks
19
 */
20
21
abstract class UnleashedUpdateOrderTask extends UnleashedBuildTask
22
{
23
    /**
24
     * @var string
25
     */
26
    protected $title = "Unleashed: Update Orders";
27
28
    /**
29
     * @var string
30
     */
31
    protected $description = "Update Orders in Silvershop with with data received from Unleashed.  Will update the OrderStatus of the Silvershop items.";
32
33
    protected $email_subject = "API Unleashed Software - Update Order Results";
34
35
    /**
36
     * Order status map from Unleashed to Silvershop
37
     *
38
     * For converting from Unleashed Sales Order Status to Silvershop
39
     * @var array
40
     */
41
    protected $order_status_map = [
42
        'Open' => 'Unpaid',
43
        'Parked' => 'Paid',
44
        'Backordered' => 'Processing',
45
        'Placed' => 'Processing',
46
        'Picking' => 'Processing',
47
        'Picked' => 'Processing',
48
        'Packed' => 'Processing',
49
        'Dispatched' => 'Sent',
50
        'Complete' => 'Complete',
51
        'Deleted' => 'MemberCancelled'
52
    ];
53
54
    public function run($request)
55
    {
56
        // Definitions
57
        $config = $this->config();
0 ignored issues
show
Unused Code introduced by
The assignment to $config is dead and can be removed.
Loading history...
58
        $default_source_id = Defaults::config()->source_id;
59
        $query = [];
60
        $consumer = Consumer::get()->find('Title', 'OrderUpdate');  // to get modifiedSince
61
62
        if ($consumer) {
0 ignored issues
show
introduced by
$consumer is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
63
            $date = new DateTime($consumer->ExternalLastEdited);
64
            $query['modifiedSince'] = substr($date->format('Y-m-d\TH:i:s.u'), 0, 23);
65
        }
66
67
        if ($default_source_id) {
68
            $query['sourceId'] = $default_source_id;
69
        }
70
71
        $response = UnleashedAPI::sendCall(
72
            'GET',
73
            'https://api.unleashedsoftware.com/SalesOrders',
74
            ['query' => $query]
75
        );
76
77
        if ($response->getStatusCode() == '200') {
78
            $apidata_array = json_decode($response->getBody()->getContents(), true);
79
            $apidata = $apidata_array['Items'];
80
            $pagination = $apidata_array['Pagination'];
81
            $numberofpages = (int) $pagination['NumberOfPages'];
82
83
            if ($numberofpages > 1) {
84
                for ($i = 2; $i <= $numberofpages; $i++) {
85
                    $response = UnleashedAPI::sendCall(
86
                        'GET',
87
                        'https://api.unleashedsoftware.com/SalesOrders/' . $i,
88
                        ['query' => $query]
89
                    );
90
                    if ($response->getStatusCode() == '200') {
91
                        $apidata_array = json_decode($response->getBody()->getContents(), true);
92
                        $apidata = array_merge($apidata, $apidata_array['Items']);
93
                    }
94
                }
95
            }
96
97
            $this->log('<h3>Update the OrderStatus in Silvershop</h3>');
98
            $loader = OrderBulkLoader::create('SilverShop\Model\Order');
99
            $loader->transforms = [
100
                'Status' => [
101
                    'callback' => function ($value, &$placeholder) {
0 ignored issues
show
Unused Code introduced by
The parameter $placeholder is not used and could be removed. ( Ignorable by Annotation )

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

101
                    'callback' => function ($value, /** @scrutinizer ignore-unused */ &$placeholder) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
102
                        // convert from Unleashed Sales Order status to Silvershop
103
                        return $this->order_status_map[$value];
104
                    }
105
                ]
106
            ];
107
            $results = $loader->updateRecords($apidata, $this->preview);
108
109
            if ($results->UpdatedCount()) {
110
                $this->log(Debug::text($results->getData()));
111
            }
112
            $this->log("Done");
113
114
            // Send email
115
            if ($results->Count() && $this->email_subject && !$this->preview && Email::config()->admin_email) {
116
                $data = $results->getData();
117
                $email = Email::create(
118
                    ShopConfigExtension::config()->email_from ? ShopConfigExtension::config()->email_from : Email::config()->admin_email,
119
                    Email::config()->admin_email,
120
                    $this->email_subject,
121
                    Debug::text($data)
122
                );
123
                $dispatched = $email->send();
124
                if ($dispatched) {
125
                    $this->log("Email sent");
126
                }
127
            }
128
129
            // Create/update Consumer
130
            if (!$this->preview && $apidata) {
131
                if (!$consumer) {
0 ignored issues
show
introduced by
$consumer is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
132
                    $consumer = Consumer::create([
133
                        'Title' => 'OrderUpdate',
134
                        'ExternalLastEditedKey' => 'LastModifiedOn'
135
                    ]);
136
                }
137
                $consumer->setMaxExternalLastEdited($apidata);
138
                $consumer->write();
139
            }
140
        } // end if response == 200
141
    }
142
}
143