add svc_elec_features merged from reference code RT#7643
[freeside.git] / FS / FS / cust_bill_pkg_detail.pm
1 package FS::cust_bill_pkg_detail;
2
3 use strict;
4 use vars qw( @ISA $me $DEBUG %GetInfoType );
5 use HTML::Entities;
6 use FS::Record qw( qsearch qsearchs dbdef dbh );
7 use FS::cust_bill_pkg;
8 use FS::usage_class;
9 use FS::Conf;
10
11 @ISA = qw(FS::Record);
12 $me = '[ FS::cust_bill_pkg_detail ]';
13 $DEBUG = 0;
14
15 =head1 NAME
16
17 FS::cust_bill_pkg_detail - Object methods for cust_bill_pkg_detail records
18
19 =head1 SYNOPSIS
20
21   use FS::cust_bill_pkg_detail;
22
23   $record = new FS::cust_bill_pkg_detail \%hash;
24   $record = new FS::cust_bill_pkg_detail { 'column' => 'value' };
25
26   $error = $record->insert;
27
28   $error = $new_record->replace($old_record);
29
30   $error = $record->delete;
31
32   $error = $record->check;
33
34 =head1 DESCRIPTION
35
36 An FS::cust_bill_pkg_detail object represents additional detail information for
37 an invoice line item (see L<FS::cust_bill_pkg>).  FS::cust_bill_pkg_detail
38 inherits from FS::Record.  The following fields are currently supported:
39
40 =over 4
41
42 =item detailnum - primary key
43
44 =item billpkgnum - link to cust_bill_pkg
45
46 =item amount - price of this line item detail
47
48 =item format - '' for straight text and 'C' for CSV in detail
49
50 =item classnum - link to usage_class
51
52 =item duration - granularized number of seconds for this call
53
54 =item regionname -
55
56 =item phonenum -
57
58 =item detail - detail description
59
60 =item prev_date
61
62 =item curr_date -
63
64 =item prev_read -
65
66 =item curr_read -
67
68 =item tdsp -
69
70 =item taxes -
71
72 =item rate -
73
74 =item gr_fee -
75
76 =item energy_base -
77
78 =item energy_charge -
79
80 =item setup_fee -
81
82 =item one_time_charge -
83
84 =item one_time_description -
85
86 =item balance -
87
88 =item last_pay -
89
90 =item last_pay_date -
91
92 =item return_addr -
93
94 =item bill_return_address -
95
96 =item pkg_info -
97
98
99 =back
100
101 =head1 METHODS
102
103 =over 4
104
105 =item new HASHREF
106
107 Creates a new line item detail.  To add the line item detail to the database,
108 see L<"insert">.
109
110 Note that this stores the hash reference, not a distinct copy of the hash it
111 points to.  You can ask the object for a copy with the I<hash> method.
112
113 =cut
114
115 # the new method can be inherited from FS::Record, if a table method is defined
116
117 sub table { 'cust_bill_pkg_detail'; }
118
119 =item insert
120
121 Adds this record to the database.  If there is an error, returns the error,
122 otherwise returns false.
123
124 =cut
125
126 # the insert method can be inherited from FS::Record
127
128 =item delete
129
130 Delete this record from the database.
131
132 =cut
133
134 # the delete method can be inherited from FS::Record
135
136 =item replace OLD_RECORD
137
138 Replaces the OLD_RECORD with this one in the database.  If there is an error,
139 returns the error, otherwise returns false.
140
141 =cut
142
143 # the replace method can be inherited from FS::Record
144
145 =item check
146
147 Checks all fields to make sure this is a valid line item detail.  If there is
148 an error, returns the error, otherwise returns false.  Called by the insert
149 and replace methods.
150
151 =cut
152
153 # the check method should currently be supplied - FS::Record contains some
154 # data checking routines
155
156 sub check {
157   my $self = shift;
158
159   my $conf = new FS::Conf;
160
161   my $phonenum = $self->phonenum;
162   my $phonenum_check_method;
163   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
164     $phonenum =~ s/\W//g;
165     $phonenum_check_method = 'ut_alphan';
166   } else {
167     $phonenum =~ s/\D//g;
168     $phonenum_check_method = 'ut_numbern';
169   }
170   $self->phonenum($phonenum);
171
172   $self->ut_numbern('detailnum')
173     || $self->ut_foreign_key('billpkgnum', 'cust_bill_pkg', 'billpkgnum')
174     #|| $self->ut_moneyn('amount')
175     || $self->ut_floatn('amount')
176     || $self->ut_enum('format', [ '', 'C' ] )
177     || $self->ut_numbern('duration')
178     || $self->ut_textn('regionname')
179     || $self->ut_text('detail')
180     || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum')
181     || $self->$phonenum_check_method('phonenum')
182     || $self->SUPER::check
183     || $self->ut_numbern('prev_date')
184     || $self->ut_numbern('curr_date')
185     || $self->ut_floatn('prev_read')
186     || $self->ut_floatn('curr_read')
187     || $self->ut_money('tdsp')
188     || $self->ut_money('taxes')
189     || $self->ut_money('gr_fee')
190     || $self->ut_money('energy_base')
191     || $self->ut_money('energy_charge')
192     || $self->ut_money('setup_fee')
193     || $self->ut_money('one_time_charge')
194     || $self->ut_floatn('rate')
195     || $self->ut_floatn('discount1_rate')
196     || $self->ut_floatn('discount1_total')
197     || $self->ut_numbern('number_of_days')
198     || $self->ut_floatn('average_price')
199     || $self->ut_floatn('energy_usage')
200     || $self->ut_anything('one_time_description')
201     || $self->ut_money('balance')
202     || $self->ut_money('last_pay')
203     || $self->ut_numbern('last_pay_date')
204     || $self->ut_anything('return_addr')
205     || $self->ut_textn('bill_return_address')
206     || $self->ut_floatn('meter_multiplier')
207     || $self->ut_floatn('demanded_bill')
208     || $self->ut_floatn('measured_bill')
209   ;
210
211 }
212
213 =item formatted [ OPTION => VALUE ... ]
214
215 Returns detail information for the invoice line item detail formatted for
216 display.
217
218 Currently available options are: I<format> I<escape_function>
219
220 If I<format> is set to html or latex then the format is improved
221 for tabular appearance in those environments if possible.
222
223 If I<escape_function> is set then the format is processed by this
224 function before being returned.
225
226 If I<format_function> is set then the detail is handed to this callback
227 for processing.
228
229 =cut
230
231 sub formatted {
232   my ( $self, %opt ) = @_;
233   my $format = $opt{format} || '';
234   return () unless defined dbdef->table('cust_bill_pkg_detail');
235
236   eval "use Text::CSV_XS;";
237   die $@ if $@;
238   my $csv = new Text::CSV_XS;
239
240   my $escape_function = sub { shift };
241
242   $escape_function = \&encode_entities
243     if $format eq 'html';
244
245   $escape_function =
246     sub {
247       my $value = shift;
248       $value =~ s/([#\$%&~_\^{}])( )?/"\\$1". ( ( defined($2) && length($2) ) ? "\\$2" : '' )/ge;
249       $value =~ s/([<>])/\$$1\$/g;
250       $value;
251     }
252   if $format eq 'latex';
253
254   $escape_function = $opt{escape_function} if $opt{escape_function};
255
256   my $format_sub = sub { my $detail = shift;
257                          $csv->parse($detail) or return "can't parse $detail";
258                          join(' - ', map { &$escape_function($_) }
259                                      $csv->fields
260                              );
261                        };
262
263   $format_sub = sub { my $detail = shift;
264                       $csv->parse($detail) or return "can't parse $detail";
265                       join('</TD><TD>', map { &$escape_function($_) }
266                                         $csv->fields
267                           );
268                     }
269     if $format eq 'html';
270
271   $format_sub = sub { my $detail = shift;
272                       $csv->parse($detail) or return "can't parse $detail";
273                       #join(' & ', map { '\small{'. &$escape_function($_). '}' }                      #            $csv->fields );
274                       my $result = '';
275                       my $column = 1;
276                       foreach ($csv->fields) {
277                         $result .= ' & ' if $column > 1;
278                         if ($column > 6) {                     # KLUDGE ALERT!
279                           $result .= '\multicolumn{1}{l}{\scriptsize{'.
280                                      &$escape_function($_). '}}';
281                         }else{
282                           $result .= '\scriptsize{'.  &$escape_function($_). '}';
283                         }
284                         $column++;
285                       }
286                       $result;
287                     }
288     if $format eq 'latex';
289
290   $format_sub = $opt{format_function} if $opt{format_function};
291
292   $self->format eq 'C'
293     ? &{$format_sub}( $self->detail, $self )
294     : &{$escape_function}( $self->detail )
295   ;
296 }
297
298
299 # _upgrade_data
300 #
301 # Used by FS::Upgrade to migrate to a new database.
302
303 sub _upgrade_data { # class method
304
305   my ($class, %opts) = @_;
306
307   warn "$me upgrading $class\n" if $DEBUG;
308
309   my $type = dbdef->table($class->table)->column('classnum')->type;
310   unless ( $type =~ /^int/i || $type =~ /int$/i ) {
311
312     my $dbh = dbh;
313     if ( $dbh->{Driver}->{Name} eq 'Pg' ) {
314
315       eval "use DBI::Const::GetInfoType;";
316       die $@ if $@;
317
318       my $major_version = 0;
319       $dbh->get_info( $GetInfoType{SQL_DBMS_VER} ) =~ /^(\d{2})/
320         && ( $major_version = sprintf("%d", $1) );
321
322       if ( $major_version > 7 ) {
323
324         # ideally this would be supported in DBIx-DBSchema and friends
325
326         foreach my $table ( qw( cust_bill_pkg_detail h_cust_bill_pkg_detail ) ){
327
328           warn "updating $table column classnum to integer\n" if $DEBUG;
329           my $sql = "ALTER TABLE $table ALTER classnum TYPE int USING ".
330             "int4(classnum)";
331           my $sth = $dbh->prepare($sql) or die $dbh->errstr;
332           $sth->execute or die $sth->errstr;
333
334         }
335
336       } elsif ( $dbh->{pg_server_version} =~ /^704/ ) {  # earlier?
337
338         # ideally this would be supported in DBIx-DBSchema and friends
339
340         #  XXX_FIXME better locking
341
342         foreach my $table ( qw( cust_bill_pkg_detail h_cust_bill_pkg_detail ) ){
343
344           warn "updating $table column classnum to integer\n" if $DEBUG;
345
346           my $sql = "ALTER TABLE $table RENAME classnum TO old_classnum";
347           my $sth = $dbh->prepare($sql) or die $dbh->errstr;
348           $sth->execute or die $sth->errstr;
349
350           my $def = dbdef->table($table)->column('classnum');
351           $def->type('integer');
352           $def->length(''); 
353           $sql = "ALTER TABLE $table ADD COLUMN ". $def->line($dbh);
354           $sth = $dbh->prepare($sql) or die $dbh->errstr;
355           $sth->execute or die $sth->errstr;
356
357           $sql = "UPDATE $table SET classnum = int4( text( old_classnum ) )";
358           $sth = $dbh->prepare($sql) or die $dbh->errstr;
359           $sth->execute or die $sth->errstr;
360
361           $sql = "ALTER TABLE $table DROP old_classnum";
362           $sth = $dbh->prepare($sql) or die $dbh->errstr;
363           $sth->execute or die $sth->errstr;
364
365         }
366
367       } else {
368
369         die "cust_bill_pkg_detail classnum upgrade unsupported for this Pg version\n";
370
371       }
372
373     } else {
374
375       die "cust_bill_pkg_detail classnum upgrade only supported for Pg 8+\n";
376
377     }
378
379   }
380
381
382   if ( defined( dbdef->table($class->table)->column('billpkgnum') ) &&
383        defined( dbdef->table($class->table)->column('invnum') ) &&
384        defined( dbdef->table($class->table)->column('pkgnum') ) 
385   ) {
386
387     warn "$me Checking for unmigrated invoice line item details\n" if $DEBUG;
388
389     my @cbpd = qsearch({ 'table'   => $class->table,
390                          'hashref' => {},
391                          'extra_sql' => 'WHERE invnum IS NOT NULL AND '.
392                                         'pkgnum IS NOT NULL',
393                          'order_by' => 'ORDER BY detailnum',
394                       });
395
396     if (scalar(@cbpd)) {
397       warn "$me Found unmigrated invoice line item details\n" if $DEBUG;
398
399       foreach my $cbpd ( @cbpd ) {
400         my $detailnum = $cbpd->detailnum;
401         warn "$me Contemplating detail $detailnum\n" if $DEBUG > 1;
402         my $cust_bill_pkg =
403           qsearchs({ 'table' => 'cust_bill_pkg',
404                      'hashref' => { 'invnum' => $cbpd->invnum,
405                                     'pkgnum' => $cbpd->pkgnum,
406                                   },
407                      'order_by' => 'ORDER BY billpkgnum LIMIT 1',
408                   });
409         if ($cust_bill_pkg) {
410           $cbpd->billpkgnum($cust_bill_pkg->billpkgnum);
411           $cbpd->invnum('');
412           $cbpd->pkgnum('');
413           my $error = $cbpd->replace;
414
415           warn "*** WARNING: error replacing line item detail ".
416                "(cust_bill_pkg_detail) $detailnum: $error ***\n"
417             if $error;
418         } else {
419           warn "Found orphaned line item detail $detailnum during upgrade.\n";
420         }
421
422       } # foreach $cbpd
423
424     } # if @cbpd
425
426   } # if billpkgnum, invnum, and pkgnum columns defined
427
428   '';
429
430 }                         
431
432 =back
433
434 =head1 BUGS
435
436 =head1 SEE ALSO
437
438 L<FS::cust_bill_pkg>, L<FS::Record>, schema.html from the base documentation.
439
440 =cut
441
442 1;
443