first part of ACL and re-skinning work and some other small stuff
[freeside.git] / FS / FS / m2m_Common.pm
1 package FS::m2m_Common;
2
3 use strict;
4 use vars qw( @ISA $DEBUG );
5 use FS::Schema qw( dbdef );
6 use FS::Record qw( qsearch qsearchs ); #dbh );
7
8 @ISA = qw( FS::Record );
9
10 $DEBUG = 0;
11
12 =head1 NAME
13
14 FS::m2m_Common - Base class for classes in a many-to-many relationship
15
16 =head1 SYNOPSIS
17
18 use FS::m2m_Common;
19
20 @ISA = qw( FS::m2m_Common );
21
22 =head1 DESCRIPTION
23
24 FS::m2m_Common is intended as a base class for classes which have a
25 many-to-many relationship with another table (via a linking table).
26
27 Note: It is currently assumed that the link table contains two fields
28 named the same as the primary keys of ths base and target tables.
29
30 =head1 METHODS
31
32 =over 4
33
34 =item process_m2m
35
36 =cut
37
38 sub process_m2m {
39   my( $self, %opt ) = @_;
40
41   my $self_pkey = $self->dbdef_table->primary_key;
42
43   my $link_table = $self->_load_table($opt{'link_table'});
44
45   my $target_table = $self->_load_table($opt{'target_table'});
46   my $target_pkey = dbdef->table($target_table)->primary_key;
47
48   foreach my $target_obj ( qsearch($target_table, {} ) ) {
49
50     my $targetnum = $target_obj->$target_pkey();
51
52     my $link_obj = qsearchs( $link_table, {
53         $self_pkey   => $self->$self_pkey(),
54         $target_pkey => $targetnum,
55     });
56
57     if ( $link_obj && ! $opt{'params'}->{"$target_pkey$targetnum"} ) {
58
59       my $d_link_obj = $link_obj; #need to save $link_obj for below.
60       my $error = $d_link_obj->delete;
61       die $error if $error;
62
63     } elsif ( $opt{'params'}->{"$target_pkey$targetnum"} && ! $link_obj ) {
64
65       #ok to clobber it now (but bad form nonetheless?)
66       #$link_obj = new "FS::$link_table" ( {
67       $link_obj = "FS::$link_table"->new( {
68         $self_pkey   => $self->$self_pkey(),
69         $target_pkey => $targetnum,
70       });
71       my $error = $link_obj->insert;
72       die $error if $error;
73     }
74
75   }
76
77   '';
78 }
79
80 sub _load_table {
81   my( $self, $table ) = @_;
82   eval "use FS::$table";
83   die $@ if $@;
84   $table;
85 }
86
87 #=item target_table
88 #
89 #=cut
90 #
91 #sub target_table {
92 #  my $self = shift;
93 #  my $target_table = $self->_target_table;
94 #  eval "use FS::$target_table";
95 #  die $@ if $@;
96 #  $target_table;
97 #}
98
99 =back
100
101 =head1 BUGS
102
103 =head1 SEE ALSO
104
105 L<FS::Record>
106
107 =cut
108
109 1;
110