WebshopApi: Standardzahlungsbedingung korrigiert Syntax
[kivitendo-erp.git] / SL / ShopConnector / WooCommerce.pm
1 package SL::ShopConnector::WooCommerce;
2
3 use strict;
4
5 use parent qw(SL::ShopConnector::Base);
6
7 use SL::JSON;
8 use LWP::UserAgent;
9 use LWP::Authen::Digest;
10 use SL::DB::ShopOrder;
11 use SL::DB::ShopOrderItem;
12 use SL::DB::PaymentTerm;
13 use SL::DB::History;
14 use SL::DB::File;
15 use Data::Dumper;
16 use SL::Helper::Flash;
17 use Encode qw(encode_utf8);
18
19 sub get_one_order {
20   my ($self, $order_id) = @_;
21
22   my $dbh       = SL::DB::client;
23   my $number_of_orders = 0;
24   my @errors;
25
26   my $answer = $self->send_request(
27     "orders/" . $order_id,
28     undef,
29     "get"
30   );
31   my %fetched_orders;
32   if($answer->{success}) {
33     my $shoporder = $answer->{data};
34
35     $dbh->with_transaction( sub{
36         #update status on server
37         $shoporder->{status} = "processing";
38         my $answer = $self->set_orderstatus($shoporder->{id}, "completed");
39         unless($answer){
40           push @errors,($::locale->text('Saving failed. Error message from the server: #1', $answer->message));
41           return 0;
42         }
43
44         unless ($self->import_data_to_shop_order($shoporder)) { return 0;}
45
46         1;
47       })or do {
48       push @errors,($::locale->text('Saving failed. Error message from the database: #1', $dbh->error));
49     };
50
51     if(@errors){
52       flash_later('error', $::locale->text('Errors: #1', @errors));
53     } else {
54       $number_of_orders++;
55     }
56     %fetched_orders = (shop_description => $self->config->description, number_of_orders => $number_of_orders);
57   } else {
58     my %error_msg  = (
59       shop_id          => $self->config->id,
60       shop_description => $self->config->description,
61       message          => $answer->{message},
62       error            => 1,
63     );
64     %fetched_orders = %error_msg;
65   }
66   return \%fetched_orders;
67 }
68
69 sub get_new_orders {
70   my ($self) = @_;
71
72   my $dbh       = SL::DB::client;
73   my $otf              = $self->config->orders_to_fetch || 10;
74   my $number_of_orders = 0;
75   my @errors;
76
77   my $answer = $self->send_request(
78     "orders",
79     undef,
80     "get",
81     "&per_page=$otf&status=processing&after=2020-12-31T23:59:59&order=asc"
82   );
83   my %fetched_orders;
84   if($answer->{success}) {
85     my $orders = $answer->{data};
86     foreach my $shoporder(@{$orders}){
87       $dbh->with_transaction( sub{
88           #update status on server
89           $shoporder->{status} = "completed";
90           my $anwser = $self->set_orderstatus($shoporder->{id}, "completed");
91           unless($answer){
92             push @errors,($::locale->text('Saving failed. Error message from the server: #1', $answer->message));
93             return 0;
94           }
95
96           unless ($self->import_data_to_shop_order($shoporder)) { return 0;}
97
98           1;
99       })or do {
100         push @errors,($::locale->text('Saving failed. Error message from the database: #1', $dbh->error));
101       };
102
103       if(@errors){
104         flash_later('error', $::locale->text('Errors: #1', @errors));
105       } else {
106         $number_of_orders++;
107       }
108     }
109     %fetched_orders = (shop_description => $self->config->description, number_of_orders => $number_of_orders);
110
111   } else {
112     my %error_msg  = (
113       shop_id          => $self->config->id,
114       shop_description => $self->config->description,
115       message          => $answer->{message},
116       error            => 1,
117     );
118     %fetched_orders = %error_msg;
119   }
120
121   return \%fetched_orders;
122 }
123
124 sub import_data_to_shop_order {
125   my ( $self, $import ) = @_;
126   my $shop_order = $self->map_data_to_shoporder($import);
127
128   $shop_order->save;
129   my $id = $shop_order->id;
130
131   my @positions = sort { Sort::Naturally::ncmp($a->{"sku"}, $b->{"sku"}) } @{ $import->{line_items} };
132   my $position = 1;
133
134   my $active_price_source = $self->config->price_source;
135   my $tax_included = $self->config->pricetype eq 'brutto' ? 1 : 0;
136   #Mapping Positions
137   foreach my $pos(@positions) {
138     my $tax_rate = $pos->{tax_class} eq "reduced-rate" ? 7 : 19;
139     my $tax_factor = $tax_rate/100+1;
140     my $price = $pos->{price};
141     if ( $tax_included ) {
142       $price = $price * $tax_factor;
143       $price = $::form->round_amount($price,2);
144     } else {
145       $price = $::form->round_amount($price,2);
146     }
147     my %pos_columns = ( description          => $pos->{name},
148                         partnumber           => $pos->{sku}, # sku has to be a valid value in WooCommerce
149                         price                => $price,
150                         quantity             => $pos->{quantity},
151                         position             => $position,
152                         tax_rate             => $tax_rate,
153                         shop_trans_id        => $pos->{product_id},
154                         shop_order_id        => $id,
155                         active_price_source  => $active_price_source,
156                       );
157     my $pos_insert = SL::DB::ShopOrderItem->new(%pos_columns);
158     $pos_insert->save;
159     $position++;
160   }
161   $shop_order->positions($position-1);
162
163   if ( $self->config->shipping_costs_parts_id ) {
164     my $shipping_part = SL::DB::Part->find_by( id => $self->config->shipping_costs_parts_id);
165     my %shipping_pos = (
166       description    => $import->{data}->{dispatch}->{name},
167       partnumber     => $shipping_part->partnumber,
168       price          => $import->{data}->{invoiceShipping},
169       quantity       => 1,
170       position       => $position,
171       shop_trans_id  => 0,
172       shop_order_id  => $id,
173     );
174     my $shipping_pos_insert = SL::DB::ShopOrderItem->new(%shipping_pos);
175     $shipping_pos_insert->save;
176   }
177
178   my $customer = $shop_order->get_customer;
179
180   if(ref($customer)){
181     $shop_order->kivi_customer_id($customer->id);
182   }
183   $shop_order->save;
184 }
185
186
187 sub map_data_to_shoporder {
188   my ($self, $import) = @_;
189
190   my $parser = DateTime::Format::Strptime->new( pattern   => '%Y-%m-%dT%H:%M:%S',
191                                                   locale    => 'de_DE',
192                                                   time_zone => 'local'
193                                                 );
194
195   my $shop_id      = $self->config->id;
196   my $tax_included = $self->config->pricetype;
197
198   # Mapping to table shoporders. See https://woocommerce.github.io/woocommerce-rest-api-docs/?shell#order-properties
199     my $d_street;
200     if ( $import->{shipping}->{address_1} ne "" ) {
201       $d_street = $import->{shipping}->{address_1} . ($import->{shipping}->{address_2} ? " " . $import->{shipping}->{address_2} : "");
202     } else {
203       $d_street = $import->{billing}->{address_1} . ($import->{billing}->{address_2} ? " " . $import->{billing}->{address_2} : "");
204     }
205   # Mapping Zahlungsmethoden muss an Firmenkonfiguration angepasst werden
206   my %payment_ids_methods = (
207     # woocommerce_payment_method_title => kivitendo_payment_id
208   );
209   my $default_payment    = SL::DB::Manager::PaymentTerm->get_first();
210   my $default_payment_id = $default_payment ? $default_payment->id : undef;
211   my %columns = (
212 #billing Shop can have different billing addresses, and may have 1 customer_address
213     billing_firstname       => $import->{billing}->{first_name},
214     billing_lastname        => $import->{billing}->{last_name},
215     #address_1 address_2
216     billing_street         => $import->{billing}->{address_1} . ($import->{billing}->{address_2} ? " " . $import->{billing}->{address_2} : ""),
217     # ???
218     billing_city            => $import->{billing}->{city},
219     #state
220     # ???
221     billing_zipcode         => $import->{billing}->{postcode},
222     billing_country         => $import->{billing}->{country},
223     billing_email           => $import->{billing}->{email},
224     billing_phone           => $import->{billing}->{phone},
225
226     #billing_greeting        => "",
227     #billing_fax             => "",
228     #billing_vat             => "",
229     billing_company         => $import->{billing}->{company},
230     #billing_department      => "",
231
232 #customer
233     #customer_id
234     shop_customer_id        => $import->{customer_id},
235     shop_customer_number    => $import->{customer_id},
236     #customer_ip_address
237     remote_ip               => $import->{customer_ip_address},
238     #customer_user_agent
239     #customer_note
240     shop_customer_comment   => $import->{customer_note},
241
242     #customer_city           => "",
243     #customer_company        => "",
244     #customer_country        => "",
245     #customer_department     => "",
246     #customer_email          => "",
247     #customer_fax            => "",
248     #customer_firstname      => "",
249     #customer_greeting       => "",
250     #customer_lastname       => "",
251     #customer_phone          => "",
252     #customer_street         => "",
253     #customer_vat            => "",
254
255 #shipping
256     delivery_firstname      => $import->{shipping}->{first_name} || $import->{billing}->{first_name},
257     delivery_lastname       => $import->{shipping}->{last_name} || $import->{billing}->{last_name},
258     delivery_company        => $import->{shipping}->{company} || $import->{billing}->{company},
259     #address_1 address_2
260     delivery_street         => $d_street,
261     delivery_city           => $import->{shipping}->{city} || $import->{billing}->{city},
262     #state ???
263     delivery_zipcode        => $import->{shipping}->{postcode} || $import->{billing}->{postcode},
264     delivery_country        => $import->{shipping}->{country} || $import->{billing}->{country},
265     #delivery_department     => "",
266     #delivery_email          => "",
267     #delivery_fax            => "",
268     #delivery_phone          => "",
269     #delivery_vat            => "",
270
271 #other
272     #id
273     #parent_id
274     #number
275     shop_ordernumber        => $import->{number},
276     #order_key
277     #created_via
278     #version
279     #status
280     #currency
281     #date_created
282     order_date              => $parser->parse_datetime($import->{date_created}),
283     #date_created_gmt
284     #date_modified
285     #date_modified_gmt
286     #discount_total
287     #discount_tax
288     #shipping_total
289     shipping_costs          => $import->{shipping_total},
290     #shipping_tax
291     shipping_costs_net      => $import->{shipping_total},
292     #cart_tax
293     #total
294     amount                  => $import->{total},
295     #total_tax
296     netamount               => $import->{total} - $import->{total_tax},
297     #prices_include_tax
298     tax_included            => $tax_included,
299     #payment_method
300     payment_id              => $payment_ids_methods{$import->{payment_method}} || $default_payment_id,
301     #payment_method_title
302     payment_description     => $import->{payment_method_title},
303     #transaction_id
304     shop_trans_id           => $import->{id},
305     #date_paid
306     #date_paid_gmt
307     #date_completed
308     #date_completed_gmt
309
310     host                    => $import->{_links}->{self}[0]->{href},
311
312     #sepa_account_holder     => "",
313     #sepa_bic                => "",
314     #sepa_iban               => "",
315
316     #shop_c_billing_id       => "",
317     #shop_c_billing_number   => "",
318     shop_c_delivery_id      => $import->{shipping_lines}[0]->{id}, # ???
319
320 # not in Shop
321     shop_id                 => $shop_id,
322   );
323
324   my $shop_order = SL::DB::ShopOrder->new(%columns);
325   return $shop_order;
326 }
327
328 #TODO CVARS, tax and images
329 sub update_part {
330   my ($self, $shop_part, $todo) = @_;
331
332   #shop_part is passed as a param
333   die unless ref($shop_part) eq 'SL::DB::ShopPart';
334   my $part = SL::DB::Part->new(id => $shop_part->part_id)->load;
335
336   # CVARS to map
337   #my $cvars = {
338   #  map {
339   #    ($_->config->name => {
340   #      value => $_->value_as_text,
341   #      is_valid => $_->is_valid
342   #    })
343   #  }
344   #  @{ $part->cvars_by_config }
345   #};
346
347   my @categories = ();
348   foreach my $row_cat ( @{ $shop_part->shop_category } ) {
349     my $temp = { ( id => @{$row_cat}[0], ) };
350     push ( @categories, $temp );
351   }
352
353   #my @upload_img = $shop_part->get_images;
354   my $partnumber = $::form->escape($part->partnumber);#don't accept / in articlenumber
355   my $stock_status = ($part->onhand ? "instock" : "outofstock");
356   my $status = ($shop_part->active ? "publish" : "private");
357   my $tax_n_price = $shop_part->get_tax_and_price;
358   my $price = $tax_n_price->{price};
359   #my $taxrate = $tax_n_price->{tax};
360   #my $tax_class = ($taxrate >= 16 ? "standard" : "reduzierter-preis");
361
362   my %shop_data;
363
364   if($todo eq "price"){
365     %shop_data = (
366       regular_price => $price,
367     );
368   }elsif($todo eq "stock"){
369     %shop_data = (
370       stock_status => $stock_status,
371     );
372   }elsif($todo eq "price_stock"){
373     %shop_data =  (
374       stock_status => $stock_status,
375       regular_price => $price,
376     );
377   }elsif($todo eq "active"){
378     %shop_data =  (
379       status => $status,
380     );
381   }elsif($todo eq "all"){
382   # mapping  still missing attributes,metatags
383     %shop_data =  (
384       sku => $partnumber,
385       name => $part->description,
386       stock_status => $stock_status,
387       regular_price => $price,
388       status => $status,
389       description=> $shop_part->shop_description,
390       short_description=> $shop_part->shop_description,
391       categories => [ @categories ],
392       #tax_class => $tax_class,
393     );
394   }
395
396   my $dataString = SL::JSON::to_json(\%shop_data);
397   $dataString    = encode_utf8($dataString);
398
399   # LWP->post = create || LWP->put = update
400   my $answer = $self->send_request("products/", undef , "get" , "&sku=$partnumber");
401
402   if($answer->{success} && scalar @{$answer->{data}}){
403     #update
404     my $woo_shop_part_id = $answer->{data}[0]->{id};
405     $answer = $self->send_request("products/$woo_shop_part_id", $dataString, "put");
406   }else{
407     #upload
408     $answer = $self->send_request("products", $dataString, "post");
409   }
410
411   # don't know if this is needed
412   #if(@upload_img) {
413   #  my $partnumber = $::form->escape($part->partnumber);#shopware don't accept / in articlenumber
414   #  my $imgup      = $self->connector->put($url . "api/generatearticleimages/$partnumber?useNumberAsId=true");
415   #}
416
417   return $answer->{success};
418 }
419
420 sub get_article {
421   my ($self) = @_;
422   my $partnumber = $_[1];
423
424   $partnumber   = $::form->escape($partnumber);#don't accept / in partnumber
425   my $answer = $self->send_request("products/", undef , "get" , "&sku=$partnumber");
426
427   if($answer->{success} && scalar @{$answer->{data}}){
428     my $article = $answer->{data}[0];
429     return $article;
430   } else {
431     #What shut be here?
432     return $answer
433   }
434 }
435
436 sub get_categories {
437   my ($self) = @_;
438
439   my $answer = $self->send_request("products/categories",undef,"get","&per_page=100");
440   unless($answer->{success}) {
441     return $answer;
442   }
443   my @data = @{$answer->{data}};
444   my %categories = map { ($_->{id} => $_) } @data;
445
446   my @categories_tree;
447   for(@data) {
448     my $parent = $categories{$_->{parent}};
449     if($parent) {
450       $parent->{children} ||= [];
451       push @{$parent->{children}},$_;
452     } else {
453       push @categories_tree, $_;
454     }
455   }
456
457   return \@categories_tree;
458 }
459
460 sub get_version {
461   my ($self) = @_;
462
463   my $answer = $self->send_request("system_status");
464   if($answer->{success}) {
465     my $version = $answer->{data}->{environment}->{version};
466     my %return = (
467       success => 1,
468       data    => { version => $version },
469     );
470     return \%return;
471   } else {
472     return $answer;
473   }
474 }
475
476 sub set_orderstatus {
477   my ($self,$order_id, $status) = @_;
478   #  if ($status eq "fetched") { $status =  "processing"; }
479   #  if ($status eq "processing") { $status = "completed"; }
480   my %new_status = (status => $status);
481   my $status_json = SL::JSON::to_json( \%new_status);
482   my $answer = $self->send_request("orders/$order_id", $status_json, "put");
483   unless($answer->{success}){
484     return 0;
485   }
486   return 1;
487 }
488
489 sub create_url {
490   my ($self) = @_;
491   my $request = $_[1];
492   my $parameters = $_[2];
493
494   my $consumer_key = $self->config->login;
495   my $consumer_secret = $self->config->password;
496   my $protocol = $self->config->protocol;
497   my $server = $self->config->server;
498   my $port = $self->config->port;
499   my $path = $self->config->path;
500
501   return $protocol . "://". $server . ":" . $port . $path . $request . "?consumer_key=" . $consumer_key . "&consumer_secret=" . $consumer_secret . $parameters;
502 }
503
504 sub send_request {
505   my ($self) = @_;
506   my $request = $_[1];
507   my $json_data = $_[2];
508   my $method_type = $_[3];
509   my $parameters = $_[4];
510
511   my $ua = LWP::UserAgent->new;
512   my $url = $self->create_url( $request, $parameters );
513
514   my $answer;
515   if( $method_type eq "put" ) {
516     $answer = $ua->put($url, "Content-Type" => "application/json", Content => $json_data);
517   } elsif ( $method_type eq "post") {
518     $answer = $ua->post($url, "Content-Type" => "application/json", Content => $json_data);
519   } else {
520     $answer = $ua->get($url);
521   }
522
523   my $type = $answer->content_type;
524   my $status_line = $answer->status_line;
525
526   my %return;
527   if($answer->is_success && $type eq 'application/json'){
528     my $data_json = $answer->content;
529     my $json = SL::JSON::decode_json($data_json);
530     %return = (
531       success => 1,
532       data    => $json,
533     );
534   }else{
535     %return = (
536       success => 0,
537       data    => { version => $url . ": " . $status_line, data_type => $type },
538       message => "Error: $status_line",
539     );
540   }
541   #$main::lxdebug->dump(0, "TST: WooCommerce send_request return ", \%return);
542   return \%return;
543
544 }
545
546 1;