convert indentation to tabs

This commit is contained in:
0Pranav 2019-11-07 12:47:00 +05:30
parent fce8f36bb2
commit 75db6f7073
4 changed files with 328 additions and 325 deletions

View File

@ -17,203 +17,206 @@ from frappe.utils.verified_command import verify_request, get_signed_params
class Appointment(Document):
def find_lead_by_email(self):
lead_list = frappe.get_list(
'Lead', filters={'email_id': self.customer_email}, ignore_permissions=True)
if lead_list:
return lead_list[0].name
return None
def find_lead_by_email(self):
lead_list = frappe.get_list(
'Lead', filters={'email_id': self.customer_email}, ignore_permissions=True)
if lead_list:
return lead_list[0].name
return None
def before_insert(self):
number_of_appointments_in_same_slot = frappe.db.count(
'Appointment', filters={'scheduled_time': self.scheduled_time})
number_of_agents = frappe.db.get_single_value('Appointment Booking Settings', 'number_of_agents')
if(number_of_appointments_in_same_slot >= number_of_agents):
frappe.throw('Time slot is not available')
# Link lead
if not self.lead:
self.lead = self.find_lead_by_email()
def before_insert(self):
number_of_appointments_in_same_slot = frappe.db.count(
'Appointment', filters={'scheduled_time': self.scheduled_time})
number_of_agents = frappe.db.get_single_value('Appointment Booking Settings', 'number_of_agents')
if(number_of_appointments_in_same_slot >= number_of_agents):
frappe.throw('Time slot is not available')
# Link lead
if not self.lead:
self.lead = self.find_lead_by_email()
def after_insert(self):
if self.lead:
# Create Calendar event
self.auto_assign()
self.create_calendar_event()
else:
# Set status to unverified
self.status = 'Unverified'
# Send email to confirm
self.send_confirmation_email()
def after_insert(self):
if self.lead:
# Create Calendar event
self.auto_assign()
self.create_calendar_event()
else:
# Set status to unverified
self.status = 'Unverified'
# Send email to confirm
self.send_confirmation_email()
def send_confirmation_email(self):
verify_url = self._get_verify_url()
template = 'confirm_appointment'
args = {
"link":verify_url,
"site_url":frappe.utils.get_url(),
"full_name":self.customer_name,
}
frappe.sendmail(recipients=[self.customer_email],
template=template,
args=args,
subject=_('Appointment Confirmation'))
if frappe.session.user == "Guest":
frappe.msgprint(
'Please check your email to confirm the appointment')
def send_confirmation_email(self):
verify_url = self._get_verify_url()
template = 'confirm_appointment'
args = {
"link":verify_url,
"site_url":frappe.utils.get_url(),
"full_name":self.customer_name,
}
frappe.sendmail(recipients=[self.customer_email],
template=template,
args=args,
subject=_('Appointment Confirmation'))
if frappe.session.user == "Guest":
frappe.msgprint(
'Please check your email to confirm the appointment')
else :
frappe.msgprint(
'Appointment was created. But no lead was found. Please check the email to confirm')
def on_change(self):
# Sync Calendar
if not self.calendar_event:
return
cal_event = frappe.get_doc('Event', self.calendar_event)
cal_event.starts_on = self.scheduled_time
cal_event.save(ignore_permissions=True)
def on_change(self):
# Sync Calendar
if not self.calendar_event:
return
cal_event = frappe.get_doc('Event', self.calendar_event)
cal_event.starts_on = self.scheduled_time
cal_event.save(ignore_permissions=True)
def set_verified(self, email):
if not email == self.customer_email:
frappe.throw('Email verification failed.')
# Create new lead
self.create_lead_and_link()
# Remove unverified status
self.status = 'Open'
# Create calender event
self.auto_assign()
self.create_calendar_event()
self.save(ignore_permissions=True)
frappe.db.commit()
def set_verified(self, email):
if not email == self.customer_email:
frappe.throw('Email verification failed.')
# Create new lead
self.create_lead_and_link()
# Remove unverified status
self.status = 'Open'
# Create calender event
self.auto_assign()
self.create_calendar_event()
self.save(ignore_permissions=True)
frappe.db.commit()
def create_lead_and_link(self):
# Return if already linked
if self.lead:
return
lead = frappe.get_doc({
'doctype': 'Lead',
'lead_name': self.customer_name,
'email_id': self.customer_email,
'notes': self.customer_details,
'phone': self.customer_phone_number,
})
lead.insert(ignore_permissions=True)
# Link lead
self.lead = lead.name
def create_lead_and_link(self):
# Return if already linked
if self.lead:
return
lead = frappe.get_doc({
'doctype': 'Lead',
'lead_name': self.customer_name,
'email_id': self.customer_email,
'notes': self.customer_details,
'phone': self.customer_phone_number,
})
lead.insert(ignore_permissions=True)
# Link lead
self.lead = lead.name
def auto_assign(self):
from frappe.desk.form.assign_to import add as add_assignemnt
existing_assignee = self.get_assignee_from_latest_opportunity()
if existing_assignee:
# If the latest opportunity is assigned to someone
# Assign the appointment to the same
add_assignemnt({
'doctype': self.doctype,
'name': self.name,
'assign_to': existing_assignee
})
return
if self._assign:
return
available_agents = _get_agents_sorted_by_asc_workload(
self.scheduled_time.date())
for agent in available_agents:
if(_check_agent_availability(agent, self.scheduled_time)):
agent = agent[0]
add_assignemnt({
'doctype': self.doctype,
'name': self.name,
'assign_to': agent
})
break
def auto_assign(self):
from frappe.desk.form.assign_to import add as add_assignemnt
existing_assignee = self.get_assignee_from_latest_opportunity()
if existing_assignee:
# If the latest opportunity is assigned to someone
# Assign the appointment to the same
add_assignemnt({
'doctype': self.doctype,
'name': self.name,
'assign_to': existing_assignee
})
return
if self._assign:
return
available_agents = _get_agents_sorted_by_asc_workload(
self.scheduled_time.date())
for agent in available_agents:
if(_check_agent_availability(agent, self.scheduled_time)):
agent = agent[0]
add_assignemnt({
'doctype': self.doctype,
'name': self.name,
'assign_to': agent
})
break
def get_assignee_from_latest_opportunity(self):
if not self.lead:
return None
if not frappe.db.exists('Lead', self.lead):
return None
opporutnities = frappe.get_list(
'Opportunity',
filters={
'party_name': self.lead,
},
ignore_permissions=True,
order_by='creation desc')
if not opporutnities:
return None
latest_opportunity = frappe.get_doc('Opportunity', opporutnities[0].name )
assignee = latest_opportunity._assign
if not assignee:
return None
assignee = frappe.parse_json(assignee)[0]
return assignee
def get_assignee_from_latest_opportunity(self):
if not self.lead:
return None
if not frappe.db.exists('Lead', self.lead):
return None
opporutnities = frappe.get_list(
'Opportunity',
filters={
'party_name': self.lead,
},
ignore_permissions=True,
order_by='creation desc')
if not opporutnities:
return None
latest_opportunity = frappe.get_doc('Opportunity', opporutnities[0].name )
assignee = latest_opportunity._assign
if not assignee:
return None
assignee = frappe.parse_json(assignee)[0]
return assignee
def create_calendar_event(self):
if self.calendar_event:
return
appointment_event = frappe.get_doc({
'doctype': 'Event',
'subject': ' '.join(['Appointment with', self.customer_name]),
'starts_on': self.scheduled_time,
'status': 'Open',
'type': 'Public',
'send_reminder': frappe.db.get_single_value('Appointment Booking Settings', 'email_reminders'),
'event_participants': [dict(reference_doctype='Lead', reference_docname=self.lead)]
})
employee = _get_employee_from_user(self._assign)
if employee:
appointment_event.append('event_participants', dict(
reference_doctype='Employee',
reference_docname=employee.name))
appointment_event.insert(ignore_permissions=True)
self.calendar_event = appointment_event.name
self.save(ignore_permissions=True)
def _get_verify_url(self):
verify_route = '/book-appointment/verify'
params = {
'email': self.customer_email,
'appointment': self.name
}
return get_url(verify_route + '?' + get_signed_params(params))
def create_calendar_event(self):
if self.calendar_event:
return
appointment_event = frappe.get_doc({
'doctype': 'Event',
'subject': ' '.join(['Appointment with', self.customer_name]),
'starts_on': self.scheduled_time,
'status': 'Open',
'type': 'Public',
'send_reminder': frappe.db.get_single_value('Appointment Booking Settings', 'email_reminders'),
'event_participants': [dict(reference_doctype='Lead', reference_docname=self.lead)]
})
employee = _get_employee_from_user(self._assign)
if employee:
appointment_event.append('event_participants', dict(
reference_doctype='Employee',
reference_docname=employee.name))
appointment_event.insert(ignore_permissions=True)
self.calendar_event = appointment_event.name
self.save(ignore_permissions=True)
def _get_verify_url(self):
verify_route = '/book-appointment/verify'
params = {
'email': self.customer_email,
'appointment': self.name
}
return get_url(verify_route + '?' + get_signed_params(params))
def _get_agents_sorted_by_asc_workload(date):
appointments = frappe.db.get_list('Appointment', fields='*')
agent_list = _get_agent_list_as_strings()
if not appointments:
return agent_list
appointment_counter = Counter(agent_list)
for appointment in appointments:
assigned_to = frappe.parse_json(appointment._assign)
if not assigned_to:
continue
if (assigned_to[0] in agent_list) and appointment.scheduled_time.date() == date:
appointment_counter[assigned_to[0]] += 1
sorted_agent_list = appointment_counter.most_common()
sorted_agent_list.reverse()
return sorted_agent_list
appointments = frappe.db.get_list('Appointment', fields='*')
agent_list = _get_agent_list_as_strings()
if not appointments:
return agent_list
appointment_counter = Counter(agent_list)
for appointment in appointments:
assigned_to = frappe.parse_json(appointment._assign)
if not assigned_to:
continue
if (assigned_to[0] in agent_list) and appointment.scheduled_time.date() == date:
appointment_counter[assigned_to[0]] += 1
sorted_agent_list = appointment_counter.most_common()
sorted_agent_list.reverse()
return sorted_agent_list
def _get_agent_list_as_strings():
agent_list_as_strings = []
agent_list = frappe.get_doc('Appointment Booking Settings').agent_list
for agent in agent_list:
agent_list_as_strings.append(agent.user)
return agent_list_as_strings
agent_list_as_strings = []
agent_list = frappe.get_doc('Appointment Booking Settings').agent_list
for agent in agent_list:
agent_list_as_strings.append(agent.user)
return agent_list_as_strings
def _check_agent_availability(agent_email, scheduled_time):
appointemnts_at_scheduled_time = frappe.get_list(
'Appointment', filters={'scheduled_time': scheduled_time})
for appointment in appointemnts_at_scheduled_time:
if appointment._assign == agent_email:
return False
return True
appointemnts_at_scheduled_time = frappe.get_list(
'Appointment', filters={'scheduled_time': scheduled_time})
for appointment in appointemnts_at_scheduled_time:
if appointment._assign == agent_email:
return False
return True
def _get_employee_from_user(user):
employee_docname = frappe.db.exists(
{'doctype': 'Employee', 'user_id': user})
if employee_docname:
# frappe.db.exists returns a tuple of a tuple
return frappe.get_doc('Employee', employee_docname[0][0])
return None
employee_docname = frappe.db.exists(
{'doctype': 'Employee', 'user_id': user})
if employee_docname:
# frappe.db.exists returns a tuple of a tuple
return frappe.get_doc('Employee', employee_docname[0][0])
return None

