blob: 6919434bd0ce6bc08c17cfb97f22fff32facd5c4 [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
tunde32aa7c12017-09-07 06:52:15 +010012
ankitjavalkarworke60822b2014-08-26 14:29:06 +053013month_map = {'Monthly': 1, 'Quarterly': 3, 'Half-yearly': 6, 'Yearly': 12}
Anand Doshi13945092014-09-21 19:45:49 +053014date_field_map = {
15 "Sales Order": "transaction_date",
16 "Sales Invoice": "posting_date",
17 "Purchase Order": "transaction_date",
18 "Purchase Invoice": "posting_date"
19}
ankitjavalkarworke60822b2014-08-26 14:29:06 +053020
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +053021def create_recurring_documents():
22 manage_recurring_documents("Sales Order")
23 manage_recurring_documents("Sales Invoice")
Sambhaji Kolatef37d4332014-09-15 13:37:46 +053024 manage_recurring_documents("Purchase Order")
25 manage_recurring_documents("Purchase Invoice")
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +053026
ankitjavalkarworke8331d42014-08-25 18:00:12 +053027def manage_recurring_documents(doctype, next_date=None, commit=True):
28 """
29 Create recurring documents on specific date by copying the original one
30 and notify the concerned people
31 """
32 next_date = next_date or nowdate()
ankitjavalkarworke60822b2014-08-26 14:29:06 +053033
Anand Doshi13945092014-09-21 19:45:49 +053034 date_field = date_field_map[doctype]
Anand Doshic5f919e2015-09-16 19:20:55 +053035
patilsangrambf2b5112016-02-22 16:24:23 +053036 condition = " and ifnull(status, '') != 'Closed'" if doctype in ("Sales Order", "Purchase Order") else ""
ankitjavalkarworke60822b2014-08-26 14:29:06 +053037
ankitjavalkarworke8331d42014-08-25 18:00:12 +053038 recurring_documents = frappe.db.sql("""select name, recurring_id
Anand Doshi602e8252015-11-16 19:05:46 +053039 from `tab{0}` where is_recurring=1
ShashaQin8d1dea62016-02-27 14:00:58 +080040 and (docstatus=1 or docstatus=0) and next_date=%s
Nabin Hait75807232015-07-02 14:41:27 +053041 and next_date <= ifnull(end_date, '2199-12-31') {1}""".format(doctype, condition), next_date)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053042
43 exception_list = []
44 for ref_document, recurring_id in recurring_documents:
45 if not frappe.db.sql("""select name from `tab%s`
ShashaQin6071ddc2016-02-25 11:25:24 +080046 where %s=%s and recurring_id=%s and (docstatus=1 or docstatus=0)"""
ankitjavalkarworke60822b2014-08-26 14:29:06 +053047 % (doctype, date_field, '%s', '%s'), (next_date, recurring_id)):
ankitjavalkarworke8331d42014-08-25 18:00:12 +053048 try:
Anand Doshi39e2c2b2016-01-25 17:03:50 +053049 reference_doc = frappe.get_doc(doctype, ref_document)
50 new_doc = make_new_document(reference_doc, date_field, next_date)
ShashaQin6071ddc2016-02-25 11:25:24 +080051 if reference_doc.notify_by_email:
52 send_notification(new_doc)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053053 if commit:
54 frappe.db.commit()
55 except:
56 if commit:
57 frappe.db.rollback()
58
59 frappe.db.begin()
60 frappe.db.sql("update `tab%s` \
Nabin Hait91fb6612014-09-05 14:56:05 +053061 set is_recurring = 0 where name = %s" % (doctype, '%s'),
ankitjavalkarworke8331d42014-08-25 18:00:12 +053062 (ref_document))
Anand Doshi39e2c2b2016-01-25 17:03:50 +053063 notify_errors(ref_document, doctype, reference_doc.get("customer") or reference_doc.get("supplier"),
64 reference_doc.owner)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053065 frappe.db.commit()
66
67 exception_list.append(frappe.get_traceback())
68 finally:
69 if commit:
70 frappe.db.begin()
71
72 if exception_list:
73 exception_message = "\n\n".join([cstr(d) for d in exception_list])
74 frappe.throw(exception_message)
75
Anand Doshi39e2c2b2016-01-25 17:03:50 +053076def make_new_document(reference_doc, date_field, posting_date):
tunde32aa7c12017-09-07 06:52:15 +010077 from erpnext.controllers.accounts_controller import get_payment_terms
rohitwaghchaure90ff5092016-03-17 17:30:53 +053078 new_document = frappe.copy_doc(reference_doc, ignore_no_copy=False)
Anand Doshi39e2c2b2016-01-25 17:03:50 +053079 mcount = month_map[reference_doc.recurring_type]
ankitjavalkarworke8331d42014-08-25 18:00:12 +053080
Anand Doshi39e2c2b2016-01-25 17:03:50 +053081 from_date = get_next_date(reference_doc.from_date, mcount)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053082
83 # get last day of the month to maintain period if the from date is first day of its own month
84 # and to date is the last day of its own month
Anand Doshi39e2c2b2016-01-25 17:03:50 +053085 if (cstr(get_first_day(reference_doc.from_date)) == cstr(reference_doc.from_date)) and \
86 (cstr(get_last_day(reference_doc.to_date)) == cstr(reference_doc.to_date)):
87 to_date = get_last_day(get_next_date(reference_doc.to_date, mcount))
ankitjavalkarworke8331d42014-08-25 18:00:12 +053088 else:
Anand Doshi39e2c2b2016-01-25 17:03:50 +053089 to_date = get_next_date(reference_doc.to_date, mcount)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053090
91 new_document.update({
ankitjavalkarworke60822b2014-08-26 14:29:06 +053092 date_field: posting_date,
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +053093 "from_date": from_date,
94 "to_date": to_date,
tunde32aa7c12017-09-07 06:52:15 +010095 "next_date": get_next_date(reference_doc.next_date, mcount,cint(reference_doc.repeat_on_day_of_month)),
96 "payment_schedule": get_payment_terms("_Test Payment Term Template 3", posting_date, new_document.grand_total)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053097 })
98
Rushabh Mehta82c25892017-03-14 18:52:47 +053099 if new_document.meta.get_field('set_posting_time'):
100 new_document.set('set_posting_time', 1)
101
Anand Doshi39e2c2b2016-01-25 17:03:50 +0530102 # copy document fields
103 for fieldname in ("owner", "recurring_type", "repeat_on_day_of_month",
104 "recurring_id", "notification_email_address", "is_recurring", "end_date",
105 "title", "naming_series", "select_print_heading", "ignore_pricing_rule",
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530106 "posting_time", "remarks", 'submit_on_creation'):
Anand Doshi39e2c2b2016-01-25 17:03:50 +0530107 if new_document.meta.get_field(fieldname):
108 new_document.set(fieldname, reference_doc.get(fieldname))
109
110 # copy item fields
111 for i, item in enumerate(new_document.items):
112 for fieldname in ("page_break",):
113 item.set(fieldname, reference_doc.items[i].get(fieldname))
114
115 new_document.run_method("on_recurring", reference_doc=reference_doc)
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530116
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530117 if reference_doc.submit_on_creation:
Nabin Hait5996b2f2016-03-18 15:19:54 +0530118 new_document.insert()
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530119 new_document.submit()
120 else:
ShashaQin6071ddc2016-02-25 11:25:24 +0800121 new_document.docstatus=0
122 new_document.insert()
Nabin Hait91fb6612014-09-05 14:56:05 +0530123
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530124 return new_document
125
126def get_next_date(dt, mcount, day=None):
127 dt = getdate(dt)
128
129 from dateutil.relativedelta import relativedelta
130 dt += relativedelta(months=mcount, day=day)
131
132 return dt
133
134def send_notification(new_rv):
135 """Notify concerned persons about recurring document generation"""
ankitjavalkarwork737d8e42014-09-01 16:18:44 +0530136
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530137 frappe.sendmail(new_rv.notification_email_address,
138 subject= _("New {0}: #{1}").format(new_rv.doctype, new_rv.name),
139 message = _("Please find attached {0} #{1}").format(new_rv.doctype, new_rv.name),
Neil Trini Lasradoe2d8dd02015-06-22 19:06:15 +0530140 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 +0530141
Anand Doshi13945092014-09-21 19:45:49 +0530142def notify_errors(doc, doctype, party, owner):
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530143 from frappe.utils.user import get_system_managers
144 recipients = get_system_managers(only_name=True)
145
146 frappe.sendmail(recipients + [frappe.db.get_value("User", owner, "email")],
147 subject="[Urgent] Error while creating recurring %s for %s" % (doctype, doc),
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530148 message = frappe.get_template("templates/emails/recurring_document_failed.html").render({
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530149 "type": doctype,
150 "name": doc,
Anand Doshi13945092014-09-21 19:45:49 +0530151 "party": party
ankitjavalkarworkac085e02014-08-26 10:40:23 +0530152 }))
153
154 assign_task_to_owner(doc, doctype, "Recurring Invoice Failed", recipients)
155
156def assign_task_to_owner(doc, doctype, msg, users):
157 for d in users:
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530158 from frappe.desk.form import assign_to
ankitjavalkarworkac085e02014-08-26 10:40:23 +0530159 args = {
160 'assign_to' : d,
161 'doctype' : doctype,
162 'name' : doc,
163 'description' : msg,
164 'priority' : 'High'
165 }
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530166 assign_to.add(args)
167
168def validate_recurring_document(doc):
169 if doc.is_recurring:
170 validate_notification_email_id(doc)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530171 if not doc.recurring_type:
Nabin Hait5996b2f2016-03-18 15:19:54 +0530172 frappe.throw(_("Please select {0}").format(doc.meta.get_label("recurring_type")))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530173
174 elif not (doc.from_date and doc.to_date):
Nabin Hait5996b2f2016-03-18 15:19:54 +0530175 frappe.throw(_("Period From and Period To dates mandatory for recurring {0}").format(doc.doctype))
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530176
Nabin Hait5996b2f2016-03-18 15:19:54 +0530177def validate_recurring_next_date(doc):
178 posting_date = doc.get("posting_date") or doc.get("transaction_date")
179 if getdate(posting_date) > getdate(doc.next_date):
180 frappe.throw(_("Next Date must be greater than Posting Date"))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530181
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530182 next_date = getdate(doc.next_date)
183 if next_date.day != doc.repeat_on_day_of_month:
184
185 # if the repeat day is the last day of the month (31)
186 # and the current month does not have as many days,
187 # then the last day of the current month is a valid date
188 lastday = calendar.monthrange(next_date.year, next_date.month)[1]
189 if doc.repeat_on_day_of_month < lastday:
190
191 # the specified day of the month is not same as the day specified
192 # or the last day of the month
193 frappe.throw(_("Next Date's day and Repeat on Day of Month must be equal"))
Nabin Hait5996b2f2016-03-18 15:19:54 +0530194
Sambhaji Kolateb14401c2014-09-11 16:09:05 +0530195def convert_to_recurring(doc, posting_date):
Nabin Hait5996b2f2016-03-18 15:19:54 +0530196 if doc.is_recurring:
197 if not doc.recurring_id:
198 doc.db_set("recurring_id", doc.name)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530199
Nabin Hait5996b2f2016-03-18 15:19:54 +0530200 set_next_date(doc, posting_date)
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530201
Nabin Hait7504ea72016-03-23 11:16:51 +0530202 if doc.next_date:
203 validate_recurring_next_date(doc)
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530204
Nabin Hait5996b2f2016-03-18 15:19:54 +0530205 elif doc.recurring_id:
Nabin Hait7504ea72016-03-23 11:16:51 +0530206 doc.db_set("recurring_id", None)
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530207
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530208def validate_notification_email_id(doc):
ShashaQin6071ddc2016-02-25 11:25:24 +0800209 if doc.notify_by_email:
210 if doc.notification_email_address:
211 email_list = split_emails(doc.notification_email_address.replace("\n", ""))
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530212
ShashaQin6071ddc2016-02-25 11:25:24 +0800213 from frappe.utils import validate_email_add
214 for email in email_list:
215 if not validate_email_add(email):
216 throw(_("{0} is an invalid email address in 'Notification \
217 Email Address'").format(email))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530218
ShashaQin6071ddc2016-02-25 11:25:24 +0800219 else:
220 frappe.throw(_("'Notification Email Addresses' not specified for recurring %s") \
221 % doc.doctype)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530222
223def set_next_date(doc, posting_date):
224 """ Set next date on which recurring document will be created"""
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530225 if not doc.repeat_on_day_of_month:
226 msgprint(_("Please enter 'Repeat on Day of Month' field value"), raise_exception=1)
227
rohitwaghchaure90ff5092016-03-17 17:30:53 +0530228 next_date = get_next_date(posting_date, month_map[doc.recurring_type],
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530229 cint(doc.repeat_on_day_of_month))
230
Nabin Hait5996b2f2016-03-18 15:19:54 +0530231 doc.db_set('next_date', next_date)
ankitjavalkarwork737d8e42014-09-01 16:18:44 +0530232
233 msgprint(_("Next Recurring {0} will be created on {1}").format(doc.doctype, next_date))