RT# 79239 - added option to prorate first month to synchronize with customers other...
[freeside.git] / FS / FS / part_pkg / sql_external.pm
1 package FS::part_pkg::sql_external;
2 use base qw( FS::part_pkg::discount_Mixin FS::part_pkg::recur_Common );
3
4 use strict;
5 use vars qw( %info );
6 use DBI;
7 #use FS::Record qw(qsearch qsearchs);
8
9 tie our %query_style, 'Tie::IxHash', (
10   'simple'    => 'Simple (a single value for the recurring charge)',
11   'detailed'  => 'Detailed (multiple rows for invoice details)',
12 );
13
14 our @detail_cols = ( qw(amount format duration phonenum accountcode
15                         startdate regionname detail)
16                    );
17 %info = (
18   'name' => 'Base charge plus additional fees for external services from a configurable SQL query',
19   'shortname' => 'External SQL query',
20   'inherit_fields' => [ 'prorate_Mixin', 'global_Mixin' ],
21   'fields' => {
22     'sync_bill_date' => { 'name' => 'Prorate first month to synchronize '.
23                                     'with the customer\'s other packages',
24                           'type' => 'checkbox',
25                         },
26     'cutoff_day'    => { 'name' => 'Billing Day (1 - 28) for prorating or '.
27                                    'subscription',
28                          'default' => '1',
29                        },
30
31     'recur_method'  => { 'name' => 'Recurring fee method',
32                          #'type' => 'radio',
33                          #'options' => \%recur_method,
34                          'type' => 'select',
35                          'select_options' => \%FS::part_pkg::recur_Common::recur_method,
36                        },
37     'datasrc' => { 'name' => 'DBI data source',
38                    'default' => '',
39                  },
40     'db_username' => { 'name' => 'Database username',
41                        'default' => '',
42                      },
43     'db_password' => { 'name' => 'Database password',
44                        'default' => '',
45                      },
46     'query' => { 'name' => 'SQL query',
47                  'default' => '',
48                },
49
50     'query_style' => {
51       'name' => 'Query output style',
52       'type' => 'select',
53       'select_options' => \%query_style,
54     },
55
56   },
57   'fieldorder' => [qw( recur_method cutoff_day sync_bill_date),
58                    FS::part_pkg::prorate_Mixin::fieldorder,
59                    qw( datasrc db_username db_password query query_style
60                   )],
61   'weight' => '58',
62 );
63
64 sub price_info {
65     my $self = shift;
66     my $str = $self->SUPER::price_info(@_);
67     $str .= " plus per-service charges" if $str;
68     $str;
69 }
70
71 sub calc_recur {
72   my $self = shift;
73   my($cust_pkg, $sdate, $details, $param ) = @_;
74   my $price = 0;
75   my $quantity; # can be overridden; if not we use the default
76
77   my $dbh = DBI->connect( map { $self->option($_) }
78                               qw( datasrc db_username db_password )
79                         )
80     or die $DBI::errstr;
81
82   my $sth = $dbh->prepare( $self->option('query') )
83     or die $dbh->errstr;
84
85   foreach my $cust_svc (
86     grep { $_->part_svc->svcdb eq "svc_external" } $cust_pkg->cust_svc
87   ) {
88     my $id = $cust_svc->svc_x->id;
89     $sth->execute($id) or die $sth->errstr;
90
91     if ( $self->option('query_style') eq 'detailed' ) {
92
93       while (my $row = $sth->fetchrow_hashref) {
94         if (exists $row->{amount}) {
95           if ( $row->{amount} eq '' ) {
96             # treat as zero
97           } elsif ( $row->{amount} =~ /^\d+(?:\.\d+)?$/ ) {
98             $price += $row->{amount};
99           } else {
100             die "sql_external query returned non-numeric amount: $row->{amount}";
101           }
102         }
103         if (defined $row->{quantity}) {
104           if ( $row->{quantity} eq '' ) {
105             # treat as zero
106           } elsif ( $row->{quantity} =~ /^\d+$/ ) {
107             $quantity += $row->{quantity};
108           } else {
109             die "sql_external query returned non-integer quantity: $row->{quantity}";
110           }
111         }
112
113         my $detail = FS::cust_bill_pkg_detail->new;
114         foreach my $field (@detail_cols) {
115           if (exists $row->{$field}) {
116             $detail->set($field, $row->{$field});
117           }
118         }
119         if (!$detail->get('detail')) {
120           die "sql_external query did not return detail description";
121           # or make something up?
122           # or just don't insert the detail?
123         }
124
125         push @$details, $detail;
126       } # while $row
127
128     } else {
129
130       # simple style: returns only a single value, which is the price
131       $price += $sth->fetchrow_arrayref->[0];
132
133     }
134   }
135   $price = sprintf('%.2f', $price);
136
137   # XXX probably shouldn't allow package quantity > 1 on these packages.
138   if ($cust_pkg->quantity > 1) {
139     warn "sql_external package #".$cust_pkg->pkgnum." has quantity > 1\n";
140   }
141
142   $param->{'override_quantity'} = $quantity;
143   $param->{'override_charges'} = $price;
144   ($cust_pkg->quantity || 1) * $self->calc_recur_Common($cust_pkg,$sdate,$details,$param);
145 }
146
147 sub cutoff_day {
148   my $self = shift;
149   my $cust_pkg = shift;
150   my $cust_main = $cust_pkg->cust_main;
151   # force it to act like a prorate package, is what this means
152   # because we made a distinction once between prorate and flat packages
153   if ( $cust_main->force_prorate_day  and $cust_main->prorate_day ) {
154      return ( $cust_main->prorate_day );
155   }
156   if ( $self->option('sync_bill_date',1) ) {
157     my $next_bill = $cust_pkg->cust_main->next_bill_date;
158     if ( $next_bill ) {
159       return (localtime($next_bill))[3];
160     } else {
161       # This is the customer's only active package and hasn't been billed
162       # yet, so set the cutoff day to either today or tomorrow, whichever
163       # would result in a full period after rounding.
164       my $setup = $cust_pkg->setup; # because it's "now"
165       my $rounding_mode = $self->option('prorate_round_day',1);
166       return () if !$setup or !$rounding_mode;
167       my ($sec, $min, $hour, $mday, $mon, $year) = localtime($setup);
168
169       if (   ( $rounding_mode == 1 and $hour >= 12 )
170           or ( $rounding_mode == 3 and ( $sec > 0 or $min > 0 or $hour > 0 ))
171       ) {
172         # then the prorate period will be rounded down to start from
173         # midnight tomorrow, so the cutoff day should be the current day +
174         # 1.
175         $setup = timelocal(59,59,23,$mday,$mon,$year) + 1;
176         $mday = (localtime($setup))[3];
177       }
178       # otherwise, it will be rounded up, so leave the cutoff day at today.
179       return $mday;
180     }
181   }
182   return ();
183 }
184
185 sub can_discount { 1; }
186
187 sub is_free { 0; }
188
189 1;