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 $main::lxdebug->dump(0, 'WH: ANSWER ', $answer);
36 $dbh->with_transaction( sub{
37 #update status on server
38 $shoporder->{status} = "processing";
39 my $answer = $self->set_orderstatus($shoporder->{id}, "completed");
41 push @errors,($::locale->text('Saving failed. Error message from the server: #1', $answer->message));
45 unless ($self->import_data_to_shop_order($shoporder)) { return 0;}
49 push @errors,($::locale->text('Saving failed. Error message from the database: #1', $dbh->error));
53 flash_later('error', $::locale->text('Errors: #1', @errors));
57 %fetched_orders = (shop_description => $self->config->description, number_of_orders => $number_of_orders);
60 shop_id => $self->config->id,
61 shop_description => $self->config->description,
62 message => $answer->{message},
65 %fetched_orders = %error_msg;
67 return \%fetched_orders;
73 my $dbh = SL::DB::client;
74 my $otf = $self->config->orders_to_fetch || 10;
75 my $number_of_orders = 0;
78 my $answer = $self->send_request(
82 "&per_page=$otf&status=processing&after=2020-12-31T23:59:59&order=asc"
85 if($answer->{success}) {
86 my $orders = $answer->{data};
87 foreach my $shoporder(@{$orders}){
88 $dbh->with_transaction( sub{
89 #update status on server
90 $shoporder->{status} = "completed";
91 my $anwser = $self->set_orderstatus($shoporder->{id}, "completed");
93 push @errors,($::locale->text('Saving failed. Error message from the server: #1', $answer->message));
97 unless ($self->import_data_to_shop_order($shoporder)) { return 0;}
101 push @errors,($::locale->text('Saving failed. Error message from the database: #1', $dbh->error));
105 flash_later('error', $::locale->text('Errors: #1', @errors));
110 %fetched_orders = (shop_description => $self->config->description, number_of_orders => $number_of_orders);
114 shop_id => $self->config->id,
115 shop_description => $self->config->description,
116 message => $answer->{message},
119 %fetched_orders = %error_msg;
122 return \%fetched_orders;
125 sub import_data_to_shop_order {
126 my ( $self, $import ) = @_;
127 my $shop_order = $self->map_data_to_shoporder($import);
130 my $id = $shop_order->id;
132 my @positions = sort { Sort::Naturally::ncmp($a->{"sku"}, $b->{"sku"}) } @{ $import->{line_items} };
135 my $active_price_source = $self->config->price_source;
136 my $tax_included = $self->config->pricetype eq 'brutto' ? 1 : 0;
138 foreach my $pos(@positions) {
139 my $tax_rate = $pos->{tax_class} eq "reduced-rate" ? 7 : 19;
140 my $tax_factor = $tax_rate/100+1;
141 my $price = $pos->{price};
142 if ( $tax_included ) {
143 $price = $price * $tax_factor;
144 $price = $::form->round_amount($price,2);
146 $price = $::form->round_amount($price,2);
148 my %pos_columns = ( description => $pos->{name},
149 partnumber => $pos->{sku}, # sku has to be a valid value in WooCommerce
151 quantity => $pos->{quantity},
152 position => $position,
153 tax_rate => $tax_rate,
154 shop_trans_id => $pos->{product_id},
155 shop_order_id => $id,
156 active_price_source => $active_price_source,
158 my $pos_insert = SL::DB::ShopOrderItem->new(%pos_columns);
162 $shop_order->positions($position-1);
164 if ( $self->config->shipping_costs_parts_id ) {
165 my $shipping_part = SL::DB::Manager::Part->find_by( id => $self->config->shipping_costs_parts_id);
167 description => $import->{data}->{dispatch}->{name},
168 partnumber => $shipping_part->partnumber,
169 price => $import->{data}->{invoiceShipping},
171 position => $position,
173 shop_order_id => $id,
175 my $shipping_pos_insert = SL::DB::ShopOrderItem->new(%shipping_pos);
176 $shipping_pos_insert->save;
179 my $customer = $shop_order->get_customer;
182 $shop_order->kivi_customer_id($customer->id);
188 sub map_data_to_shoporder {
189 my ($self, $import) = @_;
191 my $parser = DateTime::Format::Strptime->new( pattern => '%Y-%m-%dT%H:%M:%S',
196 my $shop_id = $self->config->id;
197 my $tax_included = $self->config->pricetype;
199 # Mapping to table shoporders. See https://woocommerce.github.io/woocommerce-rest-api-docs/?shell#order-properties
201 if ( $import->{shipping}->{address_1} ne "" ) {
202 $d_street = $import->{shipping}->{address_1} . ($import->{shipping}->{address_2} ? " " . $import->{shipping}->{address_2} : "");
204 $d_street = $import->{billing}->{address_1} . ($import->{billing}->{address_2} ? " " . $import->{billing}->{address_2} : "");
206 # Mapping Zahlungsmethoden muss an Firmenkonfiguration angepasst werden
207 my %payment_ids_methods = (
208 # woocommerce_payment_method_title => kivitendo_payment_id
210 my $default_payment = SL::DB::Manager::PaymentTerm->get_first();
211 my $default_payment_id = $default_payment ? $default_payment->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 foreach my $row_cat ( @{ $shop_part->shop_category } ) {
350 my $temp = { ( id => @{$row_cat}[0], ) };
351 push ( @categories, $temp );
354 #my @upload_img = $shop_part->get_images;
355 my $partnumber = $::form->escape($part->partnumber);#don't accept / in articlenumber
356 my $stock_status = ($part->onhand ? "instock" : "outofstock");
357 my $status = ($shop_part->active ? "publish" : "private");
358 my $tax_n_price = $shop_part->get_tax_and_price;
359 my $price = $tax_n_price->{price};
360 #my $taxrate = $tax_n_price->{tax};
361 #my $tax_class = ($taxrate >= 16 ? "standard" : "reduzierter-preis");
365 if($todo eq "price"){
367 regular_price => $price,
369 }elsif($todo eq "stock"){
371 stock_status => $stock_status,
373 }elsif($todo eq "price_stock"){
375 stock_status => $stock_status,
376 regular_price => $price,
378 }elsif($todo eq "active"){
382 }elsif($todo eq "all"){
383 # mapping still missing attributes,metatags
386 name => $part->description,
387 stock_status => $stock_status,
388 regular_price => $price,
390 description=> $shop_part->shop_description,
391 short_description=> $shop_part->shop_description,
392 categories => [ @categories ],
393 #tax_class => $tax_class,
397 my $dataString = SL::JSON::to_json(\%shop_data);
398 $dataString = encode_utf8($dataString);
400 # LWP->post = create || LWP->put = update
401 my $answer = $self->send_request("products/", undef , "get" , "&sku=$partnumber");
403 if($answer->{success} && scalar @{$answer->{data}}){
405 my $woo_shop_part_id = $answer->{data}[0]->{id};
406 $answer = $self->send_request("products/$woo_shop_part_id", $dataString, "put");
409 $answer = $self->send_request("products", $dataString, "post");
412 # don't know if this is needed
414 # my $partnumber = $::form->escape($part->partnumber);#shopware don't accept / in articlenumber
415 # my $imgup = $self->connector->put($url . "api/generatearticleimages/$partnumber?useNumberAsId=true");
418 return $answer->{success};
423 my $partnumber = $_[1];
425 $partnumber = $::form->escape($partnumber);#don't accept / in partnumber
426 my $answer = $self->send_request("products/", undef , "get" , "&sku=$partnumber");
428 if($answer->{success} && scalar @{$answer->{data}}){
429 my $article = $answer->{data}[0];
440 my $answer = $self->send_request("products/categories",undef,"get","&per_page=100");
441 unless($answer->{success}) {
444 my @data = @{$answer->{data}};
445 my %categories = map { ($_->{id} => $_) } @data;
449 my $parent = $categories{$_->{parent}};
451 $parent->{children} ||= [];
452 push @{$parent->{children}},$_;
454 push @categories_tree, $_;
458 return \@categories_tree;
464 my $answer = $self->send_request("system_status");
465 if($answer->{success}) {
466 my $version = $answer->{data}->{environment}->{version};
469 data => { version => $version },
477 sub set_orderstatus {
478 my ($self,$order_id, $status) = @_;
479 # if ($status eq "fetched") { $status = "processing"; }
480 # if ($status eq "processing") { $status = "completed"; }
481 my %new_status = (status => $status);
482 my $status_json = SL::JSON::to_json( \%new_status);
483 my $answer = $self->send_request("orders/$order_id", $status_json, "put");
484 unless($answer->{success}){
493 my $parameters = $_[2];
495 my $consumer_key = $self->config->login;
496 my $consumer_secret = $self->config->password;
497 my $protocol = $self->config->protocol;
498 my $server = $self->config->server;
499 my $port = $self->config->port;
500 my $path = $self->config->path;
502 return $protocol . "://". $server . ":" . $port . $path . $request . "?consumer_key=" . $consumer_key . "&consumer_secret=" . $consumer_secret . $parameters;
508 my $json_data = $_[2];
509 my $method_type = $_[3];
510 my $parameters = $_[4];
512 my $ua = LWP::UserAgent->new;
513 my $url = $self->create_url( $request, $parameters );
516 if( $method_type eq "put" ) {
517 $answer = $ua->put($url, "Content-Type" => "application/json", Content => $json_data);
518 } elsif ( $method_type eq "post") {
519 $answer = $ua->post($url, "Content-Type" => "application/json", Content => $json_data);
521 $answer = $ua->get($url);
524 my $type = $answer->content_type;
525 my $status_line = $answer->status_line;
528 if($answer->is_success && $type eq 'application/json'){
529 my $data_json = $answer->content;
530 my $json = SL::JSON::decode_json($data_json);
538 data => { version => $url . ": " . $status_line, data_type => $type },
539 message => "Error: $status_line",
542 #$main::lxdebug->dump(0, "TST: WooCommerce send_request return ", \%return);