Salesforce Apex Create Opportunity after Custom Object field change - triggers

I have a simple trigger that is supposed to create a new opportunity when the SD_Action__c field on my custom object is a certain value. The code has no errors, but nothing happens when I try update the field in sandbox or production. What am I missing to make this great an opportunity when m.SD_Action__c=='Generate Opportunity' ?
trigger MDwinning on MD_Meeting__c (after update) {
List <Opportunity> oppToInsert = new List <Opportunity> ();
for (MD_Meeting__c m : Trigger.new) {
if (m.SD_Action__c == 'Generate Opportunity') {
Opportunity o = new Opportunity ();
// o.Owner = m.Sales_Director__c,
o.Market_Developer__c = m.Market_Developer__c;
//o.Account = m.Account__c;
oppToInsert.add(o);
}//end if
}//end for o
try {
insert oppToInsert;
} catch (system.Dmlexception e) {
system.debug (e);
}
}
Here is my test class:
#isTest (SeeAllData = true)
public with sharing class MDwinningTest {
static testMethod void MDwinningTest() {
MD_Meeting__c m = new MD_Meeting__c(
Account__c = 'test Account',
Desired_Meeting__c = 'Call',
Name = 'Meeting name',
Sales_Director__c = 'SD Name',
Market_Developer__c = 'MD Name',
Meeting_Date__c = Date.today(),
Contact__c = 'Test Contact',
Title__c = 'Boss',
Functional_Role__c = 'eCommerce - VP',
Contact_Email__c = 'test#aol.com',
SD_Action__c = 'Generate Opportunity',
Primary_URL__c = 'http://www.google.com/'
);
insert m;
}
}