View File

@ -10,29 +10,29 @@ from frappe.model.document import Document
class AppointmentBookingSettings(Document):
min_date = '01/01/1970 '
format_string = "%d/%m/%Y %H:%M:%S"
min_date = '01/01/1970 '
format_string = "%d/%m/%Y %H:%M:%S"
def validate(self):
self.validate_availability_of_slots()
def validate(self):
self.validate_availability_of_slots()
def validate_availability_of_slots(self):
for record in self.availability_of_slots:
from_time = datetime.datetime.strptime(
self.min_date+record.from_time, self.format_string)
to_time = datetime.datetime.strptime(
self.min_date+record.to_time, self.format_string)
timedelta = to_time-from_time
self.validate_from_and_to_time(from_time, to_time)
self.duration_is_divisible(from_time, to_time)
def validate_availability_of_slots(self):
for record in self.availability_of_slots:
from_time = datetime.datetime.strptime(
self.min_date+record.from_time, self.format_string)
to_time = datetime.datetime.strptime(
self.min_date+record.to_time, self.format_string)
timedelta = to_time-from_time
self.validate_from_and_to_time(from_time, to_time)
self.duration_is_divisible(from_time, to_time)
def validate_from_and_to_time(self, from_time, to_time):
if from_time > to_time:
err_msg = _('<b>From Time</b> cannot be later than <b>To Time</b> for {0}').format(record.day_of_week)
frappe.throw(_(err_msg))
def validate_from_and_to_time(self, from_time, to_time):
if from_time > to_time:
err_msg = _('<b>From Time</b> cannot be later than <b>To Time</b> for {0}').format(record.day_of_week)
frappe.throw(_(err_msg))
def duration_is_divisible(self, from_time, to_time):
timedelta = to_time - from_time
if timedelta.total_seconds() % (self.appointment_duration * 60):
frappe.throw(
_('The difference between from time and To Time must be a multiple of Appointment'))
def duration_is_divisible(self, from_time, to_time):
timedelta = to_time - from_time
if timedelta.total_seconds() % (self.appointment_duration * 60):
frappe.throw(
_('The difference between from time and To Time must be a multiple of Appointment'))

