-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.tpl
More file actions
1831 lines (1714 loc) · 57.6 KB
/
template.tpl
File metadata and controls
1831 lines (1714 loc) · 57.6 KB
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
___TERMS_OF_SERVICE___
By creating or modifying this file you agree to Google Tag Manager's Community
Template Gallery Developer Terms of Service available at
https://developers.google.com/tag-manager/gallery-tos (or such other URL as
Google may provide), as modified from time to time.
___INFO___
{
"type": "TAG",
"id": "cvt_seznam_sem",
"version": 1,
"displayName": "Seznam SEM Conversion API",
"categories": [
"ADVERTISING",
"ANALYTICS",
"CONVERSIONS",
"MARKETING"
],
"brand": {
"id": "seznam_sem",
"displayName": "Seznam SEM"
},
"description": "Server-side Google Tag Manager template for sending events to Seznam.cz SEM (Seznam Event Measurement) API. Variable-driven — assign GTM variables to each field.",
"containerContexts": [
"SERVER"
],
"securityGroups": []
}
___TEMPLATE_PARAMETERS___
[
{
"type": "SELECT",
"name": "eventNameSelect",
"displayName": "Event Name",
"selectItems": [
{ "value": "PageView", "displayValue": "PageView" },
{ "value": "ViewContent", "displayValue": "ViewContent" },
{ "value": "Purchase", "displayValue": "Purchase" },
{ "value": "Contact", "displayValue": "Contact" },
{ "value": "AddToCart", "displayValue": "AddToCart" },
{ "value": "AddToWishlist", "displayValue": "AddToWishlist" },
{ "value": "InitiateCheckout", "displayValue": "InitiateCheckout" },
{ "value": "AddPaymentInfo", "displayValue": "AddPaymentInfo" },
{ "value": "Search", "displayValue": "Search" },
{ "value": "CompleteRegistration", "displayValue": "CompleteRegistration" },
{ "value": "Lead", "displayValue": "Lead" },
{ "value": "Subscribe", "displayValue": "Subscribe" },
{ "value": "CustomizeProduct", "displayValue": "CustomizeProduct" },
{ "value": "Donate", "displayValue": "Donate" },
{ "value": "FindLocation", "displayValue": "FindLocation" },
{ "value": "Schedule", "displayValue": "Schedule" },
{ "value": "StartTrial", "displayValue": "StartTrial" },
{ "value": "SubmitApplication", "displayValue": "SubmitApplication" },
{ "value": "custom", "displayValue": "— Custom —" }
],
"simpleValueType": true,
"defaultValue": "PageView",
"help": "Select a Seznam event name, or choose Custom to enter your own.",
"valueValidators": [{ "type": "NON_EMPTY" }]
},
{
"type": "TEXT",
"name": "eventNameCustom",
"displayName": "Custom Event Name",
"simpleValueType": true,
"help": "Enter a custom event name. Used when 'Custom' is selected above.",
"enablingConditions": [
{
"paramName": "eventNameSelect",
"paramValue": "custom",
"type": "EQUALS"
}
],
"valueValidators": [{ "type": "NON_EMPTY" }]
},
{
"type": "TEXT",
"name": "semId",
"displayName": "SEM ID (Sklik Advertiser ID)",
"simpleValueType": true,
"help": "Your SEM ID (shop ID in Sklik). Required for tracking.",
"valueValidators": [
{
"type": "NON_EMPTY"
}
]
},
{
"type": "SELECT",
"name": "eventSource",
"displayName": "Event Source",
"selectItems": [
{
"value": "web",
"displayValue": "Web"
},
{
"value": "app",
"displayValue": "App"
}
],
"simpleValueType": true,
"defaultValue": "web",
"help": "Source of the event — web or app."
},
{
"type": "TEXT",
"name": "eventUrl",
"displayName": "Event URL (optional)",
"simpleValueType": true,
"help": "Page URL for the event. Falls back to the Referer header if left empty."
},
{
"type": "TEXT",
"name": "eventId",
"displayName": "Event ID (optional)",
"simpleValueType": true,
"help": "Unique event ID for deduplication. Assign a GTM variable that resolves to the frontend event ID."
},
{
"type": "TEXT",
"name": "eventTime",
"displayName": "Event Time (optional)",
"simpleValueType": true,
"help": "Event timestamp in milliseconds. Seconds input is auto-upscaled to ms. Falls back to server time if empty."
},
{
"type": "GROUP",
"name": "consentGroup",
"displayName": "Consent",
"groupStyle": "ZIPPY_CLOSED",
"subParams": [
{
"type": "TEXT",
"name": "consentModeObject",
"displayName": "Consent Mode Object (optional)",
"simpleValueType": true,
"help": "A GTM variable resolving to a consent_mode object. Supported keys: ad_storage, ad_user_data, ad_personalization, functionality_storage, analytics_storage. Unsupported keys are automatically stripped. Boolean values (true/false) are normalized to 'granted'/'denied'."
},
{
"type": "TEXT",
"name": "consentString",
"displayName": "Consent String (IAB TCF)",
"simpleValueType": true,
"help": "IAB TCF consent string from your CMP, if available."
}
]
},
{
"type": "GROUP",
"name": "userDataGroup",
"displayName": "User Data",
"groupStyle": "ZIPPY_CLOSED",
"subParams": [
{
"type": "TEXT",
"name": "userDataObject",
"displayName": "User Data Object (optional)",
"simpleValueType": true,
"help": "A GTM variable resolving to an object with user data fields (em, ph, fn, ln, etc.). Individual fields below override keys from this object."
},
{
"type": "TEXT",
"name": "sid",
"displayName": "SID (Seznam Identity)",
"simpleValueType": true,
"help": "Seznam SID cookie value — primary user identifier for S2S. Obtain via window.sznIVA.IS.getIdentity('sid') after loading sem.js. Forward to SGTM as a GTM variable."
},
{
"type": "TEXT",
"name": "userEmail",
"displayName": "Email (em)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of the normalized email (lowercase + trim). Hashing must be done on the frontend — the server-side template does not hash."
},
{
"type": "TEXT",
"name": "userPhone",
"displayName": "Phone (ph)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of the phone in E.164 format (e.g. +420606666666). Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userFirstName",
"displayName": "First Name (fn)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of the normalized first name (lowercase + trim). Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userLastName",
"displayName": "Last Name (ln)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of the normalized last name (lowercase + trim). Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userGender",
"displayName": "Gender (ge)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of 'm' / 'f' / 'o'. Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userDob",
"displayName": "Date of Birth (db)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of YYYYMMDD. Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userCity",
"displayName": "City (ct)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of the normalized city (lowercase + trim). Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userRegion",
"displayName": "Region / State (region)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of the normalized region/state (lowercase + trim). Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userZip",
"displayName": "Postal Code (zp)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of the trimmed ZIP/postal code. Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userStreet",
"displayName": "Street (sr)",
"simpleValueType": true,
"help": "Expected SHA-256 hash of the normalized street (lowercase + trim). Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userCountry",
"displayName": "Country",
"simpleValueType": true,
"help": "Expected SHA-256 hash of ISO 3166-1 alpha-2 code (lowercase). Hashing must be done on the frontend."
},
{
"type": "TEXT",
"name": "userSubscriptionId",
"displayName": "Subscription ID",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "userUdid",
"displayName": "UDID (udid)",
"simpleValueType": true,
"help": "Unique user/device ID (cookie value from sul.js). Server-side template does not hash this value."
}
]
},
{
"type": "GROUP",
"name": "eventDataGroup",
"displayName": "Event Data",
"groupStyle": "ZIPPY_CLOSED",
"subParams": [
{
"type": "TEXT",
"name": "eventDataObject",
"displayName": "Event Data Object (optional)",
"simpleValueType": true,
"help": "A GTM variable resolving to an object with event data fields (currency, value, order_id, etc.). Individual fields below override keys from this object."
},
{
"type": "TEXT",
"name": "sznaiid",
"displayName": "sznaiid (click-through ID)",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "currency",
"displayName": "Currency",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "value",
"displayName": "Value",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "orderId",
"displayName": "Order ID",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "contentType",
"displayName": "Content Type",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "contents",
"displayName": "Contents (array variable or JSON string)",
"simpleValueType": true,
"help": "Assign a GTM variable resolving to an array of SEM-native content objects [{id, quantity, unit_price, content_name, content_category}], or a JSON string in the same shape. When contents is present, content_type is required by SEM; if omitted, this template defaults it to product. No GA4 items mapping is performed — convert upstream."
},
{
"type": "TEXT",
"name": "deliveryPrice",
"displayName": "Delivery Price",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "deliveryType",
"displayName": "Delivery Type",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "paymentType",
"displayName": "Payment Type",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "otherCosts",
"displayName": "Other Costs",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "predictedLtv",
"displayName": "Predicted LTV",
"simpleValueType": true
},
{
"type": "TEXT",
"name": "valueTax",
"displayName": "Value Tax (value_tax)",
"simpleValueType": true,
"help": "Tax portion of value. Numeric."
},
{
"type": "TEXT",
"name": "reviewEmail",
"displayName": "Review Email (review_email, UNHASHED)",
"simpleValueType": true,
"help": "Zboží.cz satisfaction survey email. MUST be sent as plain text, NOT hashed. Only send with user consent."
},
{
"type": "TEXT",
"name": "productIds",
"displayName": "Product IDs (product_ids, array)",
"simpleValueType": true,
"help": "GTM variable resolving to an array of Zboží.cz product IDs (non-negative integers), or JSON string. Non-integer or negative entries are skipped with a warning."
},
{
"type": "TEXT",
"name": "goodsIntention",
"displayName": "Goods Intention (goods_intention)",
"simpleValueType": true,
"help": "User intent weight. Numeric."
},
{
"type": "TEXT",
"name": "goodsPhase",
"displayName": "Goods Phase (goods_phase)",
"simpleValueType": true,
"help": "User interest phase. Integer — non-integer values are passed through with a warning."
},
{
"type": "TEXT",
"name": "searchString",
"displayName": "Search String (search_string)",
"simpleValueType": true,
"help": "Search query text (e.g. for Search event)."
},
{
"type": "CHECKBOX",
"name": "statusEnabled",
"checkboxText": "Include status field",
"simpleValueType": true,
"defaultValue": false,
"help": "Enable this to include a boolean status in event_data. Needed because false is a legitimate value — a plain checkbox could not distinguish it from 'not set'."
},
{
"type": "SELECT",
"name": "status",
"displayName": "Status (bool)",
"selectItems": [
{ "value": "true", "displayValue": "true" },
{ "value": "false", "displayValue": "false" }
],
"simpleValueType": true,
"enablingConditions": [
{ "paramName": "statusEnabled", "paramValue": true, "type": "EQUALS" }
],
"help": "Registration/subscription status. Boolean — both true and false are legitimate values."
}
]
},
{
"type": "GROUP",
"name": "settingsGroup",
"displayName": "Settings",
"groupStyle": "ZIPPY_CLOSED",
"subParams": [
{
"type": "CHECKBOX",
"name": "testMode",
"checkboxText": "Enable Test Mode",
"simpleValueType": true,
"defaultValue": false,
"help": "Enables verbose logging of full payloads and responses. Events are still sent normally."
},
{
"type": "CHECKBOX",
"name": "useOptimisticScenario",
"checkboxText": "Use Optimistic Scenario",
"simpleValueType": true,
"defaultValue": true,
"help": "Returns success to GTM immediately without waiting for the API response. Warning: 4xx/5xx responses are logged as errors but GTM still reports success. Disable for higher observability during rollout or for critical conversion tags."
},
{
"type": "CHECKBOX",
"name": "strictEventValidation",
"checkboxText": "Strict Event Validation",
"simpleValueType": true,
"defaultValue": false,
"help": "When enabled, unknown event names and invalid JSON in object/array fields cause the tag to fail (and call gtmOnFailure) instead of just logging. Recommended for production hardening. When disabled, such issues are logged but the tag reports success."
},
{
"type": "CHECKBOX",
"name": "sendS2sHeaders",
"checkboxText": "Send S2S Headers (consent-gated)",
"simpleValueType": true,
"defaultValue": true,
"help": "When enabled, forwards client IP address, User-Agent, and Client Hints (sec-ch-ua) to Seznam for device targeting and analytics. These headers are only sent when ad_storage and ad_user_data consent are both 'granted'. Disable to never send these headers regardless of consent."
}
]
},
{
"type": "GROUP",
"name": "bigQueryLogsGroup",
"displayName": "BigQuery Logs",
"groupStyle": "ZIPPY_CLOSED",
"subParams": [
{
"type": "RADIO",
"name": "bigQueryLogType",
"radioItems": [
{ "value": "no", "displayValue": "Do not log to BigQuery" },
{ "value": "always", "displayValue": "Log to BigQuery" }
],
"simpleValueType": true,
"defaultValue": "no"
},
{
"type": "GROUP",
"name": "logsBigQueryConfigGroup",
"groupStyle": "NO_ZIPPY",
"subParams": [
{
"type": "TEXT",
"name": "logBigQueryProjectId",
"displayName": "BigQuery Project ID",
"simpleValueType": true,
"help": "Optional. If omitted, uses the GOOGLE_CLOUD_PROJECT environment variable of the server container."
},
{
"type": "TEXT",
"name": "logBigQueryDatasetId",
"displayName": "BigQuery Dataset ID",
"simpleValueType": true,
"valueValidators": [{ "type": "NON_EMPTY" }]
},
{
"type": "TEXT",
"name": "logBigQueryTableId",
"displayName": "BigQuery Table ID",
"simpleValueType": true,
"valueValidators": [{ "type": "NON_EMPTY" }]
}
],
"enablingConditions": [
{
"paramName": "bigQueryLogType",
"paramValue": "always",
"type": "EQUALS"
}
]
}
]
},
{
"type": "GROUP",
"name": "advancedOverridesGroup",
"displayName": "Advanced Overrides",
"groupStyle": "ZIPPY_CLOSED",
"subParams": [
{
"type": "SIMPLE_TABLE",
"name": "userDataOverrides",
"displayName": "User Data Overrides",
"simpleTableColumns": [
{
"defaultValue": "",
"displayName": "Property Name",
"name": "name",
"type": "TEXT"
},
{
"defaultValue": "",
"displayName": "Property Value",
"name": "value",
"type": "TEXT"
}
],
"help": "Catch-all override table for user data fields. Overrides both the object variable and individual fields above."
},
{
"type": "SIMPLE_TABLE",
"name": "eventDataOverrides",
"displayName": "Event Data Overrides",
"simpleTableColumns": [
{
"defaultValue": "",
"displayName": "Property Name",
"name": "name",
"type": "TEXT"
},
{
"defaultValue": "",
"displayName": "Property Value",
"name": "value",
"type": "TEXT"
}
],
"help": "Catch-all override table for event data fields. Values for known numeric keys (value, value_tax, delivery_price, other_costs, predicted_ltv, goods_intention, goods_phase) are auto-coerced to numbers."
}
]
}
]
___SANDBOXED_JS_FOR_SERVER___
const JSON = require('JSON');
const Math = require('Math');
const Promise = require('Promise');
const BigQuery = require('BigQuery');
const sendHttpRequest = require('sendHttpRequest');
const getTimestampMillis = require('getTimestampMillis');
const logToConsole = require('logToConsole');
const getRequestHeader = require('getRequestHeader');
const makeNumber = require('makeNumber');
const getType = require('getType');
const ALLOWED_EVENTS = [
'PageView', 'ViewContent', 'Purchase', 'Contact',
'AddToCart', 'AddToWishlist', 'InitiateCheckout', 'AddPaymentInfo',
'Search', 'CompleteRegistration', 'Lead', 'Subscribe',
'CustomizeProduct', 'Donate', 'FindLocation', 'Schedule',
'StartTrial', 'SubmitApplication'
];
const NUMERIC_KEYS = [
'value', 'value_tax', 'delivery_price', 'other_costs',
'predicted_ltv', 'goods_intention', 'goods_phase'
];
const traceId = getRequestHeader('trace-id');
const resolvedEventName = data.eventNameSelect === 'custom'
? data.eventNameCustom
: data.eventNameSelect;
const apiUrl = 'https://sem.seznam.cz/rtgconv';
// Seznam telemetry: `api.version` tracks the integration client version (bump on contract/behavior changes).
// `api.template_version` tracks our CHANGELOG release version. These are independent of the
// GTM ___INFO___.version field, which is a GTM-internal stability flag constrained to 0 or 1.
const API_CLIENT_VERSION = '1';
const TEMPLATE_VERSION = '2.1.2';
// Parse JSON object/array fields once, up-front. `validate` decides severity, `buildPayload` consumes values.
const parsed = {
consent: parseJsonObjectField('consentModeObject', data.consentModeObject),
userData: parseJsonObjectField('userDataObject', data.userDataObject),
eventData: parseJsonObjectField('eventDataObject', data.eventDataObject),
contents: parseJsonArray('contents', data.contents),
productIds: parseJsonArray('productIds', data.productIds)
};
// Preflight validation
const validationError = validate(data, parsed);
if (validationError) {
logToConsole('Seznam SEM [ERROR]: ' + validationError +
' | event=' + resolvedEventName + ' | trace=' + traceId);
logToBigQuery({ url: apiUrl }, { body: validationError });
data.gtmOnFailure();
return;
}
// Build and send
const payload = buildPayload(data, parsed);
log({
Name: 'Seznam SEM',
Type: 'Request',
TraceId: traceId,
EventName: resolvedEventName,
RequestMethod: 'POST',
RequestUrl: apiUrl,
RequestBody: payload
});
sendHttpRequest(
apiUrl,
{
headers: { 'content-type': 'application/json' },
method: 'POST'
},
JSON.stringify(payload)
).then(function(result) {
log({
Name: 'Seznam SEM',
Type: 'Response',
TraceId: traceId,
EventName: resolvedEventName,
ResponseStatusCode: result.statusCode,
ResponseHeaders: result.headers,
ResponseBody: result.body
});
logToBigQuery(
{ url: apiUrl, body: payload },
{ statusCode: result.statusCode, headers: result.headers, body: result.body }
);
if (!data.useOptimisticScenario) {
if (result.statusCode >= 200 && result.statusCode < 300) {
data.gtmOnSuccess();
} else {
logHttpError(result);
data.gtmOnFailure();
}
} else if (result.statusCode < 200 || result.statusCode >= 300) {
logHttpError(result);
}
}).catch(function() {
logToBigQuery({ url: apiUrl, body: payload });
if (!data.useOptimisticScenario) {
data.gtmOnFailure();
}
});
if (data.useOptimisticScenario) {
data.gtmOnSuccess();
}
/*******************************************************************************
* Validation
******************************************************************************/
function validate(data, parsed) {
if (!resolvedEventName) return 'eventName is required';
if (!data.semId) return 'semId is required';
// sem_id shape check: non-empty 24-character string.
// Full pattern `^[0-9a-z]{24}$` is enforced server-side — a stricter local charset check
// would need sandbox-safe string primitives we cannot verify without deploying.
if (!isValidSemId(data.semId)) {
var semIdMsg = 'semId must be a non-empty 24-character string; expected server-side pattern is ^[0-9a-z]{24}$';
if (data.strictEventValidation) {
return semIdMsg;
}
logToConsole('Seznam SEM [WARN]: ' + semIdMsg + ' | semId=' + data.semId + ' | trace=' + traceId);
}
// Event name allowlist check
var isKnown = false;
for (var i = 0; i < ALLOWED_EVENTS.length; i++) {
if (ALLOWED_EVENTS[i] === resolvedEventName) {
isKnown = true;
break;
}
}
if (!isKnown) {
var msg = 'Unknown event name: ' + resolvedEventName;
if (data.strictEventValidation) {
return msg;
}
logToConsole('Seznam SEM [WARN]: ' + msg + ' | trace=' + traceId);
}
// JSON parse errors: consent is always a WARN (optional field);
// userData/eventData/contents fail under strictEventValidation, WARN otherwise.
if (parsed.consent.error) {
logToConsole('Seznam SEM [WARN]: ' + parsed.consent.error + ' | trace=' + traceId);
}
var fatalFields = [
{ result: parsed.userData, label: 'userDataObject' },
{ result: parsed.eventData, label: 'eventDataObject' },
{ result: parsed.contents, label: 'contents' },
{ result: parsed.productIds, label: 'productIds' }
];
for (var f = 0; f < fatalFields.length; f++) {
var entry = fatalFields[f];
if (entry.result.error) {
if (data.strictEventValidation) {
return entry.result.error;
}
logToConsole('Seznam SEM [ERROR]: ' + entry.result.error + ' | trace=' + traceId);
}
}
// Purchase-specific required fields (per rtgconv.json: value, currency, order_id).
// `contents` is recommended for retargeting/attribution but not required by the schema.
if (resolvedEventName === 'Purchase') {
var missing = [];
if (!data.orderId) missing.push('orderId');
if (!data.currency) missing.push('currency');
if (data.value === undefined || data.value === null || data.value === '') missing.push('value');
if (missing.length > 0) {
return 'Purchase requires: ' + missing.join(', ');
}
if (!data.contents) {
logToConsole('Seznam SEM [WARN]: Purchase without contents is accepted by the API but strongly recommended for retargeting/attribution | trace=' + traceId);
}
}
return undefined;
}
/*******************************************************************************
* Payload builders
******************************************************************************/
function buildPayload(data, parsed) {
var eventTime = normalizeEventTime(data.eventTime);
var eventUrl = data.eventUrl || getRequestHeader('referer') || '';
var payload = {
event_name: resolvedEventName,
schema_version: 'v2',
event_type: 'rtgconv',
event_time: eventTime,
event_source: data.eventSource || 'web',
event_url: eventUrl,
event_data: buildEventData(data, parsed.eventData.value, parsed.contents.value, parsed.productIds.value),
api: {
name: 'gtm-server-template',
version: API_CLIENT_VERSION,
template_version: TEMPLATE_VERSION
}
};
addIfPresent(payload, 'event_id', data.eventId);
var consentMode = buildConsentMode(parsed.consent.value);
if (hasProperties(consentMode)) {
payload.consent_mode = consentMode;
}
addIfPresent(payload, 'consent_string', data.consentString);
var userData = buildUserData(data, parsed.userData.value);
if (hasProperties(userData)) {
payload.user_ids = { user_data: userData };
}
if (data.sendS2sHeaders &&
consentMode.ad_storage === 'granted' &&
consentMode.ad_user_data === 'granted') {
var s2sHeaders = buildS2sHeaders();
if (hasProperties(s2sHeaders)) {
payload.s2s_headers = s2sHeaders;
}
}
return payload;
}
function normalizeEventTime(rawValue) {
if (!rawValue && rawValue !== 0) {
return getTimestampMillis();
}
var num = makeNumber(rawValue);
if (!num && num !== 0) {
logToConsole('Seznam SEM [WARN]: eventTime is not numeric, using server time | trace=' + traceId);
return getTimestampMillis();
}
// Auto-detect seconds vs ms: values < 10000000000 (year 2286 in seconds) are seconds, upscale to ms.
if (num < 10000000000) {
return num * 1000;
}
return num;
}
function buildConsentMode(parsedConsent) {
var ALLOWED_CONSENT_KEYS = [
'ad_storage', 'ad_user_data', 'ad_personalization',
'functionality_storage', 'analytics_storage'
];
var raw = parsedConsent || {};
// Keep only supported keys and normalize booleans
var consent = {};
for (var i = 0; i < ALLOWED_CONSENT_KEYS.length; i++) {
var key = ALLOWED_CONSENT_KEYS[i];
if (raw.hasOwnProperty(key)) {
var val = raw[key];
if (val === true) val = 'granted';
else if (val === false) val = 'denied';
consent[key] = val;
}
}
return consent;
}
function buildS2sHeaders() {
var headers = {};
// Client IP: take first entry from x-forwarded-for
var xff = getRequestHeader('x-forwarded-for');
if (xff) {
var firstIp = xff.split(',')[0];
if (firstIp) headers.client_ip_address = firstIp.trim();
}
addIfPresent(headers, 'user_agent', getRequestHeader('user-agent'));
addIfPresent(headers, 'sec_ch_ua', getRequestHeader('sec-ch-ua'));
addIfPresent(headers, 'sec_ch_ua_mobile', getRequestHeader('sec-ch-ua-mobile'));
addIfPresent(headers, 'sec_ch_ua_model', getRequestHeader('sec-ch-ua-model'));
addIfPresent(headers, 'sec_ch_ua_platform', getRequestHeader('sec-ch-ua-platform'));
addIfPresent(headers, 'sec_ch_ua_platform_version', getRequestHeader('sec-ch-ua-platform-version'));
return headers;
}
function buildUserData(data, parsedUserDataObject) {
var userData = {};
// Layer 1: object variable
if (parsedUserDataObject) {
mergeObject(userData, parsedUserDataObject);
}
// Layer 2: individual fields
addIfPresent(userData, 'sid', data.sid);
addIfPresent(userData, 'em', data.userEmail);
addIfPresent(userData, 'ph', data.userPhone);
addIfPresent(userData, 'fn', data.userFirstName);
addIfPresent(userData, 'ln', data.userLastName);
addIfPresent(userData, 'ge', data.userGender);
addIfPresent(userData, 'db', data.userDob);
addIfPresent(userData, 'ct', data.userCity);
// `userState` retained as deprecated runtime fallback (UI renamed to `userRegion`, wire key `region`).
addIfPresent(userData, 'region', data.userRegion || data.userState);
addIfPresent(userData, 'zp', data.userZip);
addIfPresent(userData, 'sr', data.userStreet);
addIfPresent(userData, 'country', data.userCountry);
addIfPresent(userData, 'subscription_id', data.userSubscriptionId);
addIfPresent(userData, 'udid', data.userUdid);
// Layer 3: override table
applyOverrides(userData, data.userDataOverrides);
return userData;
}
function buildEventData(data, parsedEventDataObject, parsedContents, parsedProductIds) {
var ed = {};
// Layer 1: object variable
if (parsedEventDataObject) {
mergeObject(ed, parsedEventDataObject);
}
// Always set sem_id
ed.sem_id = data.semId;
// Layer 2: individual fields
addIfPresent(ed, 'sznaiid', data.sznaiid);
addIfPresent(ed, 'currency', data.currency);
if (data.currency && data.currency !== 'CZK') {
logToConsole('Seznam SEM [WARN]: currency=' + data.currency +
' - Seznam SEM currently supports only CZK | trace=' + traceId);
}
addIfNumber(ed, 'value', data.value);
addIfNumber(ed, 'value_tax', data.valueTax);
addIfPresent(ed, 'order_id', data.orderId);
addIfPresent(ed, 'content_type', data.contentType);
addIfNumber(ed, 'delivery_price', data.deliveryPrice);
addIfPresent(ed, 'delivery_type', data.deliveryType);
addIfPresent(ed, 'payment_type', data.paymentType);
addIfNumber(ed, 'other_costs', data.otherCosts);
addIfNumber(ed, 'predicted_ltv', data.predictedLtv);
addIfNumber(ed, 'goods_intention', data.goodsIntention);
addIfPresent(ed, 'search_string', data.searchString);
addIfPresent(ed, 'review_email', data.reviewEmail); // NOT hashed - intentional (Zbozi.cz survey).
// goods_phase: schema says integer; pass-through but warn for non-integers.
if (data.goodsPhase !== undefined && data.goodsPhase !== null && data.goodsPhase !== '') {
var phase = makeNumber(data.goodsPhase);
ed.goods_phase = phase;
if (!isValidInteger(phase)) {
logToConsole('Seznam SEM [WARN]: goods_phase=' + data.goodsPhase +
' is not an integer | trace=' + traceId);
}
}
// status: boolean; `statusEnabled` flag distinguishes "not set" from false.
if (data.statusEnabled) {
ed.status = (data.status === 'true' || data.status === true);
}
// product_ids: integers >= 0; invalid entries skipped with warning.
var validProductIds = coerceIntegerArray(parsedProductIds, 'productIds');
if (validProductIds) {
ed.product_ids = validProductIds;
}
// Contents: already parsed upstream. Empty array is schema-valid and passed through.
if (parsedContents !== null && parsedContents !== undefined) {
ed.contents = parsedContents;
}
// Layer 3: override table (with typed coercion for numeric keys)
applyOverrides(ed, data.eventDataOverrides);
// SEM requires content_type whenever contents is present. Checkout/cart payloads
// with product arrays should use product; explicit values still win.
if (ed.contents !== undefined && ed.contents !== null && !ed.content_type) {
ed.content_type = 'product';
logToConsole('Seznam SEM [WARN]: contents present without content_type; defaulting content_type=product | trace=' + traceId);
}
return ed;
}
/*******************************************************************************
* Shared utilities
******************************************************************************/
// Parse a field that may be an object, a JSON string, or empty. Returns {value, error}.
// Callers decide severity (WARN vs. fail) based on strictEventValidation.
// Note: sandboxed JS does not support try/catch, but JSON.parse returns undefined on invalid input.
function parseJsonObjectField(fieldName, rawValue) {
if (!rawValue) return { value: null, error: null };
if (getType(rawValue) === 'object') return { value: rawValue, error: null };
if (getType(rawValue) === 'string') {
var parsed = JSON.parse(rawValue);
if (parsed === undefined) {
return { value: null, error: 'invalid JSON in ' + fieldName };
}
if (getType(parsed) === 'object') return { value: parsed, error: null };
return { value: null, error: fieldName + ' is not a JSON object' };
}
return { value: null, error: fieldName + ' has unsupported type: ' + getType(rawValue) };
}
// Parse a field that may be an array, a JSON string of an array, or empty. Returns {value, error}.
function parseJsonArray(fieldName, rawValue) {
if (!rawValue) return { value: null, error: null };
if (getType(rawValue) === 'array') return { value: rawValue, error: null };
if (getType(rawValue) === 'string') {
var parsed = JSON.parse(rawValue);
if (parsed === undefined) {
return { value: null, error: 'invalid JSON in ' + fieldName };
}
if (getType(parsed) === 'array') return { value: parsed, error: null };
return { value: null, error: fieldName + ' is not a JSON array' };
}
return { value: null, error: fieldName + ' has unsupported type: ' + getType(rawValue) };
}
function addIfPresent(obj, key, value) {
if (value) {
obj[key] = value;
}
}
// NaN fails all comparisons, so `n === Math.floor(n)` returns false for NaN.
function isValidInteger(n) {
return n !== undefined && n !== null && n === Math.floor(n);