summaryrefslogtreecommitdiff
path: root/FS/FS/part_export/magicmail.pm
blob: ba76609ce9b2955edc5bb39041ad64a434bfad54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
package FS::part_export::magicmail;

use strict;

use base qw( FS::part_export );

use Data::Dumper;
use MIME::Base64;

use Net::HTTPS::Any qw( https_get https_post );
use XML::Simple;
use URI::Escape;

use FS::Record qw (qsearch);

use vars qw( $DEBUG );
$DEBUG = 0;

=pod

=head1 NAME

FS::part_export::magicmail

=head1 SYNOPSIS

MagicMail integration for Freeside

=head1 REQUIRES

L<Net::HTTPS::Any>

L<XML::Simple>

L<URI::Escape>

=head1 DESCRIPTION

This export offers basic svc_acct provisioning for MagicMail.  Each customer will
map to an account in MagicMail, and each svc_acct exported will map to a user/mailbox.

This module also provides generic methods for working through the MagicMail API, and can
be used as a base for more complex exports to MagicMail (just be sure to override
the C<%info> hash and the L</Hook Methods>.)

L</Hook Methods> return an error message on failure, and a blank string on success.
All other methods return a positive value (usually a hashref) on success and return
nothing on failure, instead setting the error message in the export object using 
L</Error Methods>.  Use L</error> to retrieve this message.

=cut

use vars qw( %info );

tie my %options, 'Tie::IxHash',
  'client_id'        => { label => 'API Client ID',
                          default => '' },
  'client_password'  => { label => 'API Client Password',
                          default => '' },
  'account_prefix'   => { label => 'Account Prefix',
                          default => 'FREESIDE' },
  'package'          => { label => 'Package',
                          default => 'EMAIL' },
  'port'             => { label => 'Port',
                          default => 443 },
  'autopurge'        => { type => 'checkbox',
                          label => 'Auto purge user/account on unprovision' },
  'use_agent_custid' => { type => 'checkbox',
                          label => 'Use agent_custid for Magicmail account_id when available' },
  'debug'            => { type => 'checkbox',
                          label => 'Enable debug warnings' },
;

%info = (
  'svc'             => 'svc_acct',
  'desc'            => 'Export service to MagicMail, for svc_acct services',
  'options'         => \%options,
  'notes'           => <<'END',
Add service user and email address to MagicMail<BR>
See <A HREF="http://www.freeside.biz/mediawiki/index.php/Freeside:4:Documentation:MagicMail">documentation</A> for details.
END
);

=head1 Hook Methods

=cut

=head2 _export_insert

Hook that is called when service is initially provisioned.
To avoid confusion, don't use for anything else.

For this export, creates a MagicMail account for this customer
if it doesn't exist, activates account if it is suspended/deleted,
creates a user/mailbox on that account for the provisioning service, 
assigns I<package> (specified by export option) to master user on 
account if it hasn't been, and adds the email address for the 
provisioning service.  On error, attempts to purge any newly 
created account/user and remove any newly set package via L</rollback>.

On success, also runs L</sync_magic_packages> (does not cause fatal
error on failure.)

Override this method when using this module as a base for other exports.

=cut

