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.
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";
58 public function preDisplay()
60 if (!$this->bean->ACLAccess('edit')) {
61 ACLController::displayNoAccess();
67 * @see SugarView::display()
69 public function display()
71 if (!empty($_REQUEST['handle']) && $_REQUEST['handle'] == 'save')
73 return $this->handleSave();
78 // get the EditView defs to check if opportunity_name exists, for a check below for populating data
79 $opportunityNameInLayout = false;
80 $editviewFile = 'modules/Leads/metadata/editviewdefs.php';
81 $this->medataDataFile = $editviewFile;
82 if (file_exists("custom/{$editviewFile}"))
84 $this->medataDataFile = "custom/{$editviewFile}";
86 include($this->medataDataFile);
87 foreach($viewdefs['Leads']['EditView']['panels'] as $panel_index => $section){
88 foreach($section as $row_array){
89 foreach($row_array as $cell){
90 if(isset($cell['name']) && $cell['name'] == 'opportunity_name'){
91 $opportunityNameInLayout = true;
97 $this->medataDataFile = $this->fileName;
98 if (file_exists("custom/$this->fileName"))
100 $this->medataDataFile = "custom/$this->fileName";
104 $this->checkForDuplicates($this->focus);
105 $smarty = new Sugar_Smarty();
106 $ev = new EditView();
108 $ev->view = "ConvertLead";
109 echo $this->getModuleTitle();
111 require_once("include/QuickSearchDefaults.php");
112 $qsd = new QuickSearchDefaults();
113 $qsd->setFormName("ConvertLead");
115 $this->contact = new Contact();
116 $smarty->assign("contact_def", $this->contact->field_defs);
117 $smarty->assign("form_name", "ConvertLead");
118 $smarty->assign("form_id", "ConvertLead");
119 $smarty->assign("module", "Leads");
120 $smarty->assign("view", "convertlead");
121 $smarty->assign("bean", $this->focus);
122 $smarty->assign("record_id", $this->focus->id);
123 $smarty->display("modules/Leads/tpls/ConvertLeadHeader.tpl");
125 echo "<div class='edit view' style='width:auto;'>";
127 foreach($this->defs as $module => $vdef)
129 if(!isset($beanList[$module]))
133 $bean = $beanList[$module];
134 $focus = new $bean();
135 $focus->fill_in_additional_detail_fields();
136 foreach($focus->field_defs as $field => $def)
138 if(isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData'])
140 if ($module == "Accounts" && $field == 'name')
142 $focus->name = $this->focus->account_name;
144 else if ($module == "Opportunities" && $field == 'amount')
146 $focus->amount = unformat_number($this->focus->opportunity_amount);
148 else if ($module == "Opportunities" && $field == 'name') {
149 if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)){
150 $focus->name = $this->focus->opportunity_name;
153 else if ($field == "id")
155 //If it is not a contact, don't copy the ID from the lead
156 if ($module == "Contacts") {
157 $focus->$field = $this->focus->$field;
159 } else if (is_a($focus, "Company") && $field == 'phone_office')
161 //Special case where company and person have the same field with a different name
162 $focus->phone_office = $this->focus->phone_work;
164 else if (isset($this->focus->$field))
166 $focus->$field = $this->focus->$field;
171 //Copy over email data
172 $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
174 echo($ev->display(false));
175 echo($this->getValidationJS($module, $focus, $vdef[$ev->view]));
178 echo ($qsd->getQSScriptsJSONAlreadyDefined());
179 $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
182 protected function getRecord()
184 $this->focus = new Lead();
185 if (isset($_REQUEST['record']))
187 $this->focus->retrieve($_REQUEST['record']);
191 protected function loadDefs()
194 include($this->medataDataFile);
195 $this->defs = $viewdefs;
199 * Returns the javascript to enable/disable validation of each module's sub-form
200 * //TODO: This should probably be on the smarty template
201 * @param $module String the target module name.
202 * @param $focus SugarBean instance of the target module.
203 * @param $focus EditView def for the module.
204 * @return String, javascript to echo to page.
206 protected function getValidationJS(
212 $validateSelect = isset($viewdef['required']) && $viewdef['required'] && !empty($viewdef['select']);
214 <script type='text/javascript'>
215 if (!SUGAR.convert) SUGAR.convert = {requiredFields: {}};
216 SUGAR.convert.toggle$module = function(){
218 inputsWithErrors = [];
219 if(!SUGAR.convert.{$module}Enabled)
221 for(var i in SUGAR.convert.requiredFields.$module)
223 addToValidate('ConvertLead', '$module' + i, 'varchar', true, SUGAR.convert.requiredFields.{$module}[i]);
226 if ($validateSelect) {
228 removeFromValidate('ConvertLead', '{$viewdef['select']}');";
232 SUGAR.convert.{$module}Enabled = true;
234 for(var i in SUGAR.convert.requiredFields.$module)
236 removeFromValidate('ConvertLead', '$module' + i);
238 if ($validateSelect) {
240 addToValidate('ConvertLead', '{$viewdef['select']}', 'varchar', true, '"
241 . translate($this->contact->field_defs[$viewdef['select']]['vname']) . "');";
244 SUGAR.convert.{$module}Enabled = false;
246 YAHOO.util.Dom.get('convert_create_{$module}').value = SUGAR.convert.{$module}Enabled;
249 if (isset($viewdef['required']) && $viewdef['required'])
251 if (!empty($viewdef['select']) && (empty($viewdef['default_action']) || $viewdef['default_action'] != 'create'))
254 SUGAR.convert.{$module}Enabled = true;";
257 YAHOO.util.Event.onDOMReady(SUGAR.convert.toggle$module);";
258 } else if (isset($viewdef['default_action']) && $viewdef['default_action'] == "create")
260 $jsOut .= "\n SUGAR.convert.{$module}Enabled = true;";
263 YAHOO.util.Event.addListener('new$module', 'click', SUGAR.convert.toggle$module);
264 SUGAR.convert.requiredFields.$module = {};";
265 foreach($focus->field_defs as $field => $def)
267 if (isset($def['required']) && $def['required'])
270 SUGAR.convert.requiredFields.$module.$field = '". translate($def['vname'], $module) . "';\n";
281 * Saves a new Contact as well as any related items passed in.
285 protected function handleSave()
287 require_once("include/formbase.php");
289 if (!empty($_REQUEST['record']))
292 $lead->retrieve($_REQUEST['record']);
298 $selectedBeans = array();
300 //Make sure the contact object is availible for relationships.
301 $beans['Contacts'] = new Contact();
302 $beans['Contacts']->id = create_guid();
303 $beans['Contacts']->new_with_id = true;
305 // Bug 39287 - Check for Duplicates on selected modules before save
306 if ( !empty($_REQUEST['selectedContact']) ) {
307 $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
308 if ( !empty($beans['Contacts']->id) ) {
309 $beans['Contacts']->new_with_id = false;
310 unset($_REQUEST["convert_create_Contacts"]);
311 unset($_POST["convert_create_Contacts"]);
314 elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact'])) {
315 require_once('modules/Contacts/ContactFormBase.php');
316 $contactForm = new ContactFormBase();
317 $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
318 if(isset($duplicateContacts)){
319 echo $contactForm->buildTableForm($duplicateContacts, 'Contacts');
323 if ( !empty($_REQUEST['selectedAccount']) ) {
324 $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
325 unset($_REQUEST["convert_create_Accounts"]);
326 unset($_POST["convert_create_Accounts"]);
328 elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount'])){
329 require_once('modules/Accounts/AccountFormBase.php');
330 $accountForm = new AccountFormBase();
331 $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
332 if(isset($duplicateAccounts)){
333 echo $accountForm->buildTableForm($duplicateAccounts);
338 foreach($this->defs as $module => $vdef)
340 //Create a new record if "create" was selected
341 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
343 //Save the new record
344 $bean = $beanList[$module];
345 if (empty($beans[$module]))
346 $beans[$module] = new $bean();
348 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
351 //If an existing bean was selected, relate it to the contact
352 else if (!empty($vdef['ConvertLead']['select'])) {
353 //Save the new record
354 $select = $vdef['ConvertLead']['select'];
355 $fieldDef = $beans['Contacts']->field_defs[$select];
356 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
358 $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
359 $selects[$module] = $_REQUEST[$fieldDef['id_name']];
360 if (!empty($_REQUEST[$select]))
362 $beans['Contacts']->$select = $_REQUEST[$select];
364 // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
365 $bean = loadBean($module);
366 $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
367 $selectedBeans[$module] = $bean;
372 $this->handleActivities($lead, $beans);
373 // Bug 39268 - Add the lead's activities to the selected beans
374 $this->handleActivities($lead, $selectedBeans);
376 //link selected account to lead if it exists
377 if(!empty($selectedBeans['Accounts'])){
378 $lead->account_id = $selectedBeans['Accounts']->id;
381 //Handle non-contacts relationships
382 foreach($beans as $bean)
386 if (empty($bean->assigned_user_id))
388 $bean->assigned_user_id = $lead->assigned_user_id;
390 $leadsRel = $this->findRelationship($bean, $lead);
391 if (!empty($leadsRel))
394 $bean->load_relationship ($leadsRel) ;
395 $relObject = $bean->$leadsRel->getRelationshipObject();
396 if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
398 $id_field = $relObject->rhs_key;
399 $lead->$id_field = $bean->id;
401 $bean->$leadsRel->add($lead->id);
405 //Special case code for opportunities->Accounts
406 if ($bean->object_name == "Opportunity" && empty($bean->account_id))
408 if( isset($beans['Accounts'])) {
409 $bean->account_id = $beans['Accounts']->id;
410 $bean->account_name = $beans['Accounts']->name;
412 else if (!empty($selects['Accounts'])){
413 $bean->account_id = $selects['Accounts'];
417 $this->copyAddressFields($bean, $beans['Contacts']);
422 { //Mark the original Lead converted
423 $lead->status = "Converted";
424 $lead->converted = '1';
425 $lead->in_workflow = true;
429 $this->displaySaveResults($beans);
432 protected function displaySaveResults(
438 foreach($beans as $bean)
440 $beanName = $bean->object_name;
441 if ( $beanName == 'Contact' && !$bean->new_with_id ) {
442 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
443 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
444 {$bean->get_summary_text()}
448 global $app_list_strings;
449 if(!empty($app_list_strings['moduleListSingular'][$bean->module_dir])) {
450 $module_name = $app_list_strings['moduleListSingular'][$bean->module_dir];
452 $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
454 if(empty($module_name)) {
455 $module_name = translate($beanName);
457 echo "<li>" . translate("LBL_CREATED_NEW") . ' ' . $module_name . " -
458 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
459 {$bean->get_summary_text()}
467 protected function handleActivities(
472 global $app_list_strings;
473 $parent_types = $app_list_strings['record_type_display'];
475 $activities = $this->getActivitiesFromLead($lead);
477 foreach($beans as $module => $bean)
479 if (isset($parent_types[$module]))
481 foreach($activities as $activity)
483 $this->copyActivityAndRelateToBean($activity, $bean);
490 * Gets the list of activities related to the lead
491 * @param Lead $lead Lead to get activities from
492 * @return Array of Activity SugarBeans .
494 protected function getActivitiesFromLead(
500 global $beanList, $db;
502 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
503 $activities = array();
505 foreach($activitesList as $module)
507 $beanName = $beanList[$module];
508 $activity = new $beanName();
509 $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
510 $result = $db->query($query,true);
511 while($row = $db->fetchByAssoc($result))
513 $activity = new $beanName();
514 $activity->retrieve($row['id']);
515 $activity->fixUpFormatting();
516 $activities[] = $activity;
523 protected function copyActivityAndRelateToBean(
530 $newActivity = clone $activity;
531 $newActivity->id = create_guid();
532 $newActivity->new_with_id = true;
534 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
535 if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
537 $newActivity->contact_id = $activity->contact_name = "";
540 if ($rel = $this->findRelationship($newActivity, $bean))
542 $newActivity->load_relationship ($rel) ;
543 $relObj = $newActivity->$rel->getRelationshipObject();
544 if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
546 $key = $relObj->rhs_key;
547 $newActivity->$key = $bean->id;
549 $newActivity->$rel->add($bean->id);
550 $newActivity->parent_id = $bean->id;
551 $newActivity->parent_type = $bean->module_dir;
552 $newActivity->update_date_modified = false; //bug 41747
553 $newActivity->save();
554 if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
555 UploadFile::duplicate_file($activity->id, $newActivity->id, $newActivity->filename);
561 * Populates the passed in Bean fron the contact and the $_REQUEST
562 * @param String $module Module of new bean
563 * @param SugarBean $bean SugarBean to be populated.
564 * @param Contact $contact Contact to relate the bean to.
566 protected function populateNewBean(
573 populateFromPost($module, $bean, true);
575 //Copy data from the contact to new bean
576 foreach($bean->field_defs as $field => $def)
578 if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
580 $bean->$field = $lead->$field;
581 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
584 //Try to link to the new contact
586 if (!empty($vdef['ConvertLead']['select']))
588 $select = $vdef['ConvertLead']['select'];
589 $fieldDef = $contact->field_defs[$select];
590 if (!empty($fieldDef['id_name']))
592 $bean->id = create_guid();
593 $bean->new_with_id = true;
594 $contact->$fieldDef['id_name'] = $bean->id ;
595 if ($fieldDef['id_name'] != $select) {
596 $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
597 if (!empty($rname) && isset($bean->$rname))
598 $contact->$select = $bean->$rname;
600 $contact->$select = $bean->name;
603 } else if ($module != "Contacts"){
604 $contactRel = $this->findRelationship($contact, $bean);
605 if (!empty($contactRel))
607 $bean->id = create_guid();
608 $bean->new_with_id = true;
609 $contact->load_relationship ($contactRel) ;
610 $relObject = $contact->$contactRel->getRelationshipObject();
611 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
613 $id_field = $relObject->rhs_key;
614 $bean->$id_field = $contact->id;
616 $contact->$contactRel->add($bean->id);
618 //Set the parent of activites to the new Contact
619 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
621 $bean->parent_id = $contact->id;
622 $bean->parent_type = "Contacts";
628 protected function copyAddressFields($bean, $contact)
630 //Copy over address info from the contact to any beans with address not set
631 foreach($bean->field_defs as $field => $def)
633 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
636 if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
640 if(strpos($field, "_address_street_2") !== false)
641 $type = "_address_street_2";
642 else if(strpos($field, "_address_street_3") !== false)
643 $type = "_address_street_3";
644 else if(strpos($field, "_address_street_4") !== false)
646 else if(strpos($field, "_address_street") !== false)
647 $type = "_address_street";
648 else if(strpos($field, "_address_city") !== false)
649 $type = "_address_city";
650 else if(strpos($field, "_address_state") !== false)
651 $type = "_address_state";
652 else if(strpos($field, "_address_postalcode") !== false)
653 $type = "_address_postalcode";
654 else if(strpos($field, "_address_country") !== false)
655 $type = "_address_country";
658 if (isset($contact->$var))
659 $bean->$field = $contact->$var;
665 protected function findRelationship(
671 require_once("modules/TableDictionary.php");
672 foreach ($from->field_defs as $field=>$def)
674 if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship'])) {
675 $rel_name = $def['relationship'];
677 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
679 $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
681 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
683 $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
685 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
686 && isset($dictionary[$rel_name]['relationships'][$rel_name]))
688 $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
690 if (!empty($rel_def)) {
691 if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
695 else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
706 * @see SugarView::_getModuleTitleParams()
708 protected function _getModuleTitleParams($browserTitle = false)
711 $params = parent::_getModuleTitleParams($browserTitle);
712 $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
713 $params[] = $mod_strings['LBL_CONVERTLEAD'];
718 protected function checkForDuplicates(
722 if ($lead->status == "Converted")
724 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
726 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
727 $result = $lead->db->query($q);
728 while($row = $lead->db->fetchByAssoc($result)) {
729 $contact = new Contact();
730 $contact->retrieve($row['id']);
731 $dupes[$row['id']] = $contact->name;
735 foreach($dupes as $id => $name)
737 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");