-
Notifications
You must be signed in to change notification settings - Fork 2
/
SnipWire.module.php
444 lines (399 loc) · 16.7 KB
/
SnipWire.module.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
<?php
namespace ProcessWire;
/**
* SnipWire - Full Snipcart shopping cart integration for ProcessWire CMF.
* (This module is the master for all other SnipWire modules and files)
*
* Licensed under MPL 2.0 (see LICENSE file provided with this package)
* Copyright 2023 by Martin Gartner
*
* ProcessWire 3.x, Copyright Ryan Cramer
* https://processwire.com
*/
wire('classLoader')->addNamespace('SnipWire\Helpers', __DIR__ . '/helpers');
wire('classLoader')->addNamespace('SnipWire\Services', __DIR__ . '/services');
use SnipWire\Helpers\Functions;
use SnipWire\Helpers\CurrencyFormat;
use SnipWire\Helpers\Taxes;
use SnipWire\Services\ExchangeREST;
use SnipWire\Services\SnipREST;
use SnipWire\Services\Webhooks;
use SnipWire\Services\WireHttpExtended;
class SnipWire extends WireData implements Module, ConfigurableModule
{
public static function getModuleInfo()
{
return [
'title' => __('SnipWire'),
'summary' => __('Full Snipcart shopping cart integration for ProcessWire.'),
'version' => '0.8.7',
'author' => 'Martin Gartner',
'href' => 'https://processwire.com/talk/topic/21554-snipwire-snipcart-integration-for-processwire/',
'icon' => 'shopping-cart',
'singular' => true,
'autoload' => true,
'installs' => [
'ProcessSnipWire',
'MarkupSnipWire',
'FieldtypeSnipWireTaxSelector',
'FieldtypeOptions',
],
'requires' => [
'ProcessWire>=3.0.210',
'PHP>=7.4.0',
],
];
}
const snipWireLogName = 'snipwire';
/** @var SnipWire $snipwireConfig The module config of SnipWire module */
protected $snipwireConfig = null;
/**
* Returns a template array for a currency specific price input field.
*
* Currency specific price input fields will be created on demand by selecting
* currencies in SnipWireModuleConfig.
*
* @return array
*/
public static function getCurrencyFieldTemplate()
{
return [
'name' => 'snipcart_item_price_',
'type' => 'FieldtypeText',
'label' => __('Product Price'),
'notes' => __('Decimal with a dot (.) as separator e.g. 19.99'),
'maxlength' => 20,
'required' => true,
'pattern' => '[-+]?[0-9]*[.]?[0-9]+',
'tags' => 'Snipcart',
];
}
/**
* Initialize module config variables (properties).
* (Called before module config is populated)
*/
public function __construct()
{
parent::__construct();
}
/**
* Initialize the module and set required hooks.
* (Called after module config is populated)
*
* @throws WireException
*/
public function init()
{
/** @var SnipREST $sniprest Custom ProcessWire API variable */
$this->wire('sniprest', new SnipREST());
/** @var ExchangeREST $exchangerest Custom ProcessWire API variable */
$this->wire('exchangerest', new ExchangeREST());
/** @var Webhooks $webhooks Custom ProcessWire API variable */
$this->wire('webhooks', new Webhooks());
// Get SnipWire module config.
// (Holds merged data from DB and default config.
// This works because of using the ModuleConfig class)
$this->snipwireConfig = $this->wire('modules')->get('SnipWire');
if ($this->snipwireConfig->taxes_provider == 'integrated') {
$this->addHookBefore('Modules::saveConfig', $this, 'validateTaxesRepeater');
$this->addHookAfter('Pages::added', $this, 'presetProductTaxesField', ['priority' => 99]);
}
$this->addHookAfter('Pages::added', $this, 'presetProductFields', ['priority' => 99]);
$this->addHookAfter('Pages::saveReady', $this, 'checkSKUUnique');
$this->addHookAfter('Modules::saveConfig', $this, 'manageCurrencyPriceFields');
$this->addHookBefore('ProcessPageView::execute', $this, 'checkWebhookRequest');
$this->addHookAfter('Pages::saved', $this, 'publishSnipcartProduct');
$this->addHookAfter('Pages::unpublished', $this, 'unpublishSnipcartProduct');
$this->addHookAfter('Pages::trashed', $this, 'unpublishSnipcartProduct');
$this->addHookBefore('Modules::uninstall', $this, 'convertFieldtypeTaxSelector');
}
/**
* Validate and sanitize taxes repeater input fields.
* (Method triggered before module config save)
*
* @throws WireException
*/
public function validateTaxesRepeater(HookEvent $event)
{
$class = $event->arguments(0);
if (is_object($class)) $class = $class->className();
// Get class name without namespace
$className = wireClassName($class);
if ($className != 'SnipWire') return;
$fields = $this->wire('modules')->getModuleConfigInputfields($className);
$taxesField = $fields->get('taxes');
$config = $event->arguments(1);
$taxes = wireDecodeJSON($config['taxes']);
if (!count($taxes)) {
$taxesField->error(
$this->_('Taxes repeater has no entries. At least 1 tax setting is required.')
);
return;
}
foreach ($taxes as $key => $tax) {
if (empty($tax['name']) || empty($tax['rate'])) {
$taxesField->error(sprintf(
$this->_('Taxes repeater row [%s]: "Tax name" and "Rate" may not be empty'),
$key + 1
));
}
if (!empty($tax['rate']) && !Functions::checkPattern($tax['rate'], '^[-+]?[0-9]*[.]?[0-9]+$')) {
$taxesField->error(sprintf(
$this->_('Taxes repeater row [%s]: "Rate" value needs to be float'),
$key + 1
));
}
}
}
/**
* Manage currency specific price input fields based on module "currencies" property.
* (Method triggered after module config save)
*
* - Fields will be created on demand (if not exists).
*
* @throws WireException
*/
public function manageCurrencyPriceFields(HookEvent $event)
{
$class = $event->arguments(0);
if (is_object($class)) $class = $class->className();
// Get class name without namespace
$className = wireClassName($class);
if ($className != 'SnipWire') return;
$config = $event->arguments(1);
$currencies = isset($config['currencies']) ? $config['currencies'] : false;
if (empty($currencies) || !is_array($currencies)) return;
$fields = $this->wire('fields');
$modules = $this->wire('modules');
$fieldTemplate = self::getCurrencyFieldTemplate();
$supportedCurrencies = CurrencyFormat::getSupportedCurrencies();
foreach ($currencies as $currency) {
$fieldName = $fieldTemplate['name'] . $currency;
if ($fields->get($fieldName)) continue; // No need to create - already exists!
$fieldLabelCurrencyAdd = isset($supportedCurrencies[$currency])
? $supportedCurrencies[$currency]
: $currency;
$f = new Field();
$f->type = $modules->get($fieldTemplate['type']);
$f->name = $fieldName;
$f->label = $fieldTemplate['label'] . ' (' . $fieldLabelCurrencyAdd . ')';
$f->notes = $fieldTemplate['notes'];
$f->maxlength = $fieldTemplate['maxlength'];
$f->required = $fieldTemplate['required'];
$f->pattern = $fieldTemplate['pattern'];
$f->tags = $fieldTemplate['tags'];
$f->save();
$out = sprintf(
$this->_('Created currency specific field: [%s].'),
$fieldName
);
$out .= ' ' . $this->_('You need to add this field to your product templates manually!');
$this->message($out);
}
}
/**
* Check for webhook request and process them.
* (Method triggered before ProcessPageView execute)
*
* @throws WireException
*/
public function checkWebhookRequest(HookEvent $event)
{
if ($webhooksEndpoint = $this->get('webhooks_endpoint')) {
if ($this->sanitizer->url($this->input->url) == $webhooksEndpoint) {
$this->wire('webhooks')->process();
$event->replace = true;
// @note: Tracy Debug won't work from here on as normal page rendering is omitted!
}
}
}
/**
* Preset value of field snipcart_item_id (SKU) with page ID.
* Preset value of field snipcart_item_taxes (VAT) with first element of taxes config.
* Preset value of checkbox field snipcart_item_taxable, so it's checked by default.
* Preset value of checkbox field snipcart_item_shippable, so it's checked by default.
* Preset value of checkbox field snipcart_item_recurring_shipping, so it's checked by default.
* (Method triggered after Pages added)
*
* @throws WireException
*/
public function presetProductFields(HookEvent $event)
{
$snipwire = $this->wire('snipwire');
if (!$snipwire) return;
$page = $event->arguments(0);
if ($snipwire->isProductTemplate($page->template)) {
if ($page->hasfield('snipcart_item_id')) $page->setAndSave('snipcart_item_id', $page->id);
if ($page->hasfield('snipcart_item_taxable')) $page->setAndSave('snipcart_item_taxable', 1);
if ($page->hasfield('snipcart_item_shippable')) $page->setAndSave('snipcart_item_shippable', 1);
if ($page->hasfield('snipcart_item_stackable')) $page->setAndSave('snipcart_item_stackable', 1);
if ($page->hasfield('snipcart_item_recurring_shipping')) $page->setAndSave('snipcart_item_recurring_shipping', 1);
}
}
/**
* Preset value of field snipcart_item_taxes (VAT) with first element of taxes config.
* (Method triggered after Pages added)
*
* @throws WireException
*/
public function presetProductTaxesField(HookEvent $event)
{
$snipwire = $this->wire('snipwire');
if (!$snipwire) return;
$page = $event->arguments(0);
if ($snipwire->isProductTemplate($page->template)) {
$defaultTax = Taxes::getFirstTax(false, Taxes::taxesTypeProducts);
if ($page->hasfield('snipcart_item_taxes')) $page->setAndSave('snipcart_item_taxes', $defaultTax['name']);
}
}
/**
* Check if the SKU value is unique across all product pages.
* (Method triggered after Pages saveReady -> just before page is saved)
*
* @throws WireException
*/
public function checkSKUUnique(HookEvent $event)
{
$snipwire = $this->wire('snipwire');
if (!$snipwire) return;
$page = $event->arguments(0);
if ($snipwire->isProductTemplate($page->template)) {
$field = $page->getField('snipcart_item_id');
$sku = $page->snipcart_item_id; // SKU field value
if (!$sku) return;
if ($page->isChanged('snipcart_item_id')) {
$exists = $this->wire('pages')->get("snipcart_item_id=$sku, id!=$page, status<" . Page::statusTrash);
if ($exists->id) {
// value is not unique!
$error = $this->_('SKU must be unique');
$exception = sprintf(
$this->_('SKU [%s] is already in use'),
$sku
);
$inputfield = $page->getInputfield($field);
$inputfield->error($error);
throw new WireException($exception); // Prevent saving of non-unique value!
}
}
}
}
/**
* Automatically creates/restores a Snipcart product by manually fetching URL (archived flag is set to false).
* (Method triggered after a page has just been saved)
*
* @throws WireException
*/
public function publishSnipcartProduct(HookEvent $event)
{
$snipwire = $this->wire('snipwire');
$sniprest = $this->wire('sniprest');
$log = $this->wire('log');
if (!$snipwire || !$sniprest) return;
$page = $event->arguments(0);
if ($snipwire->isProductTemplate($page->template)) {
if ($page->isPublic()) {
// Only fetch if published and viewable!
$snipcart_item_id = $page->snipcart_item_id;
$response = $sniprest->postProduct($page->httpUrl);
$dataKey = $page->httpUrl;
$content = $response[$dataKey][WireHttpExtended::resultKeyContent];
$httpCode = $response[$dataKey][WireHttpExtended::resultKeyHttpCode];
$error = $response[$dataKey][WireHttpExtended::resultKeyError];
if ($httpCode == 200 || $httpCode == 201) {
$id = isset($content[0]['id']) ? $content[0]['id'] : '';
$message = sprintf(
$this->_('Fetched Snipcart product with SKU [%1$s] / ID [%2$s]'),
$snipcart_item_id,
$id
);
} else {
$message = sprintf(
$this->_('Snipcart product with SKU [%1$s] could not be fetched. %2$s'),
$snipcart_item_id,
$error
);
}
$log->save(self::snipWireLogName, $message);
}
}
}
/**
* Archive a Snipcart product, so it won't be visible in the products listing anymore (archived flag is set to true).
* (Method triggered after a published page has just been unpublished)
*
* @throws WireException
*/
public function unpublishSnipcartProduct(HookEvent $event)
{
$snipwire = $this->wire('snipwire');
$sniprest = $this->wire('sniprest');
$log = $this->wire('log');
if (!$snipwire || !$sniprest) return;
$page = $event->arguments(0);
if ($snipwire->isProductTemplate($page->template)) {
$snipcart_item_id = $page->snipcart_item_id;
if ($id = $sniprest->getProductId($snipcart_item_id)) {
$response = $sniprest->deleteProduct($id);
$dataKey = $id;
$httpCode = $response[$dataKey][WireHttpExtended::resultKeyHttpCode];
$error = $response[$dataKey][WireHttpExtended::resultKeyError];
if ($httpCode == 200 || $httpCode == 201) {
$message = sprintf(
$this->_('Archived Snipcart product with SKU [%1$s] / ID [%2$s]'),
$snipcart_item_id,
$id
);
} else {
$message = sprintf(
$this->_('Snipcart product with SKU [%1$s] could not be archived. [%2$s]'),
$snipcart_item_id,
$error
);
}
} else {
$message = sprintf(
$this->_('Snipcart product could not be archived! SKU [%s] not found'),
$snipcart_item_id
);
}
$log->save(self::snipWireLogName, $message);
}
}
/**
* Check if there are fields which uses FieldtypeSnipWireTaxSelector and convert them to FieldtypeText.
* This is needed to enable uninstallation of the custom fieldtype and preserve products data!
* (Method triggered before modules uninstall)
*
* @param HookEvent $event
* @throws WireException
*/
public function convertFieldtypeTaxSelector(HookEvent $event)
{
$class = $event->arguments(0);
if ($class == 'SnipWire') {
$fields = $this->wire('fields')->find('type=FieldtypeSnipWireTaxSelector');
if ($fields->count()) {
foreach ($fields as $field) {
$field->type = 'FieldtypeText';
$field->save();
// This step is needed because ProcessWire removes tags when fieldtype is changed!
$field->tags = 'Snipcart';
$field->save();
}
}
}
}
/**
* Called on module uninstall
*
* @throws WireException
*/
public function ___uninstall()
{
// Remove all caches created by SnipWire (SnipWire namespace)
$this->wire('cache')->deleteFor('SnipWire');
// Remove all logs created by SnipWire
$this->wire('log')->delete(self::snipWireLogName);
$this->wire('log')->delete(Webhooks::snipWireWebhooksLogName);
}
}