Thursday, June 14, 2012

Upgrading Redmine from 1.2.2 to 2.0.2

I needed to upgrade a Redmine installation that was pretty old to the newest release 2.0.2. I was following this document on how to upgrade Redmine http://www.redmine.org/projects/redmine/wiki/RedmineUpgrade. When I got to Step 4 - Update the database

I received the following error

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
root@xxx #rake db:migrate RAILS_ENV=production --trace
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
rake aborted!
no such file to load -- dispatcher
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `block in require'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:236:in `load_dependency'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
/vol/www/sites/redmine2.appinux.com/plugins/redmine_scm/init.rb:2:in `<top (required)>'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `block in require'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:236:in `load_dependency'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:251:in `require'
/vol/www/sites/redmine2.appinux.com/lib/redmine/plugin.rb:129:in `block in load'
/vol/www/sites/redmine2.appinux.com/lib/redmine/plugin.rb:120:in `each'
/vol/www/sites/redmine2.appinux.com/lib/redmine/plugin.rb:120:in `load'
/vol/www/sites/redmine2.appinux.com/config/initializers/30-redmine.rb:13:in `<top (required)>'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:245:in `load'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:245:in `block in load'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:236:in `load_dependency'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/activesupport-3.2.5/lib/active_support/dependencies.rb:245:in `load'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/engine.rb:588:in `block (2 levels) in <class:Engine>'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/engine.rb:587:in `each'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/engine.rb:587:in `block in <class:Engine>'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/initializable.rb:30:in `instance_exec'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/initializable.rb:30:in `run'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/initializable.rb:55:in `block in run_initializers'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/initializable.rb:54:in `each'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/initializable.rb:54:in `run_initializers'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/application.rb:136:in `initialize!'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/railtie/configurable.rb:30:in `method_missing'
/vol/www/sites/redmine2.appinux.com/config/environment.rb:14:in `<top (required)>'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/application.rb:103:in `require'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/application.rb:103:in `require_environment!'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/railties-3.2.5/lib/rails/application.rb:292:in `block (2 levels) in initialize_tasks'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `call'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `block in execute'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `each'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `execute'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:176:in `block in invoke_prerequisites'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:174:in `each'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:174:in `invoke_prerequisites'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:157:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/task.rb:144:in `invoke'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/application.rb:116:in `invoke_task'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block (2 levels) in top_level'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `each'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block in top_level'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/application.rb:88:in `top_level'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/application.rb:66:in `block in run'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
/usr/local/rvm/gems/ruby-1.9.2-p180/gems/rake-0.9.2.2/bin/rake:33:in `<top (required)>'
/usr/local/rvm/gems/ruby-1.9.2-p180/bin/rake:19:in `load'
/usr/local/rvm/gems/ruby-1.9.2-p180/bin/rake:19:in `<main>'
Tasks: TOP => db:migrate => environment 
This was solved by removing the redmine_scm plugin that I copied to the plugin folder in Step 3 - Perform the upgrade - Option 1 - Downloaded release (tar.gz or zip file)

Monday, June 04, 2012

SugarCrm 6.3.1: Enhancing Importer - allow importing of related module data

Often when importing data into SugarCrm the built-in importer at a module level is working great. However if you have a need to import data that is actually modeled in SugarCrm as being 2 modules (tables) with a many-many relationship in between then the built-in importer comes up short.

The full patch can be found at the bottom of this posting. This is a non upgradesafe change. Apply at your own risk.

Let us assume that we have the following entity relational model in SugarCrm that has been configured in SugarCrm Studio or in SugarCrm Module Builder.


Module Builder

The Sugar Module Builder enables users to build custom modules from scratch or combine existing or custom objects into a brand new CRM module. Developers can leverage existing Sugar Objects such as Contacts, Accounts, Documents, Cases, and Opportunities to build a new module or create their own custom objects from scratch to form a new module. Users can build an unlimited number of custom modules, which interoperate seamlessly with Reporting, Workflow, and Sugar Studio tools. Upgrades for custom modules are fully supported. Building new modules allows developers to extend Sugar beyond the typical CRM functions and optimize Sugar for any xRM (any Relationship Management) function.

Positive Impacts

  • Create custom modules to track information critical to your business
  • Use pre-defined objects or create custom objects for the new module
  • Share or charge for custom objects on SugarForge and Sugar Exchange.

Sugar Studio

Sugar Studio is the starting place for an administrator to configure the way information is presented in Sugar. Administrators can use Sugar Studio to create and add custom fields, hide fields that are not relevant, and use the extensive customization capabilities of Sugar Logic to create calculated, dependent, and related fields. Sugar Studio is a very simple but powerful WYSIWYG interface that administrators and developers use to configure Sugar to complement a company’s existing business processes.

Positive Impacts

  •  Rearrange the order of fields according to your company’s requirements
  •  Hide fields that are not relevant to your business process
  •  Create and add new custom fields
  •  Calculate variable values based on the value of other fields like opportunity amount or expected close date
  •  Present fields only when necessary using dependent fields


If importing has been enabled for the Skill and the Language module when these modules were created then we can import Skill or Languages as standalone data. The Contact module is a built-in SugarCrm module and it has importing enabled but can also only import contact standalone data. 




There are a few challenges importing related data into SugarCrm:
  1. We need to handle relationships and splitting data into the correct modules.
  2. We need to handle the fact that the id column might not contain the actual id of the data but that another column might do instead.

Without the 2 challenges solved we will not be able to import the below data the way I would prefer.


What we really want in the database after importing the above data is.
  • 2 contacts: John and Jane
  • 3 skills: English literature, European history and PHP
  • 4 languages: English, German, Danish and Swedish 
  • as well as the many-many relations needed so we can recreate the data pictured above

The 2 above mentioned challenges have been solved the following ways:

#1: In the importer step 3 we have added all the "main module's" (Contacts in this case) related modules' fields in the module field dropdown. This way you can map any data  you want into a related module's field.

#2: A primary key field selector has been added on Step 2 in the import if you have selected "Create new records and update existing records" on Step 1 in the importer.




Lets look at the proposed solution.

Step 1: the importer has not been modified visually and looks as below.

(Please note the support for saving an import configuration is working with the new importer functionality).



Step 2: We have added a new field that allows you to select the field that is to be used as "id". It defaults to the standard importer behavior which is using the id column.



Step 3: We have added a marker for the field used as primary id ( purple box below ). Please note the text in the dropdown marked with red boxes. The field selected in the dropdown is prefixex with a module name (<modulename>.<fieldname>) this indicates that it is a field from a related module you want to map to.

As you can see from the screenshot below, the module field dropdown now contains all fields from the main module (Contacts) (main module fields are not prefixed with the module name), as well as the related modules fields (skill_Skill, and lang_Language, these fields are prefixed with the module name).



Note: Do not map any value to a related module's "ID" field. This is handled behind the scenes.


Step 4: No visual changes has happened here



There are quite a few code changes to add this new functionality into the importer and you can see the Subversion patch file below.
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
Index: include/database/DBHelper.php
===================================================================
--- include/database/DBHelper.php (revision 73)
+++ include/database/DBHelper.php (working copy)
@@ -1185,8 +1185,8 @@
                          $before_value=(float)$bean->fetched_row[$field];
                          $after_value=(float)$bean->$field;
                      } else {
-                         $before_value=$bean->fetched_row[$field];
-                         $after_value=$bean->$field;
+                         $before_value=$bean->fetched_row[$field];  
+                         $after_value=@$bean->$field;
                    }
  
      //Because of bug #25078(sqlserver haven't 'date' type, trim extra "00:00:00" when insert into *_cstm table). so when we read the audit datetime field from sqlserver, we have to replace the extra "00:00:00" again.
Index: modules/Import/Importer.php
===================================================================
--- modules/Import/Importer.php (revision 73)
+++ modules/Import/Importer.php (working copy)
@@ -59,6 +59,7 @@
      */
     private $importColumns;
  
+ private $importRelatedColumns;
     /**
      * @var importSource
      */
@@ -104,9 +105,11 @@
         //Get the default user currency
         $this->defaultUserCurrency = new Currency();
         $this->defaultUserCurrency->retrieve('-99');
-
+       
         //Get our import column definitions
         $this->importColumns = $this->getImportColumns();
+  $this->importRelatedColumns = $this->getRelatedImportColumns();
+
         $this->isUpdateOnly = ( isset($_REQUEST['import_type']) && $_REQUEST['import_type'] == 'update' );
     }
  
@@ -132,7 +135,7 @@
     protected function importRow($row)
     {
         global $sugar_config, $mod_strings;
-
+  global $beanList,$beanFiles;
         $focus = clone $this->bean;
         $focus->unPopulateDefaultValues();
         $focus->save_from_post = false;
@@ -140,6 +143,11 @@
         $this->ifs->createdBeans = array();
         $this->importSource->resetRowErrorCounter();
         $do_save = true;
+       
+        $primary_key = (isset($_REQUEST['primary_key']) && !empty($_REQUEST['primary_key'])) ? $_REQUEST['primary_key'] : false;
+        if(!$primary_key){
+            $primary_key = 'id';
+        }
  
         for ( $fieldNum = 0; $fieldNum < $_REQUEST['columncount']; $fieldNum++ )
         {
@@ -322,46 +330,58 @@
                 return;
             }
         }
-
+       
+        $focus_array = array();
+        $newRecord_array = array();
+       
         // if the id was specified
         $newRecord = true;
-        if ( !empty($focus->id) )
+        if ( !empty($focus->$primary_key) )
         {
-            $focus->id = $this->_convertId($focus->id);
-
+            if($primary_key=='id')
+                $focus->id = $this->_convertId($focus->$primary_key);
             // check if it already exists
-            $query = "SELECT * FROM {$focus->table_name} WHERE id='".$focus->db->quote($focus->id)."'";
+            $join = '';
+            $_def = $focus->getFieldDefinition($primary_key);
+            if($_def['source'] == 'custom_fields') $join = "JOIN {$focus->table_name}_cstm ON id_c = id";
+            $query = "SELECT * FROM {$focus->table_name} $join WHERE $primary_key='".$focus->db->quote($focus->$primary_key)."'";
             $result = $focus->db->query($query)
             or sugar_die("Error selecting sugarbean: ");
  
-            $dbrow = $focus->db->fetchByAssoc($result);
+            while($dbrow = $focus->db->fetchByAssoc($result)){
  
-            if (isset ($dbrow['id']) && $dbrow['id'] != -1)
+                if (isset ($dbrow[$primary_key]) && $dbrow[$primary_key] != -1)
             {
-                // if it exists but was deleted, just remove it
-                if (isset ($dbrow['deleted']) && $dbrow['deleted'] == 1 && $this->isUpdateOnly ==false)
+                    $focus->id = $dbrow['id'];
+                    // if it exists but was deleted, just remove it                                         //skiping deleted rows
+                    if (isset ($dbrow['deleted']) && $dbrow['deleted'] == 1 && $this->isUpdateOnly == false /*&& $primary_key=='id'*/)
                 {
                     $this->removeDeletedBean($focus);
                     $focus->new_with_id = true;
                 }
                 else
                 {
+                        //skiping deleted rows
+                        if(isset ($dbrow['deleted']) && $dbrow['deleted'] == 1 ) continue;
                     if( ! $this->isUpdateOnly )
                     {
-                        $this->importSource->writeError($mod_strings['LBL_ID_EXISTS_ALREADY'],'ID',$focus->id);
+                            $this->importSource->writeError($mod_strings['LBL_ID_EXISTS_ALREADY'],$primary_key,$focus->$primary_key);
                         $this->_undoCreatedBeans($this->ifs->createdBeans);
                         return;
                     }
-
+                       
                     $clonedBean = $this->cloneExistingBean($focus);
                     if($clonedBean === FALSE)
                     {
-                        $this->importSource->writeError($mod_strings['LBL_RECORD_CANNOT_BE_UPDATED'],'ID',$focus->id);
+                            $this->importSource->writeError($mod_strings['LBL_RECORD_CANNOT_BE_UPDATED'],$primary_key,$focus->$primary_key);
                         $this->_undoCreatedBeans($this->ifs->createdBeans);
                         return;
                     }
                     else
                     {
+                            $focus_array[] = clone $clonedBean;
+                            $newRecord_array[] = FALSE;
+                           
                         $focus = $clonedBean;
                         $newRecord = FALSE;
                     }
@@ -369,19 +389,100 @@
             }
             else
             {
+                    if($focus->id){
                 $focus->new_with_id = true;
+                    }else{
+                        $focus->new_with_id = false;
+                        $focus_array[] = $this->cloneExistingBean($focus);
+                        $newRecord_array[] = true;
             }
         }
-
+            }
+        }
+        if(count($focus_array)==0){
+            $focus_array[] = $focus;
+            $newRecord_array[] = $newRecord;
+        }
+        for($focus_i=0,$focus_count=count($focus_array);$focus_i<$focus_count;$focus_i++){
+            $focus = $focus_array[$focus_i];
+            $newRecord = $newRecord_array[$focus_i];
         if ($do_save)
         {
             $this->saveImportBean($focus, $newRecord);
+       $mainModuleId = $focus->id;
+       //Save records for related module
+       foreach($this->importRelatedColumns as $k=>$v)
+       {
+         $exploedFields = explode("$",$v);
+         $relatedModule[] =  $exploedFields[0];
+         $relatedModuleField[$exploedFields[0]][] = $exploedFields[1];
+       }
+                if(isset($relatedModule) && is_array($relatedModule))
+       $relatedModules = array_unique($relatedModule);
+                if(isset($relatedModule) && is_array($relatedModule))
+                    foreach($relatedModuleField as $modName => $fldsArr)
+        {
+         $haveValue = 0;
+         $relatedModuleFile = $beanList[$modName];
+         include_once($beanFiles[$relatedModuleFile]);
+         $relatedModuleObj = new $relatedModuleFile();
+         $whereArr = array();
+                        $is_custom = false;
+         foreach($fldsArr as $k=>$fldName)
+         {
+          $fld = $modName."$".$fldName;
+          $fieldNo = array_search($fld,$this->importRelatedColumns);
+          if($row[$fieldNo]!="")
+          {
+           $haveValue++;
+           $relatedModuleObj->$fldName = $row[$fieldNo];
+           $whereArr[] = $fldName ."='". $row[$fieldNo]."'";
+                                if(@$relatedModuleObj->field_defs[$fldName]['source'] == 'custom_fields')  $is_custom = true;
+          }
+         }
+         if($haveValue)
+         {
+          $where = "";
+          $where = implode(" AND ",$whereArr);
+          $sql = "select id from ".$relatedModuleObj->table_name;
+          if($is_custom) $sql .= ' inner join '.$relatedModuleObj->table_name.'_cstm on id=id_c';
+                            $sql .= " where ".$where." and deleted=0";
+                            $result2 = $relatedModuleObj->db->query($sql);
+          $rowQuery = $relatedModuleObj->db->fetchByAssoc($result2);
+          if(count($rowQuery)==0 || empty($rowQuery))
+          {
+           $this->saveImportBean($relatedModuleObj, $newRecord);
+           $relatedId = $relatedModuleObj->id;
+          }
+          else
+          {
+           $relatedId = $rowQuery['id'];
+          }
+          $rel_table = strtolower($relatedModuleObj->table_name);
+                            $foc_table = strtolower($focus->table_name);
+                            if(strlen($rel_table)>16) $rel_table = substr($rel_table,0,11).substr($rel_table,-5);
+                            if(strlen($foc_table)>16) $foc_table = substr($foc_table,0,11).substr($foc_table,-5);
+                            $rel_field = $foc_table.'_'.$rel_table;
+                            if(!$focus->load_relationship($rel_field)){      
+                                $rel_field = $rel_table.'_'.$foc_table;
+                                if(!$focus->load_relationship($rel_field)){
+                                    $GLOBALS['log']->error("SugarBean.load_relationships, relationship not found.");
+                                    $rel_field = false;
+                                }
+                            }
+                            if($rel_field){
+                                $focus->$rel_field->add($relatedId,array());
+                            }
+                             $focus->save();
+         }
+        }
+                  
             // Update the created/updated counter
             $this->importSource->markRowAsImported($newRecord);
         }
         else
             $this->_undoCreatedBeans($this->ifs->createdBeans);
-
+        }
         unset($defaultRowValue);
  
     }
@@ -544,11 +645,15 @@
          
         $firstrow    = unserialize(base64_decode($_REQUEST['firstrow']));
         $mappingValsArr = $this->importColumns;
-        $mapping_file = new ImportMap();
+        $mappingRelatedArr = $this->importRelatedColumns;
+        $mappArr = $mappingRelatedArr+$mappingValsArr;
+        $mapping_file = new ImportMap();    
+       
+       
         if ( isset($_REQUEST['has_header']) && $_REQUEST['has_header'] == 'on')
         {
             $header_to_field = array ();
-            foreach ($this->importColumns as $pos => $field_name)
+            foreach ($mappArr as $pos => $field_name)
             {
                 if (isset($firstrow[$pos]) && isset($field_name))
                 {
@@ -557,6 +662,8 @@
             }
  
             $mappingValsArr = $header_to_field;
+        }      else{
+         $mappingValsArr =    $mappArr;
         }
         //get array of values to save for duplicate and locale settings
         $advMapping = $this->retrieveAdvancedMapping();
@@ -679,7 +786,26 @@
  
         return $importColumns;
     }
+ protected function getRelatedImportColumns()
+    {
+        $importRelatedColumns = array();
+        foreach ($_REQUEST as $name => $value)
+        {
+            // only look for var names that start with "fieldNum"
+            if (strncasecmp($name, "colnum_", 7) != 0)
+                continue;
  
+            // pull out the column position for this field name
+            $pos = substr($name, 7);
+
+            if ( strpos($value,"$") )
+            {
+                // now mark that we've seen this field
+                $importRelatedColumns[$pos] = $value;
+            }
+        }
+        return $importRelatedColumns;
+    }
     protected function getFieldSanitizer()
     {
         $ifs = new ImportFieldSanitize();
Index: modules/Import/tpls/confirm.tpl
===================================================================
--- modules/Import/tpls/confirm.tpl (revision 73)
+++ modules/Import/tpls/confirm.tpl (working copy)
@@ -170,8 +170,30 @@
         </tr>
         <tr>
             <td colspan="2"><div class="hr" style="margin-top: 0px;"></div></td>
+        </tr>   
+        {if $TYPE != 'import'}
+        <tr>
+            <td colspan="2"><h3>Select primaty field&nbsp;{sugar_help text="It will update the row with the field equal to the value of the csv row"}</h3></td>
         </tr>
         <tr>
+            <td colspan="2">
+                <select name="primary_key">
+                    {foreach from=$SAMPLE_ROWS item=row name=row}
+                        {foreach from=$row item=value}
+                            {if $smarty.foreach.row.first}
+                                {if $HAS_HEADER}
+                                    <option value="{$value}"{if $value|lower == 'id'} selected='selected' {/if}>{$value}</option>
+                                {/if}
+                            {/if}
+                        {/foreach}
+                    {/foreach}
+                </select>
+            </td>
+        </tr>
+        {else}
+            <input name="primary_key" value="" type="hidden" />
+        {/if}                                                                                                
+        <tr>
             <td colspan="2"><h3>{$MOD.LBL_THIRD_PARTY_CSV_SOURCES}&nbsp;{sugar_help text=$MOD.LBL_THIRD_PARTY_CSV_SOURCES_HELP}</h3></td>
         </tr>
         <tr>
Index: modules/Import/tpls/dupcheck.tpl
===================================================================
--- modules/Import/tpls/dupcheck.tpl (revision 73)
+++ modules/Import/tpls/dupcheck.tpl (working copy)
@@ -84,6 +84,7 @@
 <input type="hidden" id="enabled_dupes" name="enabled_dupes" value="">
 <input type="hidden" id="disabled_dupes" name="disabled_dupes" value="">
 <input type="hidden" id="current_step" name="current_step" value="{$CURRENT_STEP}">
+<input type="hidden" name="primary_key" value="{$primary_field}">
  
    <div class="hr"></div>
     <div>
Index: modules/Import/tpls/step3.tpl
===================================================================
--- modules/Import/tpls/step3.tpl (revision 73)
+++ modules/Import/tpls/step3.tpl (working copy)
@@ -118,10 +118,34 @@
 {/if}
 <tr>
     {if $HAS_HEADER == 'on'}
-    <td id="row_{$smarty.foreach.rows.index}_header">{$item.cell1}</td>
+    <td id="row_{$smarty.foreach.rows.index}_header">
+        {if $primary_field==$item.cell1}
+            <b>{$item.cell1}
+            <small>*Primary Field</small>
+            </b>
+            <input type="hidden" name="primary_key" value="{$primary_field}" id="primary_key" />
+            <script>
+                {literal}
+                (function(obj, evType, fn){
+                    if (obj.addEventListener){
+                       obj.addEventListener(evType, fn, false);
+                       return true;
+                     } else if (obj.attachEvent){
+                        var r = obj.attachEvent("on"+evType, fn);
+                        return r;
+                     } else {
+                        return false;
+                     }
+                })(window,'load',function(){document.getElementById('primary_key').value=document.getElementById('primary_key_list').value})
+                {/literal}
+            </script>
+        {else}
+            {$item.cell1}
     {/if}
+    </td>
+    {/if}
     <td valign="top" align="left" id="row_{$smarty.foreach.rows.index}_col_0">
-        <select class='fixedwidth' name="colnum_{$smarty.foreach.rows.index}">
+        <select class='fixedwidth' name="colnum_{$smarty.foreach.rows.index}"{if $primary_field==$item.cell1} id="primary_key_list" onblur="document.getElementById('primary_key').value = this.value" {/if}>
             <option value="-1">{$MOD.LBL_DONT_MAP}</option>
             {$item.field_choices}
         </select>
Index: modules/Import/views/view.confirm.php
===================================================================
--- modules/Import/views/view.confirm.php (revision 73)
+++ modules/Import/views/view.confirm.php (working copy)
@@ -63,7 +63,7 @@
         global $sugar_config, $locale;
          
         $this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
-        $this->ss->assign("TYPE",( !empty($_REQUEST['type']) ? $_REQUEST['type'] : "import" ));
+        $this->ss->assign("TYPE",( !empty($_REQUEST['type']) ? $_REQUEST['type'] : ( !empty($_REQUEST['import_type'])?$_REQUEST['import_type'] : "import") ));
         $this->ss->assign("SOURCE_ID", $_REQUEST['source_id']);
  
         $this->instruction = 'LBL_SELECT_PROPERTY_INSTRUCTION';
Index: modules/Import/views/view.dupcheck.php
===================================================================
--- modules/Import/views/view.dupcheck.php (revision 73)
+++ modules/Import/views/view.dupcheck.php (working copy)
@@ -73,6 +73,7 @@
         $this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
         $this->ss->assign("CURRENT_STEP", $this->currentStep);
         $this->ss->assign("JAVASCRIPT", $this->_getJS());
+        $this->ss->assign("primary_field", @$_REQUEST['primary_key'] ? $_REQUEST['primary_key'] : 'id' );
  
         $content = $this->ss->fetch('modules/Import/tpls/dupcheck.tpl');
         $this->ss->assign("CONTENT", $content);
Index: modules/Import/views/view.last.php
===================================================================
--- modules/Import/views/view.last.php (revision 73)
+++ modules/Import/views/view.last.php (working copy)
@@ -109,6 +109,8 @@
         $this->ss->assign("errorrecordsFile",ImportCacheFiles::getErrorRecordsWithoutErrorFileName());
         $this->ss->assign("dupeFile",ImportCacheFiles::getDuplicateFileName());
          
+        $this->ss->assign("primary_field", @$_REQUEST['primary_key'] ? $_REQUEST['primary_key'] : 'id' );
+       
         if ( $this->bean->object_name == "Prospect" )
         {
          $this->ss->assign("PROSPECTLISTBUTTON", $this->_addToProspectListButton());
Index: modules/Import/views/view.step3.php
===================================================================
--- modules/Import/views/view.step3.php (revision 73)
+++ modules/Import/views/view.step3.php (working copy)
@@ -63,7 +63,7 @@
   public function display()
     {
         global $mod_strings, $app_strings, $current_user, $sugar_config, $app_list_strings, $locale;
-       
+        global $beanList,$beanFiles;
         $this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
         $has_header = ( isset( $_REQUEST['has_header']) ? 1 : 0 );
         $sugar_config['import_max_records_per_file'] = ( empty($sugar_config['import_max_records_per_file']) ? 1000 : $sugar_config['import_max_records_per_file'] );
@@ -200,7 +200,91 @@
         if (!empty($importColumns)) {
             $column_sel_from_req = true;
         }
-
+        foreach($this->bean->field_defs as $field)
+        {
+            if(0 == strcmp($field['type'],'link') && (!empty($field['module']) || !empty($field['relationship'])))
+            {
+                if(!empty($field['module']))
+                {
+                    $related_module = $field['module'];
+                }
+                elseif(!empty($field['relationship']))
+                {
+                    require_once("data/Relationships/RelationshipFactory.php");
+                    $test = SugarRelationshipFactory::getInstance()->getRelationship($field['relationship']);
+                    if($test->def['relationships'][$field['relationship']]['lhs_module'] == $this->bean->module_dir)
+                    {
+                        $relatedMods[] = $test->def['relationships'][$field['relationship']]['rhs_module'];
+                    }
+                    else
+                    {
+                        $relatedMods[] = $test->def['relationships'][$field['relationship']]['lhs_module'];
+                    }
+                }
+            }
+        }
+        //add extra related fields
+        foreach($relatedMods as $key=>$relatedModule)
+        {
+                if(array_key_exists($relatedModule,$beanList))
+                {
+                $relatedModuleFile = $beanList[$relatedModule];
+                include_once($beanFiles[$relatedModuleFile]);
+                $relatedModuleObj = new $relatedModuleFile();
+                $fieldsRel  = $relatedModuleObj->get_importable_fields();
+                $relModuleStrings = return_module_language($current_language, $relatedModuleObj->module_dir);
+                foreach ( $fieldsRel as $fieldname => $properties ) {
+                    if($properties['relationship'])
+                    continue;
+                    // get field name
+                    if (!empty($relModuleStrings['LBL_EXPORT_'.strtoupper($fieldname)]) )
+                    {
+                         $displayname = str_replace(":","", $relModuleStrings['LBL_EXPORT_'.strtoupper($fieldname)] );
+                    }
+                    else if (!empty ($properties['vname']))
+                    {
+                        $displayname = str_replace(":","",translate($properties['vname'] ,$relatedModuleObj->module_dir));
+                    }
+                    else
+                        $displayname = str_replace(":","",translate($properties['name'] ,$relatedModuleObj->module_dir));
+                   
+                    $selected = '';  
+                    if ($column_sel_from_req && isset($importColumns[$field_count])) {
+                        if ($fieldname == $importColumns[$field_count]) {
+                            //$selected = ' selected="selected" ';
+                            $defaultField = $fieldname;
+                            $mappedFields[] = $fieldname;
+                        }
+                    } else {
+                        if ( !empty($defaultValue) && !in_array($fieldname,$mappedFields)
+                                                        && !in_array($fieldname,$ignored_fields) )
+                        {
+                            if ( strtolower($fieldname) == strtolower($defaultValue)
+                                || strtolower($fieldname) == str_replace(" ","_",strtolower($defaultValue))
+                                || strtolower($displayname) == strtolower($defaultValue)
+                                || strtolower($displayname) == str_replace(" ","_",strtolower($defaultValue)) )
+                            {
+                                //$selected = ' selected="selected" ';
+                                $defaultField = $fieldname;
+                                $mappedFields[] = $fieldname;
+                            }
+                        }
+                    } 
+                    // get field type information
+                    $fieldtype = '';
+                    if ( isset($properties['type'])
+                            && isset($mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])]) )
+                        $fieldtype = ' [' . $mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])] . '] ';
+                    if ( isset($properties['comment']) )
+                        $fieldtype .= ' - ' . $properties['comment'];
+                       
+                    $optionsRelated[$relatedModuleObj->module_dir.'$'.$fieldname] = '<option value="'.$relatedModuleObj->module_dir.'$'.$fieldname.'" title="'. $displayname . htmlentities($fieldtype) . '"'
+                        . $selected . $req_class . '>'. $relatedModuleObj->module_dir.".". $displayname . '</option>\n';
+                }
+               
+                }
+        }
+       
         for($field_count = 0; $field_count < $ret_field_count; $field_count++) {
             // See if we have any field map matches
             $defaultValue = "";
@@ -225,7 +309,17 @@
             $defaultField = '';
             global $current_language;
       $moduleStrings = return_module_language($current_language, $this->bean->module_dir);
+           
+            $related_options_clone = $optionsRelated;
  
+            if(
+                isset($firstrow_name) &&
+                isset($field_map[$firstrow_name]) &&
+                isset($related_options_clone[$field_map[$firstrow_name]])
+            ){
+                $related_options_clone[$field_map[$firstrow_name]] = str_replace('<option ','<option selected="selected" ',$related_options_clone[$field_map[$firstrow_name]]);
+            }
+           
             foreach ( $fields as $fieldname => $properties ) {
                 // get field name
                 if (!empty($moduleStrings['LBL_EXPORT_'.strtoupper($fieldname)]) )
@@ -278,7 +372,6 @@
                 $options[$displayname.$fieldname] = '<option value="'.$fieldname.'" title="'. $displayname . htmlentities($fieldtype) . '"'
                     . $selected . $req_class . '>' . $displayname . $req_mark . '</option>\n';
             }
-
             // get default field value
             $defaultFieldHTML = '';
             if ( !empty($defaultField) ) {
@@ -306,6 +399,11 @@
             $cellOneData = isset($rows[0][$field_count]) ? $rows[0][$field_count] : '';
             $cellTwoData = isset($rows[1][$field_count]) ? $rows[1][$field_count] : '';
             $cellThreeData = isset($rows[2][$field_count]) ? $rows[2][$field_count] : '';
+           
+            if(count($optionsRelated)>0 && @$_REQUEST['primary_key'] != $firstrow_name)
+            {
+                $options = array_merge($options, $related_options_clone);
+            }
             $columns[] = array(
                 'field_choices' => implode('',$options),
                 'default_field' => $defaultFieldHTML,
@@ -382,6 +480,7 @@
  
         $this->ss->assign("COLUMNCOUNT",$ret_field_count);
         $this->ss->assign("rows",$columns);
+        $this->ss->assign("primary_field", @$_REQUEST['primary_key'] ? $_REQUEST['primary_key'] : 'id' );
  
         $this->ss->assign('datetimeformat', $GLOBALS['timedate']->get_cal_date_time_format());
  
@@ -768,4 +867,4 @@
  
 EOJAVASCRIPT;
     }
-}
+}
\ No newline at end of file