sub _export_insert {
  my ($self, $svc_acct) = @_;
  $self->error_init;
  my $cust_main = $svc_acct->cust_main;
  my $username = $svc_acct->username;
  my $r = {}; #rollback input

  # create customer account if it doesn't exist
  my $newacct = 0;
  my $account_id = $self->cust_account_id($cust_main);
  my $account = $self->get_account($account_id);
  return $self->error if $self->error;
  unless ($account) {
    $account = $self->add_account($account_id,
      'first_name' => $cust_main->first,
      'last_name'  => $cust_main->last,
      # could also add phone & memo
    );
    return $self->error if $self->error;
    $account_id = $account->{'id'};
    $$r{'purge_account'} = $account_id;
  }

  # activate account if suspended/deleted
  my $oldstatus = $account->{'status'};
  unless ($oldstatus eq 'active') {
    $account = $self->activate_account($account_id);
  }
  return $self->rollback($r) if $self->error;
  $$r{'delete_account'} = $account_id
    if $oldstatus eq 'deleted';
  $$r{'suspend_account'} = $account_id
    if $oldstatus eq 'suspended';

  # check for a master user, assign package if found
  my $package = $self->option('package');
  my $muser = $self->get_master_user($account_id);
  return $self->rollback($r) if $self->error;
  if ($muser) {
    my $musername = $muser->{'id'};
    my $packages = $self->get_packages($musername);
    return $self->rollback($r) if $self->error || !$packages;
    unless ($packages->{$package}) {
      $packages = $self->assign_package($musername,$package);
      return $self->rollback($r) if $self->error || !$packages || !$packages->{$package};
      $$r{'remove_package'} = [$musername,$package];
    }
  }

  # add user
  my ($first,$last) = $svc_acct->finger =~ /(.*)\s(.*)/;
  $first ||= $svc_acct->finger || '';
  $last  ||= '';
  my $user = $self->add_user($account_id,$username,
    'first_name'    => $first,
    'last_name'     => $last,
    'password'      => $svc_acct->_password_encryption eq 'plain'
                       ? $svc_acct->get_cleartext_password
                       : $svc_acct->_password,
    'password_type' => $svc_acct->_password_encryption eq 'plain'
                       ? 'plain'
                       : 'encrypted',
    # could also add memo
  );
  return $self->rollback($r) if $self->error;
  $$r{'purge_user'} = $username;

  # assign package if it hasn't been yet
  unless ($muser) {
    die "Unexpected lack of master user on account, please contact a developer"
      unless $user->{'master_user'} eq 'Y';
    $muser = $user;
    # slight false laziness with above
    my $musername = $muser->{'id'};
    my $packages = $self->get_packages($musername);
    return $self->rollback($r) if $self->error || !$packages;
    unless ($packages->{$package}) {
      $packages = $self->assign_package($musername,$package);
      return $self->rollback($r) if $self->error || !$packages || !$packages->{$package};
      $$r{'remove_package'} = [$musername,$package];
    }
  }

  # add email address
  $self->add_email_address($username,$username.'@'.$svc_acct->domain);
  return $self->rollback($r) if $self->error;

  # double-check packages (only throws warnings, no rollback on fail)
  $self->sync_magic_packages($cust_main, 'include' => $svc_acct);

  return '';
}

=head2 _export_delete

Hook that is called when service is unprovisioned.
To avoid confusion, don't use for anything else.

For this export, deletes the email address and user
associated with the provisioning service.  Only sets
an error if this part fails;  everything else simply
generates warnings.

Also attempts to delete the associated account, if there 
aren't any more users on the account.

If deleted user was master user for account and other 
users exist on the account, attempts to make another user 
the master user.

Runs L</sync_magic_packages>.

If the I<autopurge> export option is set, also purges 
newly deleted users/accounts.

Override this method when using this module as a base for other exports.

=cut

sub _export_delete {
  my ($self, $svc_acct) = @_;
  $self->error_init;
  my $cust_main = $svc_acct->cust_main;
  my $username = $svc_acct->username;

  # check account id
  my $user = $self->get_user($username);
  unless ($user) {
    $self->error("Could not remove user from magicmail, username $username not retrievable");
    $self->error_warn;
    return ''; #non-fatal error, allow svc to be unprovisioned
  }
  my $account_id = $user->{'account'};
  return $self->error("Could not remove user from magicmail, account id does not match")
    unless $account_id eq $self->cust_account_id($cust_main); #fatal, sort out before unprovisioning
  
  # check for master change
  my $newmaster;
  if ($user->{'master_user'}) {
    my $users = $self->get_users($account_id);
    if ($users && (keys %$users > 1)) {
      foreach my $somesvc (
        sort { $a->svcnum <=> $b->svcnum } # cheap way of ordering by provision date
          $self->cust_magic_services($cust_main,'ignore'=>$svc_acct)
      ) {
        next unless $users->{uc($somesvc->username)};
        $newmaster = $somesvc->username;
        last;
      }
      $self->error("Cannot find replacement master user for account $account_id")
        unless $newmaster;
    }
    $self->error_warn; #maybe this should be fatal?
  }

  # do the actual deleting
  $self->delete_user($username);
  return $self->error if $self->error;

  ## no fatal errors after this point

  # transfer master user
  $self->make_master_user($newmaster) if $newmaster;
  $self->error_warn;
  $self->sync_magic_packages($cust_main, 'ignore' => $svc_acct);

  # purge user if configured to do so
  $self->purge_user($username) if $self->option('autopurge');
  $self->error_warn;

  # delete account if there are no more users
  my $users = $self->get_users($account_id);
  $self->error_warn;
  return '' unless $users;
  return '' if keys %$users;
  $self->delete_account($account_id);
  return $self->error_warn if $self->error;

  #purge account if configured to do so
  $self->purge_account($account_id) if $self->option('autopurge');
  return $self->error_warn;
}

=head2 _export_replace

Hook that is called when provisioned service is edited.
To avoid confusion, don't use for anything else.

Updates user info & password.  Cannot be used to change user name.

Override this method when using this module as a base for other exports.

=cut

