option to reprocess CDRs when voiding an invoice, RT#79001
[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 accountcode - accountcode
59
60 =item startdate - CDR startdate, if any
61
62 =item detail - detail description
63
64 =back
65
66 =head1 METHODS
67
68 =over 4
69
70 =item new HASHREF
71
72 Creates a new line item detail.  To add the line item detail to the database,
73 see L<"insert">.
74
75 Note that this stores the hash reference, not a distinct copy of the hash it
76 points to.  You can ask the object for a copy with the I<hash> method.
77
78 =cut
79
80 # the new method can be inherited from FS::Record, if a table method is defined
81
82 sub table { 'cust_bill_pkg_detail'; }
83
84 =item insert
85
86 Adds this record to the database.  If there is an error, returns the error,
87 otherwise returns false.
88
89 =cut
90
91 sub insert {
92   my $self = shift;
93   my $error = $self->SUPER::insert(@_);
94   return $error if $error;
95
96   # link CDRs
97   my $acctids = $self->get('acctid') or return '';
98   $acctids = [ $acctids ] unless ref $acctids;
99   foreach my $acctid ( @$acctids ) {
100     my $cdr = FS::cdr->by_key($acctid);
101     $cdr->set('detailnum', $self->detailnum);
102     $error = $cdr->replace;
103     # this should never happen
104     return "error linking CDR #$acctid: $error" if $error;
105   }
106   '';
107 }
108
109 =item delete [ ARG => VALUE ... ]
110
111 Delete this record from the database.
112
113 If the "reprocess_cdrs" argument is set to true, resets the status of any
114 related CDRs (and deletes their associated cdr_termination records, if any).
115
116 =cut
117
118 sub delete {
119   my( $self, %args ) = @_;
120
121   my $error = $self->SUPER::delete;
122   return $error if $error;
123
124   foreach my $cdr (qsearch('cdr', { detailnum => $self->detailnum })) {
125
126     $cdr->set('detailnum', '');
127     $cdr->set('freesidestatus', '') if $args{'reprocess_cdrs'};
128     $error = $cdr->replace;
129     return "error unlinking CDR #" . $cdr->acctid . ": $error" if $error;
130
131     #well, technically this could have been on other invoices / termination
132     # partners... separate flag?
133     $self->scalar_sql( 'DELETE FROM cdr_termination WHERE acctid = ?',
134                        $cdr->acctid )
135       if $args{'reprocess_cdrs'};
136
137   }
138
139   '';
140 }
141
142 =item replace OLD_RECORD
143
144 Replaces the OLD_RECORD with this one in the database.  If there is an error,
145 returns the error, otherwise returns false.
146
147 =cut
148
149 # the replace method can be inherited from FS::Record (doesn't touch CDRs)
150
151 =item check
152
153 Checks all fields to make sure this is a valid line item detail.  If there is
154 an error, returns the error, otherwise returns false.  Called by the insert
155 and replace methods.
156
157 =cut
158
159 # the check method should currently be supplied - FS::Record contains some
160 # data checking routines
161
162 sub check {
163   my $self = shift;
164
165   my $conf = new FS::Conf;
166
167   my $phonenum = $self->phonenum;
168   my $phonenum_check_method;
169   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
170     $phonenum =~ s/\W//g;
171     $phonenum_check_method = 'ut_alphan';
172   } else {
173     $phonenum =~ s/\D//g;
174     $phonenum_check_method = 'ut_numbern';
175   }
176   $self->phonenum($phonenum);
177
178   $self->ut_numbern('detailnum')
179     || $self->ut_foreign_key('billpkgnum', 'cust_bill_pkg', 'billpkgnum')
180     #|| $self->ut_moneyn('amount')
181     || $self->ut_floatn('amount')
182     || $self->ut_enum('format', [ '', 'C' ] )
183     || $self->ut_numbern('duration')
184     || $self->ut_textn('regionname')
185     || $self->ut_textn('accountcode')
186     || $self->ut_text('detail')
187     || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum')
188     || $self->$phonenum_check_method('phonenum')
189     || $self->ut_numbern('startdate')
190     || $self->SUPER::check
191     ;
192
193 }
194
195 =item formatted [ OPTION => VALUE ... ]
196
197 Returns detail information for the invoice line item detail formatted for
198 display.
199
200 Currently available options are: I<format> I<escape_function>
201
202 If I<format> is set to html or latex then the format is improved
203 for tabular appearance in those environments if possible.
204
205 If I<escape_function> is set then the format is processed by this
206 function before being returned.
207
208 DEPRECATED? (mostly unused, expensive)
209 If I<format_function> is set then the detail is handed to this callback
210 for processing.
211
212 =cut
213
214 #totally false laziness w/cust_bill_pkg->detail
215 sub formatted {
216   my ( $self, %opt ) = @_;
217   my $format = $opt{format} || '';
218   return () unless defined dbdef->table('cust_bill_pkg_detail');
219
220   eval "use Text::CSV_XS;";
221   die $@ if $@;
222   my $csv = new Text::CSV_XS;
223
224   my $escape_function = sub { shift };
225
226   $escape_function = \&encode_entities
227     if $format eq 'html';
228
229   $escape_function =
230     sub {
231       my $value = shift;
232       $value =~ s/([#\$%&~_\^{}])( )?/"\\$1". ( ( defined($2) && length($2) ) ? "\\$2" : '' )/ge;
233       $value =~ s/([<>])/\$$1\$/g;
234       $value;
235     }
236   if $format eq 'latex';
237
238   $escape_function = $opt{escape_function} if $opt{escape_function};
239
240   my $format_sub = sub { my $detail = shift;
241                          $csv->parse($detail) or return "can't parse $detail";
242                          join(' - ', map { &$escape_function($_) }
243                                      $csv->fields
244                              );
245                        };
246
247   $format_sub = sub { my $detail = shift;
248                       $csv->parse($detail) or return "can't parse $detail";
249                       join('</TD><TD>', map { &$escape_function($_) }
250                                         $csv->fields
251                           );
252                     }
253     if $format eq 'html';
254
255   $format_sub = sub { my $detail = shift;
256                       $csv->parse($detail) or return "can't parse $detail";
257                       #join(' & ', map { '\small{'. &$escape_function($_). '}' }                      #            $csv->fields );
258                       my $result = '';
259                       my $column = 1;
260                       foreach ($csv->fields) {
261                         $result .= ' & ' if $column > 1;
262                         if ($column > 6) {                     # KLUDGE ALERT!
263                           $result .= '\multicolumn{1}{l}{\scriptsize{'.
264                                      &$escape_function($_). '}}';
265                         }else{
266                           $result .= '\scriptsize{'.  &$escape_function($_). '}';
267                         }
268                         $column++;
269                       }
270                       $result;
271                     }
272     if $format eq 'latex';
273
274   $format_sub = $opt{format_function} if $opt{format_function};
275
276   $self->format eq 'C'
277     ? &{$format_sub}( $self->detail, $self )
278     : &{$escape_function}( $self->detail )
279   ;
280 }
281
282 =item cust_bill_pkg
283
284 Returns the L<FS::cust_bill_pkg> object (the invoice line item) that
285 this detail belongs to.
286
287 =cut
288
289 sub cust_bill_pkg {
290   my $self = shift;
291   my $billpkgnum = $self->billpkgnum or return '';
292   FS::cust_bill_pkg->by_key($billpkgnum);
293 }
294
295 # Used by FS::Upgrade to migrate to a new database schema
296 sub _upgrade_schema { # class method
297
298   my ($class, %opts) = @_;
299
300   warn "$me upgrading $class\n" if $DEBUG;
301
302   my $classnum = dbdef->table($class->table)->column('classnum')
303     or return;
304
305   my $type = $classnum->type;
306   unless ( $type =~ /^int/i || $type =~ /int$/i ) {
307
308     my $dbh = dbh;
309     if ( $dbh->{Driver}->{Name} eq 'Pg' ) {
310
311       eval "use DBI::Const::GetInfoType;";
312       die $@ if $@;
313
314       my $major_version = 0;
315       $dbh->get_info( $GetInfoType{SQL_DBMS_VER} ) =~ /^(\d{2})/
316         && ( $major_version = sprintf("%d", $1) );
317
318       if ( $major_version > 7 ) {
319
320         # ideally this would be supported in DBIx-DBSchema and friends
321
322         foreach my $table ( qw( cust_bill_pkg_detail h_cust_bill_pkg_detail ) ){
323
324           warn "updating $table column classnum to integer\n" if $DEBUG;
325           my $sql = "ALTER TABLE $table ALTER classnum TYPE int USING ".
326             "int4(classnum)";
327           my $sth = $dbh->prepare($sql) or die $dbh->errstr;
328           $sth->execute or die $sth->errstr;
329
330         }
331
332       } elsif ( $dbh->{pg_server_version} =~ /^704/ ) {  # earlier?
333
334         # ideally this would be supported in DBIx-DBSchema and friends
335
336         #  XXX_FIXME better locking
337
338         foreach my $table ( qw( cust_bill_pkg_detail h_cust_bill_pkg_detail ) ){
339
340           warn "updating $table column classnum to integer\n" if $DEBUG;
341
342           my $sql = "ALTER TABLE $table RENAME classnum TO old_classnum";
343           my $sth = $dbh->prepare($sql) or die $dbh->errstr;
344           $sth->execute or die $sth->errstr;
345
346           my $def = dbdef->table($table)->column('classnum');
347           $def->type('integer');
348           $def->length(''); 
349           $sql = "ALTER TABLE $table ADD COLUMN ". $def->line($dbh);
350           $sth = $dbh->prepare($sql) or die $dbh->errstr;
351           $sth->execute or die $sth->errstr;
352
353           $sql = "UPDATE $table SET classnum = int4( text( old_classnum ) )";
354           $sth = $dbh->prepare($sql) or die $dbh->errstr;
355           $sth->execute or die $sth->errstr;
356
357           $sql = "ALTER TABLE $table DROP old_classnum";
358           $sth = $dbh->prepare($sql) or die $dbh->errstr;
359           $sth->execute or die $sth->errstr;
360
361         }
362
363       } else {
364
365         die "cust_bill_pkg_detail classnum upgrade unsupported for this Pg version\n";
366
367       }
368
369     } else {
370
371       die "cust_bill_pkg_detail classnum upgrade only supported for Pg 8+\n";
372
373     }
374
375   }
376
377 }
378
379 # Used by FS::Upgrade to migrate to a new database
380 sub _upgrade_data { # class method
381
382   my ($class, %opts) = @_;
383
384   warn "$me Checking for unmigrated invoice line item details\n" if $DEBUG;
385
386   my @cbpd = qsearch({ 'table'   => $class->table,
387                        'hashref' => {},
388                        'extra_sql' => 'WHERE invnum IS NOT NULL AND '.
389                                       'pkgnum IS NOT NULL',
390                     });
391
392   if (scalar(@cbpd)) {
393     warn "$me Found unmigrated invoice line item details\n" if $DEBUG;
394
395     foreach my $cbpd ( @cbpd ) {
396       my $detailnum = $cbpd->detailnum;
397       warn "$me Contemplating detail $detailnum\n" if $DEBUG > 1;
398       my $cust_bill_pkg =
399         qsearchs({ 'table' => 'cust_bill_pkg',
400                    'hashref' => { 'invnum' => $cbpd->invnum,
401                                   'pkgnum' => $cbpd->pkgnum,
402                                 },
403                    'order_by' => 'ORDER BY billpkgnum LIMIT 1',
404                 });
405       if ($cust_bill_pkg) {
406         $cbpd->billpkgnum($cust_bill_pkg->billpkgnum);
407         $cbpd->invnum('');
408         $cbpd->pkgnum('');
409         my $error = $cbpd->replace;
410
411         warn "*** WARNING: error replacing line item detail ".
412              "(cust_bill_pkg_detail) $detailnum: $error ***\n"
413           if $error;
414       } else {
415         warn "Found orphaned line item detail $detailnum during upgrade.\n";
416       }
417
418     } # foreach $cbpd
419
420   } # if @cbpd
421
422   '';
423
424 }                         
425
426 =back
427
428 =head1 BUGS
429
430 =head1 SEE ALSO
431
432 L<FS::cust_bill_pkg>, L<FS::Record>, schema.html from the base documentation.
433
434 =cut
435
436 1;
437