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