selectable sales report colors, RT#19464
[freeside.git] / FS / FS / access_user.pm
1 package FS::access_user;
2
3 use strict;
4 use base qw( FS::m2m_Common FS::option_Common ); 
5 use vars qw( $DEBUG $me $conf );
6 use FS::UID;
7 use FS::Auth;
8 use FS::Conf;
9 use FS::Record qw( qsearch qsearchs dbh );
10 use FS::access_user_pref;
11 use FS::access_usergroup;
12 use FS::agent;
13 use FS::cust_main;
14 use FS::sales;
15
16 $DEBUG = 0;
17 $me = '[FS::access_user]';
18
19 =head1 NAME
20
21 FS::access_user - Object methods for access_user records
22
23 =head1 SYNOPSIS
24
25   use FS::access_user;
26
27   $record = new FS::access_user \%hash;
28   $record = new FS::access_user { 'column' => 'value' };
29
30   $error = $record->insert;
31
32   $error = $new_record->replace($old_record);
33
34   $error = $record->delete;
35
36   $error = $record->check;
37
38 =head1 DESCRIPTION
39
40 An FS::access_user object represents an internal access user.  FS::access_user
41 inherits from FS::Record.  The following fields are currently supported:
42
43 =over 4
44
45 =item usernum - primary key
46
47 =item username - 
48
49 =item _password - 
50
51 =item last -
52
53 =item first -
54
55 =item disabled - empty or 'Y'
56
57 =back
58
59 =head1 METHODS
60
61 =over 4
62
63 =item new HASHREF
64
65 Creates a new internal access user.  To add the user to the database, see L<"insert">.
66
67 Note that this stores the hash reference, not a distinct copy of the hash it
68 points to.  You can ask the object for a copy with the I<hash> method.
69
70 =cut
71
72 # the new method can be inherited from FS::Record, if a table method is defined
73
74 sub table { 'access_user'; }
75
76 sub _option_table    { 'access_user_pref'; }
77 sub _option_namecol  { 'prefname'; }
78 sub _option_valuecol { 'prefvalue'; }
79
80 =item insert
81
82 Adds this record to the database.  If there is an error, returns the error,
83 otherwise returns false.
84
85 =cut
86
87 sub insert {
88   my $self = shift;
89
90   my $error = $self->check;
91   return $error if $error;
92
93   local $SIG{HUP} = 'IGNORE';
94   local $SIG{INT} = 'IGNORE';
95   local $SIG{QUIT} = 'IGNORE';
96   local $SIG{TERM} = 'IGNORE';
97   local $SIG{TSTP} = 'IGNORE';
98   local $SIG{PIPE} = 'IGNORE';
99
100   my $oldAutoCommit = $FS::UID::AutoCommit;
101   local $FS::UID::AutoCommit = 0;
102   my $dbh = dbh;
103
104   if ( $error ) {
105     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
106     return $error;
107   }
108
109   $error = $self->SUPER::insert(@_);
110
111   if ( $error ) {
112     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
113     return $error;
114   } else {
115     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
116     '';
117   }
118
119 }
120
121 =item delete
122
123 Delete this record from the database.
124
125 =cut
126
127 sub delete {
128   my $self = shift;
129
130   local $SIG{HUP} = 'IGNORE';
131   local $SIG{INT} = 'IGNORE';
132   local $SIG{QUIT} = 'IGNORE';
133   local $SIG{TERM} = 'IGNORE';
134   local $SIG{TSTP} = 'IGNORE';
135   local $SIG{PIPE} = 'IGNORE';
136
137   my $oldAutoCommit = $FS::UID::AutoCommit;
138   local $FS::UID::AutoCommit = 0;
139   my $dbh = dbh;
140
141   my $error = $self->SUPER::delete(@_);
142
143   if ( $error ) {
144     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
145     return $error;
146   } else {
147     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
148     '';
149   }
150
151 }
152
153 =item replace OLD_RECORD
154
155 Replaces the OLD_RECORD with this one in the database.  If there is an error,
156 returns the error, otherwise returns false.
157
158 =cut
159
160 sub replace {
161   my $new = shift;
162
163   my $old = ( ref($_[0]) eq ref($new) )
164               ? shift
165               : $new->replace_old;
166
167   local $SIG{HUP} = 'IGNORE';
168   local $SIG{INT} = 'IGNORE';
169   local $SIG{QUIT} = 'IGNORE';
170   local $SIG{TERM} = 'IGNORE';
171   local $SIG{TSTP} = 'IGNORE';
172   local $SIG{PIPE} = 'IGNORE';
173
174   my $oldAutoCommit = $FS::UID::AutoCommit;
175   local $FS::UID::AutoCommit = 0;
176   my $dbh = dbh;
177
178   return "Must change password when enabling this account"
179     if $old->disabled && !$new->disabled
180     && (      $new->_password =~ /changeme/i
181            || $new->_password eq 'notyet'
182        );
183
184   my $error = $new->SUPER::replace($old, @_);
185
186   if ( $error ) {
187     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
188     return $error;
189   } else {
190     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
191     '';
192   }
193
194 }
195
196 =item check
197
198 Checks all fields to make sure this is a valid internal access user.  If there is
199 an error, returns the error, otherwise returns false.  Called by the insert
200 and replace methods.
201
202 =cut
203
204 # the check method should currently be supplied - FS::Record contains some
205 # data checking routines
206
207 sub check {
208   my $self = shift;
209
210   my $error = 
211     $self->ut_numbern('usernum')
212     || $self->ut_alpha_lower('username')
213     || $self->ut_textn('_password')
214     || $self->ut_textn('last')
215     || $self->ut_textn('first')
216     || $self->ut_foreign_keyn('user_custnum', 'cust_main', 'custnum')
217     || $self->ut_foreign_keyn('report_salesnum', 'sales', 'salesnum')
218     || $self->ut_enum('disabled', [ '', 'Y' ] )
219   ;
220   return $error if $error;
221
222   $self->SUPER::check;
223 }
224
225 =item name
226
227 Returns a name string for this user: "Last, First".
228
229 =cut
230
231 sub name {
232   my $self = shift;
233   return $self->username
234     if $self->get('last') eq 'Lastname' && $self->first eq 'Firstname'
235     or $self->get('last') eq ''         && $self->first eq '';
236   return $self->get('last'). ', '. $self->first;
237 }
238
239 =item user_cust_main
240
241 Returns the FS::cust_main object (see L<FS::cust_main>), if any, for this
242 user.
243
244 =cut
245
246 sub user_cust_main {
247   my $self = shift;
248   qsearchs( 'cust_main', { 'custnum' => $self->user_custnum } );
249 }
250
251 =item report_sales
252
253 Returns the FS::sales object (see L<FS::sales>), if any, for this
254 user.
255
256 =cut
257
258 sub report_sales {
259   my $self = shift;
260   qsearchs( 'sales', { 'salesnum' => $self->report_salesnum } );
261 }
262
263 =item access_usergroup
264
265 Returns links to the the groups this user is a part of, as FS::access_usergroup
266 objects (see L<FS::access_usergroup>).
267
268 =cut
269
270 sub access_usergroup {
271   my $self = shift;
272   qsearch( 'access_usergroup', { 'usernum' => $self->usernum } );
273 }
274
275 #=item access_groups
276 #
277 #=cut
278 #
279 #sub access_groups {
280 #
281 #}
282 #
283 #=item access_groupnames
284 #
285 #=cut
286 #
287 #sub access_groupnames {
288 #
289 #}
290
291 =item agentnums 
292
293 Returns a list of agentnums this user can view (via group membership).
294
295 =cut
296
297 sub agentnums {
298   my $self = shift;
299   my $sth = dbh->prepare(
300     "SELECT DISTINCT agentnum FROM access_usergroup
301                               JOIN access_groupagent USING ( groupnum )
302        WHERE usernum = ?"
303   ) or die dbh->errstr;
304   $sth->execute($self->usernum) or die $sth->errstr;
305   map { $_->[0] } @{ $sth->fetchall_arrayref };
306 }
307
308 =item agentnums_href
309
310 Returns a hashref of agentnums this user can view.
311
312 =cut
313
314 sub agentnums_href {
315   my $self = shift;
316   scalar( { map { $_ => 1 } $self->agentnums } );
317 }
318
319 =item agentnums_sql [ HASHREF | OPTION => VALUE ... ]
320
321 Returns an sql fragement to select only agentnums this user can view.
322
323 Options are passed as a hashref or a list.  Available options are:
324
325 =over 4
326
327 =item null
328
329 The frament will also allow the selection of null agentnums.
330
331 =item null_right
332
333 The fragment will also allow the selection of null agentnums if the current
334 user has the provided access right
335
336 =item table
337
338 Optional table name in which agentnum is being checked.  Sometimes required to
339 resolve 'column reference "agentnum" is ambiguous' errors.
340
341 =item viewall_right
342
343 All agents will be viewable if the current user has the provided access right.
344 Defaults to 'View customers of all agents'.
345
346 =back
347
348 =cut
349
350 sub agentnums_sql {
351   my( $self ) = shift;
352   my %opt = ref($_[0]) ? %{$_[0]} : @_;
353
354   my $agentnum = $opt{'table'} ? $opt{'table'}.'.agentnum' : 'agentnum';
355
356   my @or = ();
357
358   my $viewall_right = $opt{'viewall_right'} || 'View customers of all agents';
359   if ( $self->access_right($viewall_right) ) {
360     push @or, "$agentnum IS NOT NULL";
361   } else {
362     push @or, "$agentnum IN (". join(',', $self->agentnums). ')';
363   }
364
365   push @or, "$agentnum IS NULL"
366     if $opt{'null'}
367     || ( $opt{'null_right'} && $self->access_right($opt{'null_right'}) );
368
369   return ' 1 = 0 ' unless scalar(@or);
370   '( '. join( ' OR ', @or ). ' )';
371
372 }
373
374 =item agentnum
375
376 Returns true if the user can view the specified agent.
377
378 =cut
379
380 sub agentnum {
381   my( $self, $agentnum ) = @_;
382   my $sth = dbh->prepare(
383     "SELECT COUNT(*) FROM access_usergroup
384                      JOIN access_groupagent USING ( groupnum )
385        WHERE usernum = ? AND agentnum = ?"
386   ) or die dbh->errstr;
387   $sth->execute($self->usernum, $agentnum) or die $sth->errstr;
388   $sth->fetchrow_arrayref->[0];
389 }
390
391 =item agents [ HASHREF | OPTION => VALUE ... ]
392
393 Returns the list of agents this user can view (via group membership), as
394 FS::agent objects.  Accepts the same options as the agentnums_sql method.
395
396 =cut
397
398 sub agents {
399   my $self = shift;
400   qsearch({
401     'table'     => 'agent',
402     'hashref'   => { disabled=>'' },
403     'extra_sql' => ' AND '. $self->agentnums_sql(@_),
404     'order_by'  => 'ORDER BY agent',
405   });
406 }
407
408 =item access_right RIGHTNAME | LISTREF
409
410 Given a right name or a list reference of right names, returns true if this
411 user has this right, or, for a list, one of the rights (currently via group
412 membership, eventually also via user overrides).
413
414 =cut
415
416 sub access_right {
417   my( $self, $rightname ) = @_;
418
419   $rightname = [ $rightname ] unless ref($rightname);
420
421   warn "$me access_right called on ". join(', ', @$rightname). "\n"
422     if $DEBUG;
423
424   #some caching of ACL requests for low-hanging fruit perf improvement
425   #since we get a new $CurrentUser object each page view there shouldn't be any
426   #issues with stickiness
427   if ( $self->{_ACLcache} ) {
428
429     unless ( grep !exists($self->{_ACLcache}{$_}), @$rightname ) {
430       warn "$me ACL cache hit for ". join(', ', @$rightname). "\n"
431         if $DEBUG;
432       return grep $self->{_ACLcache}{$_}, @$rightname
433     }
434
435     warn "$me ACL cache miss for ". join(', ', @$rightname). "\n"
436       if $DEBUG;
437
438   } else {
439
440     warn "initializing ACL cache\n"
441       if $DEBUG;
442     $self->{_ACLcache} = {};
443
444   }
445
446   my $has_right = ' rightname IN ('. join(',', map '?', @$rightname ). ') ';
447
448   my $sth = dbh->prepare("
449     SELECT groupnum FROM access_usergroup
450                     LEFT JOIN access_group USING ( groupnum )
451                     LEFT JOIN access_right
452                          ON ( access_group.groupnum = access_right.rightobjnum )
453       WHERE usernum = ?
454         AND righttype = 'FS::access_group'
455         AND $has_right
456       LIMIT 1
457   ") or die dbh->errstr;
458   $sth->execute($self->usernum, @$rightname) or die $sth->errstr;
459   my $row = $sth->fetchrow_arrayref;
460
461   my $return = $row ? $row->[0] : '';
462
463   #just caching the single-rightname hits should be enough of a win for now
464   if ( scalar(@$rightname) == 1 ) {
465     $self->{_ACLcache}{${$rightname}[0]} = $return;
466   }
467
468   $return;
469
470 }
471
472 =item default_customer_view
473
474 Returns the default customer view for this user, from the 
475 "default_customer_view" user preference, the "cust_main-default_view" config,
476 or the hardcoded default, "basics" (formerly "jumbo" prior to 3.0).
477
478 =cut
479
480 sub default_customer_view {
481   my $self = shift;
482
483   $self->option('default_customer_view')
484     || $conf->config('cust_main-default_view')
485     || 'basics'; #s/jumbo/basics/ starting with 3.0
486
487 }
488
489 =item spreadsheet_format [ OVERRIDE ]
490
491 Returns a hashref of this user's Excel spreadsheet download settings:
492 'extension' (xls or xlsx), 'class' (Spreadsheet::WriteExcel or
493 Excel::Writer::XLSX), and 'mime_type'.  If OVERRIDE is 'XLS' or 'XLSX',
494 use that instead of the user's setting.
495
496 =cut
497
498 # is there a better place to put this?
499 my %formats = (
500   XLS => {
501     extension => '.xls',
502     class => 'Spreadsheet::WriteExcel',
503     mime_type => 'application/vnd.ms-excel',
504   },
505   XLSX => {
506     extension => '.xlsx',
507     class => 'Excel::Writer::XLSX',
508     mime_type => # it's on wikipedia, it must be true
509       'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
510   }
511 );
512
513 sub spreadsheet_format {
514   my $self = shift;
515   my $override = shift;
516
517   my $f =  $override
518         || $self->option('spreadsheet_format') 
519         || $conf->config('spreadsheet_format')
520         || 'XLS';
521
522   $formats{$f};
523 }
524
525 =item is_system_user
526
527 Returns true if this user has the name of a known system account.  These 
528 users cannot log into the web interface and can't have passwords set.
529
530 =cut
531
532 sub is_system_user {
533   my $self = shift;
534   return grep { $_ eq $self->username } ( qw(
535     fs_queue
536     fs_daily
537     fs_selfservice
538     fs_signup
539     fs_bootstrap
540     fs_selfserv
541   ) );
542 }
543
544 =item change_password NEW_PASSWORD
545
546 =cut
547
548 sub change_password {
549   #my( $self, $password ) = @_;
550   #FS::Auth->auth_class->change_password( $self, $password );
551   FS::Auth->auth_class->change_password( @_ );
552 }
553
554 =item change_password_fields NEW_PASSWORD
555
556 =cut
557
558 sub change_password_fields {
559   #my( $self, $password ) = @_;
560   #FS::Auth->auth_class->change_password_fields( $self, $password );
561   FS::Auth->auth_class->change_password_fields( @_ );
562 }
563
564 =back
565
566 =head1 BUGS
567
568 =head1 SEE ALSO
569
570 L<FS::Record>, schema.html from the base documentation.
571
572 =cut
573
574 1;
575