Your test didn't work properly because of you use only insert operation, but your trigger works on update mode. So, you have to change test or trigger or both
#isTest
private class MDwinningTest {
#isTest
static void MDwinningTest() {
// prepare test data
MD_Meeting__c m = new MD_Meeting__c(
Account__c = 'test Account',
Desired_Meeting__c = 'Call',
Name = 'Meeting name',
Sales_Director__c = 'SD Name',
Market_Developer__c = 'MD Name',
Meeting_Date__c = Date.today(),
Contact__c = 'Test Contact',
Title__c = 'Boss',
Functional_Role__c = 'eCommerce - VP',
Contact_Email__c = 'test#aol.com',
Primary_URL__c = 'http://www.google.com/'
);
insert m;
m.SD_Action__c = 'Generate Opportunity';
update m;
System.assertEquals(1, (Integer)[SELECT Count(Id) FROM Opportunity][0].get('Expr0'));
}
}
I suggest to disable SeeAllData = true because it risky because some of org where your code might be
deployed might have no needed data and as a result your tests will be broken
Also you can change the current trigger for working on insert and update
trigger MDwinning on MD_Meeting__c (after insert, after update) {

Related

Salesforce Test class getting System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set Error

I have written a trigger and handler class (which uses a future method) and it works well. I am really struggling to write the test class for it. My first problem is that the code coverage is high (before tweaks it was 0% in the handler class). After tweaking, I am getting the following error:
System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set
I am not sure how to solve this and I am a pretty new dev so not sure what to do next . Can someone please help?
Here is my code:
Trigger:
trigger AccountTriggerKeepAcctTeam on Account (before update) {
List<AccountTeamMember> listAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember Where AccountId in : Trigger.new AND TeamMemberRole != 'Account Executive'];
for(Account acc: Trigger.new){
Account oldAccount = Trigger.oldMap.get(acc.Id);
if(acc.OwnerId != oldAccount.OwnerId){
system.debug('AccountTeamMember records: '+(JSON.serialize(listAcc)));
String str = JSON.serialize(listAcc);
//delete team member records if required
AccountTriggerKeepAcctTeamHandler.retainOldTeamMemberOnOwnerChange(str);
}
}
}
Handler:
public class AccountTriggerKeepAcctTeamHandler {
#future
public static void retainOldTeamMemberOnOwnerChange(String str){
system.debug('Future call '+str);
List<AccountTeamMember> newlistAcc = (List<AccountTeamMember>) JSON.deserialize(str,List<AccountTeamMember>.class);
for(AccountTeamMember objAccTeamMember : newlistAcc){
objAccTeamMember.Id= null;
}
system.debug('Account records to insert'+(JSON.serialize(newlistAcc)));
Upsert newlistAcc;
}
}
Test class:
#isTest
public class AccountTriggerKeepAcctTeamTest {
//#TestSetup
static testMethod void AcctOwnerChange(){
List<User> userList = TestDataFactory.createUser(true, 2);
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
User u1 = new User(Alias = 'standt', Email='standarduser#testorg1.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser#testorg01.com');
insert u1;
User u2 = new User(Alias = 'standt', Email='standarduser#testorg2.com',
EmailEncodingKey='UTF-8', LastName='Testing2', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser#testorg92.com');
insert u2;
System.runAs(u1){
Allowed_Account_Owner_Change__c setting = new Allowed_Account_Owner_Change__c();
setting.Allowed_to_change_Account_Owner__c = true;
insert setting;
fferpcore__ExchangeRateGroup__c exrg = new fferpcore__ExchangeRateGroup__c(CurrencyISOCode = 'USD', fferpcore__DefaultCurrency__c = 'USD - U.S. Dollar', Name = 'FF Shared Test Group', fferpcore__SelectedCurrencies__c = 'USD - U.S. Dollar');
insert exrg;
c2g__codaCompany__c company = new c2g__codaCompany__c();
company.Name = 'ApexTestCompany';
company.RecordTypeId = Schema.SObjectType.c2g__codaCompany__c.RecordTypeInfosByName.get('SUT').RecordTypeId;
insert company;
company.c2g__ExchangeRateGroup__c = exrg.Id;
update company;
Account acc = new Account(Name = 'Test Acc2', NumberOfEmployees = 500);//TestDataFactory.createAccountwithCurrencyMaster(true);
acc.OwnerId = userinfo.getUserId();
insert acc;
AccountTeamMember accTeam = new AccountTeamMember();
accTeam.UserId = acc.OwnerId;
accTeam.AccountAccessLevel = 'Read';
accTeam.AccountId = acc.Id;
insert accTeam;
System.debug('## User '+userinfo.getUserName());
//create opportunity
//}
// }
// static testMethod void testAcctOwnerChange(){
// User u = [Select id, LastName from User where LastName = 'Testing2'];
// Account acc = [Select id, OwnerId from Account Limit 1];
Test.startTest();
acc.OwnerId = u2.id;
update acc;
AccountTriggerKeepAcctTeamHandler.retainOldTeamMemberOnOwnerChange(JSON.serialize(acc));
//System.assertEquals(accTeam.UserId,u2.Id);
Test.stopTest();
//AccountTeamMember atm = [Select userId,AccountId, AccountAccessLevel from AccountTeamMember where AccountId =: acc.Id];
}
}
Can someone please help? I am a beginner apex dev
Trigger Attempt for Alin's test class:
trigger AccountTriggerKeepAcctTeam on Account (before update) {
Set<Id> accteammbrId = new Set<Id>();
List<AccountTeamMember> listAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember Where AccountId in : Trigger.new AND TeamMemberRole != 'Account Executive'];
for(Account acc: Trigger.new){
Account oldAccount = Trigger.oldMap.get(acc.Id);
if(acc.OwnerId != oldAccount.OwnerId){
//system.debug('AccountTeamMember records: '+(JSON.serialize(listAcc)));
//String str = JSON.serialize(listAcc);
for(AccountTeamMember actmbr : listAcc){
accteammbrId.add(actmbr.Id);
}
//delete team member records if required
AccountTriggerKeepAcctTeamHandler.retainOldTeamMemberOnOwnerChange(accteammbrId);
}
}
}
public class AccountTriggerKeepAcctTeamHandler {
#future
public static void retainOldTeamMemberOnOwnerChange(Set<Id> AccteambrId){
List<AccountTeamMember> newlistAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember Where AccountId in :AccteambrId];
//system.debug('Future call '+str);
//List<AccountTeamMember> newlistAcc = (List<AccountTeamMember>) JSON.deserialize(str,List<AccountTeamMember>.class);
for(AccountTeamMember objAccTeamMember : newlistAcc){
objAccTeamMember.Id= null;
}
//system.debug('Account records to insert'+(JSON.serialize(newlistAcc)));
system.debug('Account records to insert' + newlistAcc);
Upsert newlistAcc;
}
}
I don't understand why you have to serialize the list in the first place.
Change your retainOldTeamMemberOnOwnerChange to accept a List as parameter and don't use the JSON at all.
Then in your test class you create an account, assign an account team to it and change the owner. After that you will query the List of associated AccountTeamMember and assert it with regards to the AccountTeamMember before the ownership of the account was changed.
If it's not clear enough I can give you a code example, but I think the exercise will be good for you.
Edit: I see. My bad. This is what I use for test coverage. I can also provide code sample from the trigger if needed.
Trigger:
trigger AccountTrigger on Account (before update, After Update) {
if(trigger.isBefore){
if(trigger.isUpdate){
AccountTriggerHandler.retainAccountTeam(trigger.new, trigger.oldMap);
}
}
}
Handler:
public class AccountTriggerHandler {
public static void retainAccountTeam(List<Account> newList, Map<Id, Account> oldMap) {
Set<Id> accountsWithNewOwners = new Set<Id>();
for(Account acc : newList){
if(acc.OwnerId != oldMap.get(acc.Id).OwnerId){
accountsWithNewOwners.add(acc.Id);
}
}
if(accountsWithNewOwners.size() > 0){
List<AccountTeamMember> listAcc = [SELECT Id, AccountAccessLevel, AccountId, CaseAccessLevel, UserId, ContactAccessLevel, OpportunityAccessLevel, TeamMemberRole, PhotoUrl, Title FROM AccountTeamMember WHERE AccountId IN :accountsWithNewOwners];
system.debug('AccountTeamMember records: '+(JSON.serialize(listAcc)));
String str = JSON.serialize(listAcc);
// delete team member records if required
retainOldTeamMemberOnOwnerChange(str);
}
}
//Before Update calls the future method that basically reinserts the Account Team member records. You can also consider deleting the Account Team Member records before calling the future method.
#future
public static void retainOldTeamMemberOnOwnerChange(String str){
system.debug('Future call '+str);
List<AccountTeamMember> newlistAcc = (List<AccountTeamMember>) JSON.deserialize(str,List<AccountTeamMember>.class);
for(AccountTeamMember objAccTeamMember : newlistAcc){
objAccTeamMember.Id= null;
}
system.debug('Account records to insert'+(JSON.serialize(newlistAcc)));
Upsert newlistAcc;
}
}
Test method:
static testMethod void test_retainAccountTeam(){
Id mhbkRTId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('MHBK').getRecordTypeId();
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
User u = new User(
Alias = 'rivacon',
Email = 'rivaConnector#testorg.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Connector',
FirstName = 'Riva',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'rivaConnector#testorg.com');
insert u;
User u2 = new User(
Alias = 'updated',
Email = 'rivaConnector#testorg.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Connector',
FirstName = 'Riva2',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'rivaConnector2#testorg.com');
insert u2;
system.runAs(u){
Account acc = new Account(RecordTypeId = mhbkRTId,Name = 'test',Branch__c='London',Industry='Banking',Year_Founded__c='1900',BillingStreet = '1 Long Rd',BillingCity = 'City',CurrencyIsoCode = 'GBP');
insert acc;
AccountTeamMember atm = new AccountTeamMember();
atm.AccountId = acc.Id;
//atm.Name ='Test ATM';
atm.TeamMemberRole = 'Sales Assistant';
atm.UserId = u.Id;
insert atm;
Test.startTest();
acc.OwnerId = u2.Id;
update acc;
Test.stopTest();
System.debug('usr1 ' + u.id);
System.debug('usr2 ' + u2.id);
Account updatedAccount = [SELECT OwnerId FROM Account WHERE Id = :acc.Id];
system.assertEquals(u2.Id, updatedAccount.OwnerId);
List<AccountTeamMember> teamMembers = [SELECT Id, AccountAccessLevel, AccountId, UserId, TeamMemberRole, Title FROM AccountTeamMember WHERE AccountId = :acc.Id];
system.assertEquals(1, teamMembers.size());
system.assertEquals(teamMembers[0].TeamMemberRole, atm.TeamMemberRole);
}

Salesforce Trigger Test Class

below is my Apex Trigger. I am a beginner and trying to write its test class but continuously getting error "System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Error: You can't select products until you've chosen a price book for this opportunity on the products related list.: []".
trigger TrgrOptyHighestCustmorePrice on Opportunity (before insert, before update)
{
public Id oid;
public String bidType;
public String BUCode;
for(Opportunity o : trigger.new)
{
oid = o.Id;
bidType = o.BidType__c;
BUCode = o.Business_Line_BU__c;
}
List<OpportunityLineItem> oliList = new list<OpportunityLineItem>([SELECT id, Customer_Price__c, ReCat_Product_Line__c
FROM OpportunityLineItem
WHERE OpportunityId =: oid ORDER BY
Customer_Price__c DESC LIMIT 1]);
for(OpportunityLineItem oli : oliList)
{
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.619';
}
if(bidType == 'Competitive' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.620';
}
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.622';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.624';
}
if(bidType == 'Sole Sourced' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.621';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.623';
}
}
for(Opportunity opt : trigger.new)
{
opt.Business_Line_BU__c = BUCode;
}
}
Test Class
#isTest(seeAllData=true)
public class Test_TrgrOptyHighestCustmorePrice {
private static testmethod void TrgrOptyHighestCustmorePriceTest(){
Test.startTest();
//Insert a test product.
Product2 p1 = new Product2(Name='Product Monthly 1111', isActive=true, CurrencyIsoCode='USD', ReCat_Product_Line__c = 'DMS');
insert p1;
// Get standard price book ID.
Id pricebookId = Test.getStandardPricebookId();
// Insert a price book entry for the standard price book.
PricebookEntry standardPrice = new PricebookEntry(
Pricebook2Id = pricebookId, Product2Id = p1.Id,
UnitPrice = 10000, IsActive = true);
insert standardPrice;
Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
insert customPB;
PricebookEntry customPrice = new PricebookEntry(
Pricebook2Id = customPB.Id, Product2Id = p1.Id,
UnitPrice = 12000, IsActive = true);
insert customPrice;
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619',
PriceBook2 = customPB);
insert opt;
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id);
insert optLI;
update opt;
Test.stopTest();
}
}
I am unable to understand how can I test my simple trigger.
Its because u do not fill all required fields for the Opportunity Line Item. See: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_opportunitylineitem.htm for required fields.
This as an example will work:
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id, TotalPrice = 100, PricebookEntryId=customPrice.Id, Quantity =3);
First Insert the opportunity.
Then update the opportunity with the pricebookid.
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619'
);
insert opt;
opt.PriceBook2 = customPB;
update opt;

