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