1 package SL::ShopConnector::WooCommerce;
5 use parent qw(SL::ShopConnector::Base);
9 use LWP::Authen::Digest;
10 use SL::DB::ShopOrder;
11 use SL::DB::ShopOrderItem;
12 use SL::DB::PaymentTerm;
16 use SL::Helper::Flash;
17 use Encode qw(encode_utf8);
20 my ($self, $order_id) = @_;
22 my $dbh = SL::DB::client;
23 my $number_of_orders = 0;
26 my $answer = $self->send_request(
27 "orders/" . $order_id,
32 if($answer->{success}) {
33 my $shoporder = $answer->{data};
35 $dbh->with_transaction( sub{
36 #update status on server
37 $shoporder->{status} = "processing";
38 my $answer = $self->set_orderstatus($shoporder->{id}, "completed");
40 push @errors,($::locale->text('Saving failed. Error message from the server: #1', $answer->message));
44 unless ($self->import_data_to_shop_order($shoporder)) { return 0;}
48 push @errors,($::locale->text('Saving failed. Error message from the database: #1', $dbh->error));
52 flash_later('error', $::locale->text('Errors: #1', @errors));
56 %fetched_orders = (shop_description => $self->config->description, number_of_orders => $number_of_orders);
59 shop_id => $self->config->id,
60 shop_description => $self->config->description,
61 message => $answer->{message},
64 %fetched_orders = %error_msg;
66 return \%fetched_orders;
72 my $dbh = SL::DB::client;
73 my $otf = $self->config->orders_to_fetch || 10;
74 my $number_of_orders = 0;
77 my $answer = $self->send_request(
81 "&per_page=$otf&status=processing&after=2020-12-31T23:59:59&order=asc"
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");
92 push @errors,($::locale->text('Saving failed. Error message from the server: #1', $answer->message));
96 unless ($self->import_data_to_shop_order($shoporder)) { return 0;}
100 push @errors,($::locale->text('Saving failed. Error message from the database: #1', $dbh->error));
104 flash_later('error', $::locale->text('Errors: #1', @errors));
109 %fetched_orders = (shop_description => $self->config->description, number_of_orders => $number_of_orders);
113 shop_id => $self->config->id,
114 shop_description => $self->config->description,
115 message => $answer->{message},
118 %fetched_orders = %error_msg;
121 return \%fetched_orders;
124 sub import_data_to_shop_order {
125 my ( $self, $import ) = @_;
126 my $shop_order = $self->map_data_to_shoporder($import);
129 my $id = $shop_order->id;
131 my @positions = sort { Sort::Naturally::ncmp($a->{"sku"}, $b->{"sku"}) } @{ $import->{line_items} };
134 my $active_price_source = $self->config->price_source;
135 my $tax_included = $self->config->pricetype eq 'brutto' ? 1 : 0;
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);
145 $price = $::form->round_amount($price,2);
147 my %pos_columns = ( description => $pos->{name},
148 partnumber => $pos->{sku}, # sku has to be a valid value in WooCommerce
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,
157 #$main::lxdebug->dump(0, "TST: WooCommerce save pos", $pos);
158 #$main::lxdebug->dump(0, "TST: WooCommerce save pos_columns", \%pos_columns);
159 my $pos_insert = SL::DB::ShopOrderItem->new(%pos_columns);
163 $shop_order->positions($position-1);
165 if ( $self->config->shipping_costs_parts_id ) {
166 my $shipping_part = SL::DB::Part->find_by( id => $self->config->shipping_costs_parts_id);
168 description => $import->{data}->{dispatch}->{name},
169 partnumber => $shipping_part->partnumber,
170 price => $import->{data}->{invoiceShipping},
172 position => $position,
174 shop_order_id => $id,
176 my $shipping_pos_insert = SL::DB::ShopOrderItem->new(%shipping_pos);
177 $shipping_pos_insert->save;
180 my $customer = $shop_order->get_customer;
183 $shop_order->kivi_customer_id($customer->id);
189 sub map_data_to_shoporder {
190 my ($self, $import) = @_;
192 my $parser = DateTime::Format::Strptime->new( pattern => '%Y-%m-%dT%H:%M:%S',
197 my $shop_id = $self->config->id;
198 my $tax_included = $self->config->pricetype;
200 # Mapping to table shoporders. See https://woocommerce.github.io/woocommerce-rest-api-docs/?shell#order-properties
202 if ( $import->{shipping}->{address_1} ne "" ) {
203 $d_street = $import->{shipping}->{address_1} . ($import->{shipping}->{address_2} ? " " . $import->{shipping}->{address_2} : "");
205 $d_street = $import->{billing}->{address_1} . ($import->{billing}->{address_2} ? " " . $import->{billing}->{address_2} : "");
207 # Mapping Zahlungsmethoden muss an Firmenkonfiguration angepasst werden
208 my %payment_ids_methods = (
209 # woocommerce_payment_method_title => kivitendo_payment_id
211 my $default_payment_id = SL::DB::Manager::PaymentTerm->get_first()->id || undef;
213 #billing Shop can have different billing addresses, and may have 1 customer_address
214 billing_firstname => $import->{billing}->{first_name},
215 billing_lastname => $import->{billing}->{last_name},
217 billing_street => $import->{billing}->{address_1} . ($import->{billing}->{address_2} ? " " . $import->{billing}->{address_2} : ""),
219 billing_city => $import->{billing}->{city},
222 billing_zipcode => $import->{billing}->{postcode},
223 billing_country => $import->{billing}->{country},
224 billing_email => $import->{billing}->{email},
225 billing_phone => $import->{billing}->{phone},
227 #billing_greeting => "",
230 billing_company => $import->{billing}->{company},
231 #billing_department => "",
235 shop_customer_id => $import->{customer_id},
236 shop_customer_number => $import->{customer_id},
238 remote_ip => $import->{customer_ip_address},
241 shop_customer_comment => $import->{customer_note},
243 #customer_city => "",
244 #customer_company => "",
245 #customer_country => "",
246 #customer_department => "",
247 #customer_email => "",
249 #customer_firstname => "",
250 #customer_greeting => "",
251 #customer_lastname => "",
252 #customer_phone => "",
253 #customer_street => "",
257 delivery_firstname => $import->{shipping}->{first_name} || $import->{billing}->{first_name},
258 delivery_lastname => $import->{shipping}->{last_name} || $import->{billing}->{last_name},
259 delivery_company => $import->{shipping}->{company} || $import->{billing}->{company},
261 delivery_street => $d_street,
262 delivery_city => $import->{shipping}->{city} || $import->{billing}->{city},
264 delivery_zipcode => $import->{shipping}->{postcode} || $import->{billing}->{postcode},
265 delivery_country => $import->{shipping}->{country} || $import->{billing}->{country},
266 #delivery_department => "",
267 #delivery_email => "",
269 #delivery_phone => "",
276 shop_ordernumber => $import->{number},
283 order_date => $parser->parse_datetime($import->{date_created}),
290 shipping_costs => $import->{shipping_total},
292 shipping_costs_net => $import->{shipping_total},
295 amount => $import->{total},
297 netamount => $import->{total} - $import->{total_tax},
299 tax_included => $tax_included,
301 payment_id => $payment_ids_methods{$import->{payment_method}} || $default_payment_id,
302 #payment_method_title
303 payment_description => $import->{payment_method_title},
305 shop_trans_id => $import->{id},
311 host => $import->{_links}->{self}[0]->{href},
313 #sepa_account_holder => "",
317 #shop_c_billing_id => "",
318 #shop_c_billing_number => "",
319 shop_c_delivery_id => $import->{shipping_lines}[0]->{id}, # ???
325 my $shop_order = SL::DB::ShopOrder->new(%columns);
329 #TODO CVARS, tax and images
331 my ($self, $shop_part, $todo) = @_;
333 #shop_part is passed as a param
334 die unless ref($shop_part) eq 'SL::DB::ShopPart';
335 my $part = SL::DB::Part->new(id => $shop_part->part_id)->load;
340 # ($_->config->name => {
341 # value => $_->value_as_text,
342 # is_valid => $_->is_valid
345 # @{ $part->cvars_by_config }
349 if ($shop_part->shop_category) {
350 foreach my $row_cat ( @{ $shop_part->shop_category } ) {
351 my $temp = { ( id => @{$row_cat}[0], ) };
352 push ( @categories, $temp );
356 #my @upload_img = $shop_part->get_images;
357 my $partnumber = $::form->escape($part->partnumber);#don't accept / in partnumber
358 my $stock_status = ($part->onhand ? "instock" : "outofstock");
359 my $status = ($shop_part->active ? "publish" : "private");
360 my $tax_n_price = $shop_part->get_tax_and_price;
361 my $price = $tax_n_price->{price};
362 #my $taxrate = $tax_n_price->{tax};
363 #my $tax_class = ($taxrate >= 16 ? "standard" : "reduzierter-preis");
367 if($todo eq "price"){
369 regular_price => $price,
371 }elsif($todo eq "stock"){
373 stock_status => $stock_status,
375 }elsif($todo eq "price_stock"){
377 stock_status => $stock_status,
378 regular_price => $price,
380 }elsif($todo eq "active"){
384 }elsif($todo eq "all"){
385 # mapping still missing attributes,metatags
388 name => $part->description,
389 stock_status => $stock_status,
390 regular_price => $price,
392 description=> $shop_part->shop_description,
393 short_description=> $shop_part->shop_description,
394 categories => [ @categories ],
395 #tax_class => $tax_class,
399 my $dataString = SL::JSON::to_json(\%shop_data);
400 $dataString = encode_utf8($dataString);
402 # LWP->post = create || LWP->put = update
403 my $answer = $self->send_request("products/", undef , "get" , "&sku=$partnumber");
405 if($answer->{success} && scalar @{$answer->{data}}){
407 my $woo_shop_part_id = $answer->{data}[0]->{id};
408 $answer = $self->send_request("products/$woo_shop_part_id", $dataString, "put");
411 $answer = $self->send_request("products", $dataString, "post");
414 # don't know if this is needed
416 # my $partnumber = $::form->escape($part->partnumber);#shopware don't accept / in partnumber
417 # my $imgup = $self->connector->put($url . "api/generatepartimages/$partnumber?useNumberAsId=true");
420 return $answer->{success};
423 sub get_article_info {
425 my $partnumber = $_[1];
427 $partnumber = $::form->escape($partnumber);#don't accept / in partnumber
428 my $answer = $self->send_request("products/", undef , "get" , "&sku=$partnumber");
430 $answer->{data} = $answer->{data}[0];
431 #$main::lxdebug->dump(0, "TST: WooCommerce get_part_info ", $answer);
434 if($answer->{success} && scalar @{$answer->{data}}){
435 my $part = $self->map_data_to_part($answer->{data}[0]);
436 #$main::lxdebug->dump(0, "TST: WooCommerce get_part_info part", $part);
444 sub map_data_to_part {
445 my ($self, $part_data) = @_;
447 my %map_part_data = (
448 #id => $part_data->{},
449 partnumber => $part_data->{sku},
450 description => $part_data->{name},
451 #listprice => $part_data->{},
452 #sellprice => $part_data->{},
453 #lastcost => $part_data->{},
454 #priceupdate => $part_data->{},
455 #weight => $part_data->{},
456 notes => $part_data->{description},
457 #makemodel => $part_data->{},
458 #rop => $part_data->{},
461 #bom => $part_data->{},
462 #image => $part_data->{},
463 #drawing => $part_data->{},
464 #microfiche => $part_data->{},
465 #partsgroup_id => $part_data->{},
466 #ve => $part_data->{},
467 #gv => $part_data->{},
468 #itime => $part_data->{},
469 #mtime => $part_data->{},
470 #unit => $part_data->{},
472 #formel => $part_data->{},
473 #not_discountable => $part_data->{},
474 #buchungsgruppen_id => $part_data->{},
475 #payment_id => $part_data->{},
476 #ean => $part_data->{},
477 #price_factor_id => $part_data->{},
478 #onhand => $part_data->{},
479 #stockable => $part_data->{},
480 #has_sernumber => $part_data->{},
481 #warehouse_id => $part_data->{},
482 #bin_id => $part_data->{},
483 #df_status_aktuell => $part_data->{},
484 #df_status_verlauf => $part_data->{},
485 #active => $part_data->{},
486 #classification_id => $part_data->{},
489 return SL::DB::Part->new(%map_part_data);
492 sub map_data_to_shop_part {
493 my ($self, $part_data, $part) = @_;
496 foreach my $row_cat ( @{ $part_data->{categories} } ) {
498 push( @tmp,$row_cat->{id} );
499 push( @tmp,$row_cat->{name} );
500 push( @categories,\@tmp );
502 my %map_shop_part_data = (
504 shop_id => $self->config->id,
505 part_id => $part->id,
506 shop_description => $part_data->{description},
511 sortorder => $part_data->{menu_order},
514 shop_category => \@categories,
515 #active_price_source => ,
516 #metatag_keywords => ,
517 #metatag_description => ,
519 #shop_versandhinweis => ,
521 return SL::DB::ShopPart->new(%map_shop_part_data);
524 my ($self, $partnumber) = @_;
526 my $dbh = SL::DB::client;
528 my $number_of_parts = 0;
533 $partnumber = $::form->escape($partnumber);#don't accept / in partnumber
534 $answer = $self->send_request("products/", undef , "get" , "&sku=$partnumber");
537 $answer = $self->send_request("products/", undef , "get");
538 if ($answer->{total_pages} > 1) {
539 my $current_page = 2;
540 while ($current_page <= $answer->{total_pages}) {
541 my $tmp_answer = $self->send_request("products/", undef , "get", "&page=$current_page");
542 foreach my $part (@{$tmp_answer->{data}}) {
543 push @{$answer->{data}} , $part;
550 if($answer->{success} && scalar @{$answer->{data}}){
551 $dbh->with_transaction( sub{
552 foreach my $part_data (@{$answer->{data}}) {
553 unless (!$part_data->{sku} || SL::DB::Manager::Part->get_all_count( query => [ partnumber => $part_data->{sku} ] )) {
554 my $part = $self->map_data_to_part($part_data);
555 #$main::lxdebug->dump(0, "TST: WooCommerce get_shop_parts part ", $part);
557 my $shop_part = $self->map_data_to_shop_part($part_data, $part);
558 #$main::lxdebug->dump(0, "TST: WooCommerce get_shop_parts shop_part ", $shop_part);
565 push @errors,($::locale->text('Saving failed. Error message from the database: #1', $dbh->error));
569 flash_later('error', $::locale->text('Errors: #1', @errors));
572 shop_id => $self->config->id,
573 shop_description => $self->config->description,
574 number_of_parts => $number_of_parts,
578 shop_id => $self->config->id,
579 shop_description => $self->config->description,
580 message => $answer->{message},
583 %fetched_parts = %error_msg;
585 return \%fetched_parts;
591 my $answer = $self->send_request("products/categories",undef,"get","&per_page=100");
592 unless($answer->{success}) {
595 my @data = @{$answer->{data}};
596 my %categories = map { ($_->{id} => $_) } @data;
600 my $parent = $categories{$_->{parent}};
602 $parent->{children} ||= [];
603 push @{$parent->{children}},$_;
605 push @categories_tree, $_;
609 return \@categories_tree;
615 my $answer = $self->send_request("system_status");
616 if($answer->{success}) {
617 my $version = $answer->{data}->{environment}->{version};
620 data => { version => $version },
628 sub set_orderstatus {
629 my ($self,$order_id, $status) = @_;
630 # if ($status eq "fetched") { $status = "processing"; }
631 # if ($status eq "processing") { $status = "completed"; }
632 my %new_status = (status => $status);
633 my $status_json = SL::JSON::to_json( \%new_status);
634 my $answer = $self->send_request("orders/$order_id", $status_json, "put");
635 unless($answer->{success}){
644 my $parameters = $_[2];
646 my $consumer_key = $self->config->login;
647 my $consumer_secret = $self->config->password;
648 my $protocol = $self->config->protocol;
649 my $server = $self->config->server;
650 my $port = $self->config->port;
651 my $path = $self->config->path;
653 return $protocol . "://". $server . ":" . $port . $path . $request . "?consumer_key=" . $consumer_key . "&consumer_secret=" . $consumer_secret . $parameters;
659 my $json_data = $_[2];
660 my $method_type = $_[3];
661 my $parameters = $_[4];
663 my $ua = LWP::UserAgent->new;
664 my $url = $self->create_url( $request, $parameters );
667 if( $method_type eq "put" ) {
668 $answer = $ua->put($url, "Content-Type" => "application/json", Content => $json_data);
669 } elsif ( $method_type eq "post") {
670 $answer = $ua->post($url, "Content-Type" => "application/json", Content => $json_data);
672 $answer = $ua->get($url);
675 my $type = $answer->content_type;
676 my $status_line = $answer->status_line;
679 if($answer->is_success && $type eq 'application/json'){
680 my $data_json = $answer->content;
681 #$main::lxdebug->dump(0, "TST: WooCommerce send_request header ", $answer->header( 'Link'));
682 my $json = SL::JSON::decode_json($data_json);
686 total_pages => $answer->header( 'X-WP-TotalPages'),
687 total_elements => $answer->header( 'X-WP-Total'),
692 data => { version => $url . ": " . $status_line, data_type => $type },
693 message => "Error: $status_line",
696 #$main::lxdebug->dump(0, "TST: WooCommerce send_request return ", \%return);