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