2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
38 require_once("include/EditView/EditView2.php");
39 require_once("include/upload_file.php");
41 class ViewConvertLead extends SugarView
43 protected $fileName = "modules/Leads/metadata/convertdefs.php";
45 public function __construct(
47 $view_object_map = array()
50 parent::SugarView($bean, $view_object_map);
51 $this->medataDataFile = $this->fileName;
52 if (file_exists("custom/$this->fileName"))
54 $this->medataDataFile = "custom/$this->fileName";
59 * @see SugarView::display()
61 public function display()
63 if (!empty($_REQUEST['handle']) && $_REQUEST['handle'] == 'save')
65 return $this->handleSave();
70 // get the EditView defs to check if opportunity_name exists, for a check below for populating data
71 $opportunityNameInLayout = false;
72 $editviewFile = 'modules/Leads/metadata/editviewdefs.php';
73 $this->medataDataFile = $editviewFile;
74 if (file_exists("custom/{$editviewFile}"))
76 $this->medataDataFile = "custom/{$editviewFile}";
78 include($this->medataDataFile);
79 foreach($viewdefs['Leads']['EditView']['panels'] as $panel_index => $section){
80 foreach($section as $row_array){
81 foreach($row_array as $cell){
82 if(isset($cell['name']) && $cell['name'] == 'opportunity_name'){
83 $opportunityNameInLayout = true;
89 $this->medataDataFile = $this->fileName;
90 if (file_exists("custom/$this->fileName"))
92 $this->medataDataFile = "custom/$this->fileName";
96 $this->checkForDuplicates($this->focus);
97 $smarty = new Sugar_Smarty();
100 $ev->view = "ConvertLead";
101 echo $this->getModuleTitle();
103 require_once("include/QuickSearchDefaults.php");
104 $qsd = new QuickSearchDefaults();
105 $qsd->setFormName("ConvertLead");
107 $this->contact = new Contact();
108 $smarty->assign("contact_def", $this->contact->field_defs);
109 $smarty->assign("form_name", "ConvertLead");
110 $smarty->assign("form_id", "ConvertLead");
111 $smarty->assign("module", "Leads");
112 $smarty->assign("view", "convertlead");
113 $smarty->assign("bean", $this->focus);
114 $smarty->assign("record_id", $this->focus->id);
115 $smarty->display("modules/Leads/tpls/ConvertLeadHeader.tpl");
117 echo "<div class='edit view' style='width:auto;'>";
119 foreach($this->defs as $module => $vdef)
121 $bean = $beanList[$module];
122 $focus = new $bean();
123 $focus->fill_in_additional_detail_fields();
124 foreach($focus->field_defs as $field => $def)
126 if(isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData'])
128 if ($module == "Accounts" && $field == 'name')
130 $focus->name = $this->focus->account_name;
132 else if ($module == "Opportunities" && $field == 'amount')
134 $focus->amount = unformat_number($this->focus->opportunity_amount);
136 else if ($module == "Opportunities" && $field == 'name') {
137 if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)){
138 $focus->name = $this->focus->opportunity_name;
141 else if ($field == "id")
143 //If it is not a contact, don't copy the ID from the lead
144 if ($module == "Contacts") {
145 $focus->$field = $this->focus->$field;
147 } else if (is_a($focus, "Company") && $field == 'phone_office')
149 //Special case where company and person have the same field with a different name
150 $focus->phone_office = $this->focus->phone_work;
152 else if (isset($this->focus->$field))
154 $focus->$field = $this->focus->$field;
159 //Copy over email data
160 $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
162 echo($ev->display(false));
163 echo($this->getValidationJS($module, $focus, $vdef[$ev->view]));
166 echo ($qsd->getQSScriptsJSONAlreadyDefined());
167 $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
170 protected function getRecord()
172 $this->focus = new Lead();
173 if (isset($_REQUEST['record']))
175 $this->focus->retrieve($_REQUEST['record']);
179 protected function loadDefs()
182 include($this->medataDataFile);
183 $this->defs = $viewdefs;
187 * Returns the javascript to enable/disable validation of each module's sub-form
188 * //TODO: This should probably be on the smarty template
189 * @param $module String the target module name.
190 * @param $focus SugarBean instance of the target module.
191 * @param $focus EditView def for the module.
192 * @return String, javascript to echo to page.
194 protected function getValidationJS(
200 $validateSelect = isset($viewdef['required']) && $viewdef['required'] && !empty($viewdef['select']);
202 <script type='text/javascript'>
203 if (!SUGAR.convert) SUGAR.convert = {requiredFields: {}};
204 SUGAR.convert.toggle$module = function(){
206 inputsWithErrors = [];
207 if(!SUGAR.convert.{$module}Enabled)
209 for(var i in SUGAR.convert.requiredFields.$module)
211 addToValidate('ConvertLead', '$module' + i, 'varchar', true, SUGAR.convert.requiredFields.{$module}[i]);
214 if ($validateSelect) {
216 removeFromValidate('ConvertLead', '{$viewdef['select']}');";
220 SUGAR.convert.{$module}Enabled = true;
222 for(var i in SUGAR.convert.requiredFields.$module)
224 removeFromValidate('ConvertLead', '$module' + i);
226 if ($validateSelect) {
228 addToValidate('ConvertLead', '{$viewdef['select']}', 'varchar', true, '"
229 . translate($this->contact->field_defs[$viewdef['select']]['vname']) . "');";
232 SUGAR.convert.{$module}Enabled = false;
234 YAHOO.util.Dom.get('convert_create_{$module}').value = SUGAR.convert.{$module}Enabled;
237 if (isset($viewdef['required']) && $viewdef['required'])
239 if (!empty($viewdef['select']) && (empty($viewdef['default_action']) || $viewdef['default_action'] != 'create'))
242 SUGAR.convert.{$module}Enabled = true;";
245 YAHOO.util.Event.onDOMReady(SUGAR.convert.toggle$module);";
246 } else if (isset($viewdef['default_action']) && $viewdef['default_action'] == "create")
248 $jsOut .= "\n SUGAR.convert.{$module}Enabled = true;";
251 YAHOO.util.Event.addListener('new$module', 'click', SUGAR.convert.toggle$module);
252 SUGAR.convert.requiredFields.$module = {};";
253 foreach($focus->field_defs as $field => $def)
255 if (isset($def['required']) && $def['required'])
258 SUGAR.convert.requiredFields.$module.$field = '". translate($def['vname'], $module) . "';\n";
269 * Saves a new Contact as well as any related items passed in.
273 protected function handleSave()
275 require_once("include/formbase.php");
277 if (!empty($_REQUEST['record']))
280 $lead->retrieve($_REQUEST['record']);
286 $selectedBeans = array();
288 //Make sure the contact object is availible for relationships.
289 $beans['Contacts'] = new Contact();
290 $beans['Contacts']->id = create_guid();
291 $beans['Contacts']->new_with_id = true;
293 // Bug 39287 - Check for Duplicates on selected modules before save
294 if ( !empty($_REQUEST['selectedContact']) ) {
295 $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
296 if ( !empty($beans['Contacts']->id) ) {
297 $beans['Contacts']->new_with_id = false;
298 unset($_REQUEST["convert_create_Contacts"]);
299 unset($_POST["convert_create_Contacts"]);
302 elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact'])) {
303 require_once('modules/Contacts/ContactFormBase.php');
304 $contactForm = new ContactFormBase();
305 $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
306 if(isset($duplicateContacts)){
307 echo $contactForm->buildTableForm($duplicateContacts, 'Contacts');
311 if ( !empty($_REQUEST['selectedAccount']) ) {
312 $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
313 unset($_REQUEST["convert_create_Accounts"]);
314 unset($_POST["convert_create_Accounts"]);
316 elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount'])){
317 require_once('modules/Accounts/AccountFormBase.php');
318 $accountForm = new AccountFormBase();
319 $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
320 if(isset($duplicateAccounts)){
321 echo $accountForm->buildTableForm($duplicateAccounts);
326 foreach($this->defs as $module => $vdef)
328 //Create a new record if "create" was selected
329 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
331 //Save the new record
332 $bean = $beanList[$module];
333 if (empty($beans[$module]))
334 $beans[$module] = new $bean();
336 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
339 //If an existing bean was selected, relate it to the contact
340 else if (!empty($vdef['ConvertLead']['select'])) {
341 //Save the new record
342 $select = $vdef['ConvertLead']['select'];
343 $fieldDef = $beans['Contacts']->field_defs[$select];
344 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
346 $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
347 $selects[$module] = $_REQUEST[$fieldDef['id_name']];
348 if (!empty($_REQUEST[$select]))
350 $beans['Contacts']->$select = $_REQUEST[$select];
352 // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
353 $bean = loadBean($module);
354 $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
355 $selectedBeans[$module] = $bean;
360 $this->handleActivities($lead, $beans);
361 // Bug 39268 - Add the lead's activities to the selected beans
362 $this->handleActivities($lead, $selectedBeans);
364 //link selected account to lead if it exists
365 if(!empty($selectedBeans['Accounts'])){
366 $lead->account_id = $selectedBeans['Accounts']->id;
369 //Handle non-contacts relationships
370 foreach($beans as $bean)
374 if (empty($bean->assigned_user_id))
376 $bean->assigned_user_id = $lead->assigned_user_id;
378 $leadsRel = $this->findRelationship($bean, $lead);
379 if (!empty($leadsRel))
382 $bean->load_relationship ($leadsRel) ;
383 $relObject = $bean->$leadsRel->getRelationshipObject();
384 if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
386 $id_field = $relObject->rhs_key;
387 $lead->$id_field = $bean->id;
389 $bean->$leadsRel->add($lead->id);
393 //Special case code for opportunities->Accounts
394 if ($bean->object_name == "Opportunity" && empty($bean->account_id))
396 if( isset($beans['Accounts'])) {
397 $bean->account_id = $beans['Accounts']->id;
398 $bean->account_name = $beans['Accounts']->name;
400 else if (!empty($selects['Accounts'])){
401 $bean->account_id = $selects['Accounts'];
405 $this->copyAddressFields($bean, $beans['Contacts']);
410 { //Mark the original Lead converted
411 $lead->status = "Converted";
412 $lead->converted = '1';
413 $lead->in_workflow = true;
417 $this->displaySaveResults($beans);
420 protected function displaySaveResults(
426 foreach($beans as $bean)
428 $beanName = $bean->object_name;
429 if ( $beanName == 'Contact' && !$bean->new_with_id ) {
430 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
431 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
432 {$bean->get_summary_text()}
436 echo "<li>" . translate("LBL_CREATED_NEW") . translate($beanName) . " -
437 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
438 {$bean->get_summary_text()}
446 protected function handleActivities(
451 global $app_list_strings;
452 $parent_types = $app_list_strings['record_type_display'];
454 $activities = $this->getActivitiesFromLead($lead);
456 foreach($beans as $module => $bean)
458 if (isset($parent_types[$module]))
460 foreach($activities as $activity)
462 $this->copyActivityAndRelateToBean($activity, $bean);
469 * Gets the list of activities related to the lead
470 * @param Lead $lead Lead to get activities from
471 * @return Array of Activity SugarBeans .
473 protected function getActivitiesFromLead(
479 global $beanList, $db;
481 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
482 $activities = array();
484 foreach($activitesList as $module)
486 $beanName = $beanList[$module];
487 $activity = new $beanName();
488 $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
489 $result = $db->query($query,true);
490 while($row = $db->fetchByAssoc($result))
492 $activity = new $beanName();
493 $activity->retrieve($row['id']);
494 $activity->fixUpFormatting();
495 $activities[] = $activity;
502 protected function copyActivityAndRelateToBean(
509 $newActivity = clone $activity;
510 $newActivity->id = create_guid();
511 $newActivity->new_with_id = true;
513 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
514 if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
516 $newActivity->contact_id = $activity->contact_name = "";
519 if ($rel = $this->findRelationship($newActivity, $bean))
521 $newActivity->load_relationship ($rel) ;
522 $relObj = $newActivity->$rel->getRelationshipObject();
523 if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
525 $key = $relObj->rhs_key;
526 $newActivity->$key = $bean->id;
528 $newActivity->$rel->add($bean->id);
529 $newActivity->parent_id = $bean->id;
530 $newActivity->parent_type = $bean->module_dir;
531 $newActivity->update_date_modified = false; //bug 41747
532 $newActivity->save();
533 if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
534 UploadFile::duplicate_file($activity->id, $newActivity->id, $newActivity->filename);
540 * Populates the passed in Bean fron the contact and the $_REQUEST
541 * @param String $module Module of new bean
542 * @param SugarBean $bean SugarBean to be populated.
543 * @param Contact $contact Contact to relate the bean to.
545 protected function populateNewBean(
552 populateFromPost($module, $bean, true);
554 //Copy data from the contact to new bean
555 foreach($bean->field_defs as $field => $def)
557 if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
559 $bean->$field = $lead->$field;
560 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
563 //Try to link to the new contact
565 if (!empty($vdef['ConvertLead']['select']))
567 $select = $vdef['ConvertLead']['select'];
568 $fieldDef = $contact->field_defs[$select];
569 if (!empty($fieldDef['id_name']))
571 $bean->id = create_guid();
572 $bean->new_with_id = true;
573 $contact->$fieldDef['id_name'] = $bean->id ;
574 if ($fieldDef['id_name'] != $select) {
575 $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
576 if (!empty($rname) && isset($bean->$rname))
577 $contact->$select = $bean->$rname;
579 $contact->$select = $bean->name;
582 } else if ($module != "Contacts"){
583 $contactRel = $this->findRelationship($contact, $bean);
584 if (!empty($contactRel))
586 $bean->id = create_guid();
587 $bean->new_with_id = true;
588 $contact->load_relationship ($contactRel) ;
589 $relObject = $contact->$contactRel->getRelationshipObject();
590 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
592 $id_field = $relObject->rhs_key;
593 $bean->$id_field = $contact->id;
595 $contact->$contactRel->add($bean->id);
597 //Set the parent of activites to the new Contact
598 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
600 $bean->parent_id = $contact->id;
601 $bean->parent_type = "Contacts";
607 protected function copyAddressFields($bean, $contact)
609 //Copy over address info from the contact to any beans with address not set
610 foreach($bean->field_defs as $field => $def)
612 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
615 if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
619 if(strpos($field, "_address_street_2") !== false)
620 $type = "_address_street_2";
621 else if(strpos($field, "_address_street_3") !== false)
622 $type = "_address_street_3";
623 else if(strpos($field, "_address_street_4") !== false)
625 else if(strpos($field, "_address_street") !== false)
626 $type = "_address_street";
627 else if(strpos($field, "_address_city") !== false)
628 $type = "_address_city";
629 else if(strpos($field, "_address_state") !== false)
630 $type = "_address_state";
631 else if(strpos($field, "_address_postalcode") !== false)
632 $type = "_address_postalcode";
633 else if(strpos($field, "_address_country") !== false)
634 $type = "_address_country";
637 if (isset($contact->$var))
638 $bean->$field = $contact->$var;
644 protected function findRelationship(
650 require_once("modules/TableDictionary.php");
651 foreach ($from->field_defs as $field=>$def)
653 if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship'])) {
654 $rel_name = $def['relationship'];
656 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
658 $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
660 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
662 $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
664 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
665 && isset($dictionary[$rel_name]['relationships'][$rel_name]))
667 $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
669 if (!empty($rel_def)) {
670 if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
674 else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
685 * @see SugarView::_getModuleTitleParams()
687 protected function _getModuleTitleParams()
690 $params = parent::_getModuleTitleParams();
691 $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
692 $params[] = $mod_strings['LBL_CONVERTLEAD'];
697 protected function checkForDuplicates(
701 if ($lead->status == "Converted")
703 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
705 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
706 $result = $lead->db->query($q);
707 while($row = $lead->db->fetchByAssoc($result)) {
708 $contact = new Contact();
709 $contact->retrieve($row['id']);
710 $dupes[$row['id']] = $contact->name;
714 foreach($dupes as $id => $name)
716 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");