Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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 %info = (
10   'name' => 'Base charge plus additional fees for external services from a configurable SQL query',
11   'shortname' => 'External SQL query',
12   'inherit_fields' => [ 'prorate_Mixin', 'global_Mixin' ],
13   'fields' => {
14     'cutoff_day'    => { 'name' => 'Billing Day (1 - 28) for prorating or '.
15                                    'subscription',
16                          'default' => '1',
17                        },
18
19     'recur_method'  => { 'name' => 'Recurring fee method',
20                          #'type' => 'radio',
21                          #'options' => \%recur_method,
22                          'type' => 'select',
23                          'select_options' => \%FS::part_pkg::recur_Common::recur_method,
24                        },
25     'datasrc' => { 'name' => 'DBI data source',
26                    'default' => '',
27                  },
28     'db_username' => { 'name' => 'Database username',
29                        'default' => '',
30                      },
31     'db_password' => { 'name' => 'Database password',
32                        'default' => '',
33                      },
34     'query' => { 'name' => 'SQL query',
35                  'default' => '',
36                },
37   },
38   'fieldorder' => [qw( recur_method cutoff_day ),
39                    FS::part_pkg::prorate_Mixin::fieldorder,
40                    qw( datasrc db_username db_password query 
41                   )],
42   'weight' => '58',
43 );
44
45 sub price_info {
46     my $self = shift;
47     my $str = $self->SUPER::price_info(@_);
48     $str .= " plus per-service charges" if $str;
49     $str;
50 }
51
52 sub calc_recur {
53   my $self = shift;
54   my($cust_pkg, $sdate, $details, $param ) = @_;
55   my $price = 0;
56
57   my $dbh = DBI->connect( map { $self->option($_) }
58                               qw( datasrc db_username db_password )
59                         )
60     or die $DBI::errstr;
61
62   my $sth = $dbh->prepare( $self->option('query') )
63     or die $dbh->errstr;
64
65   foreach my $cust_svc (
66     grep { $_->part_svc->svcdb eq "svc_external" } $cust_pkg->cust_svc
67   ) {
68     my $id = $cust_svc->svc_x->id;
69     $sth->execute($id) or die $sth->errstr;
70     $price += $sth->fetchrow_arrayref->[0];
71   }
72
73   $param->{'override_charges'} = $price;
74   ($cust_pkg->quantity || 1) * $self->calc_recur_Common($cust_pkg,$sdate,$details,$param);
75 }
76
77 sub can_discount { 1; }
78
79 sub is_free { 0; }
80
81 1;