blob: a0367608d2690442d62612264e4f37722f2ad8a4 [file] [log] [blame]
ankitjavalkarworke8331d42014-08-25 18:00:12 +05301from __future__ import unicode_literals
2import frappe
Rushabh Mehtaacf28af2016-03-31 15:02:11 +05303import calendar
ankitjavalkarworke8331d42014-08-25 18:00:12 +05304import frappe.utils
5import frappe.defaults
Sambhaji Kolateb14401c2014-09-11 16:09:05 +05306
Rushabh Mehta571a9d02016-03-03 15:03:23 +05307from frappe.utils import cint, cstr, getdate, nowdate, \
8 get_first_day, get_last_day, split_emails
Sambhaji Kolateb14401c2014-09-11 16:09:05 +05309
ankitjavalkarworke8331d42014-08-25 18:00:12 +053010from frappe import _, msgprint, throw
ankitjavalkarworke8331d42014-08-25 18:00:12 +053011
ankitjavalkarworke60822b2014-08-26 14:29:06 +053012month_map = {'Monthly': 1, 'Quarterly': 3, 'Half-yearly': 6, 'Yearly': 12}
Anand Doshi13945092014-09-21 19:45:49 +053013date_field_map = {
14 "Sales Order": "transaction_date",
15 "Sales Invoice": "posting_date",
16 "Purchase Order": "transaction_date",
17 "Purchase Invoice": "posting_date"
18}
ankitjavalkarworke60822b2014-08-26 14:29:06 +053019
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +053020def create_recurring_documents():
21 manage_recurring_documents("Sales Order")
22 manage_recurring_documents("Sales Invoice")
Sambhaji Kolatef37d4332014-09-15 13:37:46 +053023 manage_recurring_documents("Purchase Order")
24 manage_recurring_documents("Purchase Invoice")
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +053025
ankitjavalkarworke8331d42014-08-25 18:00:12 +053026def manage_recurring_documents(doctype, next_date=None, commit=True):
27 """
28 Create recurring documents on specific date by copying the original one
29 and notify the concerned people
30 """
31 next_date = next_date or nowdate()
ankitjavalkarworke60822b2014-08-26 14:29:06 +053032
Anand Doshi13945092014-09-21 19:45:49 +053033 date_field = date_field_map[doctype]
Anand Doshic5f919e2015-09-16 19:20:55 +053034
patilsangrambf2b5112016-02-22 16:24:23 +053035 condition = " and ifnull(status, '') != 'Closed'" if doctype in ("Sales Order", "Purchase Order") else ""
ankitjavalkarworke60822b2014-08-26 14:29:06 +053036
ankitjavalkarworke8331d42014-08-25 18:00:12 +053037 recurring_documents = frappe.db.sql("""select name, recurring_id
Anand Doshi602e8252015-11-16 19:05:46 +053038 from `tab{0}` where is_recurring=1
ShashaQin8d1dea62016-02-27 14:00:58 +080039 and (docstatus=1 or docstatus=0) and next_date=%s
Nabin Hait75807232015-07-02 14:41:27 +053040 and next_date <= ifnull(end_date, '2199-12-31') {1}""".format(doctype, condition), next_date)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053041
42 exception_list = []
43 for ref_document, recurring_id in recurring_documents:
44 if not frappe.db.sql("""select name from `tab%s`
ShashaQin6071ddc2016-02-25 11:25:24 +080045 where %s=%s and recurring_id=%s and (docstatus=1 or docstatus=0)"""
ankitjavalkarworke60822b2014-08-26 14:29:06 +053046 % (doctype, date_field, '%s', '%s'), (next_date, recurring_id)):
ankitjavalkarworke8331d42014-08-25 18:00:12 +053047 try:
Anand Doshi39e2c2b2016-01-25 17:03:50 +053048 reference_doc = frappe.get_doc(doctype, ref_document)
49 new_doc = make_new_document(reference_doc, date_field, next_date)
ShashaQin6071ddc2016-02-25 11:25:24 +080050 if reference_doc.notify_by_email:
51 send_notification(new_doc)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053052 if commit:
53 frappe.db.commit()
54 except:
55 if commit:
56 frappe.db.rollback()
57
58 frappe.db.begin()
59 frappe.db.sql("update `tab%s` \
Nabin Hait91fb6612014-09-05 14:56:05 +053060 set is_recurring = 0 where name = %s" % (doctype, '%s'),
ankitjavalkarworke8331d42014-08-25 18:00:12 +053061 (ref_document))
Anand Doshi39e2c2b2016-01-25 17:03:50 +053062 notify_errors(ref_document, doctype, reference_doc.get("customer") or reference_doc.get("supplier"),
63 reference_doc.owner)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053064 frappe.db.commit()
65
66 exception_list.append(frappe.get_traceback())
67 finally:
68 if commit:
69 frappe.db.begin()
70
71 if exception_list:
72 exception_message = "\n\n".join([cstr(d) for d in exception_list])
73 frappe.throw(exception_message)
74
Anand Doshi39e2c2b2016-01-25 17:03:50 +053075def make_new_document(reference_doc, date_field, posting_date):
rohitwaghchaure90ff5092016-03-17 17:30:53 +053076 new_document = frappe.copy_doc(reference_doc, ignore_no_copy=False)
Anand Doshi39e2c2b2016-01-25 17:03:50 +053077 mcount = month_map[reference_doc.recurring_type]
ankitjavalkarworke8331d42014-08-25 18:00:12 +053078
Anand Doshi39e2c2b2016-01-25 17:03:50 +053079 from_date = get_next_date(reference_doc.from_date, mcount)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053080
81 # get last day of the month to maintain period if the from date is first day of its own month
82 # and to date is the last day of its own month
Anand Doshi39e2c2b2016-01-25 17:03:50 +053083 if (cstr(get_first_day(reference_doc.from_date)) == cstr(reference_doc.from_date)) and \
84 (cstr(get_last_day(reference_doc.to_date)) == cstr(reference_doc.to_date)):
85 to_date = get_last_day(get_next_date(reference_doc.to_date, mcount))
ankitjavalkarworke8331d42014-08-25 18:00:12 +053086 else:
Anand Doshi39e2c2b2016-01-25 17:03:50 +053087 to_date = get_next_date(reference_doc.to_date, mcount)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053088
89 new_document.update({
ankitjavalkarworke60822b2014-08-26 14:29:06 +053090 date_field: posting_date,
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +053091 "from_date": from_date,
92 "to_date": to_date,
rohitwaghchaure90ff5092016-03-17 17:30:53 +053093 "next_date": get_next_date(reference_doc.next_date, mcount,cint(reference_doc.repeat_on_day_of_month))
ankitjavalkarworke8331d42014-08-25 18:00:12 +053094 })
95
Anand Doshi39e2c2b2016-01-25 17:03:50 +053096 # copy document fields
97 for fieldname in ("owner", "recurring_type", "repeat_on_day_of_month",
98 "recurring_id", "notification_email_address", "is_recurring", "end_date",
99 "title", "naming_series", "select_print_heading", "ignore_pricing_rule",
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530100 "posting_time", "remarks", 'submit_on_creation'):
Anand Doshi39e2c2b2016-01-25 17:03:50 +0530101 if new_document.meta.get_field(fieldname):
102 new_document.set(fieldname, reference_doc.get(fieldname))
103
104 # copy item fields
105 for i, item in enumerate(new_document.items):
106 for fieldname in ("page_break",):
107 item.set(fieldname, reference_doc.items[i].get(fieldname))
108
109 new_document.run_method("on_recurring", reference_doc=reference_doc)
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530110
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530111 if reference_doc.submit_on_creation:
Nabin Hait5996b2f2016-03-18 15:19:54 +0530112 new_document.insert()
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530113 new_document.submit()
114 else:
ShashaQin6071ddc2016-02-25 11:25:24 +0800115 new_document.docstatus=0
116 new_document.insert()
Nabin Hait91fb6612014-09-05 14:56:05 +0530117
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530118 return new_document
119
120def get_next_date(dt, mcount, day=None):
121 dt = getdate(dt)
122
123 from dateutil.relativedelta import relativedelta
124 dt += relativedelta(months=mcount, day=day)
125
126 return dt
127
128def send_notification(new_rv):
129 """Notify concerned persons about recurring document generation"""
ankitjavalkarwork737d8e42014-09-01 16:18:44 +0530130
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530131 frappe.sendmail(new_rv.notification_email_address,
132 subject= _("New {0}: #{1}").format(new_rv.doctype, new_rv.name),
133 message = _("Please find attached {0} #{1}").format(new_rv.doctype, new_rv.name),
Neil Trini Lasradoe2d8dd02015-06-22 19:06:15 +0530134 attachments = [frappe.attach_print(new_rv.doctype, new_rv.name, file_name=new_rv.name, print_format=new_rv.recurring_print_format)])
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530135
Anand Doshi13945092014-09-21 19:45:49 +0530136def notify_errors(doc, doctype, party, owner):
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530137 from frappe.utils.user import get_system_managers
138 recipients = get_system_managers(only_name=True)
139
140 frappe.sendmail(recipients + [frappe.db.get_value("User", owner, "email")],
141 subject="[Urgent] Error while creating recurring %s for %s" % (doctype, doc),
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530142 message = frappe.get_template("templates/emails/recurring_document_failed.html").render({
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530143 "type": doctype,
144 "name": doc,
Anand Doshi13945092014-09-21 19:45:49 +0530145 "party": party
ankitjavalkarworkac085e02014-08-26 10:40:23 +0530146 }))
147
148 assign_task_to_owner(doc, doctype, "Recurring Invoice Failed", recipients)
149
150def assign_task_to_owner(doc, doctype, msg, users):
151 for d in users:
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530152 from frappe.desk.form import assign_to
ankitjavalkarworkac085e02014-08-26 10:40:23 +0530153 args = {
154 'assign_to' : d,
155 'doctype' : doctype,
156 'name' : doc,
157 'description' : msg,
158 'priority' : 'High'
159 }
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530160 assign_to.add(args)
161
162def validate_recurring_document(doc):
163 if doc.is_recurring:
164 validate_notification_email_id(doc)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530165 if not doc.recurring_type:
Nabin Hait5996b2f2016-03-18 15:19:54 +0530166 frappe.throw(_("Please select {0}").format(doc.meta.get_label("recurring_type")))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530167
168 elif not (doc.from_date and doc.to_date):
Nabin Hait5996b2f2016-03-18 15:19:54 +0530169 frappe.throw(_("Period From and Period To dates mandatory for recurring {0}").format(doc.doctype))
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530170
Nabin Hait5996b2f2016-03-18 15:19:54 +0530171def validate_recurring_next_date(doc):
172 posting_date = doc.get("posting_date") or doc.get("transaction_date")
173 if getdate(posting_date) > getdate(doc.next_date):
174 frappe.throw(_("Next Date must be greater than Posting Date"))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530175
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530176 next_date = getdate(doc.next_date)
177 if next_date.day != doc.repeat_on_day_of_month:
178
179 # if the repeat day is the last day of the month (31)
180 # and the current month does not have as many days,
181 # then the last day of the current month is a valid date
182 lastday = calendar.monthrange(next_date.year, next_date.month)[1]
183 if doc.repeat_on_day_of_month < lastday:
184
185 # the specified day of the month is not same as the day specified
186 # or the last day of the month
187 frappe.throw(_("Next Date's day and Repeat on Day of Month must be equal"))
Nabin Hait5996b2f2016-03-18 15:19:54 +0530188
Sambhaji Kolateb14401c2014-09-11 16:09:05 +0530189def convert_to_recurring(doc, posting_date):
Nabin Hait5996b2f2016-03-18 15:19:54 +0530190 if doc.is_recurring:
191 if not doc.recurring_id:
192 doc.db_set("recurring_id", doc.name)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530193
Nabin Hait5996b2f2016-03-18 15:19:54 +0530194 set_next_date(doc, posting_date)
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530195
Nabin Hait7504ea72016-03-23 11:16:51 +0530196 if doc.next_date:
197 validate_recurring_next_date(doc)
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530198
Nabin Hait5996b2f2016-03-18 15:19:54 +0530199 elif doc.recurring_id:
Nabin Hait7504ea72016-03-23 11:16:51 +0530200 doc.db_set("recurring_id", None)
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530201
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530202def validate_notification_email_id(doc):
ShashaQin6071ddc2016-02-25 11:25:24 +0800203 if doc.notify_by_email:
204 if doc.notification_email_address:
205 email_list = split_emails(doc.notification_email_address.replace("\n", ""))
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530206
ShashaQin6071ddc2016-02-25 11:25:24 +0800207 from frappe.utils import validate_email_add
208 for email in email_list:
209 if not validate_email_add(email):
210 throw(_("{0} is an invalid email address in 'Notification \
211 Email Address'").format(email))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530212
ShashaQin6071ddc2016-02-25 11:25:24 +0800213 else:
214 frappe.throw(_("'Notification Email Addresses' not specified for recurring %s") \
215 % doc.doctype)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530216
217def set_next_date(doc, posting_date):
218 """ Set next date on which recurring document will be created"""
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530219 if not doc.repeat_on_day_of_month:
220 msgprint(_("Please enter 'Repeat on Day of Month' field value"), raise_exception=1)
221
rohitwaghchaure90ff5092016-03-17 17:30:53 +0530222 next_date = get_next_date(posting_date, month_map[doc.recurring_type],
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530223 cint(doc.repeat_on_day_of_month))
224
Nabin Hait5996b2f2016-03-18 15:19:54 +0530225 doc.db_set('next_date', next_date)
ankitjavalkarwork737d8e42014-09-01 16:18:44 +0530226
227 msgprint(_("Next Recurring {0} will be created on {1}").format(doc.doctype, next_date))