textarea for SQL external statements, RT#78543
[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                  'type' => 'textarea',
48                  'default' => '',
49                },
50
51     'query_style' => {
52       'name' => 'Query output style',
53       'type' => 'select',
54       'select_options' => \%query_style,
55     },
56
57   },
58   'fieldorder' => [qw( recur_method cutoff_day sync_bill_date),
59                    FS::part_pkg::prorate_Mixin::fieldorder,
60                    qw( datasrc db_username db_password query query_style
61                   )],
62   'weight' => '58',
63 );
64
65 sub price_info {
66     my $self = shift;
67     my $str = $self->SUPER::price_info(@_);
68     $str .= " plus per-service charges" if $str;
69     $str;
70 }
71
72 sub calc_recur {
73   my $self = shift;
74   my($cust_pkg, $sdate, $details, $param ) = @_;
75   my $price = 0;
76   my $quantity; # can be overridden; if not we use the default
77
78   my $dbh = DBI->connect( map { $self->option($_) }
79                               qw( datasrc db_username db_password )
80                         )
81     or die $DBI::errstr;
82
83   my $sth = $dbh->prepare( $self->option('query') )
84     or die $dbh->errstr;
85
86   foreach my $cust_svc (
87     grep { $_->part_svc->svcdb eq "svc_external" } $cust_pkg->cust_svc
88   ) {
89     my $id = $cust_svc->svc_x->id;
90     $sth->execute($id) or die $sth->errstr;
91
92     if ( $self->option('query_style') eq 'detailed' ) {
93
94       while (my $row = $sth->fetchrow_hashref) {
95         if (exists $row->{amount}) {
96           if ( $row->{amount} eq '' ) {
97             # treat as zero
98           } elsif ( $row->{amount} =~ /^\d+(?:\.\d+)?$/ ) {
99             $price += $row->{amount};
100           } else {
101             die "sql_external query returned non-numeric amount: $row->{amount}";
102           }
103         }
104         if (defined $row->{quantity}) {
105           if ( $row->{quantity} eq '' ) {
106             # treat as zero
107           } elsif ( $row->{quantity} =~ /^\d+$/ ) {
108             $quantity += $row->{quantity};
109           } else {
110             die "sql_external query returned non-integer quantity: $row->{quantity}";
111           }
112         }
113
114         my $detail = FS::cust_bill_pkg_detail->new;
115         foreach my $field (@detail_cols) {
116           if (exists $row->{$field}) {
117             $detail->set($field, $row->{$field});
118           }
119         }
120         if (!$detail->get('detail')) {
121           die "sql_external query did not return detail description";
122           # or make something up?
123           # or just don't insert the detail?
124         }
125
126         push @$details, $detail;
127       } # while $row
128
129     } else {
130
131       # simple style: returns only a single value, which is the price
132       $price += $sth->fetchrow_arrayref->[0];
133
134     }
135   }
136   $price = sprintf('%.2f', $price);
137
138   # XXX probably shouldn't allow package quantity > 1 on these packages.
139   if ($cust_pkg->quantity > 1) {
140     warn "sql_external package #".$cust_pkg->pkgnum." has quantity > 1\n";
141   }
142
143   $param->{'override_quantity'} = $quantity;
144   $param->{'override_charges'} = $price;
145   ($cust_pkg->quantity || 1) * $self->calc_recur_Common($cust_pkg,$sdate,$details,$param);
146 }
147
148 sub cutoff_day {
149   my( $self, $cust_pkg ) = @_;
150   my $error = FS::part_pkg::flat::cutoff_day( $self, $cust_pkg );
151   return $error;
152 }
153
154 sub can_discount { 1; }
155
156 sub is_free { 0; }
157
158 1;