def handle(self, *args, **options): # Get the user inputs. schema_name = options['schema_name'][0] order_id = int_or_none(options['id'][0]) title = options['title'][0] description = options['description'][0] type_of = int_or_none(options['type_of'][0]) created_by_id = int_or_none(options['created_by_id'][0]) last_modified_by_id = int_or_none(options['last_modified_by_id'][0]) try: franchise = SharedFranchise.objects.get(schema_name=schema_name) except SharedFranchise.DoesNotExist: raise CommandError(_('Franchise does not exist!')) try: created_by = SharedUser.objects.get(id=created_by_id) last_modified_by = SharedUser.objects.get(id=last_modified_by_id) except SharedFranchise.DoesNotExist: raise CommandError(_('User ID # does not exist.')) # Connection will set it back to our tenant. connection.set_schema(schema_name, True) # Switch to Tenant. # Defensive Code: Prevent continuing if the ID# does not exist. if not WorkOrder.objects.filter(id=order_id).exists(): raise CommandError( _('ID # does not exists, please pick another ID #.')) # Create the user. work_order = WorkOrder.objects.get(id=order_id) # Created tasks. task = TaskItem.objects.create(created_by=created_by, last_modified_by=last_modified_by, type_of=type_of, due_date=work_order.start_date, is_closed=False, job=work_order, title=title, description=description) self.stdout.write(self.style.SUCCESS(_('Created "TaskItem" object.'))) work_order.latest_pending_task = task work_order.save() self.stdout.write(self.style.SUCCESS(_('Updated "WorkOrder" object.'))) # For debugging purposes. self.stdout.write( self.style.SUCCESS( _('Successfully created task in tenant account.')))
def handle(self, *args, **options): # Get the user inputs. schema_name = options['schema_name'][0] order_id = int_or_none(options['id'][0]) try: franchise = SharedFranchise.objects.get(schema_name=schema_name) except SharedFranchise.DoesNotExist: raise CommandError(_('Franchise does not exist!')) # Connection will set it back to our tenant. connection.set_schema(schema_name, True) # Switch to Tenant. # Defensive Code: Prevent continuing if the ID# does not exist. if not WorkOrder.objects.filter(id=order_id).exists(): raise CommandError( _('ID # does not exists, please pick another ID #.')) # Create the user. work_order = WorkOrder.objects.get(id=order_id) work_order.delete() self.stdout.write(self.style.SUCCESS(_('Deleted "WorkOrder" object.'))) # For debugging purposes. self.stdout.write( self.style.SUCCESS(_('Successfully deleted a tenant account.')))
def validate_account_type(self, value): """ Include validation for valid choices. """ if int_or_none(value) is None: raise serializers.ValidationError("Please select a valid choice.") return value
def create(self, validated_data): """ Override the `create` function to add extra functinality. """ #-------------------------# # Get validated POST data # #-------------------------# customer = validated_data.get('customer', None) logger.info("Detected commercial customer...") organization_name = validated_data.get('organization_name', None) organization_type_of = int_or_none( validated_data.get('organization_type_of', None)) organization_address_country = validated_data.get( 'organization_address_country', None) organization_address_locality = validated_data.get( 'organization_address_locality', None) organization_address_region = validated_data.get( 'organization_address_region', None) organization_post_office_box_number = validated_data.get( 'organization_post_office_box_number', None) organization_postal_code = validated_data.get( 'organization_postal_code', None) organization_street_address = validated_data.get( 'organization_street_address', None) organization_street_address_extra = validated_data.get( 'organization_street_address_extra', None) organization, created = Organization.objects.update_or_create( name=organization_name, type_of=organization_type_of, defaults={ 'type_of': organization_type_of, 'name': organization_name, 'address_country': organization_address_country, 'address_locality': organization_address_locality, 'address_region': organization_address_region, 'post_office_box_number': organization_post_office_box_number, 'postal_code': organization_postal_code, 'street_address': organization_street_address, 'street_address_extra': organization_street_address_extra, }) logger.info("Created organization.") if created: logger.info("Created organization.") organization.owner = customer.owner organization.save() customer.organization = organization customer.type_of = COMMERCIAL_CUSTOMER_TYPE_OF_ID customer.save() logger.info("Attached created organization to customer.") # Return the validated results. return validated_data
def create(self, validated_data): """ Override the `create` function to add extra functinality: - Create a `User` object in the public database. - Create a `SharedUser` object in the public database. - Create a `Staff` object in the tenant database. - If user has entered text in the 'extra_comment' field then we will a `Comment` object and attach it to the `Staff` object. - We will attach the staff user whom created this `Staff` object. """ # Format our telephone(s) fax_number = validated_data.get('fax_number', None) if fax_number: fax_number = phonenumbers.parse(fax_number, "CA") telephone = validated_data.get('telephone', None) if telephone: telephone = phonenumbers.parse(telephone, "CA") other_telephone = validated_data.get('other_telephone', None) if other_telephone: other_telephone = phonenumbers.parse(other_telephone, "CA") validated_data['fax_number'] = fax_number validated_data['telephone'] = telephone validated_data['other_telephone'] = other_telephone # Extract our "email" field. email = validated_data.get('email', None) personal_email = validated_data.get('personal_email', None) #------------------- # Create our user. #------------------- owner = SharedUser.objects.create( first_name=validated_data['given_name'], last_name=validated_data['last_name'], email=email, is_active=validated_data['is_active'], franchise=self.context['franchise'], was_email_activated=True) logger.info("Created shared user.") # Attach the user to the `group` group. account_type = int_or_none(validated_data.get('account_type', None)) if account_type: owner.groups.set([account_type]) # Update the password. password = validated_data.get('password', None) owner.set_password(password) owner.save() #--------------------------------------------------- # Create our `Staff` object in our tenant schema. #--------------------------------------------------- # Create an "Staff". staff = Staff.objects.create( created_by=self.context['created_by'], last_modified_by=self.context['created_by'], description=validated_data.get('description', None), # Person given_name=validated_data['given_name'], last_name=validated_data['last_name'], middle_name=validated_data['middle_name'], birthdate=validated_data.get('birthdate', None), join_date=validated_data.get('join_date', None), gender=validated_data.get('gender', None), # Misc created_from=self.context['created_from'], created_from_is_public=self.context['created_from_is_public'], # . . . # Contact Point area_served=validated_data.get('area_served', None), available_language=validated_data.get('available_language', None), contact_type=validated_data.get('contact_type', None), email=email, personal_email=personal_email, fax_number=fax_number, # 'hours_available', #TODO: IMPLEMENT. telephone=telephone, telephone_extension=validated_data.get('telephone_extension', None), telephone_type_of=validated_data.get('telephone_type_of', None), other_telephone=other_telephone, other_telephone_extension=validated_data.get( 'other_telephone_extension', None), other_telephone_type_of=validated_data.get( 'other_telephone_type_of', None), # Postal Address address_country=validated_data.get('address_country', None), address_locality=validated_data.get('address_locality', None), address_region=validated_data.get('address_region', None), post_office_box_number=validated_data.get('post_office_box_number', None), postal_code=validated_data.get('postal_code', None), street_address=validated_data.get('street_address', None), street_address_extra=validated_data.get('street_address_extra', None), # Geo-coordinate elevation=validated_data.get('elevation', None), latitude=validated_data.get('latitude', None), longitude=validated_data.get('longitude', None), # 'location' #TODO: IMPLEMENT. ) logger.info("Created staff member.") # Update our staff again. staff.owner = owner staff.email = email staff.save() logger.info("Attached user object to staff member.") #------------------------ # Set our `Tag` objects. #------------------------ tags = validated_data.get('tags', None) if tags is not None: if len(tags) > 0: staff.tags.set(tags) #----------------------------- # Create our `Comment` object. #----------------------------- extra_comment = validated_data.get('extra_comment', None) if extra_comment is not None: comment = Comment.objects.create( created_by=self.context['created_by'], last_modified_by=self.context['created_by'], text=extra_comment, created_from=self.context['created_from'], created_from_is_public=self.context['created_from_is_public']) staff_comment = StaffComment.objects.create( about=staff, comment=comment, ) # Update validation data. # validated_data['comments'] = StaffComment.objects.filter(staff=staff) validated_data['created_by'] = self.context['created_by'] validated_data['last_modified_by'] = self.context['created_by'] validated_data['extra_comment'] = None validated_data['id'] = staff.id # Return our validated data. return validated_data
def run_import_from_dict(self, row_dict, index=1): try: # For debugging purposes. # print(row_dict) # Extract the data. pk = row_dict[0] # CLIENTNO last_name = row_dict[1] # LNAME given_name = row_dict[2] # GNAMES business = row_dict[3] # BUSINESS is_active = row_dict[4] # ACTIVE? birthdate = row_dict[5] # BIRTHDATE address = row_dict[6] # ADDRESS join_date = row_dict[7] # DATE phone = row_dict[8] # PHONE cell = row_dict[9] # CELL email = row_dict[10] # E-MAIL city = row_dict[11] # CITY province = row_dict[12] # PROV postal_code = row_dict[13] # POSTCODE ldn_area = row_dict[14] # LONDAREA hourly_salary_desired = row_dict[15] # HRLYSALDESIR limit_special = row_dict[16] # LIMITSPECIAL dues_date = row_dict[17] # DUES PD commercial_insurance_expiry_date = row_dict[18] # INS DUE police_check = row_dict[19] # POLCHK drivers_license_class = row_dict[20] # DRLICCLASS comments_text = row_dict[21] # COMMENTS has_car = row_dict[22] # Car? has_van = row_dict[23] # Van? has_truck = row_dict[24] # Truck? is_full_time = row_dict[25] # Full Time is_part_time = row_dict[26] # Part Time is_contract_time = row_dict[27] # Contract is_small_job = row_dict[28] # Small Jobs how_hear = row_dict[29] # How Hear # Convert the datetime. local_birthdate = get_dt_from_toronto_timezone_ms_access_dt_string(birthdate) local_join_date = get_dt_from_toronto_timezone_ms_access_dt_string(join_date) local_dues_date = get_dt_from_toronto_timezone_ms_access_dt_string(dues_date) local_commercial_insurance_expiry_date = get_dt_from_toronto_timezone_ms_access_dt_string(commercial_insurance_expiry_date) local_police_check = get_dt_from_toronto_timezone_ms_access_dt_string(police_check) # Minor formatting. email = email.replace(';', '') email = email.replace(':', '') email = email.replace('NONE', '') email = email.replace('N/A', '') email = email.replace(' ', '') email = email.lower() address = '-' if address is '' else address address = '-' if address is None else address province = 'ON' if province is '' else province province = 'ON' if province is None else province city = "London" if city is '' else city phone = phone.replace('(', '') phone = phone.replace(')', '') phone = phone.replace('-', '') phone = phone.replace(' ', '') phone = phone.replace('.', '') cell = cell.replace('(', '') cell = cell.replace(')', '') cell = cell.replace('-', '') cell = cell.replace(' ', '') cell = cell.replace('.', '') # Convert is active to be python boolean. if is_active == '0': is_active = False if is_active == '1': is_active = True # Format the `how_hear` and `how_hear_other`. how_hear_other = None if how_hear is not None and how_hear != "" and len(how_hear) > 0: how_hear_other = how_hear how_hear = 1 # Other else: how_hear_other = None how_hear = 8 # Prefer not to say. # Create or update our user. user = None created = False if email is not None: user, created = SharedUser.objects.update_or_create( email=email, defaults={ 'first_name': given_name, 'last_name': last_name, 'email': email, 'is_active': False, # By default everyone is de-activate unless activated by O55 staff. } ) if created: # Generate and assign the password. user.set_password(get_random_string()) user.save() # Attach our user to the "Executive" user.groups.add(ASSOCIATE_GROUP_ID) # Format telephone number(s). if phone: phone = phonenumbers.parse(str(phone), "CA") if cell: cell = phonenumbers.parse(str(cell), "CA") # Update or create. associate, created_associate = Associate.objects.update_or_create( id=pk, defaults={ 'owner': user, 'last_name':last_name, 'given_name':given_name, 'business':business, # 'is_active':bool_or_none(is_active), 'birthdate':local_birthdate, 'address_country':'Canada', 'join_date':local_join_date, 'telephone':phone, 'telephone_type_of': TELEPHONE_CONTACT_POINT_TYPE_OF_ID, 'other_telephone': cell, 'other_telephone_type_of': MOBILE_CONTACT_POINT_TYPE_OF_ID, 'email':email, 'address_locality':city, 'address_region':province, 'street_address': address, 'postal_code':postal_code, 'area_served':ldn_area, 'hourly_salary_desired':int_or_none(hourly_salary_desired), 'limit_special':limit_special, 'dues_date':local_dues_date, 'commercial_insurance_expiry_date':local_commercial_insurance_expiry_date, 'police_check':local_police_check, 'drivers_license_class':drivers_license_class, # 'comments':comments, 'how_hear': how_hear, 'how_hear_other': how_hear_other, 'last_modified_by': None, 'created_by': None, 'is_ok_to_email': False, 'is_ok_to_text': False } ) # Create our comments if there is text. if comments_text is not None and comments_text != "" and len(comments_text) > 0: comment, created_comment = Comment.objects.update_or_create( text=comments_text, defaults={ 'text': comments_text } ) AssociateComment.objects.update_or_create( about=associate, comment=comment, defaults={ 'about': associate, 'comment': comment } ) # Attach the `VehicleType` objects with this Associate. if has_car: vehicle_type = VehicleType.objects.get(text="Car") associate.vehicle_types.add(vehicle_type) if has_van: vehicle_type = VehicleType.objects.get(text="Van") associate.vehicle_types.add(vehicle_type) if has_truck: vehicle_type = VehicleType.objects.get(text="Truck") associate.vehicle_types.add(vehicle_type) # For debugging purposes. # print(associate, create) except Exception as e: self.stdout.write( self.style.NOTICE(_('Importing Associate Member #%(id)s with exception "%(e)s" for %(email)s.') % { 'e': str(e), 'id': str(index), 'email': str(email) }) )
def run_import_from_dict(self, row_dict, index=1): try: # Fetch our values. pk = int_or_none(row_dict[0]) project_date = row_dict[1] last_name = row_dict[2] first_name = row_dict[3] home_phone = row_dict[4] postal_code = row_dict[5] job_info_read = row_dict[6] learn_about = row_dict[7] is_support = bool_or_none(row_dict[8]) is_senior = bool_or_none(row_dict[9]) birthdate = row_dict[10] job_description = row_dict[11] address = row_dict[12] city = row_dict[13] email = row_dict[14] url = None telephone_extension = None # Minor formatting. email = email.replace(';', '') email = email.replace(':', '') email = email.replace('NONE', '') email = email.replace('N/A', '') email = email.replace(' ', '') email = email.lower() address = '-' if address is '' else address address = '-' if address is None else address city = "London" if city is '' else city if "www" in email.lower(): url = "http://" + email.lower() email = "" if "ext" in email.lower(): telephone_extension = email email = "" home_phone = home_phone.replace('(', '') home_phone = home_phone.replace(')', '') home_phone = home_phone.replace('-', '') home_phone = home_phone.replace(' ', '') home_phone = home_phone.replace('.', '') home_phone = int_or_none(home_phone) # Convert the datetime. local_birthdate = get_utc_dt_from_toronto_dt_string(birthdate) local_project_date = get_utc_dt_from_toronto_dt_string( project_date) # Finally title the words. if first_name: first_name = first_name.title() if last_name: last_name = last_name.title() if address: address = address.title() if city: city = city.title() # Create or update our user if it exists user = None email = None created = False if email is not None and email != "": user, created = SharedUser.objects.update_or_create( first_name=first_name, last_name=last_name, email=email, defaults={ 'first_name': first_name, 'last_name': last_name, 'email': email, 'is_active': True, 'date_joined': local_project_date }) if created: # Generate and assign the password. user.set_password(get_random_string()) user.save() # Attach our user to the "CUSTOMER_GROUP_ID" user.groups.add(CUSTOMER_GROUP_ID) # Format telephone number. if home_phone: home_phone = phonenumbers.parse(str(home_phone), "CA") # Insert our extracted data into our database. customer, create = Customer.objects.update_or_create( id=pk, defaults={ 'id': pk, 'owner': user, 'last_name': last_name, 'given_name': first_name, # 'middle_name':middle_name, 'telephone': home_phone, 'telephone_extension': telephone_extension, 'telephone_type_of': TELEPHONE_CONTACT_POINT_TYPE_OF_ID, 'postal_code': postal_code, 'birthdate': local_birthdate, 'street_address': address, 'address_locality': city, 'address_country': 'Canada', 'address_region': 'Ontario', 'email': email, 'join_date': local_project_date, 'job_info_read': job_info_read, 'how_hear': learn_about, 'description': job_description, 'is_senior': bool(is_senior), 'is_support': bool(is_support), 'is_business': False, 'last_modified_by': None, 'created_by': None, 'type_of': RESIDENTIAL_CUSTOMER_TYPE_OF_ID, 'is_ok_to_email': False, 'is_ok_to_text': False }) # For debugging purposes only. # self.stdout.write( # self.style.SUCCESS(_('Imported (Personal) Customer #%(id)s.') % { # 'id': str(index) # }) # ) except Exception as e: self.stdout.write( self.style.NOTICE( _('Importing (Personal) Customer #%(id)s with exception "%(e)s" for %(email)s.' ) % { 'e': str(e), 'id': str(index), 'email': str(email) })) if "Your email is not unique!" in str(e): customer = Customer.objects.filter(email=email) print(customer) print()
def create(self, validated_data): """ Override the `create` function to add extra functinality. """ #----------------------------- # Get our inputs. #----------------------------- image_file = validated_data.get('image_file', None) upload_type_of = validated_data.get('upload_type_of', None) upload_id = int_or_none(validated_data.get('upload_id', None)) created_by = self.context['created_by'] created_from = self.context['created_from'] created_from_is_public = self.context['created_from_is_public'] # Save our object. image_upload = PublicImageUpload.objects.create( image_file=image_file, created_by=created_by, created_from=created_from, created_from_is_public=created_from_is_public, ) # For debugging purposes only. logger.info("Created public image upload.") # Attach the uploaded image to the specific object type. if upload_type_of == "associate_avatar_image": obj = Associate.objects.get(id=upload_id) if obj.avatar_image: obj.avatar_image.delete() obj.avatar_image = image_upload obj.last_modified_from = self.context['created_from'] obj.last_modified_from_is_public = self.context[ 'created_from_is_public'] obj.save() logger.info("Attached public image upload to associate.") if upload_type_of == "customer_avatar_image": obj = Customer.objects.get(id=upload_id) if obj.avatar_image: obj.avatar_image.delete() obj.avatar_image = image_upload obj.last_modified_from = self.context['created_from'] obj.last_modified_from_is_public = self.context[ 'created_from_is_public'] obj.save() logger.info("Attached public image upload to customer.") if upload_type_of == "partner_avatar_image": obj = Partner.objects.get(id=upload_id) if obj.avatar_image: obj.avatar_image.delete() obj.avatar_image = image_upload obj.last_modified_from = self.context['created_from'] obj.last_modified_from_is_public = self.context[ 'created_from_is_public'] obj.save() logger.info("Attached public image upload to partner.") if upload_type_of == "staff_avatar_image": obj = Staff.objects.get(id=upload_id) if obj.avatar_image: obj.avatar_image.delete() obj.avatar_image = image_upload obj.last_modified_from = self.context['created_from'] obj.last_modified_from_is_public = self.context[ 'created_from_is_public'] obj.save() logger.info("Attached public image upload to staff.") # Return our validated data. return validated_data