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