blob: 2df73523485d93655987425d34307ca086988e2c [file] [log] [blame]
ankitjavalkarworke8331d42014-08-25 18:00:12 +05301from __future__ import unicode_literals
2import frappe
3import frappe.utils
4import frappe.defaults
Sambhaji Kolateb14401c2014-09-11 16:09:05 +05305
Rushabh Mehta571a9d02016-03-03 15:03:23 +05306from frappe.utils import cint, cstr, getdate, nowdate, \
7 get_first_day, get_last_day, split_emails
Sambhaji Kolateb14401c2014-09-11 16:09:05 +05308
ankitjavalkarworke8331d42014-08-25 18:00:12 +05309from frappe import _, msgprint, throw
ankitjavalkarworke8331d42014-08-25 18:00:12 +053010
ankitjavalkarworke60822b2014-08-26 14:29:06 +053011month_map = {'Monthly': 1, 'Quarterly': 3, 'Half-yearly': 6, 'Yearly': 12}
Anand Doshi13945092014-09-21 19:45:49 +053012date_field_map = {
13 "Sales Order": "transaction_date",
14 "Sales Invoice": "posting_date",
15 "Purchase Order": "transaction_date",
16 "Purchase Invoice": "posting_date"
17}
ankitjavalkarworke60822b2014-08-26 14:29:06 +053018
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +053019def create_recurring_documents():
20 manage_recurring_documents("Sales Order")
21 manage_recurring_documents("Sales Invoice")
Sambhaji Kolatef37d4332014-09-15 13:37:46 +053022 manage_recurring_documents("Purchase Order")
23 manage_recurring_documents("Purchase Invoice")
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +053024
ankitjavalkarworke8331d42014-08-25 18:00:12 +053025def manage_recurring_documents(doctype, next_date=None, commit=True):
26 """
27 Create recurring documents on specific date by copying the original one
28 and notify the concerned people
29 """
30 next_date = next_date or nowdate()
ankitjavalkarworke60822b2014-08-26 14:29:06 +053031
Anand Doshi13945092014-09-21 19:45:49 +053032 date_field = date_field_map[doctype]
Anand Doshic5f919e2015-09-16 19:20:55 +053033
patilsangrambf2b5112016-02-22 16:24:23 +053034 condition = " and ifnull(status, '') != 'Closed'" if doctype in ("Sales Order", "Purchase Order") else ""
ankitjavalkarworke60822b2014-08-26 14:29:06 +053035
ankitjavalkarworke8331d42014-08-25 18:00:12 +053036 recurring_documents = frappe.db.sql("""select name, recurring_id
Anand Doshi602e8252015-11-16 19:05:46 +053037 from `tab{0}` where is_recurring=1
ShashaQin8d1dea62016-02-27 14:00:58 +080038 and (docstatus=1 or docstatus=0) and next_date=%s
Nabin Hait75807232015-07-02 14:41:27 +053039 and next_date <= ifnull(end_date, '2199-12-31') {1}""".format(doctype, condition), next_date)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053040
41 exception_list = []
42 for ref_document, recurring_id in recurring_documents:
43 if not frappe.db.sql("""select name from `tab%s`
ShashaQin6071ddc2016-02-25 11:25:24 +080044 where %s=%s and recurring_id=%s and (docstatus=1 or docstatus=0)"""
ankitjavalkarworke60822b2014-08-26 14:29:06 +053045 % (doctype, date_field, '%s', '%s'), (next_date, recurring_id)):
ankitjavalkarworke8331d42014-08-25 18:00:12 +053046 try:
Anand Doshi39e2c2b2016-01-25 17:03:50 +053047 reference_doc = frappe.get_doc(doctype, ref_document)
48 new_doc = make_new_document(reference_doc, date_field, next_date)
ShashaQin6071ddc2016-02-25 11:25:24 +080049 if reference_doc.notify_by_email:
50 send_notification(new_doc)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053051 if commit:
52 frappe.db.commit()
53 except:
54 if commit:
55 frappe.db.rollback()
56
57 frappe.db.begin()
58 frappe.db.sql("update `tab%s` \
Nabin Hait91fb6612014-09-05 14:56:05 +053059 set is_recurring = 0 where name = %s" % (doctype, '%s'),
ankitjavalkarworke8331d42014-08-25 18:00:12 +053060 (ref_document))
Anand Doshi39e2c2b2016-01-25 17:03:50 +053061 notify_errors(ref_document, doctype, reference_doc.get("customer") or reference_doc.get("supplier"),
62 reference_doc.owner)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053063 frappe.db.commit()
64
65 exception_list.append(frappe.get_traceback())
66 finally:
67 if commit:
68 frappe.db.begin()
69
70 if exception_list:
71 exception_message = "\n\n".join([cstr(d) for d in exception_list])
72 frappe.throw(exception_message)
73
Anand Doshi39e2c2b2016-01-25 17:03:50 +053074def make_new_document(reference_doc, date_field, posting_date):
rohitwaghchaure90ff5092016-03-17 17:30:53 +053075 new_document = frappe.copy_doc(reference_doc, ignore_no_copy=False)
Anand Doshi39e2c2b2016-01-25 17:03:50 +053076 mcount = month_map[reference_doc.recurring_type]
ankitjavalkarworke8331d42014-08-25 18:00:12 +053077
Anand Doshi39e2c2b2016-01-25 17:03:50 +053078 from_date = get_next_date(reference_doc.from_date, mcount)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053079
80 # get last day of the month to maintain period if the from date is first day of its own month
81 # and to date is the last day of its own month
Anand Doshi39e2c2b2016-01-25 17:03:50 +053082 if (cstr(get_first_day(reference_doc.from_date)) == cstr(reference_doc.from_date)) and \
83 (cstr(get_last_day(reference_doc.to_date)) == cstr(reference_doc.to_date)):
84 to_date = get_last_day(get_next_date(reference_doc.to_date, mcount))
ankitjavalkarworke8331d42014-08-25 18:00:12 +053085 else:
Anand Doshi39e2c2b2016-01-25 17:03:50 +053086 to_date = get_next_date(reference_doc.to_date, mcount)
ankitjavalkarworke8331d42014-08-25 18:00:12 +053087
88 new_document.update({
ankitjavalkarworke60822b2014-08-26 14:29:06 +053089 date_field: posting_date,
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +053090 "from_date": from_date,
91 "to_date": to_date,
rohitwaghchaure90ff5092016-03-17 17:30:53 +053092 "next_date": get_next_date(reference_doc.next_date, mcount,cint(reference_doc.repeat_on_day_of_month))
ankitjavalkarworke8331d42014-08-25 18:00:12 +053093 })
94
Anand Doshi39e2c2b2016-01-25 17:03:50 +053095 # copy document fields
96 for fieldname in ("owner", "recurring_type", "repeat_on_day_of_month",
97 "recurring_id", "notification_email_address", "is_recurring", "end_date",
98 "title", "naming_series", "select_print_heading", "ignore_pricing_rule",
Rushabh Mehta5839a8d2016-03-02 17:51:24 +053099 "posting_time", "remarks", 'submit_on_creation'):
Anand Doshi39e2c2b2016-01-25 17:03:50 +0530100 if new_document.meta.get_field(fieldname):
101 new_document.set(fieldname, reference_doc.get(fieldname))
102
103 # copy item fields
104 for i, item in enumerate(new_document.items):
105 for fieldname in ("page_break",):
106 item.set(fieldname, reference_doc.items[i].get(fieldname))
107
108 new_document.run_method("on_recurring", reference_doc=reference_doc)
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530109
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530110 if reference_doc.submit_on_creation:
Nabin Hait5996b2f2016-03-18 15:19:54 +0530111 new_document.insert()
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530112 new_document.submit()
113 else:
ShashaQin6071ddc2016-02-25 11:25:24 +0800114 new_document.docstatus=0
115 new_document.insert()
Nabin Hait91fb6612014-09-05 14:56:05 +0530116
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530117 return new_document
118
119def get_next_date(dt, mcount, day=None):
120 dt = getdate(dt)
121
122 from dateutil.relativedelta import relativedelta
123 dt += relativedelta(months=mcount, day=day)
124
125 return dt
126
127def send_notification(new_rv):
128 """Notify concerned persons about recurring document generation"""
ankitjavalkarwork737d8e42014-09-01 16:18:44 +0530129
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530130 frappe.sendmail(new_rv.notification_email_address,
131 subject= _("New {0}: #{1}").format(new_rv.doctype, new_rv.name),
132 message = _("Please find attached {0} #{1}").format(new_rv.doctype, new_rv.name),
Neil Trini Lasradoe2d8dd02015-06-22 19:06:15 +0530133 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 +0530134
Anand Doshi13945092014-09-21 19:45:49 +0530135def notify_errors(doc, doctype, party, owner):
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530136 from frappe.utils.user import get_system_managers
137 recipients = get_system_managers(only_name=True)
138
139 frappe.sendmail(recipients + [frappe.db.get_value("User", owner, "email")],
140 subject="[Urgent] Error while creating recurring %s for %s" % (doctype, doc),
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530141 message = frappe.get_template("templates/emails/recurring_document_failed.html").render({
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530142 "type": doctype,
143 "name": doc,
Anand Doshi13945092014-09-21 19:45:49 +0530144 "party": party
ankitjavalkarworkac085e02014-08-26 10:40:23 +0530145 }))
146
147 assign_task_to_owner(doc, doctype, "Recurring Invoice Failed", recipients)
148
149def assign_task_to_owner(doc, doctype, msg, users):
150 for d in users:
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530151 from frappe.desk.form import assign_to
ankitjavalkarworkac085e02014-08-26 10:40:23 +0530152 args = {
153 'assign_to' : d,
154 'doctype' : doctype,
155 'name' : doc,
156 'description' : msg,
157 'priority' : 'High'
158 }
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530159 assign_to.add(args)
160
161def validate_recurring_document(doc):
162 if doc.is_recurring:
163 validate_notification_email_id(doc)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530164 if not doc.recurring_type:
Nabin Hait5996b2f2016-03-18 15:19:54 +0530165 frappe.throw(_("Please select {0}").format(doc.meta.get_label("recurring_type")))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530166
167 elif not (doc.from_date and doc.to_date):
Nabin Hait5996b2f2016-03-18 15:19:54 +0530168 frappe.throw(_("Period From and Period To dates mandatory for recurring {0}").format(doc.doctype))
169
170def validate_recurring_next_date(doc):
171 posting_date = doc.get("posting_date") or doc.get("transaction_date")
172 if getdate(posting_date) > getdate(doc.next_date):
173 frappe.throw(_("Next Date must be greater than Posting Date"))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530174
Nabin Hait5996b2f2016-03-18 15:19:54 +0530175 if getdate(doc.next_date).day != doc.repeat_on_day_of_month:
176 frappe.throw(_("Next Date's day and Repeat on Day of Month must be equal"))
177
Sambhaji Kolateb14401c2014-09-11 16:09:05 +0530178def convert_to_recurring(doc, posting_date):
Nabin Hait5996b2f2016-03-18 15:19:54 +0530179 if doc.is_recurring:
180 if not doc.recurring_id:
181 doc.db_set("recurring_id", doc.name)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530182
Nabin Hait5996b2f2016-03-18 15:19:54 +0530183 set_next_date(doc, posting_date)
184
185 elif doc.recurring_id:
186 frappe.db.sql("""update `tab%s` set is_recurring = 0
187 where recurring_id = %s""" % (doc.doctype, '%s'), (doc.recurring_id))
188
189 if doc.next_date:
190 validate_recurring_next_date(doc)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530191
192def validate_notification_email_id(doc):
ShashaQin6071ddc2016-02-25 11:25:24 +0800193 if doc.notify_by_email:
194 if doc.notification_email_address:
195 email_list = split_emails(doc.notification_email_address.replace("\n", ""))
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530196
ShashaQin6071ddc2016-02-25 11:25:24 +0800197 from frappe.utils import validate_email_add
198 for email in email_list:
199 if not validate_email_add(email):
200 throw(_("{0} is an invalid email address in 'Notification \
201 Email Address'").format(email))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530202
ShashaQin6071ddc2016-02-25 11:25:24 +0800203 else:
204 frappe.throw(_("'Notification Email Addresses' not specified for recurring %s") \
205 % doc.doctype)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530206
207def set_next_date(doc, posting_date):
208 """ Set next date on which recurring document will be created"""
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530209 if not doc.repeat_on_day_of_month:
210 msgprint(_("Please enter 'Repeat on Day of Month' field value"), raise_exception=1)
211
rohitwaghchaure90ff5092016-03-17 17:30:53 +0530212 next_date = get_next_date(posting_date, month_map[doc.recurring_type],
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530213 cint(doc.repeat_on_day_of_month))
214
Nabin Hait5996b2f2016-03-18 15:19:54 +0530215 doc.db_set('next_date', next_date)
ankitjavalkarwork737d8e42014-09-01 16:18:44 +0530216
217 msgprint(_("Next Recurring {0} will be created on {1}").format(doc.doctype, next_date))