sub _export_replace {
  my($self, $new, $old) = @_;
  $self->error_init;
  my $username = $new->username;

  return "Cannot change username on a magicmail account"
    unless $username eq $old->username;

  # check account id
  my $user = $self->get_user($username);
  return $self->error("Could not update user, username $username not retrievable")
    unless $user;
  my $account_id = $user->{'account'};
  return $self->error("Could not update user $username, account id does not match")
    unless $account_id eq $self->cust_account_id($new); #fatal, sort out before updating

  # update user
  my ($first,$last) = $new->finger =~ /(.*)\s(.*)/;
  $first ||= $new->finger || '';
  $last  ||= '';
  $user = $self->update_user($account_id,$username,
    'first_name'    => $first,
    'last_name'     => $last,
    'password'      => $new->_password_encryption eq 'plain'
                       ? $new->get_cleartext_password
                       : $new->_password,
    'password_type' => $new->_password_encryption eq 'plain'
                       ? 'plain'
                       : 'encrypted',
    # could also add memo
  );
  return $self->error;
}

=head2 _export_suspend

Hook that is called when service is suspended.
To avoid confusion, don't use for anything else.

=cut

sub _export_suspend {
  my ($self, $svc_acct) = @_;
  $self->error_init;
  my $username = $svc_acct->username;

  # check account id
  my $user = $self->get_user($username);
  return $self->error("Could not update user, username $username not retrievable")
    unless $user;
  my $account_id = $user->{'account'};
  return $self->error("Could not update user $username, account id does not match")
    unless $account_id eq $self->cust_account_id($svc_acct); #fatal, sort out before updating

  #suspend user
  $self->suspend_user($username);
  return $self->error;
}

=head2 _export_unsuspend

Hook that is called when service is unsuspended.
To avoid confusion, don't use for anything else.

=cut

sub _export_unsuspend {
  my ($self, $svc_acct) = @_;
  $self->error_init;
  my $username = $svc_acct->username;

  # check account id
  my $user = $self->get_user($username);
  return $self->error("Could not update user, username $username not retrievable")
    unless $user;
  my $account_id = $user->{'account'};
  return $self->error("Could not update user $username, account id does not match")
    unless $account_id eq $self->cust_account_id($svc_acct); #fatal, sort out before updating

  #suspend user
  $self->activate_user($username);
  return $self->error;
}

=head1 Freeside Methods

These methods are specific to freeside, used to translate 
freeside customers/services/exports
into magicmail accounts/users/packages.

=head2 cust_account_id

Accepts either I<$cust_main> or I<$svc_acct>.
Returns MagicMail account_id for this customer under this export.

=cut

sub cust_account_id {
  my ($self, $in) = @_;
  my $cust_main = ref($in) eq 'FS::cust_main' ? $in : $in->cust_main;
  return $self->option('account_prefix').
         ( ($self->option('use_agent_custid') && $cust_main->agent_custid)
             ? $cust_main->agent_custid
             : $cust_main->custnum
         );
}

=head2 cust_magic_services

Accepts I<$cust_main> or I<$svc_acct> and the following options:

I<ignore> - I<$svc_acct> to be ignored

I<include> - I<$svc_acct> to be included

Returns a list services owned by the customer
that are provisioned in MagicMail with the same I<account_prefix>
(not necessarily the same export.)

I<include> is not checked for compatability with the current 
export.  It will probably cause errors if you pass a service
that doesn't use the current export.

=cut

sub cust_magic_services {
  my ($self, $in, %opt) = @_;
  my $cust_main = ref($in) eq 'FS::cust_main' ? $in : $in->cust_main;
  my @out = 
    grep {
      $opt{'ignore'} ? ($_->svcnum != $opt{'ignore'}->svcnum) : 1;
    }
    map {
      qsearch('svc_acct', { 'svcnum' => $_->svcnum })
    }
    grep {
      grep {
        ($_->exporttype eq 'magicmail')
          && ($_->option('account_prefix') eq $self->option('account_prefix'))
      }
      map {
        qsearch('part_export',{ 'exportnum' => $_->exportnum })
      }
      qsearch('export_svc',{ 'svcpart' => $_->svcpart }) 
    }
    qsearch({
      'table' => 'cust_svc',
      'addl_from' => 'INNER JOIN cust_pkg ON (cust_svc.pkgnum = cust_pkg.pkgnum)',
      'hashref' => { 'cust_pkg.custnum' => $cust_main->custnum }
    }); #end of @out =
  push(@out,$opt{'include'})
    unless grep { $opt{'include'} ? ($_->svcnum == $opt{'include'}->svcnum) : 1 } @out;
  return @out;
}

=head2 cust_magic_packages

Accepts I<$cust_main> or I<$svc_acct> and the same options as L</cust_magic_services>.

Returns list of MagicMail packages for this customer's L</cust_magic_services>
(ie packages that the master user for this customer should have assigned to it.)

=cut

