]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Leads/views/view.convertlead.php
Release 6.4.0beta3
[Github/sugarcrm.git] / modules / Leads / views / view.convertlead.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 require_once("include/EditView/EditView2.php");
39 require_once("include/upload_file.php");
40
41 class ViewConvertLead extends SugarView
42 {
43     protected $fileName = "modules/Leads/metadata/convertdefs.php";
44     protected $new_contact = false;
45
46     public function __construct(
47         $bean = null,
48         $view_object_map = array()
49         )
50     {
51         parent::SugarView($bean, $view_object_map);
52         $this->medataDataFile = $this->fileName;
53         if (file_exists("custom/$this->fileName"))
54         {
55             $this->medataDataFile = "custom/$this->fileName";
56         }
57     }
58
59     public function preDisplay()
60     {
61         if (!$this->bean->ACLAccess('edit')) {
62             ACLController::displayNoAccess();
63             sugar_die('');
64         }
65     }
66
67     /**
68          * @see SugarView::display()
69          */
70         public function display()
71     {
72         if (!empty($_REQUEST['handle']) && $_REQUEST['handle'] == 'save')
73         {
74                 return $this->handleSave();
75         }
76
77         global $beanList;
78
79         // get the EditView defs to check if opportunity_name exists, for a check below for populating data
80         $opportunityNameInLayout = false;
81         $editviewFile = 'modules/Leads/metadata/editviewdefs.php';
82         $this->medataDataFile = $editviewFile;
83         if (file_exists("custom/{$editviewFile}"))
84         {
85             $this->medataDataFile = "custom/{$editviewFile}";
86         }
87         include($this->medataDataFile);
88         foreach($viewdefs['Leads']['EditView']['panels'] as $panel_index => $section){
89             foreach($section as $row_array){
90                 foreach($row_array as $cell){
91                         if(isset($cell['name']) && $cell['name'] == 'opportunity_name'){
92                             $opportunityNameInLayout = true;
93                         }
94                 }
95             }
96         }
97
98         $this->medataDataFile = $this->fileName;
99         if (file_exists("custom/$this->fileName"))
100         {
101             $this->medataDataFile = "custom/$this->fileName";
102         }
103         $this->loadDefs();
104         $this->getRecord();
105         $this->checkForDuplicates($this->focus);
106         $smarty = new Sugar_Smarty();
107         $ev = new EditView();
108         $ev->ss = $smarty;
109         $ev->view = "ConvertLead";
110         echo $this->getModuleTitle();
111
112         require_once("include/QuickSearchDefaults.php");
113         $qsd = new QuickSearchDefaults();
114         $qsd->setFormName("ConvertLead");
115
116         $this->contact = new Contact();
117         $smarty->assign("contact_def", $this->contact->field_defs);
118         $smarty->assign("form_name", "ConvertLead");
119         $smarty->assign("form_id", "ConvertLead");
120         $smarty->assign("module", "Leads");
121         $smarty->assign("view", "convertlead");
122         $smarty->assign("bean", $this->focus);
123                 $smarty->assign("record_id", $this->focus->id);
124         global $mod_strings;
125         $smarty->assign('MOD', $mod_strings);
126         $smarty->display("modules/Leads/tpls/ConvertLeadHeader.tpl");
127
128         echo "<div class='edit view' style='width:auto;'>";
129
130         global $sugar_config, $app_list_strings;
131         $smarty->assign('lead_conv_activity_opt', $sugar_config['lead_conv_activity_opt']);
132         $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));
133
134         foreach($this->defs as $module => $vdef)
135         {
136             if(!isset($beanList[$module]))
137             {
138                 continue;
139             }
140             $bean = $beanList[$module];
141             $focus = new $bean();
142             $focus->fill_in_additional_detail_fields();
143             foreach($focus->field_defs as $field => $def)
144             {
145                 if(isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData'])
146                 {
147                         if ($module == "Accounts" && $field == 'name')
148                         {
149                             $focus->name = $this->focus->account_name;
150                         }
151                         else if ($module == "Opportunities" && $field == 'amount')
152                         {
153                             $focus->amount = unformat_number($this->focus->opportunity_amount);
154                         } 
155                         else if ($module == "Opportunities" && $field == 'name') {
156                                 if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)){
157                            $focus->name = $this->focus->opportunity_name;
158                                 }
159                         }
160                         else if ($field == "id")
161                     {
162                                                 //If it is not a contact, don't copy the ID from the lead
163                         if ($module == "Contacts") {
164                            $focus->$field = $this->focus->$field;
165                         }
166                     } else if (is_a($focus, "Company") && $field == 'phone_office')
167                         {
168                                 //Special case where company and person have the same field with a different name
169                                 $focus->phone_office = $this->focus->phone_work;
170                         }
171                                         else if (strpos($field, "billing_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */         
172                                         {
173                                                 $tmp_field = str_replace("billing_", "primary_", $field);
174                                                 $focus->field_defs[$field]["type"] = "text";
175                         if (isset($this->focus->$tmp_field)) {
176                                                     $focus->$field = $this->focus->$tmp_field;
177                         }
178                                          }
179
180                                         else if (strpos($field, "shipping_address") !== false && $focus->field_defs[$field]["type"] == "varchar") /* Bug 42219 fix */
181                                         {
182                                                 $tmp_field = str_replace("shipping_", "primary_", $field);
183                                                 if (isset($this->focus->$tmp_field)) {
184                             $focus->$field = $this->focus->$tmp_field;
185                         }
186                                                 $focus->field_defs[$field]["type"] = "text";
187                                         }                                       
188                     else if (isset($this->focus->$field))
189                     {
190                         $focus->$field = $this->focus->$field;
191                     }
192                 }
193             }
194
195             //Copy over email data
196             $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
197             $ev->process();
198             echo($ev->display(false));
199             echo($this->getValidationJS($module, $focus, $vdef[$ev->view]));
200         }
201         echo "</div>";
202         echo ($qsd->getQSScriptsJSONAlreadyDefined());
203         $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
204     }
205
206     protected function getRecord()
207     {
208         $this->focus = new Lead();
209         if (isset($_REQUEST['record']))
210         {
211                 $this->focus->retrieve($_REQUEST['record']);
212         }
213     }
214
215     protected function loadDefs()
216     {
217         $viewdefs = array();
218         include($this->medataDataFile);
219         $this->defs = $viewdefs;
220     }
221
222     /**
223      * Returns the javascript to enable/disable validation of each module's sub-form
224      * //TODO: This should probably be on the smarty template
225      * @param $module String the target module name.
226      * @param $focus SugarBean instance of the target module.
227      * @param $focus EditView def for the module.
228      * @return String, javascript to echo to page.
229      */
230     protected function getValidationJS(
231         $module,
232         $focus,
233         $viewdef
234         )
235     {
236         $validateSelect = isset($viewdef['required']) && $viewdef['required'] && !empty($viewdef['select']);
237         $jsOut  = "
238         <script type='text/javascript'>
239             if (!SUGAR.convert)  SUGAR.convert = {requiredFields: {}};
240             SUGAR.convert.toggle$module = function(){
241                 clear_all_errors();
242                 inputsWithErrors = [];
243                 if(!SUGAR.convert.{$module}Enabled)
244                 {
245                     for(var i in SUGAR.convert.requiredFields.$module)
246                     {
247                         addToValidate('ConvertLead', '$module' + i, 'varchar', true, SUGAR.convert.requiredFields.{$module}[i]);
248                     }
249                     ";
250         if ($validateSelect) {
251                 $jsOut  .= "
252                     removeFromValidate('ConvertLead', '{$viewdef['select']}');";
253         }
254
255         $jsOut .= "
256                     SUGAR.convert.{$module}Enabled = true;
257                 } else {
258                     for(var i in SUGAR.convert.requiredFields.$module)
259                     {
260                         removeFromValidate('ConvertLead', '$module' + i);
261                     }";
262         if ($validateSelect) {
263             $jsOut  .= "
264                 addToValidate('ConvertLead', '{$viewdef['select']}', 'varchar', true, '"
265             . translate($this->contact->field_defs[$viewdef['select']]['vname']) . "');";
266         }
267         $jsOut .= "
268                     SUGAR.convert.{$module}Enabled = false;
269                 }
270                 YAHOO.util.Dom.get('convert_create_{$module}').value = SUGAR.convert.{$module}Enabled;
271             };\n";
272
273         if (isset($viewdef['required']) && $viewdef['required'])
274         {
275             if (!empty($viewdef['select']) && (empty($viewdef['default_action']) || $viewdef['default_action'] != 'create'))
276             {
277                 $jsOut .= "
278             SUGAR.convert.{$module}Enabled = true;";
279             }
280             $jsOut .= "
281             YAHOO.util.Event.onDOMReady(SUGAR.convert.toggle$module);";
282         } else if (isset($viewdef['default_action'])  && $viewdef['default_action'] == "create")
283         {
284              $jsOut .= "\n            SUGAR.convert.{$module}Enabled = true;";
285         }
286         $jsOut .= "
287             YAHOO.util.Event.addListener('new$module', 'click', SUGAR.convert.toggle$module);
288             SUGAR.convert.requiredFields.$module = {};";
289         foreach($focus->field_defs as $field => $def)
290         {
291             if (isset($def['required']) && $def['required'])
292             {
293                 $jsOut .= "
294             SUGAR.convert.requiredFields.$module.$field = '". translate($def['vname'], $module) . "';\n";
295             }
296         }
297
298         $jsOut .= "
299         </script>";
300
301         return $jsOut;
302     }
303
304     /**
305      * Saves a new Contact as well as any related items passed in.
306      *
307      * @return null
308      */
309     protected function handleSave()
310     {
311         require_once('modules/Campaigns/utils.php');
312         require_once("include/formbase.php");
313         $lead = false;
314         if (!empty($_REQUEST['record']))
315         {
316             $lead = new Lead();
317             $lead->retrieve($_REQUEST['record']);
318         }
319
320         global $beanList;
321         $this->loadDefs();
322         $beans = array();
323         $selectedBeans = array();
324         $selects = array();
325         //Make sure the contact object is availible for relationships.
326         $beans['Contacts'] = new Contact();
327         $beans['Contacts']->id = create_guid();
328         $beans['Contacts']->new_with_id = true;
329
330         // Bug 39287 - Check for Duplicates on selected modules before save
331         if (!empty($_REQUEST['selectedContact']))
332         {
333             $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
334             if (!empty($beans['Contacts']->id))
335             {
336                 $beans['Contacts']->new_with_id = false;
337                 unset($_REQUEST["convert_create_Contacts"]);
338                 unset($_POST["convert_create_Contacts"]);
339             }
340         }
341         elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact'])) 
342         {
343             require_once('modules/Contacts/ContactFormBase.php');
344             $contactForm = new ContactFormBase();
345             $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
346
347             if (isset($duplicateContacts))
348             {
349                 echo $contactForm->buildTableForm($duplicateContacts,  'Contacts');
350                 return;
351             }
352             $this->new_contact = true;
353         }
354         if (!empty($_REQUEST['selectedAccount']))
355         {
356             $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
357             unset($_REQUEST["convert_create_Accounts"]);
358             unset($_POST["convert_create_Accounts"]);
359         }
360         elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount']))
361         {
362             require_once('modules/Accounts/AccountFormBase.php');
363             $accountForm = new AccountFormBase();
364             $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
365             if (isset($duplicateAccounts))
366             {
367                 echo $accountForm->buildTableForm($duplicateAccounts);
368                 return;
369             }
370         }
371
372         foreach ($this->defs as $module => $vdef)
373         {
374             //Create a new record if "create" was selected
375                 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
376             {
377                 //Save the new record
378                 $bean = $beanList[$module];
379                     if (empty($beans[$module]))
380                         $beans[$module] = new $bean();
381
382                 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
383
384             }
385             //If an existing bean was selected, relate it to the contact
386             else if (!empty($vdef['ConvertLead']['select'])) 
387             {
388                 //Save the new record
389                 $select = $vdef['ConvertLead']['select'];
390                 $fieldDef = $beans['Contacts']->field_defs[$select];
391                 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
392                 {
393                     $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
394                     $selects[$module] = $_REQUEST[$fieldDef['id_name']];
395                     if (!empty($_REQUEST[$select]))
396                     {
397                         $beans['Contacts']->$select = $_REQUEST[$select];
398                     }
399                     // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
400                     $bean = loadBean($module);
401                     $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
402                     $selectedBeans[$module] = $bean;
403                 }
404             }
405         }
406
407         $this->handleActivities($lead, $beans);
408         // Bug 39268 - Add the lead's activities to the selected beans
409         $this->handleActivities($lead, $selectedBeans);
410
411         //link selected account to lead if it exists
412         if (!empty($selectedBeans['Accounts']))
413         {
414             $lead->account_id = $selectedBeans['Accounts']->id;
415         }
416
417         //Handle non-contacts relationships
418         foreach ($beans as $bean)
419         {
420
421             if (!empty($lead))
422             {
423                 if (empty($bean->assigned_user_id))
424                 {
425                     $bean->assigned_user_id = $lead->assigned_user_id;
426                 }
427                 $leadsRel = $this->findRelationship($bean, $lead);
428                 if (!empty($leadsRel))
429                 {
430                     $bean->load_relationship($leadsRel);
431                     $relObject = $bean->$leadsRel->getRelationshipObject();
432                     if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
433                     {
434                         $id_field = $relObject->rhs_key;
435                         $lead->$id_field = $bean->id;
436                     }
437                     else 
438                     {
439                         $bean->$leadsRel->add($lead->id);
440                     }
441                 }
442             }
443             //Special case code for opportunities->Accounts
444             if ($bean->object_name == "Opportunity" && empty($bean->account_id))
445             {
446                 if (isset($beans['Accounts']))
447                 {
448                     $bean->account_id = $beans['Accounts']->id;
449                     $bean->account_name = $beans['Accounts']->name;
450                 }
451                 else if (!empty($selects['Accounts']))
452                 {
453                     $bean->account_id = $selects['Accounts'];
454                 }
455             }
456
457             //create meetings-users relationship
458             if ($bean->object_name == "Meeting")
459             {
460                 $bean = $this->setMeetingsUsersRelationship($bean);
461             }
462             $this->copyAddressFields($bean, $beans['Contacts']);
463
464             $bean->save();
465             //if campaign id exists then there should be an entry in campaign_log table for the newly created contact: bug 44522        
466             if (isset($lead->campaign_id) && $lead->campaign_id != null && $bean->object_name == "Contact")
467             {
468                 campaign_log_lead_or_contact_entry($lead->campaign_id, $lead, $beans['Contacts'], 'contact');
469             }
470         }
471         if (!empty($lead))
472         {       //Mark the original Lead converted
473             $lead->status = "Converted";
474             $lead->converted = '1';
475             $lead->in_workflow = true;
476             $lead->save();
477         }
478
479         $this->displaySaveResults($beans);
480     }
481
482     public function setMeetingsUsersRelationship($bean)
483     {
484         global $current_user;
485         $meetingsRel = $this->findRelationshipByName($bean, $this->defs['Meetings']['ConvertLead']['relationship']);
486         if (!empty($meetingsRel))
487         {
488             $bean->load_relationship($meetingsRel);
489             $bean->$meetingsRel->add($current_user->id);
490             return $bean;
491         }
492         else
493         {
494             return false;
495         }
496     }
497     protected function displaySaveResults(
498         $beans
499         )
500     {
501         global $beanList;
502         echo "<div><ul>";
503         foreach($beans as $bean)
504         {
505             $beanName = $bean->object_name;
506             if ( $beanName == 'Contact' && !$this->new_contact ) {
507                 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
508                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
509                        {$bean->get_summary_text()}
510                     </a></li>";
511             }
512             else {
513                 global $app_list_strings;
514                 if(!empty($app_list_strings['moduleListSingular'][$bean->module_dir])) {
515                     $module_name = $app_list_strings['moduleListSingular'][$bean->module_dir];
516                 } else {
517                     $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
518                 }
519                 if(empty($module_name)) {
520                     $module_name = translate($beanName);
521                 }
522                 echo "<li>" . translate("LBL_CREATED_NEW") . ' ' . $module_name . " -
523                     <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
524                        {$bean->get_summary_text()}
525                     </a></li>";
526             }
527         }
528
529         echo "</ul></div>";
530     }
531
532     protected function handleActivities(
533         $lead,
534         $beans
535         )
536     {
537         global $app_list_strings;
538         global $sugar_config;
539         $parent_types = $app_list_strings['record_type_display'];
540
541         $activities = $this->getActivitiesFromLead($lead);
542
543         foreach($beans as $module => $bean)
544         {
545                 if (isset($parent_types[$module]))
546                 {
547                 if (empty($bean->id))
548                 {
549                     $bean->id = create_guid();
550                             $bean->new_with_id = true;
551                 }
552                 foreach($activities as $activity)
553                         {
554                             if (!isset($sugar_config['lead_conv_activity_opt']) || $sugar_config['lead_conv_activity_opt'] == 'copy') {
555                                 if (isset($_POST['lead_conv_ac_op_sel'])) {
556                                     //if the copy to module(s) are defined, copy only to those module(s)
557                                     if (is_array($_POST['lead_conv_ac_op_sel'])) {
558                                         foreach ($_POST['lead_conv_ac_op_sel'] as $mod) {
559                                             if ($mod == $module) {
560                                                 $this->copyActivityAndRelateToBean($activity, $bean);
561                                                 break;
562                                             }
563                                         }
564                                     }
565                                 }
566                             }
567                             else if ($sugar_config['lead_conv_activity_opt'] == 'move') {
568                                 // if to move activities, should be only one module selected
569                                 if ($_POST['lead_conv_ac_op_sel'] == $module) {
570                                     $this->moveActivity($activity, $bean);
571                                 }
572                             }
573                         }
574                 }
575         }
576     }
577
578     /**
579      * Change the parent id and parent type of an activity
580      * @param $activity Activity to be modified
581      * @param $bean New parent bean of the activity
582      */
583     protected function moveActivity($activity, $bean) {
584         global $beanList;
585
586         $lead = null;
587         if (!empty($_REQUEST['record']))
588         {
589             $lead = new Lead();
590             $lead->retrieve($_REQUEST['record']);
591         }
592
593         // delete the old relationship to the old parent (lead)
594         if ($rel = $this->findRelationship($activity, $lead)) {
595             $activity->load_relationship ($rel) ;
596
597             if ($activity->parent_id && $activity->id) {
598                 $activity->$rel->delete($activity->id, $activity->parent_id);
599             }
600         }
601
602         // add the new relationship to the new parent (contact, account, etc)
603         if ($rel = $this->findRelationship($activity, $bean)) {
604             $activity->load_relationship ($rel) ;
605
606             $relObj = $activity->$rel->getRelationshipObject();
607             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
608             {
609                 $key = $relObj->rhs_key;
610                 $activity->$key = $bean->id;
611             }
612             $activity->$rel->add($bean);
613         }
614
615         // set the new parent id and type
616         $activity->parent_id = $bean->id;
617         $activity->parent_type = $bean->module_dir;
618
619         $activity->save();
620     }
621
622     /**
623      * Gets the list of activities related to the lead
624      * @param Lead $lead Lead to get activities from
625      * @return Array of Activity SugarBeans .
626      */
627         protected function getActivitiesFromLead(
628             $lead
629             )
630         {
631                 if (!$lead) return;
632
633                 global $beanList, $db;
634
635                 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
636                 $activities = array();
637
638                 foreach($activitesList as $module)
639                 {
640                         $beanName = $beanList[$module];
641                         $activity = new $beanName();
642                         $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
643                         $result = $db->query($query,true);
644             while($row = $db->fetchByAssoc($result))
645             {
646                 $activity = new $beanName();
647                                 $activity->retrieve($row['id']);
648                                 $activity->fixUpFormatting();
649                                 $activities[] = $activity;
650             }
651                 }
652
653                 return $activities;
654         }
655
656         protected function copyActivityAndRelateToBean(
657             $activity,
658             $bean
659             )
660         {
661                 global $beanList;
662
663                 $newActivity = clone $activity;
664                 $newActivity->id = create_guid();
665                 $newActivity->new_with_id = true;
666
667                 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
668         if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
669         {
670                 $newActivity->contact_id = $activity->contact_name = "";
671         }
672
673                 if ($rel = $this->findRelationship($newActivity, $bean))
674         {
675             $newActivity->load_relationship ($rel) ;
676             $relObj = $newActivity->$rel->getRelationshipObject();
677             if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
678             {
679                 $key = $relObj->rhs_key;
680                 $newActivity->$key = $bean->id;
681             }
682             $newActivity->parent_id = $bean->id;
683                 $newActivity->parent_type = $bean->module_dir;
684                 $newActivity->update_date_modified = false; //bug 41747 
685                 $newActivity->save();
686             $newActivity->$rel->add($bean);
687             if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
688                         UploadFile::duplicate_file($activity->id, $newActivity->id,  $newActivity->filename);
689                 }
690          }
691         }
692
693     /**
694      * Populates the passed in Bean fron the contact and the $_REQUEST
695      * @param String $module Module of new bean
696      * @param SugarBean $bean SugarBean to be populated.
697      * @param Contact $contact Contact to relate the bean to.
698      */
699         protected function populateNewBean(
700             $module,
701             $bean,
702             $contact,
703             $lead
704             )
705         {
706                 populateFromPost($module, $bean, true);
707
708                 //Copy data from the contact to new bean
709                 foreach($bean->field_defs as $field => $def)
710                 {
711                         if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
712                         {
713                                 $bean->$field = $lead->$field;
714                                 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
715                         }
716                 }
717                 //Try to link to the new contact
718                 $contactRel = "";
719                 if (!empty($vdef['ConvertLead']['select']))
720                 {
721                         $select = $vdef['ConvertLead']['select'];
722                         $fieldDef = $contact->field_defs[$select];
723                         if (!empty($fieldDef['id_name']))
724                         {
725                                 $bean->id = create_guid();
726                                 $bean->new_with_id = true;
727                                 $contact->$fieldDef['id_name'] = $bean->id ;
728                                 if ($fieldDef['id_name'] != $select) {
729                                         $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
730                                         if (!empty($rname) && isset($bean->$rname))
731                                                 $contact->$select = $bean->$rname;
732                                         else
733                                                 $contact->$select = $bean->name;
734                                 }
735                         }
736                 } else if ($module != "Contacts"){
737                         $contactRel = $this->findRelationship($contact, $bean);
738                         if (!empty($contactRel))
739                         {
740                                 $bean->id = create_guid();
741                                 $bean->new_with_id = true;
742                                 $contact->load_relationship ($contactRel) ;
743                                 $relObject = $contact->$contactRel->getRelationshipObject();
744                                 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
745                                 {
746                                         $id_field = $relObject->rhs_key;
747                                         $bean->$id_field = $contact->id;
748                                 } else {
749                                         $contact->$contactRel->add($bean);
750                                 }
751                                 //Set the parent of activites to the new Contact
752                                 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
753                                 {
754                                         $bean->parent_id = $contact->id;
755                                         $bean->parent_type = "Contacts";
756                                 }
757                         }
758                 }
759         }
760
761         protected function copyAddressFields($bean, $contact)
762         {
763         //Copy over address info from the contact to any beans with address not set
764                 foreach($bean->field_defs as $field => $def)
765                         {
766                                 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
767                                 {
768                                         $set = "primary";
769                                         if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
770                                                 $set = "alt";
771                                         $type = "";
772
773                                         if(strpos($field, "_address_street_2") !== false)
774                                                 $type = "_address_street_2";
775                                         else if(strpos($field, "_address_street_3") !== false)
776                                                 $type = "_address_street_3";
777                                         else if(strpos($field, "_address_street_4") !== false)
778                                                 $type = "";
779                                         else if(strpos($field, "_address_street") !== false)
780                                                 $type = "_address_street";
781                                         else if(strpos($field, "_address_city") !== false)
782                                                 $type = "_address_city";
783                                         else if(strpos($field, "_address_state") !== false)
784                                                 $type = "_address_state";
785                                         else if(strpos($field, "_address_postalcode") !== false)
786                                                 $type = "_address_postalcode";
787                                         else if(strpos($field, "_address_country") !== false)
788                                                 $type = "_address_country";
789
790                                                 $var = $set.$type;
791                                         if (isset($contact->$var))
792                                                 $bean->$field = $contact->$var;
793                                 }
794                         }
795         }
796
797
798     protected function findRelationship(
799         $from,
800         $to
801         )
802     {
803         global $dictionary;
804         require_once("modules/TableDictionary.php");
805         foreach ($from->field_defs as $field=>$def)
806         {
807             if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship'])) 
808                         {
809                 $rel_name = $def['relationship'];
810                 $rel_def = "";
811                 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
812                 {
813                     $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
814                 }
815                 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
816                 {
817                     $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
818                 }
819                 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
820                         && isset($dictionary[$rel_name]['relationships'][$rel_name]))
821                 {
822                         $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
823                 }
824                 if (!empty($rel_def)) {
825                     if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
826                     {
827                         return $field;
828                     }
829                     else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
830                     {
831                         return $field;
832                     }
833                 }
834             }
835         }
836         return false;
837     }
838
839     protected function findRelationshipByName($from, $rel_name)
840     {
841         global $dictionary;
842         require_once("modules/TableDictionary.php");
843         foreach ($from->field_defs as $field => $def)
844         {
845             if (isset($def['relationship']) && $def['relationship'] == $rel_name) 
846             {
847                 return $field;
848             }
849         }
850         return false;
851     }
852         /**
853          * @see SugarView::_getModuleTitleParams()
854          */
855         protected function _getModuleTitleParams($browserTitle = false)
856         {
857             global $mod_strings;
858             $params = parent::_getModuleTitleParams($browserTitle);
859             $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
860             $params[] = $mod_strings['LBL_CONVERTLEAD'];
861         return $params;
862     }
863
864
865     protected function checkForDuplicates(
866         $lead
867         )
868     {
869         if ($lead->status == "Converted")
870         {
871                 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
872                 $dupes = array();
873                 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
874                 $result = $lead->db->query($q);
875                 while($row = $lead->db->fetchByAssoc($result)) {
876                         $contact = new Contact();
877                         $contact->retrieve($row['id']);
878                         $dupes[$row['id']] = $contact->name;
879                 }
880                 if (!empty($dupes))
881                 {
882                         foreach($dupes as $id => $name)
883                         {
884                                 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");
885                                 break;
886                         }
887                 }
888                 echo "</span>";
889         }
890         return false;
891     }
892 }