Get the ID of a selected value from a dropdown selectbox using Laravel 5.1

I've been on this for a while, what I want to do is to get the id of the selected value from a select box. Using this snippet, it doesn't get the id and I wonder why. I'm confused what what could be wrong
This code is to get the id of the selected value:
private static function compareCompany(ProductRequest $productRequest){
$companyPicked = $productRequest->companyname;
$listedCompanies = Company::where('user_id', '=', Auth::user()->id);
$companies = new Company;
if($companies->user_id === Auth::user()->id)
{
foreach($listedCompanies as $company) {
if($company->companyname === $companyPicked)
{
return $company->id;
}
}
}
}
This is to create a new product using the id returned for a company
public function store(ProductRequest $productRequest)
{
$product = new Product;
$company = new Company;
if($productRequest->isMethod('post')){
$product->user_id = Auth::user()->id;
$product->company_id = $this->compareCompany($productRequest);
$product->companyname = $productRequest->companyname;
$product->productname = $productRequest->productname;
$product->save();
return redirect()->route('companyindex')->with('message', 'Your question has been posted.');
}else{
return redirect('company-create')->withErrors($productRequest)->withInput();
}
}
THis is the view:
<p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies) !!} </p>
THis is the code used in binding the returned value to the view:
public function create()
{
$listCompanies = Company::where('user_id', '=', Auth::user()->id)->orderBy('companyname', 'desc')->lists('companyname', 'companyname')->toArray();
return view('product.create')
->with('listCompanies', $listCompanies);
}
I suspect that the problem is with your compareCompany method. There are a couple of issues there.
Here's your code (cleaned up a bit):
private static function compareCompany(ProductRequest $productRequest)
{
$companyPicked = $productRequest->companyname;
$listedCompanies = Company::where('user_id', '=', Auth::user()->id);
$companies = new Company;
if($companies->user_id === Auth::user()->id)
{
foreach($listedCompanies as $company) {
if($company->companyname === $companyPicked)
{
return $company->id;
}
}
}
}
And here are the issues:
$listedCompanies = Company::where('user_id', '=', Auth::user()->id);
This statement doesn't actually produce a list of companies. You need to add ->get() at the end, like this:
$listedCompanies = Company::where('user_id', '=', Auth::user()->id)->get();
$companies = new Company;
This creates a new, uninitialized instance of the Company model. On the next line you go on to check the user_id property of that instance, but it's not set to anything because it's brand new. So the first if() statement always fails. It's not clear what you're trying to do here, so I'm not sure how to fix this one. My guess is that you're trying to filter out only the companies that belong to the current user, but you've already done that with your Company::where(...)->get(), so this is not necessary.
Change ->lists('companyname', 'companyname') to ->lists('companyname', 'id')
It will return the id of the table of Company model.

