Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 140
0.00% covered (danger)
0.00%
0 / 11
CRAP
n/a
0 / 0
zeroBS_integrations_getCustomer
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
zeroBS_integrations_addOrUpdateCustomer
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
600
zeroBS_integrations_addOrUpdateCompany
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
552
zeroBS_integrations_getCompany
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
zeroBS_integrations_addOrUpdateTransaction
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
380
zeroBS_integrations_addOrUpdateTask
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
72
zeroBS_integrations_getTransaction
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
zeroBS_integrations_getAllCategories
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
2
zeroBS_integrations_searchCustomers
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
zeroBS_integrations_addLog
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
zeroBS_integrations_getCustomFields
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/*
3 * Jetpack CRM
4 * https://jetpackcrm.com
5 * V1.20
6 *
7 * Copyright 2020 Automattic
8 *
9 * Date: 01/11/16
10 */
11
12defined( 'ZEROBSCRM_PATH' ) || exit( 0 );
13
14/*
15======================================================
16    Integration specific extension functions (#MIKELOOK)
17    ====================================================== */
18
19/*
20    |=======================================
21    |   zeroBS_integrations_getCustomer
22    |=======================================
23    | Retrieves a customer record (as usual _getCustomer func) - but one that has been inserted via import from an external source
24    | E.g. Woo Imported, Paypal imported, whatever
25    | A customer can exist with multiple import IDs, which lets us patch across services.
26    | E.g. Customer has a woo id of customer1@gmail.com (woo uses emails), and a paypal id of customer1@gmail.com (or another email, paypal will also use emails)
27    | Then that customer could be called with either of these, but would get the same main "customer" record
28    | zeroBS_integrations_getCustomer('woo','customer1@gmail.com')
29    | zeroBS_integrations_getCustomer('pay','customer1@gmail.com')
30    | These "externalSource"s can be flags we agree on, and add here for reference
31    |       23/01/2015:
32    |           'woo' = WooCommerce
33    |           'pay' = Paypal
34    |       ... for these to work they must be added to $zbscrmApprovedExternalSources; at top of ZeroBSCRMExternalSources.php or via extension hook in
35    | To be further expanded if  req.
36    |=======================================
37    | Returns:
38    |   Customer obj (std class)
39    |       or
40    |   False (boolean) (customer does not exist)
41    |=======================================
42    | Check via: if ($customerobj !== false)
43    |=======================================
44*/
45function zeroBS_integrations_getCustomer( $externalSource = '', $externalID = '' ) {
46
47    #} Do query for ID
48    $potentialCustomerID = zeroBS_getCustomerIDWithExternalSource( $externalSource, $externalID );
49
50    if ( $potentialCustomerID !== false ) {
51
52        #} If so, pass full deets via this
53        return zeroBS_getCustomer( $potentialCustomerID );
54
55    }
56
57    #} If it gets here, it failed
58    return false;
59}
60
61/*
62    |=======================================
63    |   zeroBS_integrations_addOrUpdateCustomer
64    |=======================================
65    | Add's a new customer, or updates an existing customer, where their externalSource + externalID matches an existing customer (if specified)
66    | e.g. if it's a woo customer import and woo uses 'usersemail' as their unique id, then you'd specify 'woo' and 'theiremail@whatever.com' as the source + ID
67    | This only works with specific external sources, as 'zeroBS_integrations_getCustomer'
68    | These "externalSource"s can be flags we agree on, and add here for reference
69    |       01/06/2016:
70    |           'woo' = WooCommerce
71    |           'pay' = Paypal
72    |       01/08/2016:
73    |           'form' = Form Capture
74    |       11/12/2016:
75    |           'grav' = Gravity Forms
76    |
77    | Usage:
78
79            zeroBS_integrations_addOrUpdateCustomer('woo','woodyhayday2@smt.com',array(
80
81                'zbsc_email' => 'woodyhayday2@smt.com',
82
83                'zbsc_status' => 'Lead',
84                'zbsc_prefix' => 'Mr',
85                'zbsc_fname' => 'Woody',
86                'zbsc_lname' => 'Hayday',
87                'zbsc_addr1' => 'First Addr',
88                'zbsc_addr2' => '2nd Addr',
89                'zbsc_city' => 'London',
90                'zbsc_county' => 'G London',
91                'zbsc_postcode' => 'AL1 111',
92                'zbsc_hometel' => '0123456789',
93                'zbsc_worktel' => '999',
94                'zbsc_mobtel' => '333',
95                'zbsc_notes' => 'Multi Line
96                Notes
97                Kick Ass',
98
99                #} custom fields are set as cf(int) and so are per-install dependent, you probs don't ever want to insert these :) :D
100                #'zbsc_cf1' => 'Google'
101
102            ),
103
104                'customer_date as per mike!',
105
106                'none',
107
108                false,
109
110                false
111
112            );
113
114    |
115    | ... note "woo" external source flag
116    | ... note "woodyhayday2@smt.com" - my ID within woo
117    | ... note normal customer fields in array, prefixed with 'zbsc_'
118    | ... NOTE: Mike added customer_date
119    | ... Note: From v1.1.18 we also have fallback logs:
120    | --------------------------------------------------
121    | Fallback Logs:
122    |   Pass either:
123    |       'none' = do nothing if user already exists
124    |       'auto' = automatically create log (NOT WORKING YET)
125    |       OR:
126    |       array(
127    |           'type' => 'Form Filled',#'form_filled',
128    |           'shortdesc' => 'Dude filled out the form x on y',
129    |           'longdesc' => ''
130    |       )
131    |
132    |           (Long desc is optional)
133    |
134    |           #} CURRENT Note Types (use first field/key e.g. "form_filled") (v1.1.18 - 20/09/16)
135    |
136    |           'note': { label: 'Note', ico: 'fa-sticky-note-o' },
137    |           'call': { label: 'Call', ico: 'fa-phone-square' },
138    |           'email': { label: 'Email', ico: 'fa-envelope-o' },
139    |           'meeting': { label: 'Meeting', ico: 'fa-users' },
140    |           'quote__sent': { label: 'Quote: Sent', ico: 'fa-share-square-o' },
141    |           'quote__accepted': { label: 'Quote: Accepted', ico: 'fa-thumbs-o-up' },
142    |           'quote__refused': { label: 'Quote: Refused', ico: 'fa-ban' },
143    |           'invoice__sent': { label: 'Invoice: Sent', ico: 'fa-share-square-o' },
144    |           'invoice__part_paid': { label: 'Invoice: Part Paid', ico: 'fa-money' },
145    |           'invoice__paid': { label: 'Invoice: Paid', ico: 'fa-money' },
146    |           'invoice__refunded': { label: 'Invoice: Refunded', ico: 'fa-money' },
147    |           'transaction': { label: 'Transaction', ico: 'fa-credit-card' },
148    |           'tweet': { label: 'Tweet', ico: 'fa-twitter' },
149    |           'facebook_post': { label: 'Facebook Post', ico: 'fa-facebook-official' },
150    |           'created': { label: 'Created', ico: 'fa-plus-circle' },
151    |           'updated': { label: 'Updated', ico: 'fa-pencil-square-o' },
152    |           'quote_created': { label: 'Quote Created', ico: 'fa-plus-circle' },
153    |           'invoice_created': { label: 'Invoice Created', ico: 'fa-plus-circle' },
154    |           'form_filled': { label: 'Form Filled', ico: 'fa-wpforms'}
155    |
156    | --------------------------------------------------
157    |
158    |
159    |
160    |   #} RE: $extraMeta (This isn't used anywhere yet, talk to WH before using)
161    |
162    |       ... this is a key value array passable to add extra values to customers
163    |       ... should look like:
164    |
165    |       $extraMeta = array(
166    |
167    |           array('key_here',12345),
168    |           array('another','what')
169    |
170    |       )
171    |
172    |       ... which will add the following meta to a customer:
173    |
174    |       zbs_customer_extra_key_here = 12345
175    |       zbs_customer_extra_another = what
176    |
177    |       ... BRUTALLY - no checking, just overwrites! (so be careful)
178    |
179    |   #} Re: $automatorPassthrough
180    |
181    |       ... adding anything here allows it to be passed through to the internal automator (which currently sets notes)
182    |       ... this means you can pass an array with note str overrides... e.g.
183    |
184    |       array(
185    |
186    |           'note_override' => array(
187    |
188    |                       'type' => 'Form Filled',#'form_filled',
189    |                       'shortdesc' => 'Dude filled out the form x on y',
190    |                       'longdesc' => ''
191    |
192    |           )
193    |
194    |       )
195    |
196    |       ... see recipes to see what's useful :)
197    |
198    |=======================================
199    |   27/09/16: $emailAlreadyExistsAction
200    |
201    |       This is a flag to say what to do in this circumstance: User obj passed has an email (in $customerFields['zbsc_email']) which matches a customer in DB already
202    |       ... options:
203    |           'update': Update customer record (and add external source) (BRUTAL override)
204    |           'skip': Do nothing
205    |           'notifyexit': quit + notify
206    |       ... this func is mostly future proofing, as there may be times we want to avoid overriding existing data from an import e.g.
207    |
208    |=======================================
209    | ... Made this func super easy so you can just fire it when you're not sure if add or update... :) it'll deal.
210    |=======================================
211    | Returns:
212    |   Customer ID
213    |       or
214    |   False (boolean) (customer create/update failed)
215    |=======================================
216*/
217function zeroBS_integrations_addOrUpdateCustomer( $externalSource = '', $externalID = '', $customerFields = array(), $customerDate = '', $fallbackLog = 'auto', $extraMeta = false, $automatorPassthroughArray = false, $emailAlreadyExistsAction = 'update', $fieldPrefix = 'zbsc_' ) {
218
219    #} leave this true and it'll run as normal.
220    $usualUpdate = true;
221
222    $potentialCustomerIDfromEmail = false;
223
224    if ( ! empty( $externalSource ) && ! empty( $externalID ) && is_array( $customerFields ) && count( $customerFields ) > 0 ) {
225
226        if ( isset( $customerFields['zbsc_email'] ) && ! empty( $customerFields['zbsc_email'] ) ) {
227
228            #} First check for email in cust list
229            $potentialCustomerIDfromEmail = zeroBS_getCustomerIDWithEmail( $customerFields['zbsc_email'] );
230
231            #} If so... act based on $emailAlreadyExistsAction param
232            if ( ! empty( $potentialCustomerIDfromEmail ) ) {
233
234                #} So we have a customer with this email...
235                switch ( $emailAlreadyExistsAction ) {
236
237                    /*
238                    not built out yet...
239                    case 'addextsrc':
240
241                        #} Just add the external source
242
243                        break; */
244                    case 'update':
245                        #} Just let it roll on...
246                        $usualUpdate = true;
247
248                        break;
249                    case 'skip':
250                        #} don't do nothin :)
251                        $usualUpdate = false;
252
253                        break;
254                    case 'notifyexit':
255                        #} Notify + exit
256                        echo esc_html( 'Contact Add/Update Issue: A contact already exists with the email "' . $customerFields['zbsc_email'] . '" (ID: ' . $potentialCustomerIDfromEmail . '), user could not be processed!' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
257                        exit( 0 );
258
259                        break;
260
261                }
262            }
263        }
264
265        #} =========================================================================================
266        #} NO existing user! Proceed as before!
267        #} =========================================================================================
268        if ( $usualUpdate ) {
269
270            // if ID specifically passed, use that :)
271            if ( isset( $customerFields['id'] ) && ! empty( $customerFields['id'] ) && $customerFields['id'] > 0 ) {
272
273                $potentialCustomerID = $customerFields['id'];
274
275            } else {
276
277                #} Do query for ID
278                $potentialCustomerID = zeroBS_getCustomerIDWithExternalSource( $externalSource, $externalID );
279
280            }
281
282            #} If ID empty, but $potentialCustomerIDfromEmail (from above) not, use $potentialCustomerIDfromEmail
283            if ( ( $potentialCustomerID === false || $potentialCustomerID == -1 ) && $potentialCustomerIDfromEmail !== false ) {
284                $potentialCustomerID = $potentialCustomerIDfromEmail;
285            }
286
287            #} Default fallback log creation
288            $fallbackLogToPass = false;
289            if (
290                ! isset( $fallbackLog ) ||
291                ! is_array( $fallbackLog )
292            ) {
293
294                #} create default fallback log, unless $fallbackLog is set to 'none'
295                if ( $fallbackLog !== 'none' ) {
296
297                    #} Autogen
298                    #} Left this out for v1.1.18... needs thought.
299                    #} Do we really want to put "woo source added"? It might get added loads.
300                    #} For now leave as manual...
301
302                }
303            } elseif ( is_array( $fallbackLog ) ) {
304
305                #} Fallback log is probably set, just pass it along.
306                $fallbackLogToPass = $fallbackLog;
307
308            }
309
310            #} Here we're passing along any automator pass through
311            #} ... which will typically be overrides for creation logs or any extra params to give to internal automator.
312            $automatorPassthrough = false;
313            if ( isset( $automatorPassthroughArray ) && is_array( $automatorPassthroughArray ) ) {
314                $automatorPassthrough = $automatorPassthroughArray;
315            }
316
317            #} Not yet used, ask WH
318            // Now passing through 2.24+ $extraMeta = false;
319
320            #} Brutal add/update
321            #} MS - 3rd Jan 2019 - this (eventually) just calls the usual _addUpdateCustomer function
322            $customerID = zeroBS_addUpdateCustomer( $potentialCustomerID, $customerFields, $externalSource, $externalID, $customerDate, $fallbackLogToPass, $extraMeta, $automatorPassthrough, -1, $fieldPrefix );
323            return $customerID;
324
325        } #} / usual update
326
327    } else {
328        return false;
329    }
330}
331
332/*
333    |=======================================
334    |   zeroBS_integrations_addOrUpdateCompany
335    |=======================================
336    | Add's a new Company, or updates an existing Company, where their externalSource + externalID matches an existing Company (if specified)
337    | NOTE: This is different from zeroBS_integrations_addOrUpdateCustomer, in that the externalID must be COMPANY NAME
338    | This only works with specific external sources, as 'zeroBS_integrations_getCompany'
339    | These "externalSource"s can be flags we agree on, and add here for reference
340    |       23/01/2015:
341    |           'woo' = WooCommerce
342    |           'pay' = Paypal
343    |           'form' = Form Capture
344    |
345    | Usage:
346
347            zeroBS_integrations_addOrUpdateCompany('woo','Dell',array(
348
349                'zbsc_coname' => 'Dell',
350
351                'zbsc_status' => 'Lead',
352                'zbsc_addr1' => 'First Addr',
353                'zbsc_addr2' => '2nd Addr',
354                'zbsc_city' => 'London',
355                'zbsc_county' => 'G London',
356                'zbsc_postcode' => 'AL1 111',
357                'zbsc_hometel' => '0123456789',
358                'zbsc_worktel' => '999',
359                'zbsc_mobtel' => '333',
360                'zbsc_notes' => 'Multi Line
361                Notes
362                Kick Ass',
363
364                #} custom fields are set as cf(int) and so are per-install dependent, you probs don't ever want to insert these :) :D
365                #'zbsc_cf1' => 'Google'
366
367            ),
368
369                'customer_date as per mike!',
370
371                'none',
372
373                false,
374
375                false
376
377            );
378
379    |
380    | ... note "woo" external source flag
381    | ... note "woodyhayday2@smt.com" - my ID within woo
382    | ... note normal customer fields in array, prefixed with 'zbsc_'
383    | ... NOTE: Mike added customer_date
384    | ... Note: From v1.1.18 we also have fallback logs:
385    | --------------------------------------------------
386    | Fallback Logs:
387    |   Pass either:
388    |       'none' = do nothing if user already exists
389    |       'auto' = automatically create log (NOT WORKING YET)
390    |       OR:
391    |       array(
392    |           'type' => 'Form Filled',#'form_filled',
393    |           'shortdesc' => 'Dude filled out the form x on y',
394    |           'longdesc' => ''
395    |       )
396    |
397    |           (Long desc is optional)
398    |
399    |           #} CURRENT Note Types (use first field/key e.g. "form_filled") (v1.1.18 - 20/09/16)
400    |
401    |           'note': { label: 'Note', ico: 'fa-sticky-note-o' },
402    |           'call': { label: 'Call', ico: 'fa-phone-square' },
403    |           'email': { label: 'Email', ico: 'fa-envelope-o' },
404    |           'meeting': { label: 'Meeting', ico: 'fa-users' },
405    |           'quote__sent': { label: 'Quote: Sent', ico: 'fa-share-square-o' },
406    |           'quote__accepted': { label: 'Quote: Accepted', ico: 'fa-thumbs-o-up' },
407    |           'quote__refused': { label: 'Quote: Refused', ico: 'fa-ban' },
408    |           'invoice__sent': { label: 'Invoice: Sent', ico: 'fa-share-square-o' },
409    |           'invoice__part_paid': { label: 'Invoice: Part Paid', ico: 'fa-money' },
410    |           'invoice__paid': { label: 'Invoice: Paid', ico: 'fa-money' },
411    |           'invoice__refunded': { label: 'Invoice: Refunded', ico: 'fa-money' },
412    |           'transaction': { label: 'Transaction', ico: 'fa-credit-card' },
413    |           'tweet': { label: 'Tweet', ico: 'fa-twitter' },
414    |           'facebook_post': { label: 'Facebook Post', ico: 'fa-facebook-official' },
415    |           'created': { label: 'Created', ico: 'fa-plus-circle' },
416    |           'updated': { label: 'Updated', ico: 'fa-pencil-square-o' },
417    |           'quote_created': { label: 'Quote Created', ico: 'fa-plus-circle' },
418    |           'invoice_created': { label: 'Invoice Created', ico: 'fa-plus-circle' },
419    |           'form_filled': { label: 'Form Filled', ico: 'fa-wpforms'}
420    |
421    | --------------------------------------------------
422    |
423    |
424    |
425    |   #} RE: $extraMeta (This isn't used anywhere yet, talk to WH before using)
426    |
427    |       ... this is a key value array passable to add extra values to customers
428    |       ... should look like:
429    |
430    |       $extraMeta = array(
431    |
432    |           array('key_here',12345),
433    |           array('another','what')
434    |
435    |       )
436    |
437    |       ... which will add the following meta to a customer:
438    |
439    |       zbs_customer_extra_key_here = 12345
440    |       zbs_customer_extra_another = what
441    |
442    |       ... BRUTALLY - no checking, just overwrites! (so be careful)
443    |
444    |   #} Re: $automatorPassthrough
445    |
446    |       ... adding anything here allows it to be passed through to the intval(var)ternal automator (which currently sets notes)
447    |       ... this means you can pass an array with note str overrides... e.g.
448    |
449    |       array(
450    |
451    |           'note_override' => array(
452    |
453    |                       'type' => 'Form Filled',#'form_filled',
454    |                       'shortdesc' => 'Dude filled out the form x on y',
455    |                       'longdesc' => ''
456    |
457    |           )
458    |
459    |       )
460    |
461    |       ... see recipes to see what's useful :)
462    |
463    |=======================================
464    |   27/09/16: $conameAlreadyExistsAction
465    |
466    |       This is a flag to say what to do in this circumstance: User obj passed has an email (in $companyFields['zbsc_coname']) which matches a company in DB already
467    |       ... options:
468    |           'update': Update company record (and add external source) (BRUTAL override)
469    |           'skip': Do nothing
470    |           'notifyexit': quit + notify
471    |       ... this func is mostly future proofing, as there may be times we want to avoid overriding existing data from an import e.g.
472    |
473    |=======================================
474    | ... Made this func super easy so you can just fire it when you're not sure if add or update... :) it'll deal.
475    |=======================================
476    | Returns:
477    |   Company ID
478    |       or
479    |   False (boolean) (Company create/update failed)
480    |=======================================
481*/
482
483#} External source + (externalID = Co NAME)
484
485function zeroBS_integrations_addOrUpdateCompany(
486    $externalSource = '',
487    $externalID = '',
488    $companyFields = array(),
489    $companyDate = '',
490    $fallbackLog = 'auto',
491    $extraMeta = false,
492    $automatorPassthroughArray = false,
493    $conameAlreadyExistsAction = 'update',
494    $fieldPrefix = 'zbsc_'
495) {
496
497    global $zbs;
498
499    #} leave this true and it'll run as normal.
500    $usualUpdate = true;
501
502    if ( ! empty( $externalSource ) && ! empty( $externalID ) && is_array( $companyFields ) && count( $companyFields ) > 0 ) {
503
504        $potentialCompanyIDfromName = false;
505        $potentialCoName            = '';
506
507        // <3.0
508        if ( isset( $companyFields[ $fieldPrefix . 'coname' ] ) && ! empty( $companyFields[ $fieldPrefix . 'coname' ] ) ) {
509            $potentialCoName = $companyFields[ $fieldPrefix . 'coname' ];
510        }
511        // 3.0
512        if ( isset( $companyFields[ $fieldPrefix . 'name' ] ) && ! empty( $companyFields[ $fieldPrefix . 'name' ] ) ) {
513            $potentialCoName = $companyFields[ $fieldPrefix . 'name' ];
514        }
515
516        if ( $potentialCoName !== '' ) {
517
518            #} First check for name in company list
519            $potentialCompanyIDfromName = zeroBS_getCompanyIDWithName( $potentialCoName );
520
521            #} If so... act based on $conameAlreadyExistsAction param
522            if ( ! empty( $potentialCompanyIDfromName ) ) {
523
524                #} So we have a customer with this email...
525                switch ( $conameAlreadyExistsAction ) {
526
527                    /*
528                    not built out yet...
529                    case 'addextsrc':
530
531                        #} Just add the external source
532
533                        break; */
534                    case 'update':
535                        #} Just let it roll on...
536                        $usualUpdate = true;
537
538                        break;
539                    case 'skip':
540                        #} don't do nothin :)
541                        $usualUpdate = false;
542
543                        break;
544                    case 'notifyexit':
545                        #} Notify + exit
546                        echo esc_html( __( jpcrm_label_company() . ' Add/Update Issue: A ' . jpcrm_label_company() . ' already exists with the name "', 'zero-bs-crm' ) . $potentialCoName . '" (ID: ' . $potentialCompanyIDfromName . '), ' . __( 'could not be processed!', 'zero-bs-crm' ) );
547                        exit( 0 );
548
549                        break;
550
551                }
552            }
553        }
554
555        #} =========================================================================================
556        #} NO existing user! Proceed as before!
557        #} =========================================================================================
558        if ( $usualUpdate ) {
559
560            #} Do query for ID
561            $potentialCompanyID = zeroBS_getCompanyIDWithExternalSource( $externalSource, $externalID );
562
563            #} If ID empty, but $potentialCompanyIDfromName (from above) not, use $potentialCompanyIDfromName
564            if ( $potentialCompanyID === false && $potentialCompanyIDfromName !== false ) {
565                $potentialCompanyID = $potentialCompanyIDfromName;
566            }
567
568            #} Default fallback log creation
569            $fallbackLogToPass = false;
570            if (
571                ! isset( $fallbackLog ) ||
572                ! is_array( $fallbackLog )
573            ) {
574
575                #} create default fallback log, unless $fallbackLog is set to 'none'
576                if ( $fallbackLog !== 'none' ) {
577
578                    #} Autogen
579                    #} Left this out for v1.1.18... needs thought.
580                    #} Do we really want to put "woo source added"? It might get added loads.
581                    #} For now leave as manual...
582
583                }
584            } elseif ( is_array( $fallbackLog ) ) {
585
586                #} Fallback log is probably set, just pass it along.
587                $fallbackLogToPass = $fallbackLog;
588
589            }
590
591            #} Here we're passing along any automator pass through
592            #} ... which will typically be overrides for creation logs or any extra params to give to internal automator.
593            $automatorPassthrough = false;
594            if ( isset( $automatorPassthroughArray ) && is_array( $automatorPassthroughArray ) ) {
595                $automatorPassthrough = $automatorPassthroughArray;
596            }
597
598            #} Not yet used, ask WH
599            $extraMeta = false;
600
601            #} Brutal add/update
602            $companyID = zeroBS_addUpdateCompany( $potentialCompanyID, $companyFields, $externalSource, $externalID, $companyDate, $fallbackLogToPass, $extraMeta, $automatorPassthrough, -1, $fieldPrefix );
603
604            return $companyID;
605
606        } #} / usual update
607
608    } else {
609        return false;
610    }
611}
612
613/*
614    |=======================================
615    |   zeroBS_integrations_getCompany
616    |=======================================
617    | Retrieves a Company record (as usual _getCompany func) - but one that has been inserted via import from an external source
618    | E.g. Woo Imported, Paypal imported, whatever
619    | A Company can exist with multiple import IDs, which lets us patch across services.
620    | E.g. Company has a woo id of 1234, and a paypal Company id of x3da9j3d9jad2
621    | Then that Company could be called with either of these, but would get the same main "Company" record
622    | zeroBS_integrations_getCompany('woo','1234')
623    | zeroBS_integrations_getCompany('pay','x3da9j3d9jad2')
624    |=======================================
625    | Returns:
626    |   Company obj (std class)
627    |       or
628    |   False (boolean) (Company does not exist)
629    |=======================================
630    | Check via: if ($coobj !== false)
631    |=======================================
632*/
633function zeroBS_integrations_getCompany( $externalSource = '', $externalID = '' ) {
634
635    #} Do query for ID
636    $potentialCompanyID = zeroBS_getCompanyIDWithExternalSource( $externalSource, $externalID );
637
638    if ( $potentialCompanyID !== false ) {
639
640        #} If so, pass full deets via this
641        return zeroBS_getCompany( $potentialCompanyID );
642
643    }
644
645    #} If it gets here, it failed
646    return false;
647}
648
649/*
650    |=======================================
651    |   zeroBS_integrations_addOrUpdateTransaction
652    |=======================================
653    | Add's a new Transaction, or updates an existing Transaction, where their externalSource + externalID matches an existing Transaction (if specified)
654    | NOTE: This is different from zeroBS_integrations_addOrUpdateCustomer, in that the externalID must be Transaction ID
655    | This only works with specific external sources, as 'zeroBS_integrations_getTransaction'
656    | Usage:
657
658            zeroBS_integrations_addOrUpdateTransaction('woo','#123456',array(
659
660                REQUIRED:
661                'orderid' => 'UNIQUEID',
662                'customer' => CustomerID,
663                'status' => 'Completed', 'Refunded' similar.
664                'total' => 123.99,
665
666                RECOMMENDED:
667                'date' => 12345TIME,
668                'currency' => 'USD',
669                'item' => 'TITLE',
670                'net' => 0,
671                'tax' => 0,
672                'fee' => 0,
673                'discount' => 0,
674                'tax_rate' => 0,
675
676            ), array(
677                TAGS:
678                'sale','bill','chargeback','refund','echeckchargeback','cancel-rebill','uncancel-rebill' etc.
679
680            ),
681
682                'date as per mike!',
683
684                'none',
685
686                false,
687
688                false
689
690            );
691
692    |
693    | ... note "woo" external source flag
694    | ... note "woodyhayday2@smt.com" - my ID within woo
695    | ... note normal customer fields in array, prefixed with 'zbsc_'
696    | ... NOTE: Mike added date
697    | ... Note: From v1.1.18 we also have fallback logs:
698    | --------------------------------------------------
699    | Fallback Logs:
700    |   Pass either:
701    |       'none' = do nothing if user already exists
702    |       'auto' = automatically create log (NOT WORKING YET)
703    |       OR:
704    |       array(
705    |           'type' => 'Form Filled',#'form_filled',
706    |           'shortdesc' => 'Dude filled out the form x on y',
707    |           'longdesc' => ''
708    |       )
709    |
710    |           (Long desc is optional)
711    |
712    | --------------------------------------------------
713    |
714    |
715    |   #} RE: $extraMeta
716    |
717    |       ... this is a key value array passable to add extra values to customers
718    |       ... should look like:
719    |
720    |       $extraMeta = array(
721    |
722    |           array('key_here',12345),
723    |           array('another','what')
724    |
725    |       )
726    |
727    |       ... which will add the following meta to a customer:
728    |
729    |       zbs_customer_extra_key_here = 12345
730    |       zbs_customer_extra_another = what
731    |
732    |       ... BRUTALLY - no checking, just overwrites! (so be careful)
733    |
734    | --------------------------------------------------
735    |
736    |   #} Re: $automatorPassthrough
737    |
738    |       ... adding anything here allows it to be passed through to the internal automator (which currently sets notes)
739    |       ... this means you can pass an array with note str overrides... e.g.
740    |
741    |       array(
742    |
743    |           'note_override' => array(
744    |
745    |                       'type' => 'Form Filled',#'form_filled',
746    |                       'shortdesc' => 'Dude filled out the form x on y',
747    |                       'longdesc' => ''
748    |
749    |           )
750    |
751    |       )
752    |
753    |       ... see recipes to see what's useful :)
754    |
755    |=======================================
756    | Returns:
757    |   Transaction ID
758    |       or
759    |   False (boolean) (Transaction create/update failed)
760    |=======================================
761*/
762function zeroBS_integrations_addOrUpdateTransaction(
763    $transactionExternalSource = '', // Required, e.g. 'str'.
764    $transactionExternalID = '', // Required, e.g. 'ch_1DqSxpBy0i6Hd9AL4noH4Yhx'.
765    $transactionFields = array(), // Required keys: orderid, customer, status, total.
766    $transactionTags = array(),
767    $transactionDate = '',
768    $fallbackLog = 'auto',
769    $extraMeta = false,
770    $automatorPassthroughArray = false,
771    $fieldPrefix = 'zbst_'
772) {
773
774    #} Check req.
775    if (
776        ! empty( $transactionExternalSource ) && ! empty( $transactionExternalID ) && is_array( $transactionFields ) && count( $transactionFields ) > 0 &&
777
778        (
779            // v2
780            ( isset( $transactionFields['orderid'] ) && ! empty( $transactionFields['orderid'] ) )
781            ||
782            // v3
783            ( isset( $transactionFields['ref'] ) && ! empty( $transactionFields['ref'] ) )
784
785        ) &&
786        // isset($transactionFields['customer']) && !empty($transactionFields['customer']) &&
787        isset( $transactionFields['status'] ) && ! empty( $transactionFields['status'] ) &&
788        isset( $transactionFields['total'] ) && ! empty( $transactionFields['total'] )
789    ) {
790
791        #} Do query for ID
792        $potentialTransactionID = zeroBS_getTransactionIDWithExternalSource( $transactionExternalSource, $transactionExternalID );
793
794        #} Default fallback log creation
795        $fallbackLogToPass = false;
796        if (
797            ! isset( $fallbackLog ) ||
798            ! is_array( $fallbackLog )
799        ) {
800
801            #} create default fallback log, unless $fallbackLog is set to 'none'
802            if ( $fallbackLog !== 'none' ) {
803
804                #} Autogen
805                #} Left this out for v1.1.18... needs thought.
806                #} Do we really want to put "woo source added"? It might get added loads.
807                #} For now leave as manual...
808
809            }
810        } elseif ( is_array( $fallbackLog ) ) {
811
812            #} Fallback log is probably set, just pass it along.
813            $fallbackLogToPass = $fallbackLog;
814
815        }
816
817        #} Here we're passing along any automator pass through
818        #} ... which will typically be overrides for creation logs or any extra params to give to internal automator.
819        $automatorPassthrough = false;
820        if ( isset( $automatorPassthroughArray ) && is_array( $automatorPassthroughArray ) ) {
821            $automatorPassthrough = $automatorPassthroughArray;
822        }
823
824        #} Brutal add/update
825        $transactionWPID = zeroBS_addUpdateTransaction( $potentialTransactionID, $transactionFields, $transactionExternalSource, $transactionExternalID, $transactionDate, $transactionTags, $fallbackLogToPass, $extraMeta, $automatorPassthrough, $fieldPrefix );
826
827        #} Update any title
828        #} Not needed for transactions: if ($transactionWPID !== false) zbsCustomer_updateCompanyNameInPostTitle($companyID,false);
829
830        return $transactionWPID;
831
832    } else { // no source/id/fields
833
834        return false;
835
836    }
837}
838
839/**
840 * Adds or updates a task via integrations.
841 *
842 * @param int   $task_id        Task ID.
843 * @param array $data_array     Task data. Required keys: 'title', 'to', 'from'.
844 * @param array $task_reminders Task reminders. Keys: 'remind_at', 'sent' (v3+).
845 */
846function zeroBS_integrations_addOrUpdateTask(
847    $task_id = -1,
848    $data_array = array(),
849    $task_reminders = array()
850) {
851
852    #} Check req.
853    if (
854        is_array( $data_array )
855        && count( $data_array ) > 0
856        && ! empty( $data_array['title'] )
857        && (
858            // old params
859            ( ! empty( $data_array['to'] ) && ! empty( $data_array['from'] ) )
860            ||
861            // new params
862            ( ! empty( $data_array['start'] ) && ! empty( $data_array['end'] ) )
863        )
864    ) {
865        return zeroBS_addUpdateEvent( $task_id, $data_array, $task_reminders );
866    } else { // no source/id/fields
867        return false;
868    }
869}
870
871/*
872    |=======================================
873    |   zeroBS_integrations_getTransaction
874    |=======================================
875    | Retrieves a transaction record (as usual _getTransaction func) - but one that has been inserted via import from an external source
876    | E.g. Woo Imported, Paypal imported, whatever
877    | A transaction can exist with multiple import IDs, which lets us patch across services.
878    | E.g. transaction has a woo id of 1234, and a paypal transaction id of x3da9j3d9jad2
879    | Then that transaction could be called with either of these, but would get the same main "transaction" record
880    | zeroBS_integrations_getTransaction('woo','1234')
881    | zeroBS_integrations_getTransaction('pay','x3da9j3d9jad2')
882    |=======================================
883    | Returns:
884    |   transaction obj (std class)
885    |       or
886    |   False (boolean) (transaction does not exist)
887    |=======================================
888    | Check via: if ($transobj !== false)
889    |=======================================
890*/
891function zeroBS_integrations_getTransaction( $transactionExternalSource = '', $transactionExternalID = '' ) {
892
893    #} Do query for ID
894    $potentialTransactionID = zeroBS_getTransactionIDWithExternalSource( $transactionExternalSource, $transactionExternalID );
895
896    if ( $potentialTransactionID !== false ) {
897
898        #} If so, pass full deets via this
899        return zeroBS_getTransaction( $potentialTransactionID );
900
901    }
902
903    #} If it gets here, it failed
904    return false;
905}
906
907/*
908    For now a wrapper, later will allow us to seemlessly feed in customer generated cats
909*/
910function zeroBS_integrations_getAllCategories( $incEmpty = false ) {
911
912    global $zbs;
913
914    return array(
915        'zerobscrm_customertag' => $zbs->DAL->getTagsForObjType(
916            array(
917
918                'objtypeid'    => ZBS_TYPE_CONTACT,
919                'excludeEmpty' => ! $incEmpty,
920                'withCount'    => true,
921                'ignoreowner'  => true,
922                // sort
923                'sortByField'  => 'zbstag_name',
924                'sortOrder'    => 'ASC',
925
926            )
927        ),
928    );
929}
930
931#} For now just a wrapper
932function zeroBS_integrations_searchCustomers( $args = array() ) {
933
934    if ( ! empty( $args ) && isset( $args['searchPhrase'] ) ) {
935        return zeroBS_searchCustomers( $args );
936    }
937
938    return array();
939}
940
941/**
942 * Adds a log entry (currently a wrapper for zeroBS_addUpdateLog).
943 *
944 * @param int    $objID      Object ID.
945 * @param int    $logDate    Log date timestamp.
946 * @param array  $noteFields Note fields array. May include 'meta_assoc_id'
947 *                           (e.g. campaign ID for 'email sent' logs) and 'meta_assoc_src'
948 *                           (e.g. 'mailcamp').
949 * @param string $objType    Object type, e.g. 'zerobs_customer' or a ZBS_TYPE_* constant.
950 */
951function zeroBS_integrations_addLog(
952    $objID = -1,
953    $logDate = -1,
954    $noteFields = array(),
955    $objType = ''
956) {
957
958    if ( ! empty( $objID ) ) {
959
960        #} Add fresh log:
961        zeroBS_addUpdateLog( $objID, -1, $logDate, $noteFields, $objType );
962
963        return true;
964
965    }
966
967    return false;
968}
969
970// WH added, backward compat:
971// only works DAL2 +
972function zeroBS_integrations_getCustomFields( $objTypeID = -1 ) {
973
974    $objTypeID = (int) $objTypeID;
975
976    if ( $objTypeID > 0 ) {
977
978        global $zbs;
979
980        return $zbs->DAL->getActiveCustomFields( array( 'objtypeid' => $objTypeID ) ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase,WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
981
982    }
983
984    return array();
985}
986
987/*
988======================================================
989    / Integration specific extension functions
990    ====================================================== */