add time to payment report, RT#21061
[freeside.git] / FS / FS / UI / Web.pm
1 package FS::UI::Web;
2
3 use strict;
4 use vars qw($DEBUG @ISA @EXPORT_OK $me);
5 use Exporter;
6 use Carp qw( confess );
7 use HTML::Entities;
8 use FS::Conf;
9 use FS::Misc::DateTime qw( parse_datetime );
10 use FS::Record qw(dbdef);
11 use FS::cust_main;  # are sql_balance and sql_date_balance in the right module?
12
13 #use vars qw(@ISA);
14 #use FS::UI
15 #@ISA = qw( FS::UI );
16 @ISA = qw( Exporter );
17
18 @EXPORT_OK = qw( svc_url );
19
20 $DEBUG = 0;
21 $me = '[FS::UID::Web]';
22
23 ###
24 # date parsing
25 ###
26
27 use Date::Parse;
28 sub parse_beginning_ending {
29   my($cgi, $prefix) = @_;
30   $prefix .= '_' if $prefix;
31
32   my $beginning = 0;
33   if ( $cgi->param($prefix.'begin') =~ /^(\d+)$/ ) {
34     $beginning = $1;
35   } elsif ( $cgi->param($prefix.'beginning') =~ /^([ 0-9\-\/\:]{1,64})$/ ) {
36     $beginning = parse_datetime($1) || 0;
37   }
38
39   my $ending = 4294967295; #2^32-1
40   if ( $cgi->param($prefix.'end') =~ /^(\d+)$/ ) {
41     $ending = $1 - 1;
42   } elsif ( $cgi->param($prefix.'ending') =~ /^([ 0-9\-\/\:]{1,64})$/ ) {
43     #probably need an option to turn off the + 86399
44
45     #no, this should be add one day minus one second...
46     #  86399 is wrong twice a year when daylight savings time changes
47     #        and leap seconds too but only a second rather than an hour..
48     $ending = parse_datetime($1) + 86399;
49   }
50
51   ( $beginning, $ending );
52 }
53
54 =item svc_url
55
56 Returns a service URL, first checking to see if there is a service-specific
57 page to link to, otherwise to a generic service handling page.  Options are
58 passed as a list of name-value pairs, and include:
59
60 =over 4
61
62 =item * m - Mason request object ($m)
63
64 =item * action - The action for which to construct "edit", "view", or "search"
65
66 =item ** part_svc - Service definition (see L<FS::part_svc>)
67
68 =item ** svcdb - Service table
69
70 =item *** query - Query string
71
72 =item *** svc   - FS::cust_svc or FS::svc_* object
73
74 =item ahref - Optional flag, if set true returns <A HREF="$url"> instead of just the URL.
75
76 =back 
77
78 * Required fields
79
80 ** part_svc OR svcdb is required
81
82 *** query OR svc is required
83
84 =cut
85
86   # ##
87   # #required
88   # ##
89   #  'm'        => $m, #mason request object
90   #  'action'   => 'edit', #or 'view'
91   #
92   #  'part_svc' => $part_svc, #usual
93   #   #OR
94   #  'svcdb'    => 'svc_table',
95   #
96   #  'query'    => #optional query string
97   #                # (pass a blank string if you want a "raw" URL to add your
98   #                #  own svcnum to)
99   #   #OR
100   #  'svc'      => $svc_x, #or $cust_svc, it just needs a svcnum
101   #
102   # ##
103   # #optional
104   # ##
105   #  'ahref'    => 1, # if set true, returns <A HREF="$url">
106
107 use FS::CGI qw(rooturl);
108 sub svc_url {
109   my %opt = @_;
110
111   #? return '' unless ref($opt{part_svc});
112
113   my $svcdb = $opt{svcdb} || $opt{part_svc}->svcdb;
114   my $query = exists($opt{query}) ? $opt{query} : $opt{svc}->svcnum;
115   my $url;
116   warn "$me [svc_url] checking for /$opt{action}/$svcdb.cgi component"
117     if $DEBUG;
118   if ( $opt{m}->interp->comp_exists("/$opt{action}/$svcdb.cgi") ) {
119     $url = "$svcdb.cgi?";
120   } else {
121
122     my $generic = $opt{action} eq 'search' ? 'cust_svc' : 'svc_Common';
123
124     $url = "$generic.html?svcdb=$svcdb;";
125     $url .= 'svcnum=' if $query =~ /^\d+(;|$)/ or $query eq '';
126   }
127
128   import FS::CGI 'rooturl'; #WTF!  why is this necessary
129   my $return = rooturl(). "$opt{action}/$url$query";
130
131   $return = qq!<A HREF="$return">! if $opt{ahref};
132
133   $return;
134 }
135
136 sub svc_link {
137   my($m, $part_svc, $cust_svc) = @_ or return '';
138   svc_X_link( $part_svc->svc, @_ );
139 }
140
141 sub svc_label_link {
142   my($m, $part_svc, $cust_svc) = @_ or return '';
143   my($svc, $label, $svcdb) = $cust_svc->label;
144   svc_X_link( $label, @_ );
145 }
146
147 sub svc_X_link {
148   my ($x, $m, $part_svc, $cust_svc) = @_ or return '';
149
150   return $x
151    unless $FS::CurrentUser::CurrentUser->access_right('View customer services');
152
153   confess "svc_X_link called without a service ($x, $m, $part_svc, $cust_svc)\n"
154     unless $cust_svc;
155
156   my $ahref = svc_url(
157     'ahref'    => 1,
158     'm'        => $m,
159     'action'   => 'view',
160     'part_svc' => $part_svc,
161     'svc'      => $cust_svc,
162   );
163
164   "$ahref$x</A>";
165 }
166
167 #this probably needs an ACL too...
168 sub svc_export_links {
169   my ($m, $part_svc, $cust_svc) = @_ or return '';
170
171   my $ahref = $cust_svc->export_links;
172
173   join('', @$ahref);
174 }
175
176 sub parse_lt_gt {
177   my($cgi, $field) = @_;
178
179   my @search = ();
180
181   my %op = ( 
182     'lt' => '<',
183     'gt' => '>',
184   );
185
186   foreach my $op (keys %op) {
187
188     warn "checking for ${field}_$op field\n"
189       if $DEBUG;
190
191     if ( $cgi->param($field."_$op") =~ /^\s*\$?\s*(-?[\d\,\s]+(\.\d\d)?)\s*$/ ) {
192
193       my $num = $1;
194       $num =~ s/[\,\s]+//g;
195       my $search = "$field $op{$op} $num";
196       push @search, $search;
197
198       warn "found ${field}_$op field; adding search element $search\n"
199         if $DEBUG;
200     }
201
202   }
203
204   @search;
205
206 }
207
208 ###
209 # cust_main report subroutines
210 ###
211
212
213 =item cust_header [ CUST_FIELDS_VALUE ]
214
215 Returns an array of customer information headers according to the supplied
216 customer fields value, or if no value is supplied, the B<cust-fields>
217 configuration value.
218
219 =cut
220
221 use vars qw( @cust_fields @cust_colors @cust_styles @cust_aligns );
222
223 sub cust_header {
224
225   warn "FS::UI:Web::cust_header called"
226     if $DEBUG;
227
228   my $conf = new FS::Conf;
229
230   my %header2method = (
231     'Customer'                 => 'name',
232     'Cust. Status'             => 'ucfirst_cust_status',
233     'Cust#'                    => 'custnum',
234     'Name'                     => 'contact',
235     'Company'                  => 'company',
236     '(bill) Customer'          => 'name',
237     '(service) Customer'       => 'ship_name',
238     '(bill) Name'              => 'contact',
239     '(service) Name'           => 'ship_contact',
240     '(bill) Company'           => 'company',
241     '(service) Company'        => 'ship_company',
242     'Address 1'                => 'address1',
243     'Address 2'                => 'address2',
244     'City'                     => 'city',
245     'State'                    => 'state',
246     'Zip'                      => 'zip',
247     'Country'                  => 'country_full',
248     'Day phone'                => 'daytime', # XXX should use msgcat, but how?
249     'Night phone'              => 'night',   # XXX should use msgcat, but how?
250     'Fax number'               => 'fax',
251     '(bill) Address 1'         => 'address1',
252     '(bill) Address 2'         => 'address2',
253     '(bill) City'              => 'city',
254     '(bill) State'             => 'state',
255     '(bill) Zip'               => 'zip',
256     '(bill) Country'           => 'country_full',
257     '(bill) Day phone'         => 'daytime', # XXX should use msgcat, but how?
258     '(bill) Night phone'       => 'night',   # XXX should use msgcat, but how?
259     '(bill) Fax number'        => 'fax',
260     '(service) Address 1'      => 'ship_address1',
261     '(service) Address 2'      => 'ship_address2',
262     '(service) City'           => 'ship_city',
263     '(service) State'          => 'ship_state',
264     '(service) Zip'            => 'ship_zip',
265     '(service) Country'        => 'ship_country_full',
266     '(service) Day phone'      => 'ship_daytime', # XXX should use msgcat, how?
267     '(service) Night phone'    => 'ship_night',   # XXX should use msgcat, how?
268     '(service) Fax number'     => 'ship_fax',
269     'Invoicing email(s)'       => 'invoicing_list_emailonly_scalar',
270     'Payment Type'             => 'payby',
271     'Current Balance'          => 'current_balance',
272   );
273   $header2method{'Cust#'} = 'display_custnum'
274     if $conf->exists('cust_main-default_agent_custid');
275
276   my %header2colormethod = (
277     'Cust. Status' => 'cust_statuscolor',
278   );
279   my %header2style = (
280     'Cust. Status' => 'b',
281   );
282   my %header2align = (
283     'Cust. Status' => 'c',
284     'Cust#'        => 'r',
285   );
286
287   my $cust_fields;
288   my @cust_header;
289   if ( @_ && $_[0] ) {
290
291     warn "  using supplied cust-fields override".
292           " (ignoring cust-fields config file)"
293       if $DEBUG;
294     $cust_fields = shift;
295
296   } else {
297
298     if (    $conf->exists('cust-fields')
299          && $conf->config('cust-fields') =~ /^([\w\. \|\#\(\)]+):?/
300        )
301     {
302       warn "  found cust-fields configuration value"
303         if $DEBUG;
304       $cust_fields = $1;
305     } else { 
306       warn "  no cust-fields configuration value found; using default 'Cust. Status | Customer'"
307         if $DEBUG;
308       $cust_fields = 'Cust. Status | Customer';
309     }
310   
311   }
312
313   @cust_header = split(/ \| /, $cust_fields);
314   @cust_fields = map { $header2method{$_} || $_ } @cust_header;
315   @cust_colors = map { exists $header2colormethod{$_}
316                          ? $header2colormethod{$_}
317                          : ''
318                      }
319                      @cust_header;
320   @cust_styles = map { exists $header2style{$_} ? $header2style{$_} : '' }
321                      @cust_header;
322   @cust_aligns = map { exists $header2align{$_} ? $header2align{$_} : 'l' }
323                      @cust_header;
324
325   #my $svc_x = shift;
326   @cust_header;
327 }
328
329 =item cust_sql_fields [ CUST_FIELDS_VALUE ]
330
331 Returns a list of fields for the SELECT portion of an SQL query.
332
333 As with L<the cust_header subroutine|/cust_header>, the fields returned are
334 defined by the supplied customer fields setting, or if no customer fields
335 setting is supplied, the <B>cust-fields</B> configuration value. 
336
337 =cut
338
339 sub cust_sql_fields {
340
341   my @fields = qw( last first company );
342   push @fields, map "ship_$_", @fields;
343   push @fields, 'country';
344
345   cust_header(@_);
346   #inefficientish, but tiny lists and only run once per page
347
348   my @add_fields = qw( address1 address2 city state zip daytime night fax );
349   push @fields,
350     grep { my $field = $_; grep { $_ eq $field } @cust_fields }
351          ( @add_fields, ( map "ship_$_", @add_fields ), 'payby' );
352
353   push @fields, 'agent_custid';
354
355   my @extra_fields = ();
356   if (grep { $_ eq 'current_balance' } @cust_fields) {
357     push @extra_fields, FS::cust_main->balance_sql . " AS current_balance";
358   }
359
360   map("cust_main.$_", @fields), @extra_fields;
361 }
362
363 =item cust_fields OBJECT [ CUST_FIELDS_VALUE ]
364
365 Given an object that contains fields from cust_main (say, from a
366 JOINed search.  See httemplate/search/svc_* for examples), returns an array
367 of customer information, or "(unlinked)" if this service is not linked to a
368 customer.
369
370 As with L<the cust_header subroutine|/cust_header>, the fields returned are
371 defined by the supplied customer fields setting, or if no customer fields
372 setting is supplied, the <B>cust-fields</B> configuration value. 
373
374 =cut
375
376
377 sub cust_fields {
378   my $record = shift;
379   warn "FS::UI::Web::cust_fields called for $record ".
380        "(cust_fields: @cust_fields)"
381     if $DEBUG > 1;
382
383   #cust_header(@_) unless @cust_fields; #now need to cache to keep cust_fields
384   #                                     #override incase we were passed as a sub
385   
386   my $seen_unlinked = 0;
387
388   map { 
389     if ( $record->custnum ) {
390       warn "  $record -> $_" if $DEBUG > 1;
391       encode_entities( $record->$_(@_) );
392     } else {
393       warn "  ($record unlinked)" if $DEBUG > 1;
394       $seen_unlinked++ ? '' : '(unlinked)';
395     }
396   } @cust_fields;
397 }
398
399 =item cust_fields_subs
400
401 Returns an array of subroutine references for returning customer field values.
402 This is similar to cust_fields, but returns each field's sub as a distinct 
403 element.
404
405 =cut
406
407 sub cust_fields_subs {
408   my $unlinked_warn = 0;
409   return map { 
410     my $f = $_;
411     if( $unlinked_warn++ ) {
412       sub {
413         my $record = shift;
414         if( $record->custnum ) {
415           $record->$f(@_);
416         }
417         else {
418           '(unlinked)'
419         };
420       }
421     } 
422     else {
423       sub {
424         my $record = shift;
425         $record->$f(@_) if $record->custnum;
426       }
427     }
428   } @cust_fields;
429 }
430
431 =item cust_colors
432
433 Returns an array of subroutine references (or empty strings) for returning
434 customer information colors.
435
436 As with L<the cust_header subroutine|/cust_header>, the fields returned are
437 defined by the supplied customer fields setting, or if no customer fields
438 setting is supplied, the <B>cust-fields</B> configuration value. 
439
440 =cut
441
442 sub cust_colors {
443   map { 
444     my $method = $_;
445     if ( $method ) {
446       sub { shift->$method(@_) };
447     } else {
448       '';
449     }
450   } @cust_colors;
451 }
452
453 =item cust_styles
454
455 Returns an array of customer information styles.
456
457 As with L<the cust_header subroutine|/cust_header>, the fields returned are
458 defined by the supplied customer fields setting, or if no customer fields
459 setting is supplied, the <B>cust-fields</B> configuration value. 
460
461 =cut
462
463 sub cust_styles {
464   map { 
465     if ( $_ ) {
466       $_;
467     } else {
468       '';
469     }
470   } @cust_styles;
471 }
472
473 =item cust_aligns
474
475 Returns an array or scalar (depending on context) of customer information
476 alignments.
477
478 As with L<the cust_header subroutine|/cust_header>, the fields returned are
479 defined by the supplied customer fields setting, or if no customer fields
480 setting is supplied, the <B>cust-fields</B> configuration value. 
481
482 =cut
483
484 sub cust_aligns {
485   if ( wantarray ) {
486     @cust_aligns;
487   } else {
488     join('', @cust_aligns);
489   }
490 }
491
492 =item is_mobile
493
494 Utility function to determine if the client is a mobile browser.
495
496 =cut
497
498 sub is_mobile {
499   my $ua = $ENV{'HTTP_USER_AGENT'} || '';
500   if ( $ua =~ /(?:hiptop|Blazer|Novarra|Vagabond|SonyEricsson|Symbian|NetFront|UP.Browser|UP.Link|Windows CE|MIDP|J2ME|DoCoMo|J-PHONE|PalmOS|PalmSource|iPhone|iPod|AvantGo|Nokia|Android|WebOS|S60|Opera Mini|Opera Mobi)/io ) {
501     return 1;
502   }
503   return 0;
504 }
505     
506 ###
507 # begin JSRPC code...
508 ###
509
510 package FS::UI::Web::JSRPC;
511
512 use strict;
513 use vars qw($DEBUG);
514 use Carp;
515 use Storable qw(nfreeze);
516 use MIME::Base64;
517 use JSON;
518 use FS::UID qw(getotaker);
519 use FS::Record qw(qsearchs);
520 use FS::queue;
521 use FS::CGI qw(rooturl);
522
523 $DEBUG = 0;
524
525 sub new {
526         my $class = shift;
527         my $self  = {
528                 env => {},
529                 job => shift,
530                 cgi => shift,
531         };
532
533         bless $self, $class;
534
535         croak "CGI object required as second argument" unless $self->{'cgi'};
536
537         return $self;
538 }
539
540 sub process {
541
542   my $self = shift;
543
544   my $cgi = $self->{'cgi'};
545
546   # XXX this should parse JSON foo and build a proper data structure
547   my @args = $cgi->param('arg');
548
549   #work around konqueror bug!
550   @args = map { s/\x00$//; $_; } @args;
551
552   my $sub = $cgi->param('sub'); #????
553
554   warn "FS::UI::Web::JSRPC::process:\n".
555        "  cgi=$cgi\n".
556        "  sub=$sub\n".
557        "  args=".join(', ',@args)."\n"
558     if $DEBUG;
559
560   if ( $sub eq 'start_job' ) {
561
562     $self->start_job(@args);
563
564   } elsif ( $sub eq 'job_status' ) {
565
566     $self->job_status(@args);
567
568   } else {
569
570     die "unknown sub $sub";
571
572   }
573
574 }
575
576 sub start_job {
577   my $self = shift;
578
579   warn "FS::UI::Web::start_job: ". join(', ', @_) if $DEBUG;
580 #  my %param = @_;
581   my %param = ();
582   while ( @_ ) {
583     my( $field, $value ) = splice(@_, 0, 2);
584     unless ( exists( $param{$field} ) ) {
585       $param{$field} = $value;
586     } elsif ( ! ref($param{$field}) ) {
587       $param{$field} = [ $param{$field}, $value ];
588     } else {
589       push @{$param{$field}}, $value;
590     }
591   }
592   $param{CurrentUser} = getotaker();
593   $param{RootURL} = rooturl($self->{cgi}->self_url);
594   warn "FS::UI::Web::start_job\n".
595        join('', map {
596                       if ( ref($param{$_}) ) {
597                         "  $_ => [ ". join(', ', @{$param{$_}}). " ]\n";
598                       } else {
599                         "  $_ => $param{$_}\n";
600                       }
601                     } keys %param )
602     if $DEBUG;
603
604   #first get the CGI params shipped off to a job ASAP so an id can be returned
605   #to the caller
606   
607   my $job = new FS::queue { 'job' => $self->{'job'} };
608   
609   #too slow to insert all the cgi params as individual args..,?
610   #my $error = $queue->insert('_JOB', $cgi->Vars);
611   
612   #warn 'froze string of size '. length(nfreeze(\%param)). " for job args\n"
613   #  if $DEBUG;
614
615   my $error = $job->insert( '_JOB', encode_base64(nfreeze(\%param)) );
616
617   if ( $error ) {
618
619     warn "job not inserted: $error\n"
620       if $DEBUG;
621
622     $error;  #this doesn't seem to be handled well,
623              # will trigger "illegal jobnum" below?
624              # (should never be an error inserting the job, though, only thing
625              #  would be Pg f%*kage)
626   } else {
627
628     warn "job inserted successfully with jobnum ". $job->jobnum. "\n"
629       if $DEBUG;
630
631     $job->jobnum;
632   }
633   
634 }
635
636 sub job_status {
637   my( $self, $jobnum ) = @_; #$url ???
638
639   sleep 1; # XXX could use something better...
640
641   my $job;
642   if ( $jobnum =~ /^(\d+)$/ ) {
643     $job = qsearchs('queue', { 'jobnum' => $jobnum } );
644   } else {
645     die "FS::UI::Web::job_status: illegal jobnum $jobnum\n";
646   }
647
648   my @return;
649   if ( $job && $job->status ne 'failed' && $job->status ne 'done' ) {
650     my ($progress, $action) = split ',', $job->statustext, 2; 
651     $action ||= 'Server processing job';
652     @return = ( 'progress', $progress, $action );
653   } elsif ( !$job ) { #handle job gone case : job successful
654                       # so close popup, redirect parent window...
655     @return = ( 'complete' );
656   } elsif ( $job->status eq 'done' ) {
657     @return = ( 'done', $job->statustext, '' );
658   } else {
659     @return = ( 'error', $job ? $job->statustext : $jobnum );
660   }
661
662   #to_json(\@return);  #waiting on deb 5.0 for new JSON.pm?
663   #silence the warning though
664   my $to_json = JSON->can('to_json') || JSON->can('objToJson');
665   &$to_json(\@return);
666
667 }
668
669 1;
670