sub cust_magic_packages {
  my ($self, $in, %opt) = @_;
  my $out = {};
  my @svcs = $self->cust_magic_services($in);
  foreach my $svc ($self->cust_magic_services($in,%opt)) {
    # there really should only be one export per service, but loop just in case
    foreach my $export ( $svc->cust_svc->part_svc->part_export('magicmail') ) {
      $out->{$export->option('package')} = 1;
    }
  }
  return keys %$out;
}

=head2 sync_magic_packages

Accepts I<$cust_main> or I<$svc_acct> and the same options as L</cust_magic_services>.

Assigns or removes packages from the master user of L</cust_account_id> so
that they match L</cust_magic_packages>.  (Will only attempt to remove 
non-matching packages if matching packages are all successfully assigned.)

All errors will be immediately cleared by L</error_warn>.
No meaningful return value.

=cut

sub sync_magic_packages {
  my ($self, $in, %opt) = @_;
  my $cust_main = ref($in) eq 'FS::cust_main' ? $in : $in->cust_main;
  my $account_id = $self->cust_account_id($cust_main);
  my $muser = $self->get_master_user($account_id);
  return $self->error_warn if $self->error;
  return $self->error_warn("Could not find master user for account $account_id")
    unless $muser && $muser->{'id'};
  my $musername = $muser->{'id'};
  my $have = $self->get_packages($musername);
  return $self->error_warn if $self->error;
  my %dont = map { $_ => 1 } keys %$have;
  foreach my $want ($self->cust_magic_packages($cust_main,%opt)) {
    delete $dont{$want};
    $self->assign_package($musername,$want)
      unless $have->{$want};
  }
  return $self->error_warn if $self->error;
  foreach my $dont (keys %dont) {
    $self->remove_package($musername,$dont)
  }
  return $self->error_warn;
}

=head1 Helper Methods

These methods combine account, user and package information
through multiple API requests.

=head2 get_accounts_and_users

Returns results of L</get_accounts> with extra 'users' key for
each account, the value of which is the result of L</get_users>
for that account.

=cut

sub get_accounts_and_users {
  my ($self) = @_;
  my $accounts = $self->get_accounts() or return;
  foreach my $account (keys %$accounts) {
    $accounts->{$account}->{'users'} = $self->get_users($account) or return;
  }
  return $accounts;
}

=head2 get_master_user

Accepts I<$account_id>.  Returns hashref of details on master user
for that account (as would be returned by L</get_user>.)
Returns nothing without setting error if master user is not found.

=cut

sub get_master_user {
  my ($self,$account_id) = @_;
  my $users = $self->get_users($account_id);
  return if $self->error || !$users;
  foreach my $username (keys %$users) {
    if ($users->{$username}->{'master_user'} eq 'Y') {
      $users->{$username}->{'id'} = $username;
      return $users->{$username};
    }
  }
  return;
}

=head2 request

	#send a request to https://machine/api/v2/some/function
	my $result = $export->request('POST','/some/function',%args);

Accepts I<$method>, I<$path> and optional I<%args>.  Sends request
to server and returns server response as a hashref (converted from
XML by L<XML::Simple>.)  I<%args> can include a ForceArray key that 
will be passed to L<XML::Simple/XMLin>;  all other args will be
passed in the reqest.  Do not include 'client_type' in I<%args>,
and do not include '/api/v2' in I<$path>.

Used by other methods to send requests;  unless you're editing
this module, you should probably be using those other methods instead.

=cut

sub request {
  my ($self,$method,$path,%args) = @_;
  local $Data::Dumper::Terse = 1;
  unless (grep(/^$method$/,('GET','POST'))) {
    return if $self->error("Can't request method $method");
  }
  my $get = $method eq 'GET';
  my $forcearray = [];
  if (exists $args{'ForceArray'}) {
    $forcearray = delete $args{'ForceArray'};
  }
  $args{'client_type'} = 'FREESIDE';
  my %request = (
    'host'    => $self->machine,
    'port'    => $self->option('port'),
    'path'    => '/api/v2' . $path,
    'headers' => { 
      'Authorization' => 'Basic ' . MIME::Base64::encode(
                                      $self->option('client_id') 
                                      . ':' 
                                      . $self->option('client_password'),
                                    ''),
    },
  );
  my ( $page, $response, %reply_headers );
  if ($get) {
    my $pathargs = '';
    foreach my $field (keys %args) {
      $pathargs .= $pathargs ? '&' : '?';
      $pathargs .= $field . '=' . uri_escape_utf8($args{$field});
    }
    $request{'path'} .= $pathargs;
    warn "Request = " . Dumper(\%request) if $self->debug;
    ( $page, $response, %reply_headers ) = https_get(%request);
  } else {
    foreach my $field (keys %args) {
      $request{'content'} .= '&' if $request{'content'};
      $request{'content'} .= $field . '=' . uri_escape_utf8($args{$field});
    }
    warn "Request = " . Dumper(\%request) if $self->debug;
    ( $page, $response, %reply_headers ) = https_post(%request);
  }
  unless ($response =~ /^(200|400|500)/) {
    return if $self->error("Bad Response: $response");
  }
  warn "Response = " . Dumper($page) if $self->debug;
  my $result = $page ? XMLin($page, ForceArray => $forcearray) : {};
  warn "Result = " . Dumper($result) if $self->debug;
  return $result;
}

