blob: 2f5fccc390f4b7b48822b29798f462d043dfe3ca [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):
ankitjavalkarworke8331d42014-08-25 18:00:12 +053075 from erpnext.accounts.utils import get_fiscal_year
Anand Doshi39e2c2b2016-01-25 17:03:50 +053076 new_document = frappe.copy_doc(reference_doc, ignore_no_copy=True)
77 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,
ShashaQin6071ddc2016-02-25 11:25:24 +080093 "fiscal_year": get_fiscal_year(posting_date)[0],
94 "next_date": get_next_date(from_date, mcount,cint(reference_doc.repeat_on_day_of_month))
ankitjavalkarworke8331d42014-08-25 18:00:12 +053095 })
96
Anand Doshi39e2c2b2016-01-25 17:03:50 +053097 # copy document fields
98 for fieldname in ("owner", "recurring_type", "repeat_on_day_of_month",
99 "recurring_id", "notification_email_address", "is_recurring", "end_date",
100 "title", "naming_series", "select_print_heading", "ignore_pricing_rule",
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530101 "posting_time", "remarks", 'submit_on_creation'):
Anand Doshi39e2c2b2016-01-25 17:03:50 +0530102 if new_document.meta.get_field(fieldname):
103 new_document.set(fieldname, reference_doc.get(fieldname))
104
105 # copy item fields
106 for i, item in enumerate(new_document.items):
107 for fieldname in ("page_break",):
108 item.set(fieldname, reference_doc.items[i].get(fieldname))
109
110 new_document.run_method("on_recurring", reference_doc=reference_doc)
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530111
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530112 if reference_doc.submit_on_creation:
113 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)
165
Rushabh Mehta571a9d02016-03-03 15:03:23 +0530166 if not doc.recurring_id and not doc.is_new():
Rushabh Mehta756e5182016-03-03 13:00:17 +0530167 doc.recurring_id = doc.name
168
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530169 if not doc.recurring_type:
170 msgprint(_("Please select {0}").format(doc.meta.get_label("recurring_type")),
171 raise_exception=1)
172
173 elif not (doc.from_date and doc.to_date):
Anand Doshiaba8fdd2015-10-31 22:49:42 +0530174 throw(_("Period From and Period To dates mandatory for recurring {0}").format(doc.doctype))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530175
Sambhaji Kolateb14401c2014-09-11 16:09:05 +0530176#
177def convert_to_recurring(doc, posting_date):
178 if doc.is_recurring:
Sambhaji Kolateb14401c2014-09-11 16:09:05 +0530179 set_next_date(doc, posting_date)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530180
Sambhaji Kolateb14401c2014-09-11 16:09:05 +0530181 elif doc.recurring_id:
182 frappe.db.sql("""update `tab%s` set is_recurring = 0
183 where recurring_id = %s""" % (doc.doctype, '%s'), (doc.recurring_id))
184#
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530185
186def validate_notification_email_id(doc):
ShashaQin6071ddc2016-02-25 11:25:24 +0800187 if doc.notify_by_email:
188 if doc.notification_email_address:
189 email_list = split_emails(doc.notification_email_address.replace("\n", ""))
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530190
ShashaQin6071ddc2016-02-25 11:25:24 +0800191 from frappe.utils import validate_email_add
192 for email in email_list:
193 if not validate_email_add(email):
194 throw(_("{0} is an invalid email address in 'Notification \
195 Email Address'").format(email))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530196
ShashaQin6071ddc2016-02-25 11:25:24 +0800197 else:
198 frappe.throw(_("'Notification Email Addresses' not specified for recurring %s") \
199 % doc.doctype)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530200
201def set_next_date(doc, posting_date):
202 """ Set next date on which recurring document will be created"""
Nabin Hait91fb6612014-09-05 14:56:05 +0530203
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530204 if not doc.repeat_on_day_of_month:
205 msgprint(_("Please enter 'Repeat on Day of Month' field value"), raise_exception=1)
206
ShashaQin6071ddc2016-02-25 11:25:24 +0800207 next_date = doc.next_date or get_next_date(doc.from_date, month_map[doc.recurring_type],
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530208 cint(doc.repeat_on_day_of_month))
209
ankitjavalkarwork737d8e42014-09-01 16:18:44 +0530210 frappe.db.set(doc, 'next_date', next_date)
211
212 msgprint(_("Next Recurring {0} will be created on {1}").format(doc.doctype, next_date))