def get_target_user(self, source_user_id): user_id = self.user_cache.get(source_user_id) user = None if not user_id: # print('DEBUG - User cache MISS for %s' % user_id) source = self.source_client.users(id=source_user_id) if source: search_val = urllib.parse.quote( source.email) if source.email else None users = self.target_client.search(type='user', email=search_val) if users and len(users) > 0: user = next(users) user_id = user.id print('- User found for %s' % source.email) elif self.DEBUG: print('- DEBUG Creating user: %s' % source.email) else: new_user = User(email=source.email, name=source.name, locale_id=source.locale_id, phone=source.phone, role=source.role, time_zone=source.time_zone, verified=source.verified, suspended=source.suspended, tags=source.tags) if source.organization_id: new_org_id = self.get_target_org_id( source.organization_id) new_user.organization_id = new_org_id print('- Creating user: %s' % new_user.email) created_user = self.target_client.users.create(new_user) user_id = created_user.id # Identities for source_identity in self.source_client.users.identities( id=source_user_id): if not source_identity.primary: identity = Identity(user_id=user_id, type=source_identity.type, value=source_identity.value) self.target_client.users.identities.create( user_id, identity) user = created_user if not created_user: print('ERROR - Unable to create user %s' % source.email) self.user_cache[source_user_id] = user_id else: user = self.target_client.users(id=user_id) return user
def create_support_request(user, email, message, attachments=()): client = Zenpy( subdomain=settings.ZENDESK_SUBDOMAIN, email=settings.ZENDESK_EMAIL, token=settings.ZENDESK_TOKEN, ) ticket_audit = client.tickets.create( Ticket( subject='Data Workspace Support Request', description=message, requester=User(email=email, name=user.get_full_name()), custom_fields=[ CustomField( id=zendesk_service_field_id, value=zendesk_service_field_value ) ], ) ) if attachments: uploads = [client.attachments.upload(x) for x in attachments] ticket_audit.ticket.comment = Comment( body='Additional attachments', uploads=[x.token for x in uploads] ) client.tickets.update(ticket_audit.ticket) return ticket_audit.ticket.id
def create_ticket(title, description, impact, history, name, email): global ticket_number zendesk_client = Zenpy(**creds) # Create a new ticket ticket_audit = zendesk_client.tickets.create( Ticket( subject=title, requester=User(name=name, email=email), comment=Comment( html_body= '<h3>Request Details</h3><pre><code>Title: {}<br>Request: {}<br>' 'Impact: {}<br>History: {}</code></pre><h3>Submitter Details</h3><pre><code>' 'Name: {}<br>Email: {}</code></pre>'.format( title, description, impact, history, name, email)), type="problem", priority="normal", requester_id="366101959011", submitter_id="366101959011", ticket_form_id="360000072631", group_id="360000964291", collaborator_ids=["443254580", "656182144"], follower_ids=["443254580", "656182144"], custom_fields=[ CustomField(id=360005680151, value='request_to_update_existing_process') ])) ticket_number = ticket_audit.ticket.id
def create_basic_user(zc, id, usr_map): # Create a simple user with only an id and name and email usr = User(id=id, email="usr_" + str(id) + "@example.com", name="usr_" + str(id), tags=['RJC']) created_user = zc.users.create(usr) # Save the new user in the user map usr_map[id] = created_user.id return usr_map
def create_zendesk_ticket(self): zenpy_client = Zenpy( subdomain=settings.ZENDESK_SUBDOMAIN, email=settings.ZENDESK_EMAIL, token=settings.ZENDESK_TOKEN, ) attachments = [ value for field, value in self.cleaned_data.items() if field.startswith('attachment') and value ] if attachments: uploads = [] for attachment in attachments: upload_instance = zenpy_client.attachments.upload( attachment.temporary_file_path()) uploads.append(upload_instance.token) else: uploads = None service = SERVICE_FIELD_MAPPING[self.cleaned_data['platform']] custom_fields = [ CustomField(id=30041969, value=service), # service CustomField(id=360000180437, value=self.cleaned_data['department']), # directorate CustomField(id=45522485, value=self.cleaned_data['email']), # email CustomField(id=360000188178, value=self.cleaned_data['telephone']), # Phone number CustomField( id=360000182638, value=self.cleaned_data['request_type']), # Content request CustomField(id=360000180477, value=self.cleaned_data['publication_date_explanation'] ), # reason CustomField(id=360000180457, value=str( self.cleaned_data['publication_date'])) # due date ] ticket = zenpy_client.tickets.create( Ticket(subject=self.cleaned_data['title_of_request'], custom_fields=custom_fields, tags=['content_delivery', self.cleaned_data['platform']], comment=Comment(html_body=self.formatted_text(), uploads=uploads), requester=User(name=self.cleaned_data['name'], email=self.cleaned_data['email']))).ticket return ticket.id
def executeAction(self): try: if self._dictInternal[ "noDefaultToken"] is True and self._dictInternal[ "token"] is not None: self._token = self._dictInternal["token"] if self._dictInternal["action"] == "create": self.resultCreate = self.createTicket() if self._dictInternal['getID'] is True: print(self.jobStatus(self.resultCreate.id)) else: print(self.resultCreate.id) elif self._dictInternal["action"] == "update": self._updateObject = self.searchID() for self.item in self._listValues: if self._dictValues[ self.item] is not None and self._dictValues[ self.item] is not False: if self._dictInternal[ "noKeepTags"] is not True and self.item == "tags": self._updateObject.tags.append( self._dictValues["tags"]) elif self.item == "requester" and self._dictValues[ self.item] is not None: self._updateObject.requester = User( name=self._dictValues[self.item].split("@")[0], email=self._dictValues[self.item]) elif self.item == "comment" and self._dictValues[ self.item] is not None: self.commentTicket() elif self.item == "macro_ids" and self._dictValues[ self.item] is not None: self.updateTicket(self.macroID().ticket) else: print(self.item) setattr(self._updateObject, self.item, self._dictValues[self.item]) self.updateTicket(self._updateObject) elif self._dictInternal["action"] == "search": if self._dictInternal["ticketID"] is not None: self._searchObject = self.searchID() print(self._searchObject.to_dict()) elif self._dictInternal["jobID"] is not None: print(self.jobStatus(self._dictInternal["jobID"])) except Exception as er: if self._log is not None: self._log.error("{} - {}".format(self.__class__.__name__, er)) else: print("{} - {}".format(self.__class__.__name__, er)) return False
def update_users(self, doc, migration_id): user = User( id=doc.id, name=doc.name, email=doc.email, phone=doc.name, organization_id=doc.organization_id ) updated_user = self.zenpy_client.users.create_or_update(user) if hasattr(updated_user, "error"): frappe.log_error("Id {0}: {1}".format(migration_id, updated_user.description), "Zendesk Contact Update Error") else: return {self.name_field: updated_user.id}
def insert_users(self, doc): user = User( id=doc.id, name=doc.name, email=doc.email, phone=doc.phone, organization_id=doc.organization_id ) created_user = self.zenpy_client.users.create(user) if hasattr(created_user, "error"): frappe.log_error("Doc {0}: {1}".format(doc, created_user.description), "Zendesk Contact Insert Response Error") else: return {self.name_field: created_user.id}
def create_support_request(user, email, message): client = Zenpy( subdomain=settings.ZENDESK_SUBDOMAIN, email=settings.ZENDESK_EMAIL, token=settings.ZENDESK_TOKEN, ) ticket_audit = client.tickets.create( Ticket( subject='Data Workspace Support Request', description=message, requester=User(email=email, name=user.get_full_name()), custom_fields=[ CustomField(id=zendesk_service_field_id, value=zendesk_service_field_value) ], )) return ticket_audit.ticket.id
def create_zendesk_ticket( contact_email, user, goal, justification_text, approval_url, dataset_name, dataset_url, information_asset_owner, # nb this can be null information_asset_manager, # so can this ): client = Zenpy( subdomain=settings.ZENDESK_SUBDOMAIN, email=settings.ZENDESK_EMAIL, token=settings.ZENDESK_TOKEN, ) ticket_description = build_ticket_description_text( dataset_name, dataset_url, contact_email, user, justification_text, goal ) private_comment = build_private_comment_text( information_asset_owner, information_asset_manager, approval_url ) username = get_username(user) subject = f'Access Request for {dataset_name}' ticket_audit = client.tickets.create( Ticket( subject=subject, description=ticket_description, requester=User(email=contact_email, name=username), custom_fields=[ CustomField( id=zendesk_service_field_id, value=zendesk_service_field_value ) ], ) ) ticket_audit.ticket.comment = Comment(body=private_comment, public=False) client.tickets.update(ticket_audit.ticket) return ticket_audit.ticket.id
def create_zendesk_ticket(request, access_request, catalogue_item=None): client = Zenpy( subdomain=settings.ZENDESK_SUBDOMAIN, email=settings.ZENDESK_EMAIL, token=settings.ZENDESK_TOKEN, ) access_request_url = request.build_absolute_uri( reverse("admin:request_access_accessrequest_change", args=(access_request.id, ))) authorize_url = request.build_absolute_uri( reverse("admin:auth_user_change", args=[access_request.requester.id])) ticket_description = build_ticket_description_text(access_request, access_request_url, catalogue_item) private_comment = (build_private_comment_text( catalogue_item, authorize_url) if catalogue_item else None) username = get_username(access_request.requester) subject = f"Access Request for {catalogue_item if catalogue_item else username}" ticket_audit = client.tickets.create( Ticket( subject=subject, description=ticket_description, requester=User(email=access_request.requester.email, name=username), custom_fields=[ CustomField(id=zendesk_service_field_id, value=zendesk_service_field_value) ], )) ticket_audit.ticket.comment = Comment(body=private_comment, public=False) client.tickets.update(ticket_audit.ticket) return ticket_audit.ticket.id
def get_or_add_user(fullname: str, email: str, org_id: str): user_notes = 'Community Connect Pod User' e_user = search_users(email) if e_user: notes = e_user.notes + '\n\n' if e_user.notes else '' do_update = False if user_notes not in notes: e_user.notes = notes + user_notes do_update = True if e_user.organization_id != org_id: e_user.organization_id = org_id do_update = True if not e_user.verified: e_user.verified = True do_update = True if 'community_connect' not in [t.lower() for t in e_user.tags]: e_user.tags.append('Community_Connect') do_update = True if do_update: e_user = z_client.users.update(e_user) else: n_user = User(name=fullname, email=email, organization_id=org_id, role='end-user', verified=True, notes=user_notes, tags=['Community_Connect'], ticket_restriction='requested', only_private_comments=False) z_client.users.create(n_user)
"""insert into %s values (%%s,%%s,%%s,%%s,%%s)""" % ("offenen_eigene_rechnungen_VIP"), (date_, date_, row[11], "yes", 29.95)) von = "Internes To Do: VIP Model Abbuchung pending" email = "*****@*****.**" betreff = "Abbuchung VIP Model " + str( now.month) + "/" + str( now.year ) + " pending: Kundennummer #" + row[11] message = """Abbuchnung von 29,95 EUR fuer VIP Model """ + str( now.month ) + "/" + str( now.year ) + """ noch durchzufuehren. Email-Adresse des Kunden ist """ + row[ 0] + """. Zahlungsmittel ist """ + row[56] creds = { 'email': '*****@*****.**', 'token': 'oY8q9R9T4io7ZwQ1KdDktKwXgF3sWhMneMECjpL0', 'subdomain': 'darlinglace' } zenpy_client = Zenpy(**creds) zenpy_client.tickets.create( Ticket(description=message, subject=betreff, requester=User(name=von, email=email))) conn.commit()
def test_run(self): # Default test setup # Create the connection for Zendesk conn_id = connections.ensure_connection(self) # Run a check job using orchestrator check_job_name = runner.run_check_mode(self, conn_id) exit_status = menagerie.get_exit_status(conn_id, check_job_name) menagerie.verify_check_exit_status(self, exit_status, check_job_name) # Verify schemas discovered were discovered self.found_catalogs = menagerie.get_catalogs(conn_id) self.assertEqual(len(self.found_catalogs), len(self.expected_check_streams())) # Verify the schemas discovered were exactly what we expect found_catalog_names = {catalog['tap_stream_id'] for catalog in self.found_catalogs if catalog['tap_stream_id'] in self.expected_check_streams()} self.assertSetEqual(self.expected_check_streams(), found_catalog_names) # Select our catalogs our_catalogs = [c for c in self.found_catalogs if c.get('tap_stream_id') in self.expected_sync_streams()] for catalog in our_catalogs: schema = menagerie.get_annotated_schema(conn_id, catalog['stream_id']) connections.select_catalog_and_fields_via_metadata(conn_id, catalog, schema, [], []) # Clear state before our run menagerie.set_state(conn_id, {}) # Run a sync job using orchestrator sync_job_name = runner.run_sync_mode(self, conn_id) # Verify tap and target exit codes exit_status = menagerie.get_exit_status(conn_id, sync_job_name) menagerie.verify_sync_exit_status(self, exit_status, sync_job_name) # Verify actual rows were synced record_count_by_stream = runner.examine_target_output_file(self, conn_id, self.expected_sync_streams(), self.expected_pks()) replicated_row_count = reduce(lambda accum,c : accum + c, record_count_by_stream.values()) self.assertGreater(replicated_row_count, 0, msg="failed to replicate any data: {}".format(record_count_by_stream)) print("total replicated row count: {}".format(replicated_row_count)) # Ensure all records have a value for PK(s) records = runner.get_records_from_target_output() for stream in self.expected_sync_streams(): messages = records.get(stream, {}).get('messages', []) for m in messages: pk_set = self.expected_pks()[stream] for pk in pk_set: self.assertIsNotNone(m.get('data', {}).get(pk), msg="oh no! {}".format(m)) satisfaction_ratings_bookmark = "2020-03-05T14:14:42Z" state = menagerie.get_state(conn_id) state['bookmarks']['satisfaction_ratings']['updated_at'] = satisfaction_ratings_bookmark menagerie.set_state(conn_id, state) # Create a new record creds = { "email": "*****@*****.**", "subdomain": self.get_properties()['subdomain'], "token": os.getenv('TAP_ZENDESK_API_TOKEN') } self.client = Zenpy(**creds) # Create some new objects group_name = str(uuid.uuid4()) group = Group(name=group_name) self.created_group = self.client.groups.create(group) org_name = str(uuid.uuid4()) org = Organization(name=org_name) self.created_org = self.client.organizations.create(org) user = User(name="John Doe", email="{}@mailinator.com".format(uuid.uuid4())) self.created_user = self.client.users.create(user) # Sleeping 1 minute to validate lookback behavior needed in tap # We've observed a delay between when users are created and when # they're available through the API print("sleeping for 60 seconds") time.sleep(60) # Run another Sync sync_job_name = runner.run_sync_mode(self, conn_id) exit_status = menagerie.get_exit_status(conn_id, sync_job_name) menagerie.verify_sync_exit_status(self, exit_status, sync_job_name) # Check both sets of records and make sure we have our new rows records = runner.get_records_from_target_output() messages = records.get('groups', {}).get('messages', []) new_record = [r for r in messages if r['data']['id'] == self.created_group.id] self.assertTrue(any(new_record)) self.assertEqual(len(messages), 2, msg="Sync'd incorrect count of messages: {}".format(len(messages))) messages = records.get('organizations', {}).get('messages', []) new_record = [r for r in messages if r['data']['id'] == self.created_org.id] self.assertTrue(any(new_record)) self.assertEqual(len(messages), 2, msg="Sync'd incorrect count of messages: {}".format(len(messages))) messages = records.get('users', {}).get('messages', []) new_record = [r for r in messages if r['data']['id'] == self.created_user.id] self.assertTrue(any(new_record)) # NB: GreaterEqual because we suspect Zendesk updates users in the backend # >= 1 because we're no longer inclusive of the last replicated user record. The lookback will control this going forward. # If we get the user we wanted and then some, this assertion should succeed self.assertGreaterEqual(len(messages), 1, msg="Sync'd incorrect count of messages: {}".format(len(messages))) messages = records.get('satisfaction_ratings', {}).get('messages', []) new_record = [r for r in messages if r['data']['id'] in [364471784994, 364465631433, 364465212373]] self.assertTrue(any(new_record)) self.assertGreaterEqual(len(messages), 3, msg="Sync'd incorrect count of messages: {}".format(len(messages))) for message in messages: self.assertGreaterEqual(message.get('data', {}).get('updated_at', ''), satisfaction_ratings_bookmark)
def _get_zendesk_user_id(self, selected_user=None): """ # | Function to get keystone user detail. # | Also this function will create a user with random password # | if no user found. # | # | Arguments: None # | # | Return Type: User object """ #Checking the user is selected user_selected = False if selected_user != None: if selected_user['user'] != '': user_selected = True user_data = selected_user['user'] user_data = user_data.split('--') email = user_data[1] zend_name = user_data[2] ks_id = user_data[0] else: email = self._request.session['zendesksupport'][ 'ks_user_email'] else: if 'zendesk_user_id' in self._request.session['zendesksupport']: return self._request.session['zendesksupport'][ 'zendesk_user_id'] if not self._user_has_email(): # | If there is no email, then there is # | no point to check the user, simple return False raise False email = self._request.session['zendesksupport']['ks_user_email'] users = self._zenpy.search("email:" + email, type="user") # Search user by email, will result maximum one user oly if users.count != 1: # | If no user found, then create a new user if user_selected: pass else: zend_name = self._request.user #Creating new user with the details set new_user = User(name=str(zend_name), email=email, password=self._random_pass()) #uid = self._zenpy.users.create(new_user).id uid = self._zenpy.users.create_or_update(new_user).id self._request.session['zendesksupport']['zendesk_user_id'] = uid extra = {"submitter_id": uid} if user_selected: self.keystone.users.update(ks_id, **extra) else: self.keystone.users.update( self._request.session['zendesksupport']['ks_user_id'], **extra) return uid for user in users: # | As there will be only one user # | so return at first attempt itself. self._request.session['zendesksupport'][ 'zendesk_user_id'] = user.id return user.id
def create_user(zc, user_content, org_map, user_map): # Format the list like strings from the data into proper python lists tags = user_content['tags'] \ .replace("(", "") \ .replace(")", "") \ .replace("[", "") \ .replace("]", "") \ .replace("'", "") tags = tags.split(",") tags.append("RJC") org_id = user_content['organization_id'] \ .replace("(", "") \ .replace(")", "") \ .replace("[", "") \ .replace("]", "") \ .replace("'", "") org_id = org_id.split(",") org_id = list(map(int, org_id)) # Set status variables email_already_present = False update = False # Loop through users in zendesk for user in zc.users(): # if the provided email is in zendesk set the related status to true if user.email == user_content['email']: email_already_present = True # if the user is already in zendesk set the related status to true and save the zendesk id if user.email == user_content['email'] and user.name == user_content['name'] and user.organization_id == \ org_map[org_id[0]]: update = True update_id = user.id # Define the user object from the given data to import into zendesk usr = User(name=user_content['name'], organization_id=org_map[org_id[0]], role=user_content['role'], notes=user_content['notes'], tags=tags, user_fields={ 'group': user_content['group'].replace(" ", ""), 'subscription': user_content['api_subscription'], 'promotion_code': user_content['promotion_code'], 'employee_id': str(user_content['employee_id']), 'secondary_email': "" } ) # if the user is already present in zendesk, update the user if update: # initialize invalid email count variable invalid_email_count = 0 # Save the zendesk user id to the user object and store the provided email in the "secondary email" field usr.id = update_id usr.user_fields["secondary_email"] = user_content['email'] while True: # Save the primary email for the user as an invalid email address usr.email = "invalid" + str(invalid_email_count) + "@example.com" # Attempt to create the user try: created_user = zc.users.update(usr) # if user creation error, try another invalid email except zenpy.lib.exception.APIException: invalid_email_count = invalid_email_count + 1 # if any other error break from the loop else: break # if the email is already present create a user with an invalid email address elif email_already_present: invalid_email_count = 0 usr.user_fields["secondary_email"] = user_content['email'] while True: usr.email = "invalid" + str(invalid_email_count) + "@example.com" try: created_user = zc.users.create(usr) except zenpy.lib.exception.APIException: invalid_email_count = invalid_email_count + 1 else: break # if the email is uniques and the user isn't in zendesk create the user else: usr.email = user_content['email'] created_user = zc.users.create(usr) # Create organization members ships for the provided organization ties for org in org_id: o_id = org_map[org] create_organization_membership(zc, created_user.id, o_id) # update the user map with the new user new_user_map = user_map new_user_map[user_content['id']] = created_user.id return new_user_map
def create_ticket(username: str, email: str, title: str, description: str): settings.ZENPY_CLIENT.tickets.create( Ticket(title=title, description=description, requester=User(name=username, email=email)))
def create_adf_zendesk_tickets(instances): try: print('init adf creation') zenpy_client = Zenpy(**settings.ZENDESK) scs = ScheduledExam.objects.filter(id__in=instances) if not scs: print("No adf tickets to create") return onesc = scs.first() mp = onesc.prescription desc = """Data de abertura: {} Laboratório:{} Exames: {} """ lab_name = onesc.laboratory.description if onesc.laboratory else '' print(desc) ticket = zenpy_client.tickets.create( Ticket( subject='Abertura de ficha para: {} no laboratório: {}'.format( mp.patient.full_name, lab_name), requester=User(name=mp.patient.full_name, external_id=mp.patient.user.id, email=mp.patient.user.email), type='task', status='open', priority='normal', due_at=onesc.scheduled_time, custom_fields=[ CustomField(id=114103586991, value='patient_requested'), CustomField(id=114103769352, value=mp.patient.phone), CustomField(id=114103769652, value=mp.patient.gender), CustomField(id=360002412071, value=onesc.scheduled_time.date()) ], description=desc.format( onesc.scheduled_time.strftime('%d/%m/%Y %H:%M'), onesc.laboratory.description, ', '.join([i.exam.name for i in scs])))) et = ticket.ticket tdata = et.to_dict() del (tdata['via']) print(tdata) try: zticket = ZendeskASFTicket.objects.create(external_id=et.id, content=tdata) except Exception as e: print('*** {} ***'.format(e)) print("Ticket for exams: {} already created".format( scs.values('id'))) zticket = ZendeskASFTicket.objects.filter( external_id=et.id).first() print(zticket) et.external_id = zticket.id et.tags.extend([u'saracare', u'aberturadeficha']) ppieces = [] for name, file in [ ("RG frente", mp.picture_id_front_uploadcare.file if mp.picture_id_front_uploadcare else None), ("RG verso", mp.picture_id_back_uploadcare.file if mp.picture_id_back_uploadcare else None), ("Plano frente", mp.picture_insurance_card_front_uploadcare.file if mp.picture_insurance_card_front_uploadcare else None), ("Plano verso", mp.picture_insurance_card_back_uploadcare.file if mp.picture_insurance_card_back_uploadcare else None) ] + ppieces: if file: upload_instance = zenpy_client.attachments.upload(file) et.comment = Comment(body=name, uploads=[upload_instance.token]) zenpy_client.tickets.update(et) zenpy_client.tickets.update(et) scs.update(zendesk_adf_ticket=zticket) except Exception as e: print("Creation Error: {}".format(e))
def create_zendesk_ticket(instance): try: zenpy_client = Zenpy(**settings.ZENDESK) if type(instance) in [str, int]: instance = domain_models.MedicalPrescription.objects.filter( id=int(instance)).first() desc = "" if instance.period_info: desc = "Última menstruação: {}".format(instance.period_info) desc = """{} Informações Adicionais: {}""".format(desc, instance.additional_info or "Nenhuma") try: if instance.preferred_laboratory: desc = """{} Laboratório preferido: {}""".format( desc, instance.preferred_laboratory.description or "Nenhuma") except Exception: print(instance.preferred_laboratory) try: if instance.preferred_date_to_schedule: desc = """{} Data preferida: {}""".format( desc, instance.preferred_date_to_schedule.strftime( "%Y-%m-%d %H:%M:%S") or "Nenhuma") except Exception: print(instance.preferred_date_to_schedule) selfie = '' if instance.patient.selfie_uploadcare: selfie = instance.patient.selfie_uploadcare.url elif instance.patient.selfie: selfie = instance.patient.selfie.url ticket = zenpy_client.tickets.create( Ticket(subject='Prescrição para: {}'.format( instance.patient.full_name), requester=User(name=instance.patient.full_name, external_id=instance.patient.user.id, email=instance.patient.user.email, remote_photo_url=selfie, user_fields=UserField( gender=instance.patient.gender, phone=str(instance.patient.phone))), type='task', priority='normal', custom_fields=[ CustomField(id=114103586991, value='patient_requested'), CustomField(id=114103769352, value=instance.patient.phone), CustomField(id=114103769652, value=instance.patient.gender) ], description=desc)) # a = MedicalPrescription.objects.all().last() # from general_utils.utils import create_zendesk_ticket # create_zendesk_ticket(a) et = ticket.ticket tdata = et.to_dict() del (tdata['via']) print(tdata) try: print('###') zticket = ZendeskTicket.objects.create(external_id=et.id, prescription=instance, content=tdata) except Exception: print('***') zticket = ZendeskTicket.objects.filter( prescription=instance).first() zticket.external_id = et.id zticket.content = tdata zticket.save() print(zticket) et.external_id = zticket.id et.tags.extend([u'prescrição', u'saracare']) # # from general_utils.utils import create_zendesk_ticket # p = MedicalPrescription.objects.all().last() # create_zendesk_ticket(p) ppieces = [] for ppiece in instance.pieces.all(): if ppiece.picture: ppieces.append(("Precrição", ppiece.picture.file)) for name, file in [ ("RG frente", instance.picture_id_front_uploadcare.file if instance.picture_id_front_uploadcare else None), ("RG verso", instance.picture_id_back_uploadcare.file if instance.picture_id_back_uploadcare else None), ("Plano frente", instance.picture_insurance_card_front_uploadcare.file if instance.picture_insurance_card_front_uploadcare else None), ("Plano verso", instance.picture_insurance_card_back_uploadcare.file if instance.picture_insurance_card_back_uploadcare else None) ] + ppieces: if file: upload_instance = zenpy_client.attachments.upload(file) et.comment = Comment(body=name, uploads=[upload_instance.token]) zenpy_client.tickets.update(et) zenpy_client.tickets.update(et) except Exception as e: print("Creation Error: {}".format(e))
def createTicket(self): """ :return: """ try: if self._dictValues["subject"] is not None and self._dictValues[ "description"] is not None: print("Ok") if self._dictValues['requester'] is not None: self.createTicketObject = self.connectZendesk.tickets.create( [ Ticket( subject=self._dictValues["subject"], description=self._dictValues["description"], assignee_id=self._dictValues["assignee_id"], group_id=self._dictValues["group_id"], organization_id=self. _dictValues["organization_id"], priority=self._dictValues["priority"], problem_id=self._dictValues["problem_id"], status=self._dictValues["status"], tags=self._dictValues["tags"], requester=User( name=self._dictValues['requester'].split( "@")[0], email=self._dictValues['requester']), submitter_id=self._dictValues["submitter_id"], ticket_form_id=self. _dictValues["ticket_form_id"], assignee_email=self. _dictValues["assignee_email"], collaborator_ids=self. _dictValues["collaborator_ids"]) ]) else: self.createTicketObject = self.connectZendesk.tickets.create( [ Ticket( subject=self._dictValues["subject"], description=self._dictValues["description"], assignee_id=self._dictValues["assignee_id"], group_id=self._dictValues["group_id"], organization_id=self. _dictValues["organization_id"], priority=self._dictValues["priority"], problem_id=self._dictValues["problem_id"], status=self._dictValues["status"], tags=self._dictValues["tags"], requester_id=self._dictValues["requester_id"], submitter_id=self._dictValues["submitter_id"], ticket_form_id=self. _dictValues["ticket_form_id"], assignee_email=self. _dictValues["assignee_email"], collaborator_ids=self. _dictValues["collaborator_ids"]) ]) return self.createTicketObject else: self._log.error("{} - {}".format( self.__class__.__name__, "Object description or subject empty")) return False except Exception as er: if self._log is not None: self._log.error("{} - {}".format(self.__class__.__name__, er)) else: print("{} - {}".format(self.__class__.__name__, er)) return False