=head1 Account Methods

Make individual account-related API requests.

=head2 add_account

Accepts I<$account_id> and the following options:

I<first_name>

I<last_name>

I<phone>

I<memo>

Returns a hashref containing the created account details.

=cut

sub add_account {
  my ($self,$id,%opt) = @_;
  warn "CREATING ACCOUNT $id\n" if $self->debug;
  my %args;
  foreach my $field ( qw( first_name last_name phone memo ) ) {
    $args{$field} = $opt{$field} if $opt{$field};
  }
  my $result = $self->request('POST', '/account/'.uri_escape_utf8($id), %args );
  return if $self->check_for_error($result);
  return $result->{'account'};
}

=head2 get_account

Accepts I<$account_id>.
Returns a hashref containing account details.  
Returns nothing without setting error if account is not found.

=cut

sub get_account {
  my ($self,$id) = @_;
  warn "GETTING ACCOUNT $id\n" if $self->debug;
  my $result = $self->request('GET','/account/'.uri_escape_utf8($id));
  if ($result->{'error'}) {
    return if $result->{'error'}->{'code'} eq 'account.error.not_found';
  }
  return if $self->check_for_error($result);
  return $result->{'account'};
}

=head2 get_accounts

No input.  Returns a hashref, keys are account_id, values
are hashrefs of account details.

=cut

sub get_accounts {
  my ($self) = @_;
  warn "GETTING ALL ACCOUNTS\n" if $self->debug;
  my $result = $self->request('GET','/account','ForceArray' => ['account']);
  return if $self->check_for_error($result);
  return $result->{'accounts'}->{'account'} || {};
}

=head2 update_account

Accepts I<$account_id> and the same options as L</add_account>.
Updates an existing account.
Returns a hashref containing the updated account details.

=cut

sub update_account {
  my ($self,$id,%opt) = @_;
  warn "UPDATING ACCOUNT $id\n" if $self->debug;
  my %args;
  foreach my $field ( qw( first_name last_name phone memo ) ) {
    $args{$field} = $opt{$field} if $opt{$field};
  }
  my $result = $self->request('POST', '/account/'.uri_escape_utf8($id), %args, action => 'update' );
  return if $self->check_for_error($result);
  return $result->{'account'};
}

=head2 suspend_account

Accepts I<$account_id>.  Sets account status to suspended.
Returns a hashref containing the updated account details.

=cut

sub suspend_account {
  my ($self,$id) = @_;
  warn "SUSPENDING ACCOUNT $id\n" if $self->debug;
  my $result = $self->request('POST', '/account/'.uri_escape_utf8($id), status => 'suspended', action => 'update' );
  return if $self->check_for_error($result);
  return $result->{'account'};
}

=head2 activate_account

Accepts I<$account_id>.  Sets account status to active.
Returns a hashref containing the updated account details.

=cut

sub activate_account {
  my ($self,$id) = @_;
  warn "ACTIVATING ACCOUNT $id\n" if $self->debug;
  my $result = $self->request('POST', '/account/'.uri_escape_utf8($id), status => 'active', action => 'update' );
  return if $self->check_for_error($result);
  return $result->{'account'};
}

=head2 delete_account

Accepts I<$account_id>.  Sets account status to deleted.
Returns a hashref containing the updated account details.

=cut

sub delete_account {
  my ($self,$id) = @_;
  warn "DELETING ACCOUNT $id\n" if $self->debug;
  my $result = $self->request('POST', '/account/'.uri_escape_utf8($id), status => 'deleted', action => 'update' );
  return if $self->check_for_error($result);
  return $result->{'account'};
}

=head2 purge_account

Accepts account I<$id> and the following options:

I<force> - if true, purges account even if it wasn't first deleted

Purges account from system.
No meaningful return value.

=cut

sub purge_account {
  my ($self,$id,%opt) = @_;
  my %args;
  $args{'force'} = 'true' if $opt{'force'};
  warn "PURGING ACCOUNT $id\n" if $self->debug;
  my $result = $self->request('POST', '/account/'.uri_escape_utf8($id), %args, action => 'purge' );
  $self->check_for_error($result);
  return;
}

=head1 User Methods

