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