Anda di halaman 1dari 12

@RestResource(urlMapping = '/RestAPI/*')

global with sharing class CustomRestAPI {

@HttpPost
global static String postMethod() {

boolean parseAllObjects = false;

String requestBody = RestContext.request.requestBody.toString();


System.debug(requestBody);

JSONParser parser = JSON.createParser(requestBody);

for(integer i = 0; i<10; i++){


parser.nextToken();

if(parser.getText() == 'hearingTests')
parseAllObjects = true;
}

if(parseAllObjects)
parseAllObjects(requestBody);
else
parseHearingTest(requestBody);

//system.debug(requestbody);
if(parseAllObjects)
return 'ParseAllObjects executed';
else
return 'ParseHearingTest executed';
}

public static void parseAllObjects(String requestBody){


Pricebook2 pb = [select Name from Pricebook2 where isStandard=true ];

User currentUser = [select Last_Added_Hearing_Test__c, Last_Added_Order__c,


Last_Added_OrderItem__c, Last_Added_User__c from User where email =
'igor@quadrixsoft.com'];

Map<String, Id> myMap = new Map<String, Id>();


Map<String, Integer> prices = new Map<String, Integer>();

Map<String, Decimal> hearingTestToneMap = new Map<String,Decimal>{ '1' =>


0, '2' => 10,'3' => 15, '4' => 20,'5' => 30, '6' => 35,
'7' => 40, '8' => 50,'9' => 55, '10' => 60, '11' => 70, '12' => 80};

for(Account objCS : [Select User_Id__c, Id From Account a ])


myMap.put(String.valueof(objCS.User_Id__c), objCS.Id);

system.debug(pb);

List<String> listeningEffort = new List<String>{'I have trouble hearing


over the telephone',
'I have to strain to understand what people say',
'People complain that the TV volume is too high',
'Family members or coworkers tell me that I am not hearing what they
say',
'Many people I talk to seem to mumble or not speak clearly',
'I often ask people to repeat what they have said',
'I have trouble understanding women and children',
'None'};

List<String> SpeechInNoise = new List<String>{'I have trouble


understanding when 2 or more people talk at the same time',
'I have trouble hearing in noisy places',
'I have trouble hearing in a restaurant',
'None'};

JSON2Apex j2a = JSON2Apex.parse(requestBody);

List<SObject> soToInsert = new List<SObject>();


List<order> orderList = new List<Order>();
List<PricebookEntry> pbeList = new List<PricebookEntry>();
List<Account> accToUpsert = new List<Account>();
List<Product2> prod2ToUpsert = new List<Product2>();
List<Hearing_Test_Information__c> hearingTestsToUpsert = new
List<Hearing_Test_Information__c>();
List<Payments_Declines_Information__c> pdiToUpsert = new
List<Payments_Declines_Information__c>();
List<OrderItem> oiToUpsert = new List<OrderItem>();
//List<PricebookEntry> pbeList = new List<PricebookEntry>();
List<Attachment> attList = new List<Attachment>();

List<Datetime> dateTimeList = new List<Datetime>();

if(j2a.users != null){
for (JSON2Apex.Users u: j2a.users){

Account a = new Account();

a.User_ID__c = u.id;
a.Name = u.first_name + ' ' + u.last_name;
a.Phone = u.phone_number;
a.Created_At__c = createDateTime(u.created_at);
if(u.updated_at != null){
a.Updated_At__c = createDateTime(u.updated_at);
dateTimeList.add(a.Updated_At__c);
system.debug('updated at' + a.Updated_At__c);
}
else{
dateTimeList.add(a.Created_At__c);
system.debug('updated at' + a.Created_At__c);
}

a.Email__c = u.email;

//soToInsert.add(a);
accToUpsert.add(a);

//system.debug( 'List before sorting' + DatetimeList);


dateTimeList.sort();

system.debug('List after sorting' + DatetimeList);


if(dateTimeList.size() > 0){
currentUser.Last_Added_User__c = datetimelist[dateTimeList.size() -
1];
}

}
else{
system.debug('User list is empty');
}

if(j2a.hearingTests != null){

dateTimeList.clear();

for (JSON2Apex.HearingTests hti: j2a.hearingTests) {


Hearing_Test_Information__c newHti= new
Hearing_Test_Information__c();

//newHti.Email__c = hti.email; // Email__c is a formula.


if(hti.updated_at != null){
newHti.Taken_At__c = createDateTime(hti.updated_at);

}
else{
newHti.Taken_At__c = createDateTime(hti.created_at);
}
dateTimeList.add(newHti.Taken_At__c);
if(hti.result != null ){
if(hti.result.tone != null){
if(hti.result.tone.Left !=null){
newHti.L500__c =
hearingTestToneMap.get(String.valueof(hti.result.tone.Left.X500));
newHti.L1000__c =
hearingTestToneMap.get(String.valueof(hti.result.tone.Left.X1000));
newHti.L2000__c =
hearingTestToneMap.get(String.valueof(hti.result.tone.Left.X2000));
newHti.L4000__c =
hearingTestToneMap.get(String.valueof(hti.result.tone.Left.X4000));
}

if(hti.result.tone.Right != null){
newHti.R500__c =
hearingTestToneMap.get(String.valueof(hti.result.tone.Right.X500));
newHti.R1000__c =
hearingTestToneMap.get(String.valueof(hti.result.tone.Right.X1000));
newHti.R2000__c =
hearingTestToneMap.get(String.valueof(hti.result.tone.Right.X2000));
newHti.R4000__c =
hearingTestToneMap.get(String.valueof(hti.result.tone.Right.X4000));
}
newhti.Has_Tone_Results__c = true;

}
if(hti.result.position != null){
newHti.Step_Name__c = hti.result.position.stepname;
newHti.Step_Page_Name__c =
hti.result.position.stepPageName;
}
newHti.Wearing_Hearing_Aids__c = hti.result.wearingHearingAids;
newHti.Willing_To_Spend__c = hti.result.willingtoSpend;
newHti.Age__c = hti.result.age ;
newHti.Have_Smartphone__c = hti.result.haveSmartphone;
newHti.Zip_Code__c = hti.result.zipcode;
newHti.Lead__r = new Lead (Hearing_Test_Id__c = hti.test_id);
//newHti.Hearing_Survey_Responses__c =
String.valueOf(hti.result);
/*
if(hti.result.position != null){
if(hti.result.position.stepname != null){
newHti.Hearing_Survey_Responses__c += 'Step Name: '
+ string.valueOf(hti.result.position.stepname) + '\n';
}
if(hti.result.position.stepPageName != null){
newHti.Hearing_Survey_Responses__c += 'Step Page
Name: ' + string.valueOf(hti.result.position.stepPageName) + '\n';
}
}

if(hti.result.wearingHearingAids != null){
newHti.Hearing_Survey_Responses__c += 'Wearing Hearing
Aids: ' + string.valueOf(hti.result.wearingHearingAids) + '\n';
}

if(hti.result.questionare != null){
if(hti.result.questionare.listeningEffort != null){
newHti.Hearing_Survey_Responses__c = 'Listening effort:
' + string.valueOf(hti.result.questionare.listeningEffort) + '\n';
}
if(hti.result.questionare.speechInNoise != null){
newHti.Hearing_Survey_Responses__c += 'Speech In Noise:
' + string.valueOf(hti.result.questionare.speechInNoise) + '\n';
}

if(hti.result.willingtoSpend != null){
newHti.Hearing_Survey_Responses__c += 'Willing To
Spend: ' + string.valueOf(hti.result.willingtoSpend) + '\n';
}

if(hti.result.age != null){
newHti.Hearing_Survey_Responses__c += 'Age: ' +
string.valueOf(hti.result.age) + '\n';
}
if(hti.result.haveSmartphone != null){
newHti.Hearing_Survey_Responses__c += 'Have Smartphone:
' + string.valueOf(hti.result.haveSmartphone) + '\n';
}
*/
if(hti.result.questionare != null){
if(hti.result.questionare.listeningEffort != null){
newhti.Hearing_Survey_Responses__c = 'Listening Effort:
\n';
for(Integer i : hti.result.questionare.listeningEffort)
{
if(i>= 0 && i<=7)
newHti.Hearing_Survey_Responses__c += ' ' +
listeningEffort[i] + '\n';
}
}
if(hti.result.questionare.speechInNoise != null){
newhti.Hearing_Survey_Responses__c += 'Speech In Noise:
\n';
for(Integer i : hti.result.questionare.speechInNoise){
if(i>= 0 && i<=3)
newHti.Hearing_Survey_Responses__c += ' ' +
speechInNoise[i] + '\n';
}
}
}

newHti.test_id__c = hti.test_id;
newHti.Email__c = hti.email;
//system.debug(hearingTestsToUpsert);
hearingTestsToUpsert.add(newHti);

if(hti.location != null){
Attachment att = new Attachment();
att.Body = hti.location;
att.Name = 'Audiogram.' + hti.extension;
//att.ParentId = hti.id;
att.Description = hti.test_id;
attList.add(att);
}

dateTimeList.sort();
if(dateTimeList.size() > 0){
currentUser.Last_Added_Hearing_Test__c =
datetimelist[dateTimeList.size() - 1];
}
}
else{
system.debug('Hearing tests list is empty');
}

if(j2a.orders != null){

dateTimeList.clear();

for(JSON2Apex.Orders ord : j2a.orders){


Order o = new Order();
if(ord.user_id != null){
Account a = new Account (user_id__c = ord.user_id);

o.Account = a;
}
o.Created_at__c = CreateDateTime(ord.created_at);
dateTimeList.add(o.Created_at__c);
o.Status = 'Draft';
o.EffectiveDate = system.today().addDays(100);
o.Order_ID__c = ord.order_id;
o.Ordered_At__c = ord.created_at != null ?
createdate(ord.created_at.substring(0,9)) : null;
o.Address_Street_1__c = ord.address1;
o.Address_Street_2__c = ord.address2;
//shipping to name // get from account
o.Total_Billed__c = ord.order_total;
o.City__c = ord.city;
o.State__c = ord.state_code;
if (ord.zip_code != null){
o.ZIP__c = ord.zip_code;
}
o.Pricebook2Id = pb.Id;
//if(ord.hearing_test_id != null){
//o.Hearing_Test_Information__r = new
Hearing_Test_Information__c(Test_Id__c = ord.hearing_test_id);
//}
o.Hearing_Test_Id__c = ord.hearing_test_id;
//o.Color__c = ???

JSON2Apex.Coupons cou;
if(j2a.coupons != null)
{
for(JSON2Apex.Coupons c: j2a.coupons){
if(c.code == ord.coupon_code){
o.DiscountCodeID__c = c.code;
o.Code__c = c.code;
o.Discount_Code_Description__c =
c.user_facing_description;
o.User_Facing_Description__c =
c.user_facing_description;
o.Price_Drop__c = c.price_drop != null?
String.valueOf(c.price_drop) : null;
o.Percentage_Off__c = c.precentage_off != null?
string.valueof(c.precentage_off): null;
o.Gift__c = c.gift;
}
}
}

for(JSON2Apex.Payments p : j2a.payments){

if(p.order_id == o.Order_ID__c){
o.Payment_Method__c = p.payment_type;
o.Transaction_ID__c = p.transaction_id;
o.Autorization_Code__c = p.proccessor_auth_code;
o.Payment_status__c = p.status;
//o.Total_Billed__c = //???
o.Affirm_Fee__c = p.merchant_fee; // ???
}
}

//soToInsert.add(o);
orderList.add(o);
}

dateTimeList.sort();
if(dateTimeList.size() > 0){
currentUser.Last_Added_Order__c =
datetimelist[dateTimeList.size() - 1];
}
}
else{
system.debug('Order list is empty');
}

if(j2a.products != null){
for(JSON2Apex.Products pr : j2a.products){

if(! myMap.containsKey(pr.sku)){
Product2 pr2 = new Product2();
pr2.Name = pr.sku;
pr2.Description = pr.description;
pr2.Sku_ExternalID__c= pr.sku;
prod2ToUpsert.add(pr2);

}
}
Schema.SObjectField f = Product2.Fields.Sku_ExternalID__c;
Database.upsert(prod2ToUpsert , f, false);
for(Product2 objCS: [select Sku_ExternalID__c, Id from Product2])
myMap.put(objCS.Sku_ExternalID__c, objCS.Id);
System.debug(myMap);
for(JSON2Apex.Products pr : j2a.products){

if(myMap.containsKey(pr.sku)){
PricebookEntry pbe = new PricebookEntry();
pbe.Pricebook2Id = pb.id;
pbe.Product2Id = myMap.get(pr.sku);
pbe.UnitPrice = pr.price != 0? pr.price : 1800;
pbe.IsActive = true;
pbe.External_Id__c = pb.id + pr.sku;

prices.put(pbe.External_Id__c, Integer.valueOf(pbe.UnitPrice));

pbeList.add(pbe);

}
}

}
else{
system.debug('Product list is empty');
}

if(j2a.orderItems != null){

dateTimeList.clear();
for(JSON2Apex.OrderItems oi : j2a.orderItems){
OrderItem newOi = new OrderItem();

newOi.external_id__c = oi.order_id + oi.product_id;


newOi.order = new Order(Order_ID__c = oi.order_id);
newOi.Product2 = new Product2(Sku_ExternalID__c = oi.product_id);
newOi.PricebookEntry = new PricebookEntry(External_Id__c = pb.id +
oi.product_id);
newoi.Quantity = 1;
newoi.UnitPrice = prices.get(pb.id + oi.product_id);
newoi.created_at__c = createDateTime(oi.created_at);
dateTimeList.add(newoi.created_at__c);
oitoupsert.add(newoi);
}

dateTimeList.sort();
if(dateTimeList.size() > 0){
currentUser.Last_Added_OrderItem__c =
datetimelist[dateTimeList.size() - 1];
}
}
else{
system.debug('OrderItem list is empty');
}

if(j2a.paymentDeclines != null){
for(JSON2Apex.PaymentDeclines pd : j2a.paymentDeclines){
Payments_Declines_Information__c pdi = new
Payments_Declines_Information__c();

pdi.User_ID__c = String.valueOf(pd.user_id);
pdi.Transaction_ID__c = pd.transaction_id;
pdi.Account__r = new Account(User_ID__c = pd.user_id);
pdi.Order_Sum__c = pd.order_sum;
pdi.Payment_Token__c = pd.payment_token;
pdi.Payment_Status__c = pd.payment_status;
pdi.Payment_Type__c = pd.payment_type;
pdi.Processor_Response_Code__c = pd.processor_response_code;
pdi.Error_Message__c = pd.error_message;
pdi.Created_at__c = pd.created_at;

soToInsert.add(pdi);
}
}
else{
system.debug('Payment declines list is empty');
}

System.debug(soToInsert);

List<Lead> leadToUpsert = new List<Lead>();

system.debug('Sizes ' + hearingTestsToUpsert.size() + ' ' +


accToUpsert.size());
for(Integer i=0; i<hearingTestsToUpsert.size(); i++){
system.debug(i);
boolean foundAccount = false;
for(Integer j=0; j<accToUpsert.size(); j++){
if(accToUpsert[j].email__c == hearingTestsToUpsert[i].email__c &&
hearingTestsToUpsert[i].email__c != null){
Decimal User_ID = accToUpsert[j].user_id__c;
Account newAcc = new Account(User_ID__c = User_ID);
hearingTestsToUpsert[i].User_ID__r = newAcc;
foundAccount = true;
}
}

if(!foundAccount){
Lead l = new Lead();
l.Company = '/';
l.Email = hearingTestsToUpsert[i].Email__c != null ?
hearingTestsToUpsert[i].Email__c : '';
l.lastName = 'Hearing Test Lead';
l.Status = 'New';
l.Hearing_Test_Id__c = hearingTestsToUpsert[i].Test_Id__c;
leadToUpsert.add(l);
}

Schema.SObjectField leadExtField = lead.Fields.Hearing_Test_Id__c;


Database.upsert(leadToUpsert , leadExtField, false);

Schema.SObjectField AccountExtField = Account.Fields.User_Id__c;


Database.upsert(accToUpsert , AccountExtField, false);

//system.debug(accToUpsert);

Schema.SObjectField htiExtField =
Hearing_test_information__c.Fields.Test_Id__c;
Database.upsert(hearingTestsToUpsert , htiExtField, false);

//system.debug(hearingTestsToUpsert);

Schema.SObjectField OrderExtField = Order.Fields.Order_ID__c;


Database.upsert(orderList , OrderExtField, false);

//system.debug(orderList);

Schema.SObjectField pbeExtField = pricebookentry.Fields.External_Id__c;


Database.upsert(pbeList , pbeExtField, false);

//system.debug(pbeList);

Schema.SObjectField pdiExtField =
Payments_Declines_Information__c.Fields.transaction_id__c;
Database.upsert(pdiToUpsert , pdiExtField, false);

//system.debug(pdiToUpsert);

Schema.SObjectField oiExtField = OrderItem.Fields.External_Id__c;


Database.upsert(oiToUpsert , oiExtField, false);

system.debug(oiToUpsert);
update currentUser;

//upsert prod2ToUpsert;
system.debug(soToInsert);
insert soToInsert;

if(j2a.hearingTests != null){
for(Hearing_Test_Information__c hti: hearingTestsToUpsert ){

for(Attachment att : attList){


if(att.Description == hti.test_id__c){
att.ParentId = hti.id;
}
}

}
}

insert attList;
}
public static void parseHearingTest(String requestBody){

JSON2ApexHearingTest j2a = JSON2ApexHearingTest.parse(requestBody);

Hearing_Test_Information__c newHti = new Hearing_Test_Information__c();

}
@HttpGet
global static String doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
//String accountId =
req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
//Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id =
:accountId];
//
User selectedUser = [select Last_Added_User__c, Last_Added_OrderItem__c,
Last_Added_Order__c, Last_Added_Hearing_Test__c from User where email =
'igor@quadrixsoft.com'];

LastTimeCreatedDates dates = new


LastTimeCreatedDates(String.valueOf(selectedUser.Last_Added_User__c.addHours(7)),

String.valueOf(selectedUser.Last_Added_Hearing_Test__c.addHours(7)),

String.valueOf(selectedUser.Last_Added_OrderItem__c.addHours(7)),

String.valueOf(selectedUser.Last_Added_Order__c.addHours(7)));

String result = JSON.serialize(dates);

return result;
}
public static Date createDate(String CreatedAt){

Date d;

List<string> tokens = CreatedAt.split('-');

Integer year = Integer.valueOf(tokens[0]);


Integer month = Integer.valueOf(tokens[1]);
Integer day = Integer.valueOf(tokens[2]);

d = Date.newInstance(year, month, day);

//system.debug(d);
return d;
}

public static DateTime createDateTime(String CreatedAt){

//2018-08-30T12:47:30.554Z
String timeOnly = createdAt.substring(11,19);
String dateOnly = createdAt.substring(0,10);

//system.debug(dateOnly);
DateTime d;

List<string> tokensDate = dateOnly.split('-');

Integer year = Integer.valueOf(tokensDate[0]);


Integer month = Integer.valueOf(tokensDate[1]);
Integer day = Integer.valueOf(tokensDate[2]);

//system.debug(tokensDate);

List<string> tokensTime = timeOnly.split(':');

Integer hour = Integer.valueOf(tokensTime[0]);


Integer minute = Integer.valueOf(tokensTime[1]);
Integer second = Integer.valueOf(tokensTime[2]);

d = Datetime.newInstanceGmT(year, month, day, hour, minute, second);

//system.debug(d);

//d.addHours(-7);

return d;
}

public class LastTimeCreatedDates {


public String Last_Added_User{get;set;}
public String Last_Added_hearingTest{get;set;}
public String Last_Added_OrderItemm{get;set;}
public String Last_Added_orderr{get;set;}

public LastTimeCreatedDates(String u, String h, String oi, String o){


Last_Added_User = u;
Last_Added_hearingTest = h;
Last_Added_OrderItemm = oi;
Last_Added_orderr = o;
}
}
}

Anda mungkin juga menyukai