Make individual user-related API requests.

=head2 add_user

Accepts I<$account_id>, I<$username> and the following options:

I<first_name>

I<last_name>

I<memo>

I<password>

I<password_type> - plain or encrypted

Returns a hashref containing the created user details.

=cut

sub add_user {
  my ($self,$account_id,$username,%opt) = @_;
  warn "CREATING USER $username FOR ACCOUNT $account_id\n" if $self->debug;
  my %args;
  foreach my $field ( qw( first_name last_name memo password password_type ) ) {
    $args{$field} = $opt{$field} if $opt{$field};
  }
  $args{'account'} = $account_id;
  unless ($account_id) {
    return if $self->error("Account ID required");
  }
  if ($args{'password_type'} && !grep(/$args{'password_type'}/,('plain','encrypted'))) {
    return if $self->error("Illegal password_type $args{'password_type'}");
  }
  my $result = $self->request('POST', '/user/'.uri_escape_utf8($username), %args );
  return if $self->check_for_error($result);
  return $result->{'user'};
}

=head2 get_user

Accepts I<$username>.
Returns a hashref containing user details.  
Returns nothing without setting error if user is not found.

=cut

sub get_user {
  my ($self,$username) = @_;
  warn "GETTING USER $username\n" if $self->debug;
  my $result = $self->request('GET','/user/'.uri_escape_utf8($username));
  if ($result->{'error'}) {
    return if $result->{'error'}->{'code'} eq 'account.error.not_found';
  }
  return if $self->check_for_error($result);
  return $result->{'user'};
}

=head2 get_users

Accepts I<$account_id>.  Returns a hashref, keys are username, values
are hashrefs of user details.

=cut

sub get_users {
  my ($self,$account_id) = @_;
  warn "GETTING ALL USERS FOR ACCOUNT $account_id\n" if $self->debug;
  my $result = $self->request('GET','/user','ForceArray' => ['user'],'account' => $account_id);
  return if $self->check_for_error($result);
  return $result->{'users'}->{'user'} || {};
}

=head2 update_user

Accepts I<$account_id>, I<$username> and the same options as L</add_user>.
Updates an existing user.
Returns a hashref containing the updated user details.

=cut

sub update_user {
  my ($self,$account_id,$username,%opt) = @_;
  warn "UPDATING USER $username\n" if $self->debug;
  my %args;
  foreach my $field ( qw( first_name last_name memo password password_type ) ) {
    $args{$field} = $opt{$field} if $opt{$field};
  }
  if ($args{'password_type'} && !grep(/$args{'password_type'}/,('plain','encrypted'))) {
    return if $self->error("Illegal password_type $args{'password_type'}");
  }
  $args{'account'} = $account_id;
  my $result = $self->request('POST', '/user/'.uri_escape_utf8($username), %args, action => 'update' );
  return if $self->check_for_error($result);
  return $result->{'user'};
}

=head2 make_master_user

Accepts I<$username>.  Sets user to be master user for account.
Returns a hashref containing the updated user details.

Caution: does not unmake existing master user.

=cut

sub make_master_user {
  my ($self,$username) = @_;
  warn "MAKING MASTER USER $username\n" if $self->debug;
  my $result = $self->request('POST', '/user/'.uri_escape_utf8($username),
    master_user => 'Y',
    action => 'update'
  );
  return if $self->check_for_error($result);
  return $result->{'user'};
}

=head2 suspend_user

Accepts I<$username>.  Sets user status to suspended.
Returns a hashref containing the updated user details.

=cut

sub suspend_user {
  my ($self,$username) = @_;
  warn "SUSPENDING USER $username\n" if $self->debug;
  my $result = $self->request('POST', '/user/'.uri_escape_utf8($username), status => 'suspended', action => 'update' );
  return if $self->check_for_error($result);
  return $result->{'user'};
}

=head2 activate_user

Accepts I<$username>.  Sets user status to active.
Returns a hashref containing the updated user details.

=cut

sub activate_user {
  my ($self,$username) = @_;
  warn "ACTIVATING USER $username\n" if $self->debug;
  my $result = $self->request('POST', '/user/'.uri_escape_utf8($username), status => 'active', action => 'update' );
  return if $self->check_for_error($result);
  return $result->{'user'};
}

=head2 delete_user

Accepts I<$username>.  Sets user status to deleted.
Returns a hashref containing the updated user details.

=cut

sub delete_user {
  my ($self,$username) = @_;
  warn "DELETING USER $username\n" if $self->debug;
  my $result = $self->request('POST', '/user/'.uri_escape_utf8($username), status => 'deleted', action => 'update' );
  return if $self->check_for_error($result);
  return $result->{'user'};
}

=head2 purge_user

Accepts I<$username> and the following options:

