8d0ed7e0c74e015c3ff382659a972ed762accde0
[kivitendo-erp.git] / SL / DB / Helper / Mappings.pm
1 package SL::DB::Helper::Mappings;
2
3 use utf8;
4 use strict;
5
6 use SL::Util qw(camelify);
7
8 require Exporter;
9 our @ISA       = qw(Exporter);
10 our @EXPORT_OK = qw(get_table_for_package get_package_for_table get_package_names);
11
12 # these will not be managed as Rose::DB models, because they are not normalized,
13 # significant changes are needed to get them done, or they were done by CRM.
14 my @kivitendo_blacklist_permanent = qw(
15   leads
16 );
17
18 # these are not managed _yet_, but will hopefully at some point.
19 # if you are confident that one of these works, remove it here.
20 my @kivitendo_blacklist_temp = qw(
21 );
22
23 # tables created by crm module
24 my @crm_blacklist = qw(
25   blz_data
26   bundesland
27   contmasch
28   contract
29   crm
30   crmdefaults
31   crmemployee
32   custmsg
33   docfelder
34   documents
35   documenttotc
36   docvorlage
37   extra_felder
38   geodb_changelog
39   geodb_coordinates
40   geodb_floatdata
41   geodb_hierarchies
42   geodb_intdata
43   geodb_locations
44   geodb_textdata
45   geodb_type_names
46   grpusr
47   gruppenname
48   history
49   labels
50   labeltxt
51   mailvorlage
52   maschine
53   maschmat
54   opport_status
55   opportunity
56   postit
57   repauftrag
58   telcall
59   telcallhistory
60   telnr
61   tempcsvdata
62   termdate
63   termincat
64   termine
65   terminmember
66   timetrack
67   tt_event
68   tt_parts
69   wiedervorlage
70   wissencategorie
71   wissencontent
72 );
73
74 # tables created by cash register
75 my @cash_register_blacklist = qw(
76 ekartikel ekbon ekkunde ektext erptasten
77 );
78
79 my @kivitendo_blacklist = (@kivitendo_blacklist_permanent, @kivitendo_blacklist_temp, @crm_blacklist, @cash_register_blacklist);
80
81 # map table names to their models.
82 # unlike rails we have no singular<->plural magic.
83 # remeber: tables should be named as the plural of the model name.
84 my %kivitendo_package_names = (
85   # TABLE                           # MODEL (given in C style)
86   acc_trans                      => 'acc_transaction',
87   additional_billing_addresses   => 'additional_billing_address',
88   'auth.clients'                 => 'auth_client',
89   'auth.clients_users'           => 'auth_client_user',
90   'auth.clients_groups'          => 'auth_client_group',
91   'auth.group'                   => 'auth_group',
92   'auth.group_rights'            => 'auth_group_right',
93   'auth.master_rights'           => 'auth_master_right',
94   'auth.schema_info'             => 'auth_schema_info',
95   'auth.session'                 => 'auth_session',
96   'auth.session_content'         => 'auth_session_content',
97   'auth.user'                    => 'auth_user',
98   'auth.user_config'             => 'auth_user_config',
99   'auth.user_group'              => 'auth_user_group',
100   ar                             => 'invoice',
101   ap                             => 'purchase_invoice',
102   ap_gl                          => 'ap_gl',
103   assembly                       => 'assembly',
104   assortment_items               => 'assortment_item',
105   background_jobs                => 'background_job',
106   background_job_histories       => 'background_job_history',
107   ap                             => 'purchase_invoice',
108   bank_accounts                  => 'bank_account',
109   bank_transactions              => 'bank_transaction',
110   bank_transaction_acc_trans     => 'bank_transaction_acc_trans',
111   buchungsgruppen                => 'buchungsgruppe',
112   bin                            => 'bin',
113   business                       => 'business',
114   chart                          => 'chart',
115   contact_departments            => 'contact_department',
116   contact_titles                 => 'contact_title',
117   contacts                       => 'contact',
118   customer                       => 'customer',
119   csv_import_profiles            => 'csv_import_profile',
120   csv_import_profile_settings    => 'csv_import_profile_setting',
121   csv_import_reports             => 'csv_import_report',
122   csv_import_report_rows         => 'csv_import_report_row',
123   csv_import_report_status       => 'csv_import_report_status',
124   currencies                     => 'currency',
125   custom_data_export_queries     => 'CustomDataExportQuery',
126   custom_data_export_query_parameters => 'CustomDataExportQueryParameter',
127   custom_variable_config_partsgroups => 'custom_variable_config_partsgroup',
128   custom_variable_configs        => 'custom_variable_config',
129   custom_variables               => 'custom_variable',
130   custom_variables_validity      => 'custom_variable_validity',
131   datev                          => 'datev',
132   defaults                       => 'default',
133   delivery_orders                => 'delivery_order',
134   delivery_order_items           => 'delivery_order_item',
135   delivery_order_items_stock     => 'delivery_order_items_stock',
136   delivery_terms                 => 'delivery_term',
137   department                     => 'department',
138   drafts                         => 'draft',
139   dunning                        => 'dunning',
140   dunning_config                 => 'dunning_config',
141   email_journal                  => 'EmailJournal',
142   email_journal_attachments      => 'EmailJournalAttachment',
143   employee                       => 'employee',
144   employee_project_invoices      => 'EmployeeProjectInvoices',
145   exchangerate                   => 'exchangerate',
146   files                          => 'file',
147   finanzamt                      => 'finanzamt',
148   follow_up_access               => 'follow_up_access',
149   follow_up_links                => 'follow_up_link',
150   follow_ups                     => 'follow_up',
151   generic_translations           => 'generic_translation',
152   gl                             => 'GLTransaction',
153   greetings                      => 'greeting',
154   history_erp                    => 'history',
155   inventory                      => 'inventory',
156   invoice                        => 'invoice_item',
157   language                       => 'language',
158   letter                         => 'letter',
159   letter_draft                   => 'letter_draft',
160   makemodel                      => 'make_model',
161   notes                          => 'note',
162   orderitems                     => 'order_item',
163   oe                             => 'order',
164   parts                          => 'part',
165   partsgroup                     => 'parts_group',
166   part_classifications           => 'PartClassification',
167   part_customer_prices           => 'PartCustomerPrice',
168   parts_price_history            => 'PartsPriceHistory',
169   payment_terms                  => 'payment_term',
170   periodic_invoices              => 'periodic_invoice',
171   periodic_invoices_configs      => 'periodic_invoices_config',
172   prices                         => 'price',
173   price_factors                  => 'price_factor',
174   price_rules                    => 'price_rule',
175   price_rule_items               => 'price_rule_item',
176   pricegroup                     => 'pricegroup',
177   printers                       => 'printer',
178   project                        => 'project',
179   project_participants           => 'project_participant',
180   project_phase_participants     => 'project_phase_participant',
181   project_phases                 => 'project_phase',
182   project_roles                  => 'project_role',
183   project_statuses               => 'project_status',
184   project_types                  => 'project_type',
185   reconciliation_links           => 'reconciliation_link',
186   record_links                   => 'record_link',
187   record_templates               => 'record_template',
188   record_template_items          => 'record_template_item',
189   requirement_spec_acceptance_statuses => 'RequirementSpecAcceptanceStatus',
190   requirement_spec_complexities        => 'RequirementSpecComplexity',
191   requirement_spec_item_dependencies   => 'RequirementSpecDependency',
192   requirement_spec_items               => 'RequirementSpecItem',
193   requirement_spec_orders              => 'RequirementSpecOrder',
194   requirement_spec_parts               => 'RequirementSpecPart',
195   requirement_spec_pictures            => 'RequirementSpecPicture',
196   requirement_spec_predefined_texts    => 'RequirementSpecPredefinedText',
197   requirement_spec_risks               => 'RequirementSpecRisk',
198   requirement_spec_statuses            => 'RequirementSpecStatus',
199   requirement_spec_text_blocks         => 'RequirementSpecTextBlock',
200   requirement_spec_types               => 'RequirementSpecType',
201   requirement_spec_versions            => 'RequirementSpecVersion',
202   requirement_specs                    => 'RequirementSpec',
203   sepa_export                    => 'sepa_export',
204   sepa_export_items              => 'sepa_export_item',
205   sepa_export_message_ids        => 'SepaExportMessageId',
206   schema_info                    => 'schema_info',
207   shipto                         => 'shipto',
208   shops                          => 'shop',
209   shop_images                    => 'shop_image',
210   shop_orders                    => 'shop_order',
211   shop_order_items               => 'shop_order_item',
212   shop_parts                     => 'shop_part',
213   status                         => 'status',
214   stocktakings                   => 'stocktaking',
215   tax                            => 'tax',
216   taxkeys                        => 'tax_key',
217   tax_zones                      => 'tax_zone',
218   taxzone_charts                 => 'taxzone_chart',
219   time_recording_articles        => 'time_recording_article',
220   time_recordings                => 'time_recording',
221   todo_user_config               => 'todo_user_config',
222   transfer_type                  => 'transfer_type',
223   translation                    => 'translation',
224   trigger_information            => 'trigger_information',
225   units                          => 'unit',
226   units_language                 => 'units_language',
227   user_preferences               => 'user_preference',
228   vendor                         => 'vendor',
229   warehouse                      => 'warehouse',
230 );
231
232 my (%kivitendo_tables_to_packages, %kivitendo_tables_to_manager_packages, %kivitendo_packages_to_tables);
233
234 sub get_blacklist {
235   return KIVITENDO => \@kivitendo_blacklist;
236 }
237
238 sub get_package_names {
239   return KIVITENDO => \%kivitendo_package_names;
240 }
241
242 sub get_name_for_table {
243   return $kivitendo_package_names{ $_[0] };
244 }
245
246 sub get_package_for_table {
247   %kivitendo_tables_to_packages = map { ($_ => "SL::DB::" . camelify($kivitendo_package_names{$_})) } keys %kivitendo_package_names
248     unless %kivitendo_tables_to_packages;
249
250   return $kivitendo_tables_to_packages{ $_[0] };
251 }
252
253 sub get_manager_package_for_table {
254   %kivitendo_tables_to_manager_packages = map { ($_ => "SL::DB::Manager::" . camelify($kivitendo_package_names{$_})) } keys %kivitendo_package_names
255     unless %kivitendo_tables_to_manager_packages;
256
257   return $kivitendo_tables_to_manager_packages{ $_[0] };
258 }
259
260 sub get_table_for_package {
261   get_package_for_table('dummy') if !%kivitendo_tables_to_packages;
262   %kivitendo_packages_to_tables = reverse %kivitendo_tables_to_packages unless %kivitendo_packages_to_tables;
263
264   my $package = $_[0] =~ m/^SL::DB::/ ? $_[0] : "SL::DB::" . $_[0];
265   return $kivitendo_packages_to_tables{ $package };
266 }
267
268 sub db {
269   my $string = $_[0];
270   my $lookup = $kivitendo_package_names{$_[0]} ||
271       plurify($kivitendo_package_names{singlify($_[0])});
272
273   for my $thing ($string, $lookup) {
274
275     # best guess? its already the name. like part. camelize it first
276     my $class = "SL::DB::" . camelify($thing);
277     return $class if defined *{ $class. '::' };
278
279     # next, someone wants a manager and pluralized.
280     my $manager = "SL::DB::Manager::" . singlify(camelify($thing));
281     return $manager if defined *{ $manager . '::' };
282   }
283
284   die "Can't resolve '$string' as a database model, sorry. Did you perhaps forgot to load it?";
285 }
286
287 sub plurify {
288   my ($str) = @_;
289   $str . 's';
290 }
291
292 sub singlify {
293   my ($str) = @_;
294   local $/ = 's';
295   chomp $str;
296   $str;
297 }
298
299 1;
300
301 __END__
302
303 =encoding utf8
304
305 =head1 NAME
306
307 SL::DB::Helper::Mappings - Rose Table <-> Model mapping information
308
309 =head1 SYNOPSIS
310
311   use SL::DB::Helper::Mappings qw(@blacklist %table2model);
312
313 =head1 DESCRIPTION
314
315 This modul stores table <-> model mappings used by the
316 L<scripts/rose_auto_create_model.pl> script.  If you add a new table that has
317 custom mappings, add it here.
318
319 =head1 FUNCTIONS
320
321 =over 4
322
323 =item C<db $name>
324
325 A special function provided here is C<db>. Without it you'd have to write:
326
327   my $part = SL::DB::Part->new(id => 1234);
328   my @all_parts = SL::DB::Manager::Part->get_all;
329
330 with them it becomes:
331
332   my $part = db('part')->new(id => 123);
333   my @all_parts = db('parts')->get_all;
334
335 You don't have to care about add that SL::DB:: incantation anymore. Also, a
336 simple s at the end will get you the associated Manager class.
337
338 db is written to try to make sense of what you give it, but if all fails, it
339 will die with an error.
340
341 =item C<get_package_for_table $table_name>
342
343 Returns the package name for a table name:
344
345   SL::DB::Helper::Mappings::get_package_for_table('oe')
346   # SL::DB::Order
347
348 =item C<get_manager_package_for_table $table_name>
349
350 Returns the manager package name for a table name:
351
352   SL::DB::Helper::Mappings::get_manager_package_for_table('oe')
353   # SL::DB::Manager::Order
354
355 =item C<get_table_for_package $package_name>
356
357 Returns the table name for a package name:
358
359   SL::DB::Helper::Mappings::get_table_for_package('SL::DB::Order')
360   # oe
361   SL::DB::Helper::Mappings::get_table_for_package('Order')
362   # oe
363
364 =back
365
366 =head1 BUGS
367
368 nothing yet
369
370 =head1 SEE ALSO
371
372 L<scripts/rose_auto_create_model.pl>
373
374 =head1 AUTHOR
375
376 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>,
377 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
378
379 =cut