add skip_dcontext_suffix to skip CDRs with dcontext ending in a definable string...
[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 (defined $row->{quantity}) {
100           if ( $row->{quantity} eq '' ) {
101             # treat as zero
102           } elsif ( $row->{quantity} =~ /^\d+$/ ) {
103             $quantity += $row->{quantity};
104           } else {
105             die "sql_external query returned non-integer quantity: $row->{quantity}";
106           }
107         }
108
109         my $detail = FS::cust_bill_pkg_detail->new;
110         foreach my $field (@detail_cols) {
111           if (exists $row->{$field}) {
112             $detail->set($field, $row->{$field});
113           }
114         }
115         if (!$detail->get('detail')) {
116           die "sql_external query did not return detail description";
117           # or make something up?
118           # or just don't insert the detail?
119         }
120
121         push @$details, $detail;
122       } # while $row
123
124     } else {
125
126       # simple style: returns only a single value, which is the price
127       $price += $sth->fetchrow_arrayref->[0];
128
129     }
130   }
131   $price = sprintf('%.2f', $price);
132
133   # XXX probably shouldn't allow package quantity > 1 on these packages.
134   if ($cust_pkg->quantity > 1) {
135     warn "sql_external package #".$cust_pkg->pkgnum." has quantity > 1\n";
136   }
137
138   $param->{'override_quantity'} = $quantity;
139   $param->{'override_charges'} = $price;
140   ($cust_pkg->quantity || 1) * $self->calc_recur_Common($cust_pkg,$sdate,$details,$param);
141 }
142
143 sub can_discount { 1; }
144
145 sub is_free { 0; }
146
147 1;