Apex - Test class adding Chatter Free users

I'm a newbie trying to build a test class for a registration handler that allows new chatter free users to be created for an org. To create the chatter free user, the working trigger checks a new user's email domain against a predefined list of acceptable email domains that are stored in a custom object named DomainList.
Looking for suggestions on how to better structure a test class for code coverage. Any ideas appreciated, thanks!
global class RegHandlerDomain implements Auth.RegistrationHandler {
global User createUser(Id portalId, Auth.UserData data) {
String domain = data.email.split('#')[1];
List<DomainList__c> listedDomains = [SELECT id,
name
FROM DomainList__c
WHERE Email_Domain__c = : domain];
if (listedDomains.size() == 1) {
User u = new User();
Profile p = [SELECT Id
FROM profile WHERE name = 'Chatter Free User'];
// Use incoming email for username
u.username = data.email;
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
u.alias = (data.username != null) ? data.username : data.identifier;
if (u.alias.length() > 8) {
u.alias = u.alias.substring(0, 8);
}
u.languagelocalekey = UserInfo.getLocale();
u.localesidkey = UserInfo.getLocale();
u.emailEncodingKey = 'UTF-8';
u.timeZoneSidKey = 'America/Los_Angeles';
u.profileId = p.Id;
System.debug('Returning new user record for ' + data.username);
return u;
} else return null;
}
global void updateUser(Id userId, Id portalId, Auth.UserData data) {
User u = new User(id = userId);
u.email = data.email;
u.lastName = data.lastName;
u.firstName = data.firstName;
System.debug('Updating user record for ' + data.username);
update(u);
}
}
Test class is looking for a '}' before the insert
#isTest(SeeAllData = true)
public class RegHandlerTest {
public void myTestMethod1() {
//CREATE CHATTER FREE TEST USER
Profile p = [select id
from profile where name = 'Chatter Free User'];
User u1 = new User(alias = 'chfree01',
email = 'chatterfreeuser101#testorg.com',
emailencodingkey = 'UTF-8',
lastname = 'Testing',
companyname = 'testorg',
languagelocalekey = 'en_US',
localesidkey = 'en_US',
profileId = p.Id,
timezonesidkey = 'America/Los_Angeles',
username = 'chatterfreeuser101#testorg.com');
insert u1;
}
//CHECK NEW USER EMAIL DOMAIN TO SEE IF IN CUSTOM OBJECT DOMAINLIST
List<DomainList__c> listedDomains = [select id, email_domain__c
from DomainList__c
where name = 'testorg' LIMIT 1];
if (listedDomains.size() == 1) System.debug('WORKS');
}
Fir of all you need create a proper unit test, because your is not correct.
#isTest(SeeAllData = true)
public class RegHandlerTest {
#isTest private static void verifyInsertChatterFreeUser() {
//CREATE CHATTER FREE TEST USER
Profile p = [SELECT id
FROM profile
WHERE name = 'Chatter Free User'];
User u1 = new User(alias = 'chfree01',
email = 'chatterfreeuser101#testorg.com',
emailencodingkey = 'UTF-8',
lastname = 'Testing',
companyname = 'testorg',
languagelocalekey = 'en_US',
localesidkey = 'en_US',
profileId = p.Id,
timezonesidkey = 'America/Los_Angeles',
username = 'chatterfreeuser101#testorg.com');
insert u1;
// perform some assertions regarding expected state of user after insert
//CHECK NEW USER EMAIL DOMAIN TO SEE IF IN CUSTOM OBJECT DOMAINLIST
List<DomainList__c> listedDomains = [SELECT id, email_domain__c
FROM DomainList__c
WHERE name = 'testorg' LIMIT 1];
// as you've annotated class with SeeAllData=true, this assertion always will be true
System.assertEquals(1, listedDomains.size());
}
#isTest private static void verifyUpdateChatterFreeUser() {
//CREATE CHATTER FREE TEST USER
Profile p = [SELECT id
FROM profile
WHERE name = 'Chatter Free User'];
User u1 = new User(alias = 'chfree01',
email = 'chatterfreeuser101#testorg.com',
emailencodingkey = 'UTF-8',
lastname = 'Testing',
companyname = 'testorg',
languagelocalekey = 'en_US',
localesidkey = 'en_US',
profileId = p.Id,
timezonesidkey = 'America/Los_Angeles',
username = 'chatterfreeuser101#testorg.com');
insert u1;
// perform some assertion regarding expected state of user after insert
// change something on user
u1.email = 'test.chatter.free#gmail.com';
update u1;
// perform some assertions regarding expected state of user after update
// System.assertEquals('expected value', u1.field);
}
}

