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