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