test action
[kivitendo-erp.git] / SL / DB / ShopOrder.pm
1 # This file has been auto-generated only because it didn't exist.
2 # Feel free to modify it at will; it will not be overwritten automatically.
3
4 package SL::DB::ShopOrder;
5
6 use strict;
7
8 use SL::DBUtils;
9 use SL::DB::Shop;
10 use SL::DB::MetaSetup::ShopOrder;
11 use SL::DB::Manager::ShopOrder;
12 use SL::DB::PaymentTerm;
13 use SL::DB::Helper::LinkedRecords;
14 use SL::Locale::String qw(t8);
15 use Carp;
16
17 __PACKAGE__->meta->add_relationships(
18   shop_order_items => {
19     class      => 'SL::DB::ShopOrderItem',
20     column_map => { id => 'shop_order_id' },
21     type       => 'one to many',
22   },
23 );
24
25 __PACKAGE__->meta->initialize;
26
27 sub convert_to_sales_order {
28   my ($self, %params) = @_;
29
30   my $customer  = delete $params{customer};
31   my $employee  = delete $params{employee};
32   my $transdate = delete $params{transdate} // DateTime->today_local;
33   croak "param customer is missing" unless ref($customer) eq 'SL::DB::Customer';
34   croak "param employee is missing" unless ref($employee) eq 'SL::DB::Employee';
35
36   require SL::DB::Order;
37   require SL::DB::OrderItem;
38   require SL::DB::Part;
39   require SL::DB::Shipto;
40   my @error_report;
41
42   my @items = map{
43
44     my $part = SL::DB::Manager::Part->find_by(partnumber => $_->partnumber);
45
46     unless($part){
47       push @error_report, t8('Part with partnumber: #1 not found', $_->partnumber);
48     }else{
49       my $current_order_item = SL::DB::OrderItem->new(
50         parts_id            => $part->id,
51         description         => $part->description,
52         qty                 => $_->quantity,
53         sellprice           => $_->price,
54         unit                => $part->unit,
55         position            => $_->position,
56         active_price_source => $_->active_price_source,
57       );
58     }
59   }@{ $self->shop_order_items };
60
61   if(!scalar(@error_report)){
62
63     my $shipto_id;
64     if ($self->has_differing_delivery_address) {
65       if(my $address = SL::DB::Manager::Shipto->find_by( shiptoname   => $self->delivery_fullname,
66                                                          shiptostreet => $self->delivery_street,
67                                                          shiptocity   => $self->delivery_city,
68                                                         )) {
69         $shipto_id = $address->{shipto_id};
70       } else {
71         my $deliveryaddress = SL::DB::Shipto->new;
72         $deliveryaddress->assign_attributes(
73           shiptoname         => $self->delivery_fullname,
74           shiptodepartment_1 => $self->delivery_company,
75           shiptodepartment_2 => $self->delivery_department,
76           shiptostreet       => $self->delivery_street,
77           shiptozipcode      => $self->delivery_zipcode,
78           shiptocity         => $self->delivery_city,
79           shiptocountry      => $self->delivery_country,
80           trans_id           => $customer->id,
81           module             => "CT",
82         );
83         $deliveryaddress->save;
84         $shipto_id = $deliveryaddress->{shipto_id};
85       }
86     }
87
88     my $shop = SL::DB::Manager::Shop->find_by(id => $self->shop_id);
89     my $order = SL::DB::Order->new(
90       amount                  => $self->amount,
91       cusordnumber            => $self->shop_ordernumber,
92       customer_id             => $customer->id,
93       shipto_id               => $shipto_id,
94       orderitems              => [ @items ],
95       employee_id             => $employee->id,
96       intnotes                => $customer->notes,
97       salesman_id             => $employee->id,
98       taxincluded             => $self->tax_included,
99       payment_id              => $self->payment_id,
100       taxzone_id              => $customer->taxzone_id,
101       currency_id             => $customer->currency_id,
102       transaction_description => $shop->transaction_description,
103       transdate               => $transdate,
104     );
105      return $order;
106    }else{
107      my %error_order = (error   => 1,
108                         errors  => [ @error_report ],
109                        );
110      return \%error_order;
111    }
112 };
113
114 sub check_for_existing_customers {
115   my ($self, %params) = @_;
116   my $customers;
117
118   my $name             = $self->billing_lastname ne '' ? $self->billing_firstname . " " . $self->billing_lastname : '';
119   my $lastname         = $self->billing_lastname ne '' ? "%" . $self->billing_lastname . "%"                      : '';
120   my $company          = $self->billing_company  ne '' ? "%" . $self->billing_company  . "%"                      : '';
121   my $street           = $self->billing_street   ne '' ?  $self->billing_street                                   : '';
122   my $street_not_fuzzy = $self->billing_street   ne '' ?  "%" . $self->billing_street . "%"                       : '';
123   my $zipcode          = $self->billing_street   ne '' ?  $self->billing_zipcode                                  : '';
124   my $email            = $self->billing_street   ne '' ?  $self->billing_email                                    : '';
125
126   if(check_trgm($::form->get_standard_dbh())) {
127     # Fuzzysearch for street to find e.g. "Dorfstrasse - Dorfstr. - Dorfstraße"
128     my $fs_query = <<SQL;
129 SELECT *
130 FROM customer
131 WHERE (
132    (
133     ( name ILIKE ? OR name ILIKE ? )
134       AND
135     zipcode ILIKE ?
136    )
137  OR
138    ( street % ?  AND zipcode ILIKE ?)
139  OR
140    email ILIKE ?
141 ) AND obsolete = 'F'
142 SQL
143
144     my @values = ($lastname, $company, $self->billing_zipcode, $street, $self->billing_zipcode, $self->billing_email);
145
146     $customers = SL::DB::Manager::Customer->get_objects_from_sql(
147       sql  => $fs_query,
148       args => \@values,
149     );
150   }else{
151     # If trgm extension is not installed
152     $customers = SL::DB::Manager::Customer->get_all(
153       where => [
154           or => [
155             and => [
156                      or => [ 'name' => { ilike => $lastname },
157                              'name' => { ilike => $company  },
158                            ],
159                      'zipcode' => { ilike => $zipcode },
160                    ],
161             and => [
162                      and => [ 'street'  => { ilike => $street_not_fuzzy },
163                               'zipcode' => { ilike => $zipcode },
164                             ],
165                    ],
166             or  => [ 'email' => { ilike => $email } ],
167           ],
168       ],
169     );
170   }
171
172   return $customers;
173 }
174
175 sub check_for_open_invoices {
176   my ($self) = @_;
177     my $open_invoices = SL::DB::Manager::Invoice->get_all_count(
178       query => [customer_id => $self->{kivi_customer_id},
179               paid => {lt_sql => 'amount'},
180       ],
181     );
182   return $open_invoices;
183 }
184
185 sub get_customer{
186   my ($self, %params) = @_;
187   my $shop = SL::DB::Manager::Shop->find_by(id => $self->shop_id);
188   my $customer_proposals = $self->check_for_existing_customers;
189   my $name = $self->billing_firstname . " " . $self->billing_lastname;
190   my $customer = 0;
191   my $default_payment    = SL::DB::Manager::PaymentTerm->get_first();
192   my $payment_id = $default_payment ? $default_payment->id : undef;
193   if(!scalar(@{$customer_proposals})){
194     my %address = ( 'name'                  => $name,
195                     'department_1'          => $self->billing_company,
196                     'department_2'          => $self->billing_department,
197                     'street'                => $self->billing_street,
198                     'zipcode'               => $self->billing_zipcode,
199                     'city'                  => $self->billing_city,
200                     'email'                 => $self->billing_email,
201                     'country'               => $self->billing_country,
202                     'greeting'              => $self->billing_greeting,
203                     'fax'                   => $self->billing_fax,
204                     'phone'                 => $self->billing_phone,
205                     'ustid'                 => $self->billing_vat,
206                     'taxincluded_checked'   => $shop->pricetype eq "brutto" ? 1 : 0,
207                     'taxincluded'           => $shop->pricetype eq "brutto" ? 1 : 0,
208                     'pricegroup_id'         => (split '\/',$shop->price_source)[0] eq "pricegroup" ?  (split '\/',$shop->price_source)[1] : undef,
209                     'taxzone_id'            => $shop->taxzone_id,
210                     'currency'              => $::instance_conf->get_currency_id,
211                     'payment_id'            => $payment_id,
212                   );
213     $customer = SL::DB::Customer->new(%address);
214
215     $customer->save;
216     my $snumbers = "customernumber_" . $customer->customernumber;
217     SL::DB::History->new(
218                       trans_id    => $customer->id,
219                       snumbers    => $snumbers,
220                       employee_id => SL::DB::Manager::Employee->current->id,
221                       addition    => 'SAVED',
222                       what_done   => 'Shopimport',
223                     )->save();
224
225   }elsif(scalar(@{$customer_proposals}) == 1){
226     # check if the proposal is the right customer, could be different names under the same address. Depends on how first- and familyname is handled. Here is for customername = companyname or customername = "firstname familyname"
227     $customer = SL::DB::Manager::Customer->find_by( id       => $customer_proposals->[0]->id,
228                                                     name     => $name,
229                                                     email    => $self->billing_email,
230                                                     street   => $self->billing_street,
231                                                     zipcode  => $self->billing_zipcode,
232                                                     city     => $self->billing_city,
233                                                     obsolete => 'F',
234                                                   );
235   }
236
237   return $customer;
238 }
239
240 sub compare_to {
241   my ($self, $other) = @_;
242
243   return  1 if  $self->transfer_date && !$other->transfer_date;
244   return -1 if !$self->transfer_date &&  $other->transfer_date;
245
246   my $result = 0;
247   $result    = $self->transfer_date <=> $other->transfer_date if $self->transfer_date;
248   return $result || ($self->id <=> $other->id);
249 }
250
251 sub has_differing_delivery_address {
252   my ($self) = @_;
253   ($self->billing_firstname // '') ne ($self->delivery_firstname // '') ||
254   ($self->billing_lastname  // '') ne ($self->delivery_lastname  // '') ||
255   ($self->billing_city      // '') ne ($self->delivery_city      // '') ||
256   ($self->billing_street    // '') ne ($self->delivery_street    // '')
257 }
258
259 sub delivery_fullname {
260   ($_[0]->delivery_firstname // '') . " " . ($_[0]->delivery_lastname // '')
261 }
262
263 1;
264
265 __END__
266
267 =pod
268
269 =encoding utf-8
270
271 =head1 NAME
272
273 SL::DB::ShopOrder - Model for the 'shop_orders' table
274
275 =head1 SYNOPSIS
276
277 This is a standard Rose::DB::Object based model and can be used as one.
278
279 =head1 METHODS
280
281 =over 4
282
283 =item C<convert_to_sales_order>
284
285 =item C<check_for_existing_customers>
286
287 Inexact search for possible matches with existing customers in the database.
288
289 Returns all found customers as an arrayref of SL::DB::Customer objects.
290
291 =item C<get_customer>
292
293 returns only one customer from the check_for_existing_customers if the return from it is 0 or 1 customer.
294
295 When it is 0 get customer creates a new customer object of the shop order billing data and returns it
296
297 =item C<compare_to>
298
299 =back
300
301 =head1 TODO
302
303 some variables like payments could be better implemented. Transaction description is hardcoded
304
305 =head1 AUTHORS
306
307 Werner Hahn E<lt>wh@futureworldsearch.netE<gt>
308
309 G. Richardson E<lt>grichardson@kivitendo-premium.deE<gt>
310
311 =cut