· 6 years ago · Nov 21, 2019, 05:44 PM
1uses
2 'MainScript.pas', 'Email.pas', 'FTP.pas' ;
3
4const
5// if debug set to false then import will pull files from FTP
6 Debug=False;
7 SendErrorsOnly = True;
8
9// IMPORT_FILE = 'C:\dev\export_order_00001594.xml';
10// IMPORT_FILE = 'C:\Program Files (x86)\Cegid\Cegid RIT\WOCDEVTEST\TWDC_WebSrvCreateOrder\Samples\example_order_export_simple_product_with_pormotions.xml';
11var
12 ErrorList,ZORDERLINE :TStringList;
13 GP_LIBREPIECE1,CreateCustomerXML :string;
14 LineNum,OL_Bundel,OL_LineNumDW,RetryCnt,OrderIsCorrect :Integer;
15
16function CreateOrder(FileName: string; var WebErrorCode:string): Boolean;
17
18var
19 XmlDoc: TritXmlDoc;
20 order,customer,billingaddress,ResponceKey: TritXmlNode;
21 I: Integer;
22 RIT_ERROR,ABody,customer_email,OrderType,Stump,Num,
23 CreateRequest,Response,CustomerId,sql,orderno,CreateCustomerXMLResp :string;
24begin
25
26 Result := False;
27 OrderIsCorrect := 1;
28// ShowMessage(FileName);
29 ZORDERLINE.Clear();
30 if (not FileExists(FileName)) or (ExtractFileExt(FileName) <> '.xml') then exit;
31 XmlDoc := TritXmlDoc.Create('utf-8');
32 try
33 XmlDoc.LoadFromFile(FileName);
34 order := XmlDoc.SelectSingleNode('/orders/order');
35 if not order.Assigned then
36 begin
37 ABody := 'Invalid Order.';
38 SendMail(customer_email,'Order format error',ABody,FileName);
39 Exit;
40 end;
41
42
43// SelectNodes('/orders/order').Item[0];
44 orderno := NodeGetValueDef(order,'original-order-no');
45 if order.ChildNodeByName('giftcertificate-lineitems').Assigned then
46 begin
47 ABody := 'No <giftcertificate-lineitems> allow on orders. Invalid Order.';
48 LogError('Shipments format error: ' + ABody);
49 SendMail(customer_email,'Customer order creation error' + orderno,ABody,FileName);
50 Exit;
51 end;
52
53
54 Log('orderno', orderno);
55 customer := order.SelectNodes('customer').Item[0];
56 customer_email := NodeGetValueDef(customer,'customer-email');
57 Log('Customer', customer_email);
58// CustomerId := 'W0000000000293941';
59 Response := SearchCustomerIdsByEmail(customer_email);
60 CustomerId := GetCustomerId(Response);
61 // This is where the customer lookup and creation update occurrs
62 // We lookup via email in CBR
63 if CustomerId = '' then
64 begin
65 CreateCustomerXMLResp := AddNewCustomer(customer);
66 Log('CreateCustomerXMLResp',CreateCustomerXMLResp);
67 CustomerId := GetAddNewCustomerResult(CreateCustomerXMLResp);
68 if CustomerId = '' then
69 begin
70 ABody := CreateCustomerXMLResp;
71 SendMail(customer_email,'Can not create new customer(' + customer_email + ') for order: ' + orderno,ABody,'');
72 Exit;
73 end;
74 end
75 else
76 UpdateCustomer(CustomerId,customer);
77
78 Log('Customer Id', CustomerId);
79//
80 CreateRequest := InsertSQLXMLexcapeChars(SaleDocumentServiceCreateRequest(order,CustomerId,orderno));
81 if OrderIsCorrect = 0 then
82 begin
83 ABody := 'More than one <shipping-lineitems> shipping lines on the order.';
84 Log('Shipments format error',ABody);
85 SendMail(customer_email,'Customer order creation error' + orderno,ABody,FileName);
86 Exit;
87 end;
88 sql := 'insert into [ZORDERXML] ([OX_OrderNo],[OX_Order],[OX_Filename],[OX_OrderCreate]) ' +
89 'SELECT '''+orderno+''','''+ InsertSQLXMLexcapeChars(XmlDoc.XML.Text) +''','''+
90 FileName+''',''' + CreateRequest + '''' +
91 ' WHERE not exists (select OX_OrderNo from [ZORDERXML] WHERE OX_OrderNo =''' + orderno+''')';
92 SqlExecute(sql);
93 Response := SendCreateRequest(CreateRequest);
94 if Response = '' then
95 begin
96 ABody := 'Socket Error # 10054 Connection reset by peer.';
97 SendMail(customer_email,'Customer order creation error:' + orderno,ABody,'');
98 end;
99
100 XmlDoc.LoadFromXML(Response);
101 RIT_ERROR := ShowErrorResponse(Response,WebErrorCode);
102
103 sql := 'UPDATE [ZORDERXML] SET [OX_OrderResp] = ''' +
104 InsertSQLXMLexcapeChars(Response) +
105 ''',[OX_OrderRespDT]= GETDATE(),[OX_CustomerCreate] = ''' +
106 InsertSQLXMLexcapeChars(CreateCustomerXML) + ''',[OX_CustomerResp] = ''' +
107 InsertSQLXMLexcapeChars(CreateCustomerXMLResp) +
108 ''' WHERE OX_OrderNo = '''+orderno + '''';
109
110 if ExecuteSingleSql(sql) = 0 then
111 LogError(sql);
112
113 if RIT_ERROR = '' then
114 begin
115 XmlDoc.LoadFromXML(Response);
116
117 ResponceKey := XmlDoc.SelectSingleNode('/s:Envelope/s:Body/CreateResponse/CreateResult/Key');
118 Num := NodeGetValueDef(ResponceKey,'Number');
119 Stump := NodeGetValueDef(ResponceKey,'Stump');
120 OrderType := NodeGetValueDef(ResponceKey,'Type');
121 if (Num <> '')and(Stump <> '')and(OrderType<>'') then
122 begin
123 ABody := 'Customer order:' + Num + ', Store:' + Stump;
124 if not SendErrorsOnly then
125 SendMail(customer_email,'Customer order created:' + orderno,ABody,'');
126
127 sql := 'UPDATE [ZORDERXML] SET [OX_Numero] = ''' + Num +
128 ''',[OX_Souche]= ''' + Stump + ''',[OX_Naturepieceg]=''' +
129 ConvertType(OrderType) + ''',[OX_OrderType] = ''' + GP_LIBREPIECE1 + ''' WHERE OX_OrderNo = '''+orderno + '''';
130 ExecuteSingleSql(sql);
131 sql := 'INSERT INTO RIT_EVENTS (EVENT_TYPE,EVENT_STATUS,EVENT_KEY, DOC_ID,FIELDS_DATA,FLAG3,FLAG1) ' +
132 ' values ( ''SALESFORCECC'',''New'',''' +Stump+
133 ''',' +Num+ ',''GP_LIBREPIECE1=' + GP_LIBREPIECE1 +
134 ''' +CHAR(11)+ ''GP_NATUREPIECEG=' + ConvertType(OrderType) + ''',''' + GP_LIBREPIECE1 + ''',''' + Num + ''')';
135 // Inserr rit Events only for C&C and Standard Web orders
136 if (GP_LIBREPIECE1='CACWCC') or (GP_LIBREPIECE1 = 'CACWST') then
137 begin
138 try
139 SqlExecute(sql);
140 except
141 LogError('INSERT EVENT ERROR: ' + ExceptionMessage);
142 end;
143 end;
144
145 // Add orderlines in orderlines table
146 for I := 0 to ZORDERLINE.Count - 1 do
147 begin
148 sql := ZORDERLINE.Strings[I];
149 sql := StringReplace(sql,'{OL_OrderNo}',orderno,True);
150 ExecuteSingleSql(sql);
151 end;
152 Result := True;
153
154 end else
155 begin
156 ABody := 'Customer order:' + Num + ', Store:' + Stump;
157 SendMail(customer_email,'Error processing file:' + ExtractFileName(FileName) ,ABody,FileName);
158 Result := False;
159 end;
160
161 end else
162 begin
163 SendMail(customer_email,'Error processing file:' + ExtractFileName(FileName) ,RIT_ERROR,FileName);
164 Result := False;
165 end;
166
167 finally
168 XmlDoc.Free;
169 end;
170
171end;
172
173function InsertSQLXMLexcapeChars(sXML :string): string;
174begin
175 result := sXML;
176 result := StringReplace(sXML,'<?xml version="1.0" encoding="UTF-8"?>','<?xml version="1.0"?>',True);
177 result := StringReplace(result,'''','&ap' + 'os;',True);
178 result := StringReplace(result,'''','''''',True);
179 result := StringReplace(result,'&','&am' + 'p;',True);
180end;
181
182function ExcapeXMLNode(sXML :string): string;
183begin
184 result := sXML;
185 result := StringReplace(result,'&','&am' + 'p;',True);
186 result := StringReplace(result,'"','&qu' + 'ot;',True);
187 result := StringReplace(result,'''','&ap' + 'os;',True);
188 result := StringReplace(result,'''','''''',True);
189 result := StringReplace(result,'<','&l' + 't;',True);
190 result := StringReplace(result,'>','&g' + 't;',True);
191end;
192
193
194function ConvertType(OldType :string): string;
195begin
196 case OldType of
197 'Receipt' : Result := 'FFO';
198 'CustomerOrder' : Result := 'CC';
199 else
200 Result := 'ERR';
201end
202end;
203
204
205
206procedure WinSCPLoadFiles();
207var
208 I,J,K,L : Integer;
209 Session,
210 SessionOpt,
211 TransferOpt,
212 EnumerationOptions,
213 files,
214 TransferResult: Variant;
215 FName,FName2,DownloadDir,RemoteDir: String;
216 MoveDirName :String;
217 Suc :Boolean;
218 WebErrorCode :String;
219begin
220//Register Winscp Type library
221//%WINDIR%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe "C:\Program Files (x86)\WinSCP\WinSCPnet.dll" /codebase /tlb:WinSCPnet32.tlb
222
223
224 try
225 SessionOpt := CreateOleObject('WinSCP.SessionOptions');
226 except
227 Log ('winscp.EXE ERROR:',ExceptionMessage);
228 end;
229
230 SessionOpt.Hostname := FTPHostname;
231
232// Testing
233 SessionOpt.Username := FTPUsername;
234 SessionOpt.Password := FTPPassword;
235 SessionOpt.Protocol := FTPProtocol; // 0=SFTP, 1=SCP, 2=FTP, 3=WebDAV
236 SessionOpt.PortNumber := FTPPortNumber;
237 SessionOpt.SshHostKeyFingerprint := FTPSshHostKeyFingerprint;
238 Session := CreateOleObject('WinSCP.Session');
239 Session.Open(SessionOpt);
240 if Session.Opened then Log('Connected to FTP Host:', FTPHostname);
241// FName := ExtractFilePath(ParamStr(0)) + 'WinSCP.Log';
242// Session.DebugLogPath := FName;
243 try
244 TransferOpt := CreateOleObject('WinSCP.TransferOptions');
245 TransferOpt.TransferMode := FTPTransferMode; // Binary
246// TransferResult := Session.PutFiles(FName, RemoteDir, False, TransferOpt);
247
248 DownloadDir := ExtractFilePath(ParamStr(0)) + 'Download\';
249 RemoteDir := FTPRemoteDir;
250 files := Session.ListDirectory(RemoteDir);
251
252
253 for I:=files.files.Count - 1 downto 0 do
254 begin
255 FName := files.files.Item(I).Name;
256 if ExtractFileExt(FName) = '.xml' then
257 begin
258 TransferResult := Session.GetFiles(RemoteDir + '/' + FName , DownloadDir, False, TransferOpt);
259 if not TransferResult.IsSuccess then
260 begin
261 for J := 0 to TransferResult.Failures.Count - 1 do
262 LogError('Failures: ' + TransferResult.Failures.Item(J).Message);
263 end else
264 for K := 0 to TransferResult.Transfers.Count - 1 do
265 begin
266 FName := TransferResult.Transfers.Item(K).FileName;
267 Log('Downloaded', FName);
268 FName2 := ExtractFileName(StringReplace(Fname,'/','\',True));
269 RetryCnt := 0;
270 if CreateOrder(DownloadDir + FName2,WebErrorCode) then
271 MoveDirName := RemoteDir+'/processed/' + FName2
272 else
273 MoveDirName := RemoteDir+'/processed_error/' + FName2;
274 // CBR_002_0010 - No worker available to process message
275 // 0x80004005 - Timeout
276 // CBR_001_0003 -- Document already exists also timeout LW show bogdan in log file
277
278 if (WebErrorCode = 'CBR_002_0010') or (WebErrorCode = '0x80004005') then
279 begin
280 MoveDirName :=
281 // ExtractFilePath(StringReplace(MoveDirName,'/','\',True))
282 ExtractFileNameExtended(MoveDirName) +'_'+ WebErrorCode + '.xml';
283 end;
284 Log('Moving file',FName + '->' + MoveDirName);
285 for L := 0 to 2 do
286 begin
287 Suc := True;
288 try
289
290 Session.MoveFile(FName,MoveDirName);
291 except
292 LogError('MoveFile Error: ' + ExceptionMessage);
293 Sleep(1000);
294 Suc := False;
295 end;
296 if Suc then Break;
297 end;
298 //Delete local file
299 DeleteFile(DownloadDir + FName2);
300 end;
301 end;
302 end;
303 finally
304 Session.Dispose();
305 end;
306end;
307
308
309
310function ShowErrorResponse(Response: string; var WebErrorCode :string) :string;
311var
312 XmlDoc1: TritXmlDoc;
313 Node :TritXmlNode;
314 ERRORTEXT,FaultDetail :string;
315 SL1,SL2 :TStream;
316 I :Integer;
317begin
318 XmlDoc1 := TritXmlDoc.Create('utf-8');
319 XmlDoc1.LoadFromXML(Response);
320
321 Result := '';
322 if (Pos('<BusinessFaultDetail',Response) <> 0) then FaultDetail := 'BusinessFaultDetail'
323 else if (Pos('<CbpFaultDetail',Response) <> 0) then
324 begin
325 FaultDetail := 'CbpFaultDetail';
326 Result := XmlDoc1.SelectSingleNode('/s:Envelope/s:Body/s:Fault/detail/' +FaultDetail+ '/Message').Text;
327 WebErrorCode := 'CBR_002_0010';
328 Exit;
329 end
330 else if (Pos('<faultcode',Response) <> 0) then FaultDetail := 'CbpFaultDetail'
331 else if (Pos('<ExceptionDetail',Response) <> 0) then
332 begin
333 Result := XmlDoc1.SelectSingleNode('/s:Envelope/s:Body/s:Fault/detail/ExceptionDetail/Message').Text;
334 Exit;
335 end
336 else exit;
337
338// /s:Envelope/s:Body/s:Fault/detail/BusinessFaultDetail/Description
339
340
341
342 try
343 Node := XmlDoc1.SelectSingleNode('/s:Envelope/s:Body/s:Fault/detail/ExceptionDetail/InnerException/InnerException/Message');
344 if Node.Assigned then
345 begin
346 LogError('ERROR: ' + Node.Text );
347 result := Node.Text;
348 Exit;
349 end;
350 ERRORTEXT := XmlDoc1.SelectSingleNode('/s:Envelope/s:Body/s:Fault/detail/' +FaultDetail+ '/Description').XML;
351 ERRORTEXT := StringReplace(ERRORTEXT,'Message =',#13#10,True);
352
353 for I := 0 to ErrorList.Count - 1 do
354 begin
355 if Pos(ErrorList.Strings[I],ERRORTEXT)<>0 then
356 begin
357 WebErrorCode := ErrorList.Strings[I];
358 Result := Result + ParseStr(ERRORTEXT,ErrorList.Strings[I],#13#10);
359 end;
360 end;
361 if Result = '' then
362 begin
363 ShowMessage('Undefined Error');
364 LogError(Response );
365 end else
366 Log(Result);
367
368
369 finally
370 XmlDoc1.Free;
371 end;
372end;
373
374
375procedure SendMail(ATo,ASubject,ABody,AAttachment :string);
376const
377 EmailLog = 'To:%s Subject:%s Body:%s Attachment%s';
378var
379 Res :string;
380begin
381 Log('Sending Email',Format( EMAILEmailLog,[EMAILATo,ASubject,ABody,AAttachment]));
382 Res := PluginFn('ritSendMail',EMAILAHost,EMAILAPort,EMAILRetryTimeout,EMAILAUseTLS,
383 EMAILAUser, EMAILAPassword, EMAILAFrom, EMAILATo, ASubject, ABody,AAttachment);
384 if Res = '0' then
385 LogError('Error sending: ' + PluginFn('ritSendMailLastError'))
386
387end;
388
389
390function StartExport(customer_email: string): string;
391const
392 IMPORT_FILE = 'C:\Debug_test_order.xml';
393begin
394
395
396 RetryCnt := 0;
397 ErrorList := TStringList.Create;
398 ZORDERLINE := TStringList.Create;
399 try
400 ErrorList.Add('DOC00023'); //Problem for finding third party
401 ErrorList.Add('DOC00042'); //Document exists
402 ErrorList.Add('ART00008'); //Barcode does not match any item
403 ErrorList.Add('DOC00010'); //payment Payment method is mandatory
404 ErrorList.Add('DOC00011'); //payment Payment method does not exists
405 ErrorList.Add('CBRWP019'); //Time out during maximum processing time (10 seconds)
406 ErrorList.Add('DOC00002'); //the internal reference of the document is not specified
407 ErrorList.Add('0x80004005'); //Timeout for the requested operation has expired.
408 ErrorList.Add('ECO00033'); //The management of pick-up points for orders in store ??? in not enabled
409 ErrorList.Add('ART00011'); //Item cannot be identified; barcode or item code are not specified.
410 ErrorList.Add('ECO00034'); //The pick-up store is mandatory
411 ErrorList.Add('DOC00075'); //Store does not exist or is deleted
412
413
414
415 // Must be the last
416 ErrorList.Add('CBR00009'); //Import failed : Customer order Internal reference
417
418 if Debug then CreateOrder(IMPORT_FILE,'')
419 else WinSCPLoadFiles();
420 finally
421 ErrorList.Free;
422 ZORDERLINE.Free;
423 end;
424end;
425
426
427
428function LookupCountryCode(aPay2:string):string;
429var
430 qryTest: TDataSet;
431begin
432 Result := '';
433 try
434 try
435 qryTest := CreateDataset('select PY_PAYS from Pays where PY_CODEISO2='''+aPay2+'''');
436 qryTest.First;
437 Result:=qryTest.FieldByName('PY_PAYS').Value;
438 qryTest.Close;
439 except
440 Log('LookupCountryCode',ExceptionMessage);
441 end;
442 finally
443 qryTest.Free;
444 end;
445end;
446
447function LookupUniqueID(ID:string):string;
448// no longer used only for testing
449var
450 sql :string;
451 qryTest: TDataSet;
452begin
453 Result := '';
454 try
455 try
456 sql := 'exec ritGetUniqueID '''+ID+''',''CC''';
457 qryTest := CreateDataset(sql);
458 qryTest.First;
459 Result:=qryTest.Fields[0].Value;
460 qryTest.Close;
461 Log('LookupUniqueID value:',Result);
462 except
463 LogError('LookupUniqueID _error: ' + ExceptionMessage);
464 end;
465 finally
466 qryTest.Free;
467 end;
468end;
469
470
471function GetCustomerId(Response: string): string;
472var
473 B,E :Integer;
474begin
475 B := Pos('<CustomerId>',Response) + Length('<CustomerId>');
476 E := Pos('</CustomerId>',Response);
477 result := Copy(Response,B,E - B);
478end;
479
480function GetAddNewCustomerResult(Response: string): string;
481var
482 B,E :Integer;
483begin
484 B := Pos('<AddNewCustomerResult>',Response) + Length('<AddNewCustomerResult>');
485 E := Pos('</AddNewCustomerResult>',Response);
486 result := Copy(Response,B,E - B);
487end;
488
489
490function CalcTaxAmount(TaxAmount,QTY :string) :Double;
491begin
492 try
493 result:= StrToFloat( TaxAmount) * StrToFloat(QTY);
494 except
495 result := 0;
496 end;
497end;
498
499function GetTaxes(LineItem: TritXmlNode): string;
500var
501 SL1 :TStringList;
502 TaxAmount,QTY :string;
503 X: Double;
504 quantity: TritXmlNode;
505begin
506 if Pos('<shipping-lineitem>',LineItem.XML) <> 0 then
507 TaxAmount := lineitem.ChildNodeByName('tax').Text
508 else
509 TaxAmount := lineitem.SelectSingleNode('custom-attributes/custom-attribute[@attribute-id=''cegidUnitTaxAmount'']').Text;
510
511 quantity := lineitem.ChildNodeByName('quantity');
512 if quantity.Assigned then
513 QTY := quantity.Text
514 else
515 QTY := '1';
516 X := CalcTaxAmount(TaxAmount,QTY);
517
518 if (Pos('<tax>',LineItem.XML) = 0) then exit;
519 SL1 := TStringList.Create;
520 try
521 SL1.Add('<ns:Taxes>');
522 SL1.Add(' <ns:Create_Tax>');
523 SL1.Add(' <ns:Amount>' + FloatToStr(X) + '</ns:Amount>');
524 SL1.Add(' <ns:FamilyId>1</ns:FamilyId>');
525 SL1.Add(' </ns:Create_Tax>');
526 SL1.Add('</ns:Taxes>');
527 result := SL1.Text;
528 finally
529 SL1.Free;
530 end;
531end;
532
533function SaleDocumentServiceCreateRequestAddLines(order: TritXmlNode): string;
534var
535 SL0,SL_CL :TStringList;
536 i,j :Integer;
537 product_lineitems,priceadjustments,bundled_product_lineitems,
538 custom_attributes_price,option_lineitems :TritXmlNodeList;
539 bundled_product_lineitem,custom_attributes,priceadjustment,
540 lineitem,packageQuantity :TritXmlNode;
541 Taxes,NetUnitPrice,UnitPrice,ExternalReference :string;
542begin
543 Taxes :='';
544 LineNum := 1;
545 OL_LineNumDW := 0;
546 OL_Bundel := 0;
547 SL0 := TStringList.Create;
548 SL_CL := TStringList.Create;
549 try
550// product_lineitems := order.ChildNodeByName('product_lineitems').ChildNodes;
551// customer := order.SelectNodes('//customer').Item[0];
552// Log('XML',order.XML);
553 product_lineitems := order.SelectNodes('product-lineitems/product-lineitem');
554 for i := 0 to product_lineitems.Length - 1 do
555 begin
556 ExternalReference := '';
557 lineitem := product_lineitems.Item[i];
558 Inc(OL_LineNumDW);
559 bundled_product_lineitems := lineitem.SelectNodes('bundled-product-lineitems/bundled-product-lineitem');
560 if bundled_product_lineitems.Length() = 0 then
561 begin
562 packageQuantity := lineitem.SelectSingleNode('custom-attributes/custom-attribute[@attribute-id=''packageQuantity'']');
563 if packageQuantity.Assigned then
564 ExternalReference := packageQuantity.Text;
565 option_lineitems := lineitem.SelectNodes('option-lineitems/option-lineitem');
566 for j := 0 to option_lineitems.Length - 1 do
567 begin
568// if J<>0 then
569 ExternalReference := ExternalReference + '~';
570 ExternalReference := ExternalReference + NodeGetValueDef(option_lineitems[j],'lineitem-text') ;
571 end;
572
573 Taxes := GetTaxes(lineitem);
574 NetUnitPrice := lineitem.SelectSingleNode('custom-attributes/custom-attribute[@attribute-id=''cegidUnitNetPrice'']').Text;
575 UnitPrice := lineitem.SelectSingleNode('custom-attributes/custom-attribute[@attribute-id=''cegidUnitOriginalPrice'']').Text;
576
577 AddLineItemToSL(SL_CL,lineitem,ExternalReference,NetUnitPrice,UnitPrice,Taxes,'');
578 InsertLinesToDB(lineitem,SL_CL.Text,ExternalReference,0);
579 SL0.Text := SL0.Text + SL_CL.Text;
580 end else
581 begin
582 Inc(OL_Bundel);
583 for j := 0 to bundled_product_lineitems.Length - 1 do
584 begin
585 bundled_product_lineitem := bundled_product_lineitems.Item[j];
586// ExternalReference := IntToStr(J + 1) + '-' + IntToStr(bundled_product_lineitems.Length);
587 ExternalReference := 'SET' + IntToStr(OL_Bundel);
588 ExternalReference := ExternalReference + '~' +
589 lineitem.ChildNodeByName('product-id').Text + '~' +
590 bundled_product_lineitem.ChildNodeByName('product-name').Text;
591
592 Taxes := GetTaxes(bundled_product_lineitem);
593// Old Code LW 19 Sept 2018
594// UnitPrice := bundled_product_lineitem.SelectSingleNode('custom-attributes/custom-attribute[@attribute-id=''cegidUnitNetPrice'']').Text;
595// NetUnitPrice := bundled_product_lineitem.SelectSingleNode('custom-attributes/custom-attribute[@attribute-id=''cegidUnitOriginalPrice'']').Text;
596// fixed Code LW 19 Sept 2018
597 NetUnitPrice:= bundled_product_lineitem.SelectSingleNode('custom-attributes/custom-attribute[@attribute-id=''cegidUnitNetPrice'']').Text;
598 UnitPrice := bundled_product_lineitem.SelectSingleNode('custom-attributes/custom-attribute[@attribute-id=''cegidUnitOriginalPrice'']').Text;
599
600
601 AddLineItemToSL(SL_CL,bundled_product_lineitem,ExternalReference,NetUnitPrice,UnitPrice,Taxes,NodeGetValueDef(lineitem,'lineitem-text'));
602 bundled_product_lineitem.AddChild('parent-product-id').Text :=
603 lineitem.ChildNodeByName('product-id').Text;
604 bundled_product_lineitem.AddChild('parent-product-qty').Text :=
605 lineitem.ChildNodeByName('quantity').Text;
606 InsertLinesToDB(bundled_product_lineitem,SL_CL.Text,ExternalReference,0);
607 SL0.Text := SL0.Text + SL_CL.Text;
608 end;
609 end;
610 end;
611
612 product_lineitems := order.SelectNodes('shipping-lineitems/shipping-lineitem');
613 if product_lineitems.Length() > 1 then
614 begin
615 OrderIsCorrect := 0;
616 Exit;
617 end;
618 for i := 0 to product_lineitems.Length - 1 do
619 begin
620 Inc(OL_LineNumDW);
621 lineitem := product_lineitems.Item[i];
622 priceadjustments := lineitem.SelectNodes('price-adjustments/price-adjustment');
623 if priceadjustments.Length = 1 then
624 begin
625 priceadjustment := priceadjustments.Item[0];
626 NetUnitPrice := FloatToStr(StrToFloat(NodeGetValueDef(lineitem,'net-price')) +
627 StrToFloat(NodeGetValueDef(priceadjustment,'net-price')));
628 UnitPrice := FloatToStr(StrToFloat(NodeGetValueDef(lineitem,'gross-price')) +
629 StrToFloat(NodeGetValueDef(priceadjustment,'gross-price')));
630 end else
631 begin
632 Taxes := GetTaxes(lineitem);
633 UnitPrice := NodeGetValueDef(lineitem,'gross-price');
634 NetUnitPrice := NodeGetValueDef(lineitem,'gross-price');
635 end;
636// ExternalReference := SafeGetValue(lineitem,'item-id');
637 ExternalReference := 'Shipping';
638 lineitem.AddChild('shipping-method').Text :=
639 order.SelectSingleNode('shipments/shipment/shipping-method').Text;
640
641 AddLineItemToSL(SL_CL,lineitem,ExternalReference,NetUnitPrice,UnitPrice,Taxes,'');
642 InsertLinesToDB(lineitem,SL_CL.Text,ExternalReference,1);
643 SL0.Text := SL0.Text + SL_CL.Text;
644 end;
645 result := SL0.Text;
646 finally
647 SL0.Free;
648 SL_CL.Free;
649 end;
650end;
651
652procedure AddLineItemToSL(SL0 :TStringList ;lineitem :TritXmlNode;
653ExternalReference,NetUnitPrice,UnitPrice,Taxes,ParentLineItemText :string);
654var
655 product_id :TritXmlNode;
656 Reference,lineitem_text :string;
657begin
658 SL0.Clear;
659 product_id := lineitem.ChildNodeByName('product-id');
660 if product_id.Assigned then
661 Reference := product_id.Text
662 else
663 begin
664// ExternalReference := '';
665 Reference := NodeGetValueDef(lineitem,'shipping-method');
666 end;
667// Log('lineitem.ParentNode', lineitem.ParentNode.XML);
668 lineitem_text := NodeGetValueDef(lineitem,'lineitem-text',ParentLineItemText);
669// lineitem.ParentNode.ChildNodeByName('lineitem-text').Text);
670
671
672 SL0.Add('<ns:Create_Line>');
673 SL0.Add(' <ns:ExternalReference >' + ExternalReference + '</ns:ExternalReference >');
674 SL0.Add(' <ns:ItemIdentifier>');
675 SL0.Add(' <ns:Reference>' + Reference + '</ns:Reference>');
676 SL0.Add(' </ns:ItemIdentifier>');
677 SL0.Add(' <ns:Label>' + lineitem_text + '</ns:Label>');
678 SL0.Add(' <ns:NetUnitPrice>' + NetUnitPrice + '</ns:NetUnitPrice>');
679 SL0.Add(' <ns:Quantity>' + NodeGetValueDef(lineitem,'quantity','1') + '</ns:Quantity>');
680 SL0.Add(Taxes);
681 SL0.Add(' <ns:UnitPrice>' + UnitPrice + '</ns:UnitPrice>');
682 SL0.Add('</ns:Create_Line>');
683 SL0.Add('');
684end;
685
686procedure InsertLinesToDB(OrigLine :TritXmlNode;NewLineXML,Reference :string;IsShipping :Integer);
687var
688 sql :string;
689 OL_LineNum,OL_BundelSKU,OL_IsBundel,OL_BundelS,OL_SKU,parent_product_qty
690 ,OL_Processed,OL_Status,OX_LineOriginal,OX_LineCreate,OX_Retry
691 ,OL_Flag1,OL_Flag2,OL_Flag3,OL_Qty :string;
692// OrigLine :TritXmlNode;
693begin
694// Log('OrigLine.XML',OrigLine.XML);
695 NewLineXML := StringReplace(NewLineXML,'<ns:Create_Line>','<ns:Create_Line xmlns:ns="http://www.cegid.fr/Retail/1.0">',True);
696 OL_IsBundel := '0';
697 OL_BundelSKU := '';
698 OL_SKU := NodeGetValueDef(OrigLine,'product-id',NodeGetValueDef(OrigLine,'shipment-id',''));
699 OL_BundelS := '';
700 OL_Qty := '';
701 parent_product_qty := NodeGetValueDef(OrigLine,'parent-product-qty','NULL');
702
703 if pos('<bundled-product-lineitem>',OrigLine.XML) <> 0 then
704 begin
705 OL_IsBundel := '1';
706 OL_BundelSKU := OrigLine.ChildNodeByName('parent-product-id').Text;
707 if OL_Bundel <> 0 then
708 OL_BundelS := IntToStr(OL_Bundel);
709 end;
710 OL_Qty := StringReplace(NodeGetValueDef(OrigLine,'quantity','1'),'.0','',True);
711 OX_Retry := '0';
712 sql := 'INSERT INTO [ZORDERLINEXML]' +
713 '([OL_OrderNo],[OL_LineNum],[OL_LineNumDW],[OL_Bundle],[OL_SKU],[OL_BundleSKU] ' +
714 ',[OL_IsBundle],[OL_IsShipping],[OL_Processed],[OL_Status] ' +
715 ',[OL_LineOriginal],[OL_LineCreate],[OL_Retry],[OL_Flag1]' +
716 ',[OL_Flag2],[OL_Flag3],[OL_Ref],[OL_Qty],[OL_BundleQty]) VALUES ' +
717 '(''' + '{OL_OrderNo}' + ''',''' + IntToStr(LineNum) + ''',''' + IntToStr(OL_LineNumDW) +
718 ''',''' + OL_BundelS + ''',''' + OL_SKU + ''',''' + OL_BundelSKU +
719 ''',''' + OL_IsBundel + ''',''' + IntTostr(IsShipping) +
720 ''',GETDATE(),''' + OL_Status + ''',''' + InsertSQLXMLexcapeChars(OrigLine.XML) + ''',''' +
721 InsertSQLXMLexcapeChars(NewLineXML) + ''',''' + OX_Retry + ''',''' + OL_Flag1 + ''',''' + OL_Flag2 +
722 ''',''' + OL_Flag3 + ''',''' + InsertSQLXMLexcapeChars(Reference) + ''',''' + OL_Qty + ''','
723 + parent_product_qty +')';
724 ZORDERLINE.Add(sql);
725 LineNum := LineNum + 1;
726// SqlExecute(sql);
727
728end;
729
730
731function GetMethodId(ProcessorId :string): string;
732begin
733// added KLARNA_PAYMENTS as WEB payment method LW 19/Sept/2019
734 if (ProcessorId = 'CARD')or(ProcessorId = 'WorldPay') or (ProcessorId = 'KLARNA_PAYMENTS') then result := 'WEB';
735 if (ProcessorId = 'GIFT-VOUCHER') or(ProcessorId = 'BASIC_GIFT_CERTIFICATE') then
736 result := 'OGV';
737 if (ProcessorId = 'PAYPAL')or(ProcessorId = 'PAYPAL_EXPRESS') then result := 'PAL';
738 if (ProcessorId = 'PAY_AT_STORE') then result := ''
739
740end;
741
742function SaleDocumentServiceCreateRequestAddPayments(order: TritXmlNode;OrderType :string): string;
743var
744 SL0 :TStringList;
745 i,j :Integer;
746 payments :TritXmlNodeList;
747 payment :TritXmlNode;
748 MethodId :string;
749begin
750 SL0 := TStringList.Create;
751 try
752 payments := order.SelectNodes('payments/payment');
753 for i := 0 to payments.Length - 1 do
754 begin
755 payment := payments.Item[i];
756 MethodId := GetMethodId(payment.ChildNodeByName('processor-id').Text);
757 if MethodId <> '' then
758 begin
759 SL0.Add('<ns:Create_Payment>');
760 SL0.Add(' <ns:Amount>' + payment.ChildNodeByName('amount').Text + '</ns:Amount>');
761 SL0.Add(' <ns:CurrencyId>' + order.ChildNodeByName('currency').Text + '</ns:CurrencyId>');
762 SL0.Add(' <ns:DueDate>' + ConvertDate(NodeGetValueDef(order,'order-date')) + '</ns:DueDate>');
763 SL0.Add(' <ns:Id>' + IntToStr(i + 1) + '</ns:Id>');
764 SL0.Add(' <ns:MethodId>' + MethodId + '</ns:MethodId>');
765 SL0.Add('</ns:Create_Payment>');
766 SL0.Add('');
767 end;
768 end;
769 result := SL0.Text;
770 finally
771 SL0.Free;
772 end;
773end;
774
775
776
777
778
779
780function SaleDocumentServiceCreateRequest(order: TritXmlNode;CustomerId,InternalReference: string): string;
781var
782 SL :TStringList;
783 DeliveryStoreId,FN,OrderType,Payments,shipping_method,
784 ExternalReference,processor_id ,ShiptoCompany ,BilltoCompany :string;
785 billingaddress,DeliveryAddress,rit,payment0,shipment_custom_attribute_n :TritXmlNode;
786 shipment_custom_attributes,payment_custom_method,option_lineitems : TritXmlNodeList;
787 i :Integer;
788begin
789 SL := TStringList.Create;
790
791 try
792// customer := order.SelectNodes('//customer').Item[0];
793// customer_email := customer.ChildNodeByName('customer-email').Value;
794// CACWCR
795
796 billingaddress := order.SelectNodes('customer/billing-address').Item[0];
797 DeliveryAddress := order.SelectNodes('shipments/shipment/shipping-address').Item[0];
798// shipment_custom_attributes := order.SelectNodes('shipments/shipment/custom-attributes');
799 ExternalReference := VarToStr(order.SelectNodes('shipments/shipment').Item[0].Attributes('shipment-id'));
800// /orders/order/shipments/shipment/shipping-method
801 Log('ExternalReference',ExternalReference);
802
803
804 payment0 := order.SelectNodes('payments/payment').Item[0];
805
806// if shipment_custom_attributes.Length = 0 then
807// begin
808// OrderType := 'CACWST';
809// end else
810 begin
811 shipment_custom_attribute_n := order.SelectSingleNode('shipments/shipment/custom-attributes/custom-attribute[@attribute-id=''storeId'']');
812 if shipment_custom_attribute_n.Assigned then
813 DeliveryStoreId := shipment_custom_attribute_n.Text;
814// 'CACWCC,CACWCR: ' Sales->E-Commerce Sales ->Query of Document
815 processor_id := NodeGetValueDef(payment0,'processor-id') ;
816 Log('processor_id',processor_id);
817
818 // New Logic to be
819 shipping_method := NodeGetValueDef(order.SelectSingleNode('shipments/shipment'),'shipping-method');
820
821 if shipping_method = '' then
822 begin
823 OrderIsCorrect := 0;
824 Exit;
825 end;
826 if Pos('CR_',shipping_method) <> 0 then OrderType := 'CACWCR'
827 else if Pos('CC_',shipping_method) <> 0 then OrderType := 'CACWCC'
828 else OrderType := 'CACWST';
829
830 end;
831
832 GP_LIBREPIECE1 := OrderType;
833// OrderType := 'CACWST';
834
835// if order.SelectNodes('rit').Length = 1 then
836// begin
837// rit := order.SelectNodes('rit').Item[0];
838// OrderType := SafeGetValue(rit, 'order_type');
839// DeliveryStoreId := SafeGetValue(rit, 'DeliveryStoreId');
840// end else
841// begin
842// OrderType := 'CACWST';
843// DeliveryStoreId := 'OX1';
844// end;
845
846
847
848
849
850 FN := GetTemplateName('SaleDocumentService','CreateRequest.xml');
851 SL.LoadFromFile(FN);
852
853 SL.Text := StringReplace(SL.Text,'[InvoicingAddress_Line1]',NodeGetValueDef(billingaddress,'address1'),True);
854 SL.Text := StringReplace(SL.Text,'[InvoicingAddress_Line2]',NodeGetValueDef(billingaddress,'address2'),True);
855 // SL.Text := StringReplace(SL.Text,'[InvoicingAddress_Line3]',NodeGetValueDef(billingaddress,'state-code'),True);
856 // Remove Other from Address
857 SL.Text := StringReplace(SL.Text,'[InvoicingAddress_Line3]',StringReplace(NodeGetValueDef(billingaddress,'state-code'),'OTHER','',True),True);
858
859 SL.Text := StringReplace(SL.Text,'[InvoicingAddress_City]',NodeGetValueDef(billingaddress,'city'),True);
860 SL.Text := StringReplace(SL.Text,'[InvoicingAddress_ZipCode]',NodeGetValueDef(billingaddress,'postal-code'),True);
861 SL.Text := StringReplace(SL.Text,'[InvoicingAddress_FirstName]',NodeGetValueDef(billingaddress,'first-name'),True);
862 SL.Text := StringReplace(SL.Text,'[InvoicingAddress_LastName]',NodeGetValueDef(billingaddress,'last-name'),True);
863 SL.Text := StringReplace(SL.Text,'[InvoicingAddress_PhoneNumber]',NodeGetValueDef(billingaddress,'phone'),True);
864 SL.Text := StringReplace(SL.Text,'[InvoicingAddress_CountryId]',LookupCountryCode(NodeGetValueDef(billingaddress,'country-code')),True);
865
866 SL.Text := StringReplace(SL.Text,'[DeliveryAddress_Line1]',NodeGetValueDef(DeliveryAddress,'address1'),True);
867 SL.Text := StringReplace(SL.Text,'[DeliveryAddress_Line2]',NodeGetValueDef(DeliveryAddress,'address2'),True);
868 // SL.Text := StringReplace(SL.Text,'[DeliveryAddress_Line3]',NodeGetValueDef(DeliveryAddress,'state-code'),True);
869 // Remove Other from Address
870 SL.Text := StringReplace(SL.Text,'[DeliveryAddress_Line3]',StringReplace(NodeGetValueDef(DeliveryAddress,'state-code'),'OTHER','',True),True);
871
872
873 SL.Text := StringReplace(SL.Text,'[DeliveryAddress_City]',NodeGetValueDef(DeliveryAddress,'city'),True);
874 SL.Text := StringReplace(SL.Text,'[DeliveryAddress_ZipCode]',NodeGetValueDef(DeliveryAddress,'postal-code'),True);
875 SL.Text := StringReplace(SL.Text,'[DeliveryAddress_FirstName]',NodeGetValueDef(DeliveryAddress,'first-name'),True);
876 SL.Text := StringReplace(SL.Text,'[DeliveryAddress_LastName]',NodeGetValueDef(DeliveryAddress,'last-name'),True);
877 SL.Text := StringReplace(SL.Text,'[DeliveryAddress_PhoneNumber]',NodeGetValueDef(DeliveryAddress,'phone'),True);
878 SL.Text := StringReplace(SL.Text,'[DeliveryAddress_CountryId]',LookupCountryCode(NodeGetValueDef(DeliveryAddress,'country-code')),True);
879
880 SL.Text := StringReplace(SL.Text,'[CurrencyId]',NodeGetValueDef(order,'currency'),True);
881 SL.Text := StringReplace(SL.Text,'[CustomerId]',CustomerId,True);
882
883 if Debug then
884 SL.Text := StringReplace(SL.Text,'[Date]',ConvertCurrentDate())
885 else
886 SL.Text := StringReplace(SL.Text,'[Date]',ConvertDate(NodeGetValueDef(order,'order-date')),True);
887
888
889 SL.Text := StringReplace(SL.Text,'[ExternalReference]',ExternalReference,True);
890 SL.Text := StringReplace(SL.Text,'[InternalReference]',InternalReference,True);
891 SL.Text := StringReplace(SL.Text,'[Lines]',SaleDocumentServiceCreateRequestAddLines(order),True);
892 if OrderType <> 'CACWCR' then // Ignore Click and Reserve order types as these will be payed for instore.
893 Payments := SaleDocumentServiceCreateRequestAddPayments(order,OrderType)
894 else
895 Payments := '';
896
897 SL.Text := StringReplace(SL.Text,'[Payments]',Payments,True);
898 SL.Text := StringReplace(SL.Text,'[UserDefinedTables]',FillUserDefinedTables(OrderType),True);
899
900// User Fields
901//1 Delivery Company Name
902//2 Invoice Company Name
903 ShiptoCompany:=NodeGetValueDef(DeliveryAddress,'company');
904 BilltoCompany:=NodeGetValueDef(billingaddress,'company');
905
906 SL.Text := StringReplace(SL.Text,'[UserFields]',FillUserField(ShiptoCompany,'1')+FillUserField(BilltoCompany,'2')+,True);
907
908 SL.Text := StringReplace(SL.Text,'[OmniChannel]',FillOmniChannel(OrderType,DeliveryStoreId,order),True);
909
910 SL.Text := StringReplace(SL.Text,'[DatabaseId]',DB_NAME,True);
911 result := SL.Text;
912// log(Result);
913 finally
914 SL.Free;
915 end;
916end;
917
918function ConvertDate(nsDate :string):string;
919begin
920 result := Copy(nsDate,1,Pos('T',nsDate)) + '00:00:00.0';
921end;
922
923
924function ConvertCurrentDate:string;
925begin
926//2018-05-02T12:42:45.832Z
927
928 result := FormatDateTime('YYYY-MM-DD',Now) + 'T00:00:00.0';
929end;
930
931function CustomerWcfServiceAddNewCustomer(customer: TritXmlNode): string;
932var
933 SL :TStringList;
934 billingaddress :TritXmlNode;
935begin
936 SL := TStringList.Create;
937 try
938 billingaddress := customer.SelectNodes('billing-address').Item[0];
939 SL.LoadFromFile(GetTemplateName('CustomerWcfService','AddNewCustomer.xml'));
940
941 SL.Text := StringReplace(SL.Text,'[AddressLine1]',NodeGetValueDef(billingaddress,'address1'),True);
942 SL.Text := StringReplace(SL.Text,'[AddressLine2]',NodeGetValueDef(billingaddress,'address2'),True);
943 // Remove Other from Address template
944 SL.Text := StringReplace(SL.Text,'[AddressLine3]',StringReplace(NodeGetValueDef(billingaddress,'state-code'),'OTHER','',True),True);
945
946 SL.Text := StringReplace(SL.Text,'[City]',NodeGetValueDef(billingaddress,'city'),True);
947
948 SL.Text := StringReplace(SL.Text,'[CountryId]',LookupCountryCode(NodeGetValueDef(billingaddress,'country-code')),True);
949 SL.Text := StringReplace(SL.Text,'[Email]',NodeGetValueDef(customer,'customer-email'),True);
950 SL.Text := StringReplace(SL.Text,'[ZipCode]',NodeGetValueDef(billingaddress,'postal-code'),True);
951 SL.Text := StringReplace(SL.Text,'[FirstName]',NodeGetValueDef(billingaddress,'first-name'),True);
952 SL.Text := StringReplace(SL.Text,'[LastName]',NodeGetValueDef(billingaddress,'last-name'),True);
953 SL.Text := StringReplace(SL.Text,'[HomePhoneNumber]',NodeGetValueDef(billingaddress,'phone'),True);
954 SL.Text := StringReplace(SL.Text,'[DatabaseId]',DB_NAME,True);
955 result := SL.Text;
956 finally
957 SL.Free;
958 end;
959end;
960
961
962function CustomerWcfServiceAddUpdateCustomer(CustomerId: string;Customer :TritXmlNode): string;
963var
964 SL :TStringList;
965 billingaddress :TritXmlNode;
966begin
967 SL := TStringList.Create;
968 try
969 billingaddress := Customer.SelectNodes('billing-address').Item[0];
970 SL.LoadFromFile(GetTemplateName('CustomerWcfService','UpdateCustomer.xml'));
971
972
973 SL.Text := StringReplace(SL.Text,'[AddressLine1]',NodeGetValueDef(billingaddress,'address1'),True);
974 SL.Text := StringReplace(SL.Text,'[AddressLine2]',NodeGetValueDef(billingaddress,'address2'),True);
975 SL.Text := StringReplace(SL.Text,'[AddressLine3]',StringReplace(NodeGetValueDef(billingaddress,'state-code'),'OTHER','',True),True);
976
977 SL.Text := StringReplace(SL.Text,'[City]',NodeGetValueDef(billingaddress,'city'),True);
978 SL.Text := StringReplace(SL.Text,'[CountryId]',LookupCountryCode(NodeGetValueDef(billingaddress,'country-code')),True);
979 SL.Text := StringReplace(SL.Text,'[Email]',NodeGetValueDef(customer,'customer-email'),True);
980 SL.Text := StringReplace(SL.Text,'[ZipCode]',NodeGetValueDef(billingaddress,'postal-code'),True);
981 SL.Text := StringReplace(SL.Text,'[FirstName]',NodeGetValueDef(billingaddress,'first-name'),True);
982 SL.Text := StringReplace(SL.Text,'[LastName]',NodeGetValueDef(billingaddress,'last-name'),True);
983 SL.Text := StringReplace(SL.Text,'[HomePhoneNumber]',NodeGetValueDef(billingaddress,'phone'),True);
984 SL.Text := StringReplace(SL.Text,'[CustomerId]',CustomerId,True);
985 SL.Text := StringReplace(SL.Text,'[DatabaseId]',DB_NAME,True);
986 result := SL.Text;
987 finally
988 SL.Free;
989 end;
990end;
991
992function ICustomerWcfServiceSearchCustomerIds(CustomerId: string): string;
993var
994 SL :TStringList;
995begin
996 SL := TStringList.Create;
997 try
998 SL.LoadFromFile(GetTemplateName('CustomerWcfService','SearchCustomerIds.xml'));
999 SL.Text := StringReplace(SL.Text,'[CustomerId]',CustomerId,True);
1000 SL.Text := StringReplace(SL.Text,'[DatabaseId]',DB_NAME,True);
1001 result := SL.Text;
1002 finally
1003 SL.Free;
1004 end;
1005end;
1006
1007function ICustomerWcfServiceGetCustomerDetail(CustomerId: string): string;
1008var
1009 SL :TStringList;
1010begin
1011 SL := TStringList.Create;
1012 try
1013 SL.LoadFromFile(GetTemplateName('CustomerWcfService','GetCustomerDetail.xml'));
1014 SL.Text := StringReplace(SL.Text,'[CustomerId]',CustomerId,True);
1015 SL.Text := StringReplace(SL.Text,'[DatabaseId]',DB_NAME,True);
1016 result := SL.Text;
1017 finally
1018 SL.Free;
1019 end;
1020end;
1021
1022function ICustomerWcfServiceGetCustomerDetailByEmail(CustomerEmail: string): string;
1023var
1024 SL :TStringList;
1025begin
1026 SL := TStringList.Create;
1027 try
1028 SL.LoadFromFile(GetTemplateName('CustomerWcfService','SearchCustomerIds.xml'));
1029 SL.Text := StringReplace(SL.Text,'[Email]',CustomerEmail,True);
1030 SL.Text := StringReplace(SL.Text,'[CustomerId]','',True);
1031 SL.Text := StringReplace(SL.Text,'[DatabaseId]',DB_NAME,True);
1032 result := SL.Text;
1033 finally
1034 SL.Free;
1035 end;
1036end;
1037
1038
1039
1040function SearchCustomerIds(CustomerId: string): string;
1041begin
1042 Log('CustomerId', CustomerId);
1043 result := ICustomerWcfServiceSearchCustomerIds(CustomerId);
1044 result := SendXMLToWS('CustomerWcfService','SearchCustomerIds',result);
1045end;
1046
1047function SearchCustomerIdsByEmail(CustomerEmail: string): string;
1048var
1049 Request :string;
1050begin
1051 Log('SearchCustomerIdsByEmail', CustomerEmail);
1052 Request := ICustomerWcfServiceGetCustomerDetailByEmail(CustomerEmail);
1053 result := SendXMLToWS('CustomerWcfService','SearchCustomerIds',Request);
1054end;
1055
1056
1057function GetCustomerDetail(CustomerId: string): string;
1058begin
1059 Log('CustomerId', CustomerId);
1060 result := ICustomerWcfServiceGetCustomerDetail(CustomerId);
1061 result := SendXMLToWS('CustomerWcfService','GetCustomerDetail',result);
1062end;
1063
1064function GetCustomerDetailByEmail(CustomerEmail: string): string;
1065begin
1066 result := ICustomerWcfServiceGetCustomerDetailByEmail(CustomerEmail);
1067 result := SendXMLToWS('CustomerWcfService','SearchCustomerIds',result);
1068end;
1069
1070function AddNewCustomer(customer: TritXmlNode): string;
1071var
1072 customer_email,RIT_ERROR,Request :string;
1073begin
1074 Request := InsertSQLXMLexcapeChars(CustomerWcfServiceAddNewCustomer(customer));
1075 CreateCustomerXML := Request;
1076// Log('AddNewCustomer', Request);
1077 RetryCnt := 0;
1078 while (RetryCnt < 3)and(result = '') do
1079 begin
1080 result := SendXMLToWS('CustomerWcfService','AddNewCustomer',Request);
1081 Log('CustomerWcfService','AddNewCustomer');
1082 Inc(RetryCnt);
1083 end;
1084 RIT_ERROR := ShowErrorResponse(result,'');
1085 if RIT_ERROR <> '' then
1086 begin
1087 customer_email := NodeGetValueDef(customer,'customer-email');
1088 SendMail(customer_email,'Error processing file:' + ExtractFileName(FileName) ,RIT_ERROR,FileName);
1089 end;
1090end;
1091
1092function UpdateCustomer(CustomerId: string;Customer :TritXmlNode): string;
1093var
1094 Request :String;
1095begin
1096 Request := InsertSQLXMLexcapeChars(CustomerWcfServiceAddUpdateCustomer(CustomerId,Customer));
1097 RetryCnt := 0;
1098 while (RetryCnt < 3)and(result = '') do
1099 begin
1100 result := SendXMLToWS('CustomerWcfService','UpdateCustomer',Request);
1101 Log('CustomerWcfService','UpdateCustomer');
1102 Inc(RetryCnt);
1103 end;
1104end;
1105
1106function SafeXPath(S: string): string;
1107begin
1108 Result := '';
1109 try
1110 Result := XPath(S);
1111 except
1112 Log('XPATH not exists', S);
1113 end
1114end;
1115
1116function SendCreateRequest(Request :string): string;
1117begin
1118 RetryCnt := 0;
1119 while (RetryCnt < 3)and(result = '') do
1120 begin
1121 Inc(RetryCnt);
1122 result := SendXMLToWS('SaleDocumentService','Create',Request);
1123 Log('SaleDocumentService','Create#' + IntToStr(RetryCnt));
1124 end;
1125end;
1126
1127
1128function FillOmniChannel(OrderType,DeliveryStoreId :string; order: TritXmlNode): string;
1129var
1130 SL0 :TStringList;
1131 DeliveryType,PaymentStatus,GiftMsg,FollowUpStatus :string;
1132 shipments :TritXmlNodeList;
1133 I :Integer;
1134begin
1135 SL0 := TStringList.Create;
1136 try
1137
1138 if OrderType = 'CACWST' then
1139 begin
1140 DeliveryType := 'ShipByCentral';
1141 PaymentStatus := 'Totally';
1142 FollowUpStatus := 'Validated';
1143 end
1144 else if OrderType = 'CACWCR' then
1145 begin
1146 PaymentStatus := 'Pending';
1147 DeliveryType := 'BookedInStore';
1148 FollowUpStatus := 'ToBeProcessed';
1149 end
1150 else if OrderType = 'CACWCC' then
1151 begin
1152 DeliveryType :='PickupLocation';
1153 PaymentStatus := 'Totally';
1154 FollowUpStatus := 'Validated';
1155 end;
1156// DeliveryType := 'PickingUpInStore';
1157
1158 if OrderType = 'CACWST' then
1159 DeliveryStoreId := ''
1160 else
1161 DeliveryStoreId := DeliveryStoreId;
1162
1163// SL0.Add('<ns:OmniChannel>');
1164 GiftMsg := '';
1165 shipments := order.SelectNodes('//shipments/shipment');
1166 for I := 0 to shipments.Length() - 1 do
1167 begin
1168 if I > 0 then
1169 GiftMsg := '~' + GiftMsg;
1170 GiftMsg := GiftMsg + NodeGetValueDef(shipments.Item[I],'gift-message','');
1171 end;
1172
1173
1174 SL0.Add(' <ns:BillingStatus>Totally</ns:BillingStatus>');
1175 SL0.Add(' <ns:Comment></ns:Comment>');
1176 SL0.Add(' <ns:DeliveryStoreId>'+DeliveryStoreId+'</ns:DeliveryStoreId>');
1177 SL0.Add(' <ns:DeliveryType>'+DeliveryType+'</ns:DeliveryType>');
1178 SL0.Add(' <ns:FollowUpStatus>'+FollowUpStatus+'</ns:FollowUpStatus>');
1179 SL0.Add(' <ns:GiftMessage>' + ExcapeXMLNode(GiftMsg) + '</ns:GiftMessage>');
1180
1181 //None - No card
1182 //BlankCard - Blank card
1183 //CustomCard - Customized card
1184 SL0.Add(' <ns:GiftMessageType>CustomCard</ns:GiftMessageType>');
1185
1186 SL0.Add(' <ns:PaymentStatus>'+PaymentStatus+'</ns:PaymentStatus>');
1187 SL0.Add(' <ns:ReturnStatus>NotReturned</ns:ReturnStatus>');
1188 SL0.Add(' <ns:ShippingStatus>Pending</ns:ShippingStatus>');
1189// SL0.Add(' <ns:Tracking>None</ns:Tracking>');
1190 SL0.Add(' <ns:Transporter>None</ns:Transporter>');
1191
1192// SL0.Add('</ns:OmniChannel>');
1193 SL0.Add('');
1194 result := SL0.Text;
1195 finally
1196 SL0.Free;
1197 end;
1198end;
1199
1200function FillUserDefinedTables(OrderTypeCode :string): string;
1201var
1202 SL0 :TStringList;
1203begin
1204 SL0 := TStringList.Create;
1205 try
1206 SL0.Add('<ns:UserDefinedTables>');
1207 SL0.Add('<ns:UserDefinedTable>');
1208 SL0.Add('<ns:Id>1</ns:Id>');
1209 SL0.Add('<ns:Value>'+OrderTypeCode+'</ns:Value>');
1210 SL0.Add('</ns:UserDefinedTable>');
1211 SL0.Add('</ns:UserDefinedTables>');
1212 result := SL0.Text;
1213 finally
1214 SL0.Free;
1215 end;
1216end;
1217
1218function FillUserField(aValue :string; aID:String): string;
1219var
1220 SL0 :TStringList;
1221begin
1222// Id1 = Delivery Company Name
1223// Id2 = Invoice Company Name
1224 SL0 := TStringList.Create;
1225 try
1226 SL0.Add('<ns:UserField>');
1227 SL0.Add('<ns:Id>'+aID+'</ns:Id>');
1228 SL0.Add('<ns:TextValue>'+aValue+'</ns:TextValue>');
1229 SL0.Add('<ns:ValueType>TextValueKind</ns:ValueType>');
1230 SL0.Add('</ns:UserField>');
1231 result := SL0.Text;
1232 finally
1233 SL0.Free;
1234 end;
1235end;
1236
1237
1238function NodeGetValueDef(XmlNode: TritXmlNode; Name :string;DefVal :string = ''): string;
1239begin
1240 if not XmlNode.ChildNodeByName(Name).Assigned() then
1241 Result := DefVal
1242 else
1243 result := XmlNode.ChildNodeByName(Name).Text;
1244end;
1245
1246
1247function SendCancelOrder(CustomerId: string): string;
1248begin
1249 result := GenCancelOrder(CustomerId);
1250 result := SendXMLToWS('SaleDocumentService','Cancel',result);
1251end;
1252
1253function GenCancelOrder(CustomerId: string): string;
1254var
1255 SL :TStringList;
1256 FN :string;
1257begin
1258// ReturnNotice,CustomerOrder,AvailableOrder,CustomerReservationRequest,ReceiptOnHold,Receipt,CustomersReservation
1259 SL := TStringList.Create;
1260 FN := GetTemplateName('SaleDocumentService','Cancel.xml');
1261 SL.LoadFromFile(FN);
1262 try
1263 SL.Text := StringReplace(SL.Text,'[Number]','330226',True);
1264 SL.Text := StringReplace(SL.Text,'[Stump]','GCC',True);
1265 SL.Text := StringReplace(SL.Text,'[Type]','CustomerOrder',True);
1266 SL.Text := StringReplace(SL.Text,'[CustomerId]',CustomerId,True);
1267 SL.Text := StringReplace(SL.Text,'[InternalReference]','test02',True);
1268 SL.Text := StringReplace(SL.Text,'[Type]','CustomerOrder',True);
1269 SL.Text := StringReplace(SL.Text,'[ReasonId]','1',True);
1270 SL.Text := StringReplace(SL.Text,'[DatabaseId]',DB_NAME,True);
1271 result := SL.Text;
1272 finally
1273 SL.Free;
1274 end;
1275end;
1276
1277procedure OnConversionStart();
1278begin
1279 StartExport('Notused@all.com');
1280end;
1281
1282
1283
1284begin
1285
1286end.