View File

@ -5,158 +5,158 @@ import pytz
WEEKDAYS = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
"Thursday", "Friday", "Saturday", "Sunday"]
no_cache = 1
def get_context(context):
is_enabled = frappe.db.get_single_value(
'Appointment Booking Settings', 'enable_scheduling')
if is_enabled:
return context
else:
raise frappe.DoesNotExistError
is_enabled = frappe.db.get_single_value(
'Appointment Booking Settings', 'enable_scheduling')
if is_enabled:
return context
else:
raise frappe.DoesNotExistError
@frappe.whitelist(allow_guest=True)
def get_appointment_settings():
settings = frappe.get_doc('Appointment Booking Settings')
settings.holiday_list = frappe.get_doc('Holiday List', settings.holiday_list)
return settings
settings = frappe.get_doc('Appointment Booking Settings')
settings.holiday_list = frappe.get_doc('Holiday List', settings.holiday_list)
return settings
@frappe.whitelist(allow_guest=True)
def get_timezones():
return pytz.all_timezones
return pytz.all_timezones
@frappe.whitelist(allow_guest=True)
def get_appointment_slots(date, timezone):
import pytz
# Convert query to local timezones
format_string = '%Y-%m-%d %H:%M:%S'
query_start_time = datetime.datetime.strptime(
date + ' 00:00:00', format_string)
query_end_time = datetime.datetime.strptime(
date + ' 23:59:59', format_string)
query_start_time = convert_to_system_timezone(timezone,query_start_time)
query_end_time = convert_to_system_timezone(timezone,query_end_time)
now = convert_to_guest_timezone(timezone,datetime.datetime.now())
import pytz
# Convert query to local timezones
format_string = '%Y-%m-%d %H:%M:%S'
query_start_time = datetime.datetime.strptime(
date + ' 00:00:00', format_string)
query_end_time = datetime.datetime.strptime(
date + ' 23:59:59', format_string)
query_start_time = convert_to_system_timezone(timezone,query_start_time)
query_end_time = convert_to_system_timezone(timezone,query_end_time)
now = convert_to_guest_timezone(timezone,datetime.datetime.now())
# Database queries
settings = frappe.get_doc('Appointment Booking Settings')
holiday_list = frappe.get_doc('Holiday List', settings.holiday_list)
timeslots = get_available_slots_between(
query_start_time, query_end_time, settings)
# Database queries
settings = frappe.get_doc('Appointment Booking Settings')
holiday_list = frappe.get_doc('Holiday List', settings.holiday_list)
timeslots = get_available_slots_between(
query_start_time, query_end_time, settings)
# Filter and convert timeslots
converted_timeslots = []
for timeslot in timeslots:
converted_timeslot = convert_to_guest_timezone(timezone,timeslot)
# Check if holiday
if _is_holiday(converted_timeslot.date(), holiday_list):
converted_timeslots.append(
dict(time=converted_timeslot, availability=False))
continue
# Check availability
if check_availabilty(timeslot, settings) and converted_timeslot >= now:
converted_timeslots.append(
dict(time=converted_timeslot, availability=True))
else:
converted_timeslots.append(
dict(time=converted_timeslot, availability=False))
date_required = datetime.datetime.strptime(
date + ' 00:00:00', format_string).date()
converted_timeslots = filter_timeslots(date_required, converted_timeslots)
return converted_timeslots
# Filter and convert timeslots
converted_timeslots = []
for timeslot in timeslots:
converted_timeslot = convert_to_guest_timezone(timezone,timeslot)
# Check if holiday
if _is_holiday(converted_timeslot.date(), holiday_list):
converted_timeslots.append(
dict(time=converted_timeslot, availability=False))
continue
# Check availability
if check_availabilty(timeslot, settings) and converted_timeslot >= now:
converted_timeslots.append(
dict(time=converted_timeslot, availability=True))
else:
converted_timeslots.append(
dict(time=converted_timeslot, availability=False))
date_required = datetime.datetime.strptime(
date + ' 00:00:00', format_string).date()
converted_timeslots = filter_timeslots(date_required, converted_timeslots)
return converted_timeslots
def get_available_slots_between(query_start_time, query_end_time, settings):
records = _get_records(query_start_time, query_end_time, settings)
timeslots = []
appointment_duration = datetime.timedelta(
minutes=settings.appointment_duration)
for record in records:
if record.day_of_week == WEEKDAYS[query_start_time.weekday()]:
current_time = _deltatime_to_datetime(
query_start_time, record.from_time)
end_time = _deltatime_to_datetime(
query_start_time, record.to_time)
else:
current_time = _deltatime_to_datetime(
query_end_time, record.from_time)
end_time = _deltatime_to_datetime(
query_end_time, record.to_time)
while current_time + appointment_duration <= end_time:
timeslots.append(current_time)
current_time += appointment_duration
return timeslots
records = _get_records(query_start_time, query_end_time, settings)
timeslots = []
appointment_duration = datetime.timedelta(
minutes=settings.appointment_duration)
for record in records:
if record.day_of_week == WEEKDAYS[query_start_time.weekday()]:
current_time = _deltatime_to_datetime(
query_start_time, record.from_time)
end_time = _deltatime_to_datetime(
query_start_time, record.to_time)
else:
current_time = _deltatime_to_datetime(
query_end_time, record.from_time)
end_time = _deltatime_to_datetime(
query_end_time, record.to_time)
while current_time + appointment_duration <= end_time:
timeslots.append(current_time)
current_time += appointment_duration
return timeslots
@frappe.whitelist(allow_guest=True)
def create_appointment(date, time, tz, contact):
import pytz
appointment = frappe.new_doc('Appointment')
format_string = '%Y-%m-%d %H:%M:%S%z'
scheduled_time = datetime.datetime.strptime(
date+" "+time, format_string)
scheduled_time = scheduled_time.replace(tzinfo=None)
scheduled_time = convert_to_system_timezone(tz,scheduled_time)
scheduled_time= scheduled_time.replace(tzinfo=None)
appointment.scheduled_time = scheduled_time
contact = json.loads(contact)
appointment.customer_name = contact['name']
appointment.customer_phone_number = contact['number']
appointment.customer_skype = contact['skype']
appointment.customer_details = contact['notes']
appointment.customer_email = contact['email']
appointment.status = 'Open'
appointment.insert()
import pytz
appointment = frappe.new_doc('Appointment')
format_string = '%Y-%m-%d %H:%M:%S%z'
scheduled_time = datetime.datetime.strptime(
date+" "+time, format_string)
scheduled_time = scheduled_time.replace(tzinfo=None)
scheduled_time = convert_to_system_timezone(tz,scheduled_time)
scheduled_time= scheduled_time.replace(tzinfo=None)
appointment.scheduled_time = scheduled_time
contact = json.loads(contact)
appointment.customer_name = contact['name']
appointment.customer_phone_number = contact['number']
appointment.customer_skype = contact['skype']
appointment.customer_details = contact['notes']
appointment.customer_email = contact['email']
appointment.status = 'Open'
appointment.insert()
# Helper Functions
def filter_timeslots(date, timeslots):
filtered_timeslots = []
for timeslot in timeslots:
if(timeslot['time'].date() == date):
filtered_timeslots.append(timeslot)
return filtered_timeslots
filtered_timeslots = []
for timeslot in timeslots:
if(timeslot['time'].date() == date):
filtered_timeslots.append(timeslot)
return filtered_timeslots
def convert_to_guest_timezone(guest_tz,datetimeobject):
import pytz
guest_tz = pytz.timezone(guest_tz)
local_timezone = pytz.timezone(frappe.utils.get_time_zone())
datetimeobject = local_timezone.localize(datetimeobject)
datetimeobject = datetimeobject.astimezone(guest_tz)
return datetimeobject
import pytz
guest_tz = pytz.timezone(guest_tz)
local_timezone = pytz.timezone(frappe.utils.get_time_zone())
datetimeobject = local_timezone.localize(datetimeobject)
datetimeobject = datetimeobject.astimezone(guest_tz)
return datetimeobject
def convert_to_system_timezone(guest_tz,datetimeobject):
import pytz
guest_tz = pytz.timezone(guest_tz)
datetimeobject = guest_tz.localize(datetimeobject)
system_tz = pytz.timezone(frappe.utils.get_time_zone())
datetimeobject = datetimeobject.astimezone(system_tz)
return datetimeobject
import pytz
guest_tz = pytz.timezone(guest_tz)
datetimeobject = guest_tz.localize(datetimeobject)
system_tz = pytz.timezone(frappe.utils.get_time_zone())
datetimeobject = datetimeobject.astimezone(system_tz)
return datetimeobject
def check_availabilty(timeslot, settings):
return frappe.db.count('Appointment', {'scheduled_time': timeslot}) < settings.number_of_agents
return frappe.db.count('Appointment', {'scheduled_time': timeslot}) < settings.number_of_agents
def _is_holiday(date, holiday_list):
for holiday in holiday_list.holidays:
if holiday.holiday_date == date:
return True
return False
for holiday in holiday_list.holidays:
if holiday.holiday_date == date:
return True
return False
def _get_records(start_time, end_time, settings):
records = []
for record in settings.availability_of_slots:
if record.day_of_week == WEEKDAYS[start_time.weekday()] or record.day_of_week == WEEKDAYS[end_time.weekday()]:
records.append(record)
return records
records = []
for record in settings.availability_of_slots:
if record.day_of_week == WEEKDAYS[start_time.weekday()] or record.day_of_week == WEEKDAYS[end_time.weekday()]:
records.append(record)
return records
def _deltatime_to_datetime(date, deltatime):
time = (datetime.datetime.min + deltatime).time()
return datetime.datetime.combine(date.date(), time)
time = (datetime.datetime.min + deltatime).time()
return datetime.datetime.combine(date.date(), time)
def _datetime_to_deltatime(date_time):
midnight = datetime.datetime.combine(date_time.date(), datetime.time.min)
return (date_time-midnight)
midnight = datetime.datetime.combine(date_time.date(), datetime.time.min)
return (date_time-midnight)

View File

@ -3,18 +3,18 @@ import frappe
from frappe.utils.verified_command import verify_request
@frappe.whitelist(allow_guest=True)
def get_context(context):
if not verify_request():
context.success = False
return context
if not verify_request():
context.success = False
return context
email = frappe.form_dict['email']
appointment_name = frappe.form_dict['appointment']
email = frappe.form_dict['email']
appointment_name = frappe.form_dict['appointment']
if email and appointment_name:
appointment = frappe.get_doc('Appointment',appointment_name)
appointment.set_verified(email)
context.success = True
return context
else:
context.success = False
return context
if email and appointment_name:
appointment = frappe.get_doc('Appointment',appointment_name)
appointment.set_verified(email)
context.success = True
return context
else:
context.success = False
return context