IPP Create Customers Never Appears in QBD

I am trying to add a customer and an invoice to QuickBooks, but neither appear. QuickBooks responds with this XML:
http://pastebin.com/PLsFbA6N
My code for adding customers and invoices appears to work and I see no errors:
public Customer BuildCustomerAddRq(JMAOrder _Order)
{
// Construct subordinate required records
//BuildStandardTermsAddRq("Web Order");
// build the main customer record
Customer QBCustomerAdd = new Customer();
var Customer = _Order.BillingAddress;
var Billing = _Order.BillingAddress;
PhysicalAddress phy = new PhysicalAddress();
// if the setting is that all orders go under the same customer ID, then push
// the address lines down one and store the customer name on address line 1.
if (_qboSettings.CustomerID == "SingleName")
{
QBCustomerAdd.DBAName = "Web Store";
QBCustomerAdd.Email = new EmailAddress[] { new EmailAddress() { Address = "info#webstore.com", Tag = new string[] { "Business" } } };
QBCustomerAdd.GivenName = "Web";
QBCustomerAdd.Active = true;
QBCustomerAdd.FamilyName = "Store";
phy.Line1 = "Web Store";
phy.Line2 = "";
phy.Tag = new string[] { "Billing" };
}
else
{
//QBCustomerAdd.DBAName = GetCustId(_Order);
QBCustomerAdd.Email = new EmailAddress[] { new EmailAddress() { Address = Customer.Email, Tag = new string[] { "Business" } } };
QBCustomerAdd.GivenName = Customer.FirstName;
QBCustomerAdd.Active = true;
QBCustomerAdd.FamilyName = Customer.LastName;
if (!String.IsNullOrEmpty(Customer.PhoneNumber))
{
QBCustomerAdd.Phone = new TelephoneNumber[] { new TelephoneNumber() { FreeFormNumber = Customer.PhoneNumber, Tag = new string[] { "Business" } } };
}
phy.Line1 = Billing.Address1;
if (!String.IsNullOrEmpty(Billing.Address2))
{
phy.Line2 = Billing.Address2;
}
phy.City = Billing.City;
if (Billing.RegionName != null)
{
phy.CountrySubDivisionCode = Billing.RegionName;
}
phy.PostalCode = Billing.PostalCode;
phy.Country = Billing.CountryName;
phy.Tag = new string[] { "Billing" };
}
// build add request and exit
QBCustomerAdd.Address = new PhysicalAddress[] { phy };
try
{
Customer cu = dataServices.Add(QBCustomerAdd);
return cu;
}
catch (Exception ex)
{
ErrorMessageDataSource.Insert(new ErrorMessage(MessageSeverity.Error, "QBO", String.Format("Error adding customer : {0}", ex.ToString())));
Customer ct = new Customer();
return ct;
}
When I run Intuit Sync Manager, I see no new customer or invoice. Is it possible to add new customers to QuickBooks?
It appears that the customer entered QuickBooks in error state. I needed to add the QBCustomerAdd.Name field.
CustomerQuery cq = new CustomerQuery();
cq.ErroredObjectsOnly = true;
var bList = cq.ExecuteQuery<Customer>(dataServices.ServiceContext);