Hello everyone. A brief synopsis of my issue:
I have a helpdesk ticketing Django app and I’m trying to wire it up with my company’s Salesforce organization so that when a button (Lighting component) is clicked on a claim (Opportunity object), the user is taken to the ‘Create Ticket’ page in Django with the fields pre-populated based on several Salesforce fields. I won’t spend long talking about the Salesforce side as I’ve already verified that it can send data to a view function correctly.
Here is my Salesforce JavaScript sending the AJAX POST request:
({
doInit: function(component, event, helper) {
var action = component.get("c.getRecordData");
action.setParams({
"recordId": component.get("v.recordId")
});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === 'SUCCESS') {
// Data is now available in component's attribute
component.set("v.recordData", response.getReturnValue());
} else {
console.error("Failed with state: " + state);
}
});
$A.enqueueAction(action);
},
sendData: function(component, event, helper) {
// Get the data from the component's attribute set in doInit
var recordData = component.get("v.recordData");
// Construct the payload using the data fetched by the Apex class
var payload = {
'claim_id': recordData.Claim_ID__c,
'claim_name': recordData.Name,
'reason_for_denial': recordData.Reason_for_Denial__c,
'admit_date': recordData.Admit_Date__c,
'discharge_date': recordData.Discharge_Date__c,
'amount': recordData.Amount,
'queue': 1, // Assuming this is a fixed value; adjust as necessary
'csrfmiddlewaretoken': helper.getCSRFToken()
};
// Make the AJAX request to Django
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://theapplicationwebsite/intake-salesforce", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("X-CSRFToken", helper.getCSRFToken());
xhr.withCredentials = true;
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
console.log("Data sent successfully");
console.log()
// Redirect or handle success as needed
window.open("https://theapplicationwebsite/tickets/submit-salesforce/", "_blank");
} else {
// Handle error
console.error("Failed to send data:", xhr.responseText);
}
};
xhr.send(JSON.stringify(payload));
}
})
That request goes to my get_claim_details_from_salesforce view function here:
def get_claim_details_from_salesforce(request):
try:
data = json.loads(request.body)
response_data = {
'message': 'Success!',
'sent_values': data
}
claim_id = data.get('claim_id')
claim_name = data.get('claim_name')
reason_for_denial = data.get('reason_for_denial')
admit_date_raw = data.get('admit_date')
discharge_date_raw = data.get('discharge_date')
amount = data.get('amount')
queue = data.get('queue')
admit_date_object = datetime.strptime(admit_date_raw, '%Y-%m-%d')
admit_date = admit_date_object.strftime('%Y-%m-%d')
discharge_date_object = datetime.strptime(discharge_date_raw, '%Y-%m-%d')
discharge_date = discharge_date_object.strftime('%Y-%m-%d')
request.session['claim_ticket_data_salesforce'] = {
'claim_id': claim_id,
'claim_name': claim_name,
'reason_for_denial': reason_for_denial,
'admit_date': admit_date,
'discharge_date': discharge_date,
'amount': amount,
'queue': queue
}
# email_details(request.session['claim_ticket_data_salesforce'])
request.session.save()
return JsonResponse(response_data)
except json.JSONDecodeError:
return JsonResponse({'error': 'INVALID'})
My idea is to save it to the request.session to be accessed in the view that’s behind the ‘Create Ticket’ page. Here is that view class:
class CreateSalesforceTicketView(MustBeStaffMixin, abstract_views.AbstractCreateTicketMixin, FormView):
template_name = 'helpdesk/create_ticket.html'
form_class = TicketForm
def get_initial(self):
initial_data = super().get_initial()
ticket_data = self.request.session.get('claim_ticket_data_salesforce', {})
initial_data.update(ticket_data)
email_details(ticket_data)
return initial_data
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
queues = HelpdeskUser(self.request.user).get_queues()
kwargs["queue_choices"] = _get_queue_choices(queues)
return kwargs
def form_valid(self, form):
# Saves the initial fields
self.ticket = form.save(
user=self.request.user if self.request.user.is_authenticated else None)
# print(self.request.POST)
# Extracts the claim fields
claim_formdict = {'claim_id': self.request.POST.get('claim', None),'claim_name': self.request.POST.get('claim_name', None), 'reason_for_denial': self.request.POST.get('reason_for_denial'), 'admit_date': self.request.POST.get('admit_date', None),
'discharge_date': self.request.POST.get('discharge_date', None), 'amount': self.request.POST.get('amount', None)}
if claim_formdict['claim_id']:
self.ticket.claim = Claim.objects.get(id=int(claim_formdict['claim_id']))
# print(self.ticket.claim)
if claim_formdict['claim_name']:
self.ticket.claim_name = claim_formdict['claim_name']
if claim_formdict['reason_for_denial']:
self.ticket.reason_for_denial = claim_formdict['reason_for_denial']
if claim_formdict['admit_date']:
self.ticket.admit_date = claim_formdict['admit_date']
if claim_formdict['discharge_date']:
self.ticket.discharge_date = claim_formdict['discharge_date']
if claim_formdict['amount']:
self.ticket.amount = claim_formdict['amount']
if self.request.POST['device']:
self.ticket.device = Device.objects.get(id=int(self.request.POST['device']))
# Clear the claim fields if queue is not claim help
if self.ticket.queue.id != 1:
self.ticket.claim = None
self.ticket.claim_name = None
self.ticket.reason_for_denial = None
self.ticket.admit_date = None
self.ticket.discharge_date = None
self.ticket.amount = None
if self.ticket.queue.id != 2:
self.ticket.device = None
self.ticket.save()
if self.ticket.queue.id == 1:
del self.request.session['claim_ticket_data_salesforce']
return super().form_valid(form)
def get_success_url(self):
request = self.request
if HelpdeskUser(request.user).can_access_queue(self.ticket.queue):
return self.ticket.get_absolute_url()
else:
return reverse('helpdesk:dashboard')
def get_context_data(self):
context = super().get_context_data()
context['is_staff'] = True
return context
Because this is a CORS request, I’ve included the django-cors-headers app and included that in INSTALLED_APPS and the middleware. In addition, I’ve also set both of these in settings.py:
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
All this being said, I don’t receive any errors and the request appears to go through. The issue is that the form fields are not pre-populated as expected, and I believe that because this is a CORS request, the requests (and session) is different between my view function receiving the data from Salesforce and my class view that renders the form and pre-populates the fields. Attempting to access the request.session[‘claim_ticket_data_salesforce’] in the class view results in an empty ‘{}’. Accessing the same in my ‘intake view’ shows the session correctly populated with the data.
What can I do to either ensure that the requests are synced so that the data can be accessed through the session, or securely send data another way to the class view so that the fields can be correctly pre-populated? Any suggestions would be super helpful. Thank you in advance!