I<force> - if true, purges user even if it wasn't first deleted

Purges user from system.
No meaningful return value.

=cut

sub purge_user {
  my ($self,$username,%opt) = @_;
  my %args;
  $args{'force'} = 'true' if $opt{'force'};
  warn "PURGING USER $username\n" if $self->debug;
  my $result = $self->request('POST', '/user/'.uri_escape_utf8($username), %args, action => 'purge' );
  $self->check_for_error($result);
  return;
}

=head1 Package Methods

Make individual package-related API requests.

=head2 assign_package

Accepts I<$username> and I<$package>.  Assigns package to user.
Returns a hashref of packages assigned to this user, keys are package names
and values are hashrefs of details about those packages.  
Returns undef if none are found.

=cut

sub assign_package {
  my ($self,$username,$package) = @_;
  warn "ASSIGNING PACKAGE $package TO USER $username\n" if $self->debug;
  my $result = $self->request('POST', '/user_package/'.uri_escape_utf8($username), 
    'ForceArray' => ['package'], 
    'package' => $package,
  );
  return if $self->check_for_error($result);
  return $result->{'packages'}->{'package'};
}

=head2 get_packages

Accepts I<$username>.
Returns a hashref of packages assigned to this user, keys are package names
and values are hashrefs of details about those packages.

=cut

sub get_packages {
  my ($self,$username) = @_;
  warn "GETTING PACKAGES ASSIGNED TO USER $username\n" if $self->debug;
  my $result = $self->request('GET', '/user_package/'.uri_escape_utf8($username), 
    'ForceArray' => ['package'], 
  );
  return if $self->check_for_error($result);
  return $result->{'packages'}->{'package'} || {};
}

=head2 remove_package

Accepts I<$username> and I<$package>.  Removes package from user.
No meaningful return value.

=cut

sub remove_package {
  my ($self,$username,$package) = @_;
  warn "REMOVING PACKAGE $package FROM USER $username\n" if $self->debug;
  my $result = $self->request('POST', '/user_package/'.uri_escape_utf8($username),
    'package' => $package,
	'action' => 'purge'
  );
  $self->check_for_error($result);
  return;
}

=head1 Domain Methods

Make individual account-related API requests.

=cut

### DOMAIN METHODS HAVEN'T BEEN THOROUGLY TESTED, AREN'T CURRENTLY USED ###

=head2 add_domain

Accepts I<$account_id> and I<$domain>.  Creates domain for that account.

=cut

sub add_domain {
  my ($self,$account_id,$domain) = @_;
  warn "CREATING DOMAIN $domain FOR ACCOUNT $account_id\n" if $self->debug;
  my $result = $self->request('POST','/domain/'.uri_escape_utf8($domain), 'account' => $account_id);
  return if $self->check_for_error($result);
  return $result->{'domain'};
}

=head2 get_domain

Accepts I<$domain>.  Returns hasref of domain info if it exists,
or empty if it doesn't exist or permission denied.
Returns nothing without setting error if domain is not found.

=cut

sub get_domain {
  my ($self, $domain) = @_;
  warn "GETTING DOMAIN $domain\n" if $self->debug;
  my $result = $self->request('GET','/domain/'.uri_escape_utf8($domain));
  if ($result->{'error'}) {
    #unfortunately, no difference between 'does not exist' and true 'permission denied'
    return if $result->{'error'}->{'code'} eq 'error.permission_denied';
  }
  return if $self->check_for_error($result);
  return $result->{'domain'};
}

=head2 get_domains

Accepts I<$account_id>.  Returns hasref of domains for that account,
keys are domains, values are hashrefs of info about each domain.

=cut

sub get_domains {
  my ($self, $account_id) = @_;
  warn "GETTING DOMAINS FOR ACCOUNT $account_id\n" if $self->debug;
  my $result = $self->request('GET','/domain',
    'ForceArray' => ['domain'], 
    'account' => $account_id
  );
  return if $self->check_for_error($result);
  return $result->{'domains'}->{'domain'} || {};
}

=head2 remove_domain

Accepts I<$domain>.  Removes domain.
No meaningful return value.

=cut

sub remove_domain {
  my ($self,$domain) = @_;
  warn "REMOVING DOMAIN $domain\n" if $self->debug;
  my $result = $self->request('POST', '/domain/'.uri_escape_utf8($domain), action => 'purge');
  $self->check_for_error($result);
  return;
}

=head1 Email Address Methods

Make individual emailaddress-related API requests.

=head2 add_email_address

Accepts I<$username> and I<$address>.  Adds address for that user.
Returns hashref of details for new address.

=cut

