Revert "ShopConnector get_part in WooCommerce implemented"
[kivitendo-erp.git] / SL / ShopConnector / Shopware.pm
1 package SL::ShopConnector::Shopware;
2
3 use strict;
4
5 use parent qw(SL::ShopConnector::Base);
6
7
8 use SL::JSON;
9 use LWP::UserAgent;
10 use LWP::Authen::Digest;
11 use SL::DB::ShopOrder;
12 use SL::DB::ShopOrderItem;
13 use SL::DB::History;
14 use SL::DB::PaymentTerm;
15 use DateTime::Format::Strptime;
16 use SL::DB::File;
17 use Data::Dumper;
18 use Sort::Naturally ();
19 use SL::Helper::Flash;
20 use Encode qw(encode_utf8);
21 use SL::File;
22 use File::Slurp;
23
24 use Rose::Object::MakeMethods::Generic (
25   'scalar --get_set_init' => [ qw(connector url) ],
26 );
27
28 sub get_one_order {
29   my ($self, $ordnumber) = @_;
30
31   my $dbh       = SL::DB::client;
32   my $of        = 0;
33   my $url       = $self->url;
34   my $data      = $self->connector->get($url . "api/orders/$ordnumber?useNumberAsId=true");
35   my @errors;
36
37   my %fetched_orders;
38   if ($data->is_success && $data->content_type eq 'application/json'){
39     my $data_json = $data->content;
40     my $import    = SL::JSON::decode_json($data_json);
41     my $shoporder = $import->{data};
42     $dbh->with_transaction( sub{
43       $self->import_data_to_shop_order($import);
44       1;
45     })or do {
46       push @errors,($::locale->text('Saving failed. Error message from the database: #1', $dbh->error));
47     };
48
49     if(!@errors){
50       $self->set_orderstatus($import->{data}->{id}, "fetched");
51       $of++;
52     }else{
53       flash_later('error', $::locale->text('Database errors: #1', @errors));
54     }
55     %fetched_orders = (shop_description => $self->config->description, number_of_orders => $of);
56   } else {
57     my %error_msg  = (
58       shop_id          => $self->config->id,
59       shop_description => $self->config->description,
60       message          => "Error: $data->status_line",
61       error            => 1,
62     );
63     %fetched_orders = %error_msg;
64   }
65
66   return \%fetched_orders;
67 }
68
69 sub get_new_orders {
70   my ($self, $id) = @_;
71
72   my $url              = $self->url;
73   my $last_order_number = $self->config->last_order_number;
74   my $otf              = $self->config->orders_to_fetch;
75   my $of               = 0;
76   my $last_data      = $self->connector->get($url . "api/orders/$last_order_number?useNumberAsId=true");
77   my $last_data_json = $last_data->content;
78   my $last_import    = SL::JSON::decode_json($last_data_json);
79
80   my $orders_data      = $self->connector->get($url . "api/orders?limit=$otf&filter[1][property]=status&filter[1][value]=0&filter[0][property]=id&filter[0][expression]=>&filter[0][value]=" . $last_import->{data}->{id});
81
82   my $dbh = SL::DB->client;
83   my @errors;
84   my %fetched_orders;
85   if ($orders_data->is_success && $orders_data->content_type eq 'application/json'){
86     my $orders_data_json = $orders_data->content;
87     my $orders_import    = SL::JSON::decode_json($orders_data_json);
88     foreach my $shoporder(@{ $orders_import->{data} }){
89
90       my $data      = $self->connector->get($url . "api/orders/" . $shoporder->{id});
91       my $data_json = $data->content;
92       my $import    = SL::JSON::decode_json($data_json);
93
94       $dbh->with_transaction( sub{
95           $self->import_data_to_shop_order($import);
96
97           $self->config->assign_attributes( last_order_number => $shoporder->{number});
98           $self->config->save;
99           1;
100       })or do {
101         push @errors,($::locale->text('Saving failed. Error message from the database: #1', $dbh->error));
102       };
103
104       if(!@errors){
105         $self->set_orderstatus($shoporder->{id}, "fetched");
106         $of++;
107       }else{
108         flash_later('error', $::locale->text('Database errors: #1', @errors));
109       }
110     }
111     %fetched_orders = (shop_description => $self->config->description, number_of_orders => $of);
112   } else {
113     my %error_msg  = (
114       shop_id          => $self->config->id,
115       shop_description => $self->config->description,
116       message          => "Error: $orders_data->status_line",
117       error            => 1,
118     );
119     %fetched_orders = %error_msg;
120   }
121
122   return \%fetched_orders;
123 }
124
125 sub import_data_to_shop_order {
126   my ( $self, $import ) = @_;
127   my $shop_order = $self->map_data_to_shoporder($import);
128
129   $shop_order->save;
130   my $id = $shop_order->id;
131
132   my @positions = sort { Sort::Naturally::ncmp($a->{"articleNumber"}, $b->{"articleNumber"}) } @{ $import->{data}->{details} };
133   #my @positions = sort { Sort::Naturally::ncmp($a->{"partnumber"}, $b->{"partnumber"}) } @{ $import->{data}->{details} };
134   my $position = 1;
135   my $active_price_source = $self->config->price_source;
136   #Mapping Positions
137   foreach my $pos(@positions) {
138     my $price = $::form->round_amount($pos->{price},2);
139     my %pos_columns = ( description          => $pos->{articleName},
140                         partnumber           => $pos->{articleNumber},
141                         price                => $price,
142                         quantity             => $pos->{quantity},
143                         position             => $position,
144                         tax_rate             => $pos->{taxRate},
145                         shop_trans_id        => $pos->{articleId},
146                         shop_order_id        => $id,
147                         active_price_source  => $active_price_source,
148                       );
149     my $pos_insert = SL::DB::ShopOrderItem->new(%pos_columns);
150     $pos_insert->save;
151     $position++;
152   }
153   $shop_order->positions($position-1);
154
155   if ( $self->config->shipping_costs_parts_id ) {
156     my $shipping_part = SL::DB::Part->find_by( id => $self->config->shipping_costs_parts_id);
157     my %shipping_pos = ( description    => $import->{data}->{dispatch}->{name},
158                          partnumber     => $shipping_part->partnumber,
159                          price          => $import->{data}->{invoiceShipping},
160                          quantity       => 1,
161                          position       => $position,
162                          shop_trans_id  => 0,
163                          shop_order_id  => $id,
164                        );
165     my $shipping_pos_insert = SL::DB::ShopOrderItem->new(%shipping_pos);
166     $shipping_pos_insert->save;
167   }
168
169   my $customer = $shop_order->get_customer;
170
171   if(ref($customer)){
172     $shop_order->kivi_customer_id($customer->id);
173   }
174   $shop_order->save;
175 }
176
177 sub map_data_to_shoporder {
178   my ($self, $import) = @_;
179
180   my $parser = DateTime::Format::Strptime->new( pattern   => '%Y-%m-%dT%H:%M:%S',
181                                                   locale    => 'de_DE',
182                                                   time_zone => 'local'
183                                                 );
184   my $orderdate = $parser->parse_datetime($import->{data}->{orderTime});
185
186   my $shop_id      = $self->config->id;
187   my $tax_included = $self->config->pricetype;
188
189   # Mapping Zahlungsmethoden muss an Firmenkonfiguration angepasst werden
190   my %payment_ids_methods = (
191     # shopware_paymentId => kivitendo_payment_id
192   );
193   my $default_payment_id = SL::DB::Manager::PaymentTerm->get_first()->id || undef;
194   # Mapping to table shoporders. See http://community.shopware.com/_detail_1690.html#GET_.28Liste.29
195   my %columns = (
196     amount                  => $import->{data}->{invoiceAmount},
197     billing_city            => $import->{data}->{billing}->{city},
198     billing_company         => $import->{data}->{billing}->{company},
199     billing_country         => $import->{data}->{billing}->{country}->{name},
200     billing_department      => $import->{data}->{billing}->{department},
201     billing_email           => $import->{data}->{customer}->{email},
202     billing_fax             => $import->{data}->{billing}->{fax},
203     billing_firstname       => $import->{data}->{billing}->{firstName},
204     #billing_greeting        => ($import->{data}->{billing}->{salutation} eq 'mr' ? 'Herr' : 'Frau'),
205     billing_lastname        => $import->{data}->{billing}->{lastName},
206     billing_phone           => $import->{data}->{billing}->{phone},
207     billing_street          => $import->{data}->{billing}->{street},
208     billing_vat             => $import->{data}->{billing}->{vatId},
209     billing_zipcode         => $import->{data}->{billing}->{zipCode},
210     customer_city           => $import->{data}->{billing}->{city},
211     customer_company        => $import->{data}->{billing}->{company},
212     customer_country        => $import->{data}->{billing}->{country}->{name},
213     customer_department     => $import->{data}->{billing}->{department},
214     customer_email          => $import->{data}->{customer}->{email},
215     customer_fax            => $import->{data}->{billing}->{fax},
216     customer_firstname      => $import->{data}->{billing}->{firstName},
217     #customer_greeting       => ($import->{data}->{billing}->{salutation} eq 'mr' ? 'Herr' : 'Frau'),
218     customer_lastname       => $import->{data}->{billing}->{lastName},
219     customer_phone          => $import->{data}->{billing}->{phone},
220     customer_street         => $import->{data}->{billing}->{street},
221     customer_vat            => $import->{data}->{billing}->{vatId},
222     customer_zipcode        => $import->{data}->{billing}->{zipCode},
223     customer_newsletter     => $import->{data}->{customer}->{newsletter},
224     delivery_city           => $import->{data}->{shipping}->{city},
225     delivery_company        => $import->{data}->{shipping}->{company},
226     delivery_country        => $import->{data}->{shipping}->{country}->{name},
227     delivery_department     => $import->{data}->{shipping}->{department},
228     delivery_email          => "",
229     delivery_fax            => $import->{data}->{shipping}->{fax},
230     delivery_firstname      => $import->{data}->{shipping}->{firstName},
231     #delivery_greeting       => ($import->{data}->{shipping}->{salutation} eq 'mr' ? 'Herr' : 'Frau'),
232     delivery_lastname       => $import->{data}->{shipping}->{lastName},
233     delivery_phone          => $import->{data}->{shipping}->{phone},
234     delivery_street         => $import->{data}->{shipping}->{street},
235     delivery_vat            => $import->{data}->{shipping}->{vatId},
236     delivery_zipcode        => $import->{data}->{shipping}->{zipCode},
237     host                    => $import->{data}->{shop}->{hosts},
238     netamount               => $import->{data}->{invoiceAmountNet},
239     order_date              => $orderdate,
240     payment_description     => $import->{data}->{payment}->{description},
241     payment_id              => $payment_ids_methods{$import->{data}->{paymentId}} || $default_payment_id,
242     remote_ip               => $import->{data}->{remoteAddress},
243     sepa_account_holder     => $import->{data}->{paymentIntances}->{accountHolder},
244     sepa_bic                => $import->{data}->{paymentIntances}->{bic},
245     sepa_iban               => $import->{data}->{paymentIntances}->{iban},
246     shipping_costs          => $import->{data}->{invoiceShipping},
247     shipping_costs_net      => $import->{data}->{invoiceShippingNet},
248     shop_c_billing_id       => $import->{data}->{billing}->{customerId},
249     shop_c_billing_number   => $import->{data}->{billing}->{number},
250     shop_c_delivery_id      => $import->{data}->{shipping}->{id},
251     shop_customer_id        => $import->{data}->{customerId},
252     shop_customer_number    => $import->{data}->{billing}->{number},
253     shop_customer_comment   => $import->{data}->{customerComment},
254     shop_id                 => $shop_id,
255     shop_ordernumber        => $import->{data}->{number},
256     shop_trans_id           => $import->{data}->{id},
257     tax_included            => $tax_included eq "brutto" ? 1 : 0,
258   );
259
260   my $shop_order = SL::DB::ShopOrder->new(%columns);
261   return $shop_order;
262 }
263
264 sub get_categories {
265   my ($self) = @_;
266
267   my $url        = $self->url;
268   my $data       = $self->connector->get($url . "api/categories");
269   my $data_json  = $data->content;
270   my $import     = SL::JSON::decode_json($data_json);
271   my @daten      = @{$import->{data}};
272   my %categories = map { ($_->{id} => $_) } @daten;
273
274   my @categories_tree;
275   for(@daten) {
276     # ignore root with id=1
277     if( $_->{id} == 1) {
278       next;
279     }
280     my $parent = $categories{$_->{parentId}};
281     if($parent && $parent->{id} != 1) {
282       $parent->{children} ||= [];
283       push @{$parent->{children}},$_;
284     } else {
285       push @categories_tree, $_;
286     }
287   }
288
289   return \@categories_tree;
290 }
291
292 sub get_version {
293   my ($self) = @_;
294
295   my $url       = $self->url;
296   my $data      = $self->connector->get($url . "api/version");
297   my $type = $data->content_type;
298   my $status_line = $data->status_line;
299
300   if($data->is_success && $type eq 'application/json'){
301     my $data_json = $data->content;
302     return SL::JSON::decode_json($data_json);
303   }else{
304     my %return = ( success => 0,
305                    data    => { version => $url . ": " . $status_line, revision => $type },
306                    message => "Server not found or wrong data type",
307                 );
308     return \%return;
309   }
310 }
311
312 sub update_part {
313   my ($self, $shop_part, $todo) = @_;
314
315   #shop_part is passed as a param
316   die unless ref($shop_part) eq 'SL::DB::ShopPart';
317
318   my $url = $self->url;
319   my $part = SL::DB::Part->new(id => $shop_part->part_id)->load;
320
321   # CVARS to map
322   my $cvars = { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $part->cvars_by_config } };
323
324   my @cat = ();
325   foreach my $row_cat ( @{ $shop_part->shop_category } ) {
326     my $temp = { ( id => @{$row_cat}[0], ) };
327     push ( @cat, $temp );
328   }
329
330   my @upload_img = $shop_part->get_images;
331   my $tax_n_price = $shop_part->get_tax_and_price;
332   my $price = $tax_n_price->{price};
333   my $taxrate = $tax_n_price->{tax};
334   # mapping to shopware still missing attributes,metatags
335   my %shop_data;
336
337   if($todo eq "price"){
338     %shop_data = ( mainDetail => { number   => $part->partnumber,
339                                    prices   =>  [ { from             => 1,
340                                                     price            => $price,
341                                                     customerGroupKey => 'EK',
342                                                   },
343                                                 ],
344                                   },
345                  );
346   }elsif($todo eq "stock"){
347     %shop_data = ( mainDetail => { number   => $part->partnumber,
348                                    inStock  => $part->onhand,
349                                  },
350                  );
351   }elsif($todo eq "price_stock"){
352     %shop_data =  ( mainDetail => { number   => $part->partnumber,
353                                     inStock  => $part->onhand,
354                                     prices   =>  [ { from             => 1,
355                                                      price            => $price,
356                                                      customerGroupKey => 'EK',
357                                                    },
358                                                  ],
359                                    },
360                    );
361   }elsif($todo eq "active"){
362     %shop_data =  ( mainDetail => { number   => $part->partnumber,
363                                    },
364                     active => ($part->partnumber == 1 ? 0 : 1),
365                    );
366   }elsif($todo eq "all"){
367   # mapping to shopware still missing attributes,metatags
368     %shop_data =  (   name              => $part->description,
369                       mainDetail        => { number   => $part->partnumber,
370                                              inStock  => $part->onhand,
371                                              prices   =>  [ {          from   => 1,
372                                                                        price  => $price,
373                                                             customerGroupKey  => 'EK',
374                                                             },
375                                                           ],
376                                              active   => $shop_part->active,
377                                              #attribute => { attr1  => $cvars->{CVARNAME}->{value}, } , #HowTo handle attributes
378                                        },
379                       supplier          => 'AR', # Is needed by shopware,
380                       descriptionLong   => $shop_part->shop_description,
381                       active            => $shop_part->active,
382                       images            => [ @upload_img ],
383                       __options_images  => { replace => 1, },
384                       categories        => [ @cat ],
385                       description       => $shop_part->shop_description,
386                       categories        => [ @cat ],
387                       tax               => $taxrate,
388                     )
389                   ;
390   }
391
392   my $dataString = SL::JSON::to_json(\%shop_data);
393   $dataString    = encode_utf8($dataString);
394
395   my $upload_content;
396   my $upload;
397   my ($import,$data,$data_json);
398   my $partnumber = $::form->escape($part->partnumber);#shopware don't accept / in articlenumber
399   # Shopware RestApi sends an erroremail if configured and part not found. But it needs this info to decide if update or create a new article
400   # LWP->post = create LWP->put = update
401     $data       = $self->connector->get($url . "api/articles/$partnumber?useNumberAsId=true");
402     $data_json  = $data->content;
403     $import     = SL::JSON::decode_json($data_json);
404   if($import->{success}){
405     #update
406     my $partnumber  = $::form->escape($part->partnumber);#shopware don't accept / in articlenumber
407     $upload         = $self->connector->put($url . "api/articles/$partnumber?useNumberAsId=true", Content => $dataString);
408     my $data_json   = $upload->content;
409     $upload_content = SL::JSON::decode_json($data_json);
410   }else{
411     #upload
412     $upload         = $self->connector->post($url . "api/articles/", Content => $dataString);
413     my $data_json   = $upload->content;
414     $upload_content = SL::JSON::decode_json($data_json);
415   }
416   # don't know if this is needed
417   if(@upload_img) {
418     my $partnumber = $::form->escape($part->partnumber);#shopware don't accept / in articlenumber
419     my $imgup      = $self->connector->put($url . "api/generatearticleimages/$partnumber?useNumberAsId=true");
420   }
421
422   return $upload_content->{success};
423 }
424
425 sub get_article {
426   my ($self,$partnumber) = @_;
427
428   my $url       = $self->url;
429   $partnumber   = $::form->escape($partnumber);#shopware don't accept / in articlenumber
430   my $data      = $self->connector->get($url . "api/articles/$partnumber?useNumberAsId=true");
431   my $data_json = $data->content;
432   return SL::JSON::decode_json($data_json);
433 }
434
435 sub set_orderstatus {
436   my ($self,$order_id, $status) = @_;
437   if ($status eq "fetched") { $status = 1; }
438   if ($status eq "completed") { $status = 2; }
439   my %new_status = (orderStatusId => $status);
440   my $new_status_json = SL::JSON::to_json(\%new_status);
441   $self->connector->put($self->url . "api/orders/$order_id", Content => $new_status_json);
442 }
443
444 sub init_url {
445   my ($self) = @_;
446   $self->url($self->config->protocol . "://" . $self->config->server . ":" . $self->config->port . $self->config->path);
447 }
448
449 sub init_connector {
450   my ($self) = @_;
451   my $ua = LWP::UserAgent->new;
452   $ua->credentials(
453       $self->config->server . ":" . $self->config->port,
454       $self->config->realm,
455       $self->config->login => $self->config->password
456   );
457
458   return $ua;
459
460 }
461
462 1;
463
464 __END__
465
466 =encoding utf-8
467
468 =head1 NAME
469
470 SL::Shopconnecter::Shopware - connector for shopware 5
471
472 =head1 SYNOPSIS
473
474
475 =head1 DESCRIPTION
476
477 This is the connector to shopware.
478 In this file you can do the mapping to your needs.
479 see https://developers.shopware.com/developers-guide/rest-api/
480 for more information.
481
482 =head1 METHODS
483
484 =over 4
485
486 =item C<get_one_order>
487
488 Fetches one order specified by ordnumber
489
490 =item C<get_new_orders>
491
492 Fetches new order by parameters from shop configuration
493
494 =item C<import_data_to_shop_order>
495
496 Creates on shoporder object from json
497 Here is the mapping for the positions.
498 see https://developers.shopware.com/developers-guide/rest-api/
499 for detailed information
500
501 =item C<map_data_to_shoporder>
502
503 Here is the mapping for the order data.
504 see https://developers.shopware.com/developers-guide/rest-api/
505 for detailed information
506
507 =item C<get_categories>
508
509 =item C<get_version>
510
511 Use this for test Connection
512 see SL::Shop
513
514 =item C<update_part>
515
516 Here is the mapping for the article data.
517 see https://developers.shopware.com/developers-guide/rest-api/
518 for detailed information
519
520 =item C<get_article>
521
522 =back
523
524 =head1 INITS
525
526 =over 4
527
528 =item init_url
529
530 build an url for LWP
531
532 =item init_connector
533
534 =back
535
536 =head1 TODO
537
538 Pricesrules, pricessources aren't fully implemented yet.
539 Payments aren't implemented( need to map payments from Shopware like invoice, paypal etc. to payments in kivitendo)
540
541 =head1 BUGS
542
543 None yet. :)
544
545 =head1 AUTHOR
546
547 W. Hahn E<lt>wh@futureworldsearch.netE<gt>
548
549 =cut