blob: 713e9bac2f13d88c45a1083b397f49a5c42d1469 [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
Rushabh Mehta82c25892017-03-14 18:52:47 +053096 if new_document.meta.get_field('set_posting_time'):
97 new_document.set('set_posting_time', 1)
98
Anand Doshi39e2c2b2016-01-25 17:03:50 +053099 # copy document fields
100 for fieldname in ("owner", "recurring_type", "repeat_on_day_of_month",
101 "recurring_id", "notification_email_address", "is_recurring", "end_date",
102 "title", "naming_series", "select_print_heading", "ignore_pricing_rule",
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530103 "posting_time", "remarks", 'submit_on_creation'):
Anand Doshi39e2c2b2016-01-25 17:03:50 +0530104 if new_document.meta.get_field(fieldname):
105 new_document.set(fieldname, reference_doc.get(fieldname))
106
107 # copy item fields
108 for i, item in enumerate(new_document.items):
109 for fieldname in ("page_break",):
110 item.set(fieldname, reference_doc.items[i].get(fieldname))
111
112 new_document.run_method("on_recurring", reference_doc=reference_doc)
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530113
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530114 if reference_doc.submit_on_creation:
Nabin Hait5996b2f2016-03-18 15:19:54 +0530115 new_document.insert()
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530116 new_document.submit()
117 else:
ShashaQin6071ddc2016-02-25 11:25:24 +0800118 new_document.docstatus=0
119 new_document.insert()
Nabin Hait91fb6612014-09-05 14:56:05 +0530120
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530121 return new_document
122
123def get_next_date(dt, mcount, day=None):
124 dt = getdate(dt)
125
126 from dateutil.relativedelta import relativedelta
127 dt += relativedelta(months=mcount, day=day)
128
129 return dt
130
131def send_notification(new_rv):
132 """Notify concerned persons about recurring document generation"""
ankitjavalkarwork737d8e42014-09-01 16:18:44 +0530133
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530134 frappe.sendmail(new_rv.notification_email_address,
135 subject= _("New {0}: #{1}").format(new_rv.doctype, new_rv.name),
136 message = _("Please find attached {0} #{1}").format(new_rv.doctype, new_rv.name),
Neil Trini Lasradoe2d8dd02015-06-22 19:06:15 +0530137 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 +0530138
Anand Doshi13945092014-09-21 19:45:49 +0530139def notify_errors(doc, doctype, party, owner):
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530140 from frappe.utils.user import get_system_managers
141 recipients = get_system_managers(only_name=True)
142
143 frappe.sendmail(recipients + [frappe.db.get_value("User", owner, "email")],
144 subject="[Urgent] Error while creating recurring %s for %s" % (doctype, doc),
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530145 message = frappe.get_template("templates/emails/recurring_document_failed.html").render({
ankitjavalkarworke8331d42014-08-25 18:00:12 +0530146 "type": doctype,
147 "name": doc,
Anand Doshi13945092014-09-21 19:45:49 +0530148 "party": party
ankitjavalkarworkac085e02014-08-26 10:40:23 +0530149 }))
150
151 assign_task_to_owner(doc, doctype, "Recurring Invoice Failed", recipients)
152
153def assign_task_to_owner(doc, doctype, msg, users):
154 for d in users:
Rushabh Mehtac0bb4532014-09-09 16:15:35 +0530155 from frappe.desk.form import assign_to
ankitjavalkarworkac085e02014-08-26 10:40:23 +0530156 args = {
157 'assign_to' : d,
158 'doctype' : doctype,
159 'name' : doc,
160 'description' : msg,
161 'priority' : 'High'
162 }
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530163 assign_to.add(args)
164
165def validate_recurring_document(doc):
166 if doc.is_recurring:
167 validate_notification_email_id(doc)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530168 if not doc.recurring_type:
Nabin Hait5996b2f2016-03-18 15:19:54 +0530169 frappe.throw(_("Please select {0}").format(doc.meta.get_label("recurring_type")))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530170
171 elif not (doc.from_date and doc.to_date):
Nabin Hait5996b2f2016-03-18 15:19:54 +0530172 frappe.throw(_("Period From and Period To dates mandatory for recurring {0}").format(doc.doctype))
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530173
Nabin Hait5996b2f2016-03-18 15:19:54 +0530174def validate_recurring_next_date(doc):
175 posting_date = doc.get("posting_date") or doc.get("transaction_date")
176 if getdate(posting_date) > getdate(doc.next_date):
177 frappe.throw(_("Next Date must be greater than Posting Date"))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530178
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530179 next_date = getdate(doc.next_date)
180 if next_date.day != doc.repeat_on_day_of_month:
181
182 # if the repeat day is the last day of the month (31)
183 # and the current month does not have as many days,
184 # then the last day of the current month is a valid date
185 lastday = calendar.monthrange(next_date.year, next_date.month)[1]
186 if doc.repeat_on_day_of_month < lastday:
187
188 # the specified day of the month is not same as the day specified
189 # or the last day of the month
190 frappe.throw(_("Next Date's day and Repeat on Day of Month must be equal"))
Nabin Hait5996b2f2016-03-18 15:19:54 +0530191
Sambhaji Kolateb14401c2014-09-11 16:09:05 +0530192def convert_to_recurring(doc, posting_date):
Nabin Hait5996b2f2016-03-18 15:19:54 +0530193 if doc.is_recurring:
194 if not doc.recurring_id:
195 doc.db_set("recurring_id", doc.name)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530196
Nabin Hait5996b2f2016-03-18 15:19:54 +0530197 set_next_date(doc, posting_date)
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530198
Nabin Hait7504ea72016-03-23 11:16:51 +0530199 if doc.next_date:
200 validate_recurring_next_date(doc)
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530201
Nabin Hait5996b2f2016-03-18 15:19:54 +0530202 elif doc.recurring_id:
Nabin Hait7504ea72016-03-23 11:16:51 +0530203 doc.db_set("recurring_id", None)
Rushabh Mehtaacf28af2016-03-31 15:02:11 +0530204
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530205def validate_notification_email_id(doc):
ShashaQin6071ddc2016-02-25 11:25:24 +0800206 if doc.notify_by_email:
207 if doc.notification_email_address:
208 email_list = split_emails(doc.notification_email_address.replace("\n", ""))
Rushabh Mehta5839a8d2016-03-02 17:51:24 +0530209
ShashaQin6071ddc2016-02-25 11:25:24 +0800210 from frappe.utils import validate_email_add
211 for email in email_list:
212 if not validate_email_add(email):
213 throw(_("{0} is an invalid email address in 'Notification \
214 Email Address'").format(email))
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530215
ShashaQin6071ddc2016-02-25 11:25:24 +0800216 else:
217 frappe.throw(_("'Notification Email Addresses' not specified for recurring %s") \
218 % doc.doctype)
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530219
220def set_next_date(doc, posting_date):
221 """ Set next date on which recurring document will be created"""
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530222 if not doc.repeat_on_day_of_month:
223 msgprint(_("Please enter 'Repeat on Day of Month' field value"), raise_exception=1)
224
rohitwaghchaure90ff5092016-03-17 17:30:53 +0530225 next_date = get_next_date(posting_date, month_map[doc.recurring_type],
ankitjavalkarworkaaac7c12014-08-27 19:10:10 +0530226 cint(doc.repeat_on_day_of_month))
227
Nabin Hait5996b2f2016-03-18 15:19:54 +0530228 doc.db_set('next_date', next_date)
ankitjavalkarwork737d8e42014-09-01 16:18:44 +0530229
230 msgprint(_("Next Recurring {0} will be created on {1}").format(doc.doctype, next_date))