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";
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 $bean = $beanList[$module];
130 $focus = new $bean();
131 $focus->fill_in_additional_detail_fields();
132 foreach($focus->field_defs as $field => $def)
134 if(isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData'])
136 if ($module == "Accounts" && $field == 'name')
138 $focus->name = $this->focus->account_name;
140 else if ($module == "Opportunities" && $field == 'amount')
142 $focus->amount = unformat_number($this->focus->opportunity_amount);
144 else if ($module == "Opportunities" && $field == 'name') {
145 if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)){
146 $focus->name = $this->focus->opportunity_name;
149 else if ($field == "id")
151 //If it is not a contact, don't copy the ID from the lead
152 if ($module == "Contacts") {
153 $focus->$field = $this->focus->$field;
155 } else if (is_a($focus, "Company") && $field == 'phone_office')
157 //Special case where company and person have the same field with a different name
158 $focus->phone_office = $this->focus->phone_work;
160 else if (isset($this->focus->$field))
162 $focus->$field = $this->focus->$field;
167 //Copy over email data
168 $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
170 echo($ev->display(false));
171 echo($this->getValidationJS($module, $focus, $vdef[$ev->view]));
174 echo ($qsd->getQSScriptsJSONAlreadyDefined());
175 $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
178 protected function getRecord()
180 $this->focus = new Lead();
181 if (isset($_REQUEST['record']))
183 $this->focus->retrieve($_REQUEST['record']);
187 protected function loadDefs()
190 include($this->medataDataFile);
191 $this->defs = $viewdefs;
195 * Returns the javascript to enable/disable validation of each module's sub-form
196 * //TODO: This should probably be on the smarty template
197 * @param $module String the target module name.
198 * @param $focus SugarBean instance of the target module.
199 * @param $focus EditView def for the module.
200 * @return String, javascript to echo to page.
202 protected function getValidationJS(
208 $validateSelect = isset($viewdef['required']) && $viewdef['required'] && !empty($viewdef['select']);
210 <script type='text/javascript'>
211 if (!SUGAR.convert) SUGAR.convert = {requiredFields: {}};
212 SUGAR.convert.toggle$module = function(){
214 inputsWithErrors = [];
215 if(!SUGAR.convert.{$module}Enabled)
217 for(var i in SUGAR.convert.requiredFields.$module)
219 addToValidate('ConvertLead', '$module' + i, 'varchar', true, SUGAR.convert.requiredFields.{$module}[i]);
222 if ($validateSelect) {
224 removeFromValidate('ConvertLead', '{$viewdef['select']}');";
228 SUGAR.convert.{$module}Enabled = true;
230 for(var i in SUGAR.convert.requiredFields.$module)
232 removeFromValidate('ConvertLead', '$module' + i);
234 if ($validateSelect) {
236 addToValidate('ConvertLead', '{$viewdef['select']}', 'varchar', true, '"
237 . translate($this->contact->field_defs[$viewdef['select']]['vname']) . "');";
240 SUGAR.convert.{$module}Enabled = false;
242 YAHOO.util.Dom.get('convert_create_{$module}').value = SUGAR.convert.{$module}Enabled;
245 if (isset($viewdef['required']) && $viewdef['required'])
247 if (!empty($viewdef['select']) && (empty($viewdef['default_action']) || $viewdef['default_action'] != 'create'))
250 SUGAR.convert.{$module}Enabled = true;";
253 YAHOO.util.Event.onDOMReady(SUGAR.convert.toggle$module);";
254 } else if (isset($viewdef['default_action']) && $viewdef['default_action'] == "create")
256 $jsOut .= "\n SUGAR.convert.{$module}Enabled = true;";
259 YAHOO.util.Event.addListener('new$module', 'click', SUGAR.convert.toggle$module);
260 SUGAR.convert.requiredFields.$module = {};";
261 foreach($focus->field_defs as $field => $def)
263 if (isset($def['required']) && $def['required'])
266 SUGAR.convert.requiredFields.$module.$field = '". translate($def['vname'], $module) . "';\n";
277 * Saves a new Contact as well as any related items passed in.
281 protected function handleSave()
283 require_once("include/formbase.php");
285 if (!empty($_REQUEST['record']))
288 $lead->retrieve($_REQUEST['record']);
294 $selectedBeans = array();
296 //Make sure the contact object is availible for relationships.
297 $beans['Contacts'] = new Contact();
298 $beans['Contacts']->id = create_guid();
299 $beans['Contacts']->new_with_id = true;
301 // Bug 39287 - Check for Duplicates on selected modules before save
302 if ( !empty($_REQUEST['selectedContact']) ) {
303 $beans['Contacts']->retrieve($_REQUEST['selectedContact']);
304 if ( !empty($beans['Contacts']->id) ) {
305 $beans['Contacts']->new_with_id = false;
306 unset($_REQUEST["convert_create_Contacts"]);
307 unset($_POST["convert_create_Contacts"]);
310 elseif (!empty($_REQUEST["convert_create_Contacts"]) && $_REQUEST["convert_create_Contacts"] != "false" && !isset($_POST['ContinueContact'])) {
311 require_once('modules/Contacts/ContactFormBase.php');
312 $contactForm = new ContactFormBase();
313 $duplicateContacts = $contactForm->checkForDuplicates('Contacts');
314 if(isset($duplicateContacts)){
315 echo $contactForm->buildTableForm($duplicateContacts, 'Contacts');
319 if ( !empty($_REQUEST['selectedAccount']) ) {
320 $_REQUEST['account_id'] = $_REQUEST['selectedAccount'];
321 unset($_REQUEST["convert_create_Accounts"]);
322 unset($_POST["convert_create_Accounts"]);
324 elseif (!empty($_REQUEST["convert_create_Accounts"]) && $_REQUEST["convert_create_Accounts"] != "false" && empty($_POST['ContinueAccount'])){
325 require_once('modules/Accounts/AccountFormBase.php');
326 $accountForm = new AccountFormBase();
327 $duplicateAccounts = $accountForm->checkForDuplicates('Accounts');
328 if(isset($duplicateAccounts)){
329 echo $accountForm->buildTableForm($duplicateAccounts);
334 foreach($this->defs as $module => $vdef)
336 //Create a new record if "create" was selected
337 if (!empty($_REQUEST["convert_create_$module"]) && $_REQUEST["convert_create_$module"] != "false")
339 //Save the new record
340 $bean = $beanList[$module];
341 if (empty($beans[$module]))
342 $beans[$module] = new $bean();
344 $this->populateNewBean($module, $beans[$module], $beans['Contacts'], $lead);
347 //If an existing bean was selected, relate it to the contact
348 else if (!empty($vdef['ConvertLead']['select'])) {
349 //Save the new record
350 $select = $vdef['ConvertLead']['select'];
351 $fieldDef = $beans['Contacts']->field_defs[$select];
352 if (!empty($fieldDef['id_name']) && !empty($_REQUEST[$fieldDef['id_name']]))
354 $beans['Contacts']->$fieldDef['id_name'] = $_REQUEST[$fieldDef['id_name']];
355 $selects[$module] = $_REQUEST[$fieldDef['id_name']];
356 if (!empty($_REQUEST[$select]))
358 $beans['Contacts']->$select = $_REQUEST[$select];
360 // Bug 39268 - Add the existing beans to a list of beans we'll potentially add the lead's activities to
361 $bean = loadBean($module);
362 $bean->retrieve($_REQUEST[$fieldDef['id_name']]);
363 $selectedBeans[$module] = $bean;
368 $this->handleActivities($lead, $beans);
369 // Bug 39268 - Add the lead's activities to the selected beans
370 $this->handleActivities($lead, $selectedBeans);
372 //link selected account to lead if it exists
373 if(!empty($selectedBeans['Accounts'])){
374 $lead->account_id = $selectedBeans['Accounts']->id;
377 //Handle non-contacts relationships
378 foreach($beans as $bean)
382 if (empty($bean->assigned_user_id))
384 $bean->assigned_user_id = $lead->assigned_user_id;
386 $leadsRel = $this->findRelationship($bean, $lead);
387 if (!empty($leadsRel))
390 $bean->load_relationship ($leadsRel) ;
391 $relObject = $bean->$leadsRel->getRelationshipObject();
392 if ($relObject->relationship_type == "one-to-many" && $bean->$leadsRel->_get_bean_position())
394 $id_field = $relObject->rhs_key;
395 $lead->$id_field = $bean->id;
397 $bean->$leadsRel->add($lead->id);
401 //Special case code for opportunities->Accounts
402 if ($bean->object_name == "Opportunity" && empty($bean->account_id))
404 if( isset($beans['Accounts'])) {
405 $bean->account_id = $beans['Accounts']->id;
406 $bean->account_name = $beans['Accounts']->name;
408 else if (!empty($selects['Accounts'])){
409 $bean->account_id = $selects['Accounts'];
413 $this->copyAddressFields($bean, $beans['Contacts']);
418 { //Mark the original Lead converted
419 $lead->status = "Converted";
420 $lead->converted = '1';
421 $lead->in_workflow = true;
425 $this->displaySaveResults($beans);
428 protected function displaySaveResults(
434 foreach($beans as $bean)
436 $beanName = $bean->object_name;
437 if ( $beanName == 'Contact' && !$bean->new_with_id ) {
438 echo "<li>" . translate("LBL_EXISTING_CONTACT") . " -
439 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
440 {$bean->get_summary_text()}
444 global $app_list_strings;
445 if(!empty($app_list_strings['moduleListSingular'][$bean->module_dir])) {
446 $module_name = $app_list_strings['moduleListSingular'][$bean->module_dir];
448 $module_name = translate('LBL_MODULE_NAME', $bean->module_dir);
450 if(empty($module_name)) {
451 $module_name = translate($beanName);
453 echo "<li>" . translate("LBL_CREATED_NEW") . ' ' . $module_name . " -
454 <a href='index.php?module={$bean->module_dir}&action=DetailView&record={$bean->id}'>
455 {$bean->get_summary_text()}
463 protected function handleActivities(
468 global $app_list_strings;
469 $parent_types = $app_list_strings['record_type_display'];
471 $activities = $this->getActivitiesFromLead($lead);
473 foreach($beans as $module => $bean)
475 if (isset($parent_types[$module]))
477 foreach($activities as $activity)
479 $this->copyActivityAndRelateToBean($activity, $bean);
486 * Gets the list of activities related to the lead
487 * @param Lead $lead Lead to get activities from
488 * @return Array of Activity SugarBeans .
490 protected function getActivitiesFromLead(
496 global $beanList, $db;
498 $activitesList = array("Calls", "Tasks", "Meetings", "Emails", "Notes");
499 $activities = array();
501 foreach($activitesList as $module)
503 $beanName = $beanList[$module];
504 $activity = new $beanName();
505 $query = "SELECT id FROM {$activity->table_name} WHERE parent_id = '{$lead->id}' AND parent_type = 'Leads'";
506 $result = $db->query($query,true);
507 while($row = $db->fetchByAssoc($result))
509 $activity = new $beanName();
510 $activity->retrieve($row['id']);
511 $activity->fixUpFormatting();
512 $activities[] = $activity;
519 protected function copyActivityAndRelateToBean(
526 $newActivity = clone $activity;
527 $newActivity->id = create_guid();
528 $newActivity->new_with_id = true;
530 //Special case to prevent duplicated tasks from appearing under Contacts multiple times
531 if ($newActivity->module_dir == "Tasks" && $bean->module_dir != "Contacts")
533 $newActivity->contact_id = $activity->contact_name = "";
536 if ($rel = $this->findRelationship($newActivity, $bean))
538 $newActivity->load_relationship ($rel) ;
539 $relObj = $newActivity->$rel->getRelationshipObject();
540 if ( $relObj->relationship_type=='one-to-one' || $relObj->relationship_type == 'one-to-many' )
542 $key = $relObj->rhs_key;
543 $newActivity->$key = $bean->id;
545 $newActivity->$rel->add($bean->id);
546 $newActivity->parent_id = $bean->id;
547 $newActivity->parent_type = $bean->module_dir;
548 $newActivity->update_date_modified = false; //bug 41747
549 $newActivity->save();
550 if ($newActivity->module_dir == "Notes" && $newActivity->filename) {
551 UploadFile::duplicate_file($activity->id, $newActivity->id, $newActivity->filename);
557 * Populates the passed in Bean fron the contact and the $_REQUEST
558 * @param String $module Module of new bean
559 * @param SugarBean $bean SugarBean to be populated.
560 * @param Contact $contact Contact to relate the bean to.
562 protected function populateNewBean(
569 populateFromPost($module, $bean, true);
571 //Copy data from the contact to new bean
572 foreach($bean->field_defs as $field => $def)
574 if(!isset($_REQUEST[$module . $field]) && isset($lead->$field) && $field != 'id')
576 $bean->$field = $lead->$field;
577 if($field == 'date_entered') $bean->$field = gmdate($GLOBALS['timedate']->get_db_date_time_format()); //bug 41030
580 //Try to link to the new contact
582 if (!empty($vdef['ConvertLead']['select']))
584 $select = $vdef['ConvertLead']['select'];
585 $fieldDef = $contact->field_defs[$select];
586 if (!empty($fieldDef['id_name']))
588 $bean->id = create_guid();
589 $bean->new_with_id = true;
590 $contact->$fieldDef['id_name'] = $bean->id ;
591 if ($fieldDef['id_name'] != $select) {
592 $rname = isset($fieldDef['rname']) ? $fieldDef['rname'] : "";
593 if (!empty($rname) && isset($bean->$rname))
594 $contact->$select = $bean->$rname;
596 $contact->$select = $bean->name;
599 } else if ($module != "Contacts"){
600 $contactRel = $this->findRelationship($contact, $bean);
601 if (!empty($contactRel))
603 $bean->id = create_guid();
604 $bean->new_with_id = true;
605 $contact->load_relationship ($contactRel) ;
606 $relObject = $contact->$contactRel->getRelationshipObject();
607 if ($relObject->relationship_type == "one-to-many" && $contact->$contactRel->_get_bean_position())
609 $id_field = $relObject->rhs_key;
610 $bean->$id_field = $contact->id;
612 $contact->$contactRel->add($bean->id);
614 //Set the parent of activites to the new Contact
615 if (isset($bean->field_defs['parent_id']) && isset($bean->field_defs['parent_type']))
617 $bean->parent_id = $contact->id;
618 $bean->parent_type = "Contacts";
624 protected function copyAddressFields($bean, $contact)
626 //Copy over address info from the contact to any beans with address not set
627 foreach($bean->field_defs as $field => $def)
629 if(!isset($_REQUEST[$bean->module_dir . $field]) && strpos($field, "_address_") !== false)
632 if (strpos($field, "alt_") !== false || strpos($field, "shipping_") !== false)
636 if(strpos($field, "_address_street_2") !== false)
637 $type = "_address_street_2";
638 else if(strpos($field, "_address_street_3") !== false)
639 $type = "_address_street_3";
640 else if(strpos($field, "_address_street_4") !== false)
642 else if(strpos($field, "_address_street") !== false)
643 $type = "_address_street";
644 else if(strpos($field, "_address_city") !== false)
645 $type = "_address_city";
646 else if(strpos($field, "_address_state") !== false)
647 $type = "_address_state";
648 else if(strpos($field, "_address_postalcode") !== false)
649 $type = "_address_postalcode";
650 else if(strpos($field, "_address_country") !== false)
651 $type = "_address_country";
654 if (isset($contact->$var))
655 $bean->$field = $contact->$var;
661 protected function findRelationship(
667 require_once("modules/TableDictionary.php");
668 foreach ($from->field_defs as $field=>$def)
670 if (isset($def['type']) && $def['type'] == "link" && isset($def['relationship'])) {
671 $rel_name = $def['relationship'];
673 if (isset($dictionary[$from->object_name]['relationships']) && isset($dictionary[$from->object_name]['relationships'][$rel_name]))
675 $rel_def = $dictionary[$from->object_name]['relationships'][$rel_name];
677 else if (isset($dictionary[$to->object_name]['relationships']) && isset($dictionary[$to->object_name]['relationships'][$rel_name]))
679 $rel_def = $dictionary[$to->object_name]['relationships'][$rel_name];
681 else if (isset($dictionary[$rel_name]) && isset($dictionary[$rel_name]['relationships'])
682 && isset($dictionary[$rel_name]['relationships'][$rel_name]))
684 $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
686 if (!empty($rel_def)) {
687 if ($rel_def['lhs_module'] == $from->module_dir && $rel_def['rhs_module'] == $to->module_dir )
691 else if ($rel_def['rhs_module'] == $from->module_dir && $rel_def['lhs_module'] == $to->module_dir )
702 * @see SugarView::_getModuleTitleParams()
704 protected function _getModuleTitleParams($browserTitle = false)
707 $params = parent::_getModuleTitleParams($browserTitle);
708 $params[] = "<a href='index.php?module=Leads&action=DetailView&record={$this->bean->id}'>{$this->bean->name}</a>";
709 $params[] = $mod_strings['LBL_CONVERTLEAD'];
714 protected function checkForDuplicates(
718 if ($lead->status == "Converted")
720 echo ("<span class='error'>" . translate('LBL_CONVERTLEAD_WARNING'));
722 $q = "SELECT id, first_name, last_name FROM contacts WHERE first_name LIKE '{$lead->first_name}' AND last_name LIKE '{$lead->last_name}'";
723 $result = $lead->db->query($q);
724 while($row = $lead->db->fetchByAssoc($result)) {
725 $contact = new Contact();
726 $contact->retrieve($row['id']);
727 $dupes[$row['id']] = $contact->name;
731 foreach($dupes as $id => $name)
733 echo (translate('LBL_CONVERTLEAD_WARNING_INTO_RECORD') . "<a href='index.php?module=Contacts&action=DetailView&record=$id'>$name</a>");