sub add_email_address {
  my ($self, $username, $address) = @_;
  warn "ADDING ADDRESS $address FOR USER $username\n" if $self->debug;
  my $result = $self->request('POST','/emailaddress/'.uri_escape_utf8($address),
    'user' => $username
  );
  return if $self->check_for_error($result);
  return $result->{'emailaddress'};
}

=head2 get_email_address

Accepts I<$address>.  Returns hasref of address info if it exists,
or empty if it doesn't exist or permission denied.
Returns nothing without setting error if address is not found.

=cut

sub get_email_address {
  my ($self, $address) = @_;
  warn "GETTING ADDRESS $address\n" if $self->debug;
  my $result = $self->request('GET','/emailaddress/'.uri_escape_utf8($address));
  if ($result->{'error'}) {
    #unfortunately, no difference between 'does not exist' and true 'permission denied'
    return if $result->{'error'}->{'code'} eq 'error.permission_denied';
  }
  return if $self->check_for_error($result);
  return $result->{'emailaddress'};
}

=head2 get_email_addresses

Accepts I<$username>.  Returns hasref of email addresses for that account,
keys are domains, values are hashrefs of info about each domain.

=cut

sub get_email_addresses {
  my ($self, $username) = @_;
  warn "GETTING ADDRESSES FOR USER $username\n" if $self->debug;
  my $result = $self->request('GET','/emailaddress',
    'ForceArray' => ['emailaddress'], 
    'user' => $username,
  );
  return if $self->check_for_error($result);
  return $result->{'emailaddresses'}->{'emailaddress'} || {};
}

=head2 remove_email_address

Accepts I<$address>.  Removes address.
No meaningful return value.

=cut

sub remove_email_address {
  my ($self,$address) = @_;
  warn "REMOVING ADDRESS $address\n" if $self->debug;
  my $result = $self->request('POST', '/emailaddress/'.uri_escape_utf8($address), action => 'purge');
  $self->check_for_error($result);
  return;
}

=head1 Error Methods

Used to track errors during a request, for precision control over when
and how those errors are returned.

=head2 error

Accepts optional I<$message>, which will be appended to the internal error message on this
object if defined (use L</init_error> to clear the message.)  Returns current contents of 
internal error message on this object.

=cut

sub error {
  my ($self,$message) = @_;
  if (defined($message)) {
    $self->{'_error'} .= "\n" if $self->{'_error'};
    $self->{'_error'} .= $message;
  }
  return $self->{'_error'};
}

=head2 check_for_error

Accepts I<$result> returned by L</request>.  Sets error if I<$result>
does not exist or contains an error message.  Returns L</error>.

=cut

sub check_for_error {
  my ($self,$result) = @_;
  return $self->error("Unknown error, no result found")
    unless $result;
  return $self->error($result->{'error'}->{'code'} . ': ' . $result->{'error'}->{'message'})
    if $result->{'error'};
  return $self->error;
}

=head2 error_init

Resets error message in object to blank string.
Should only be used at the start of L</Hook Methods>.
No meaningful return value.

=cut

sub error_init {
  my ($self) = @_;
  $self->{'_error'} = '';
  return;
}

=head2 error_warn

Accepts optional I<$message>, which will be appended to the internal error message on this
object if defined.

Outputs L</error> (if there is one) using warn, then runs L</error_init>.
Returns blank string.

=cut

sub error_warn {
  my $self = shift;
  my $message = shift;
  $self->error($message) if defined($message);
  warn $self->error if $self->error;
  $self->error_init;
  return '';
}

=head2 debug

Returns true if debug is set, either as an export option or in the module code.

=cut

sub debug {
  my $self = shift;
  return $DEBUG || $self->option('debug');
}

=head2 rollback

Accepts hashref with the following fields, use for undoing recent changes:

I<remove_package> - arrayref of username and package to remove

I<purge_user> - username to be forcefully purged

I<suspend_account> - account_id to be suspended

I<delete_account> - account_id to be deleted

I<purge_account> - account_id to be forcefully purged

Indicated actions will be performed in the order listed above.
Sets generic error message if no message is found, and returns L</error>.

=cut

sub rollback {
  my ($self,$r) = @_;
  $self->error('Unknown error') unless $self->error;
  $self->remove_package(@{$$r{'remove_package'}}) if $$r{'remove_package'};
  $self->purge_user($$r{'purge_user'}, 'force' => 1) if $$r{'purge_user'};
  $self->suspend_account($$r{'suspend_account'}) if $$r{'suspend_account'};
  $self->delete_account($$r{'delete_account'}) if $$r{'delete_account'};
  $self->purge_account($$r{'purge_account'}, 'force' => 1) if $$r{'purge_account'};
  return $self->error;
}

=head1 SEE ALSO

L<FS::part_export>

=head1 AUTHOR

Jonathan Prykop 
jonathan@freeside.biz

=cut

1;