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