Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

595 rindas
16 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. # IMPORTANT: only import safe functions as this module will be included in jinja environment
  5. import frappe
  6. import operator
  7. import re, urllib, datetime, math
  8. import babel.dates
  9. # datetime functions
  10. def getdate(string_date):
  11. """
  12. Coverts string date (yyyy-mm-dd) to datetime.date object
  13. """
  14. if isinstance(string_date, datetime.date):
  15. return string_date
  16. elif isinstance(string_date, datetime.datetime):
  17. return string_date.date()
  18. if " " in string_date:
  19. string_date = string_date.split(" ")[0]
  20. return datetime.datetime.strptime(string_date, "%Y-%m-%d").date()
  21. def add_to_date(date, years=0, months=0, days=0):
  22. """Adds `days` to the given date"""
  23. format = isinstance(date, basestring)
  24. if date:
  25. date = getdate(date)
  26. else:
  27. raise Exception, "Start date required"
  28. from dateutil.relativedelta import relativedelta
  29. date += relativedelta(years=years, months=months, days=days)
  30. if format:
  31. return date.strftime("%Y-%m-%d")
  32. else:
  33. return date
  34. def add_days(date, days):
  35. return add_to_date(date, days=days)
  36. def add_months(date, months):
  37. return add_to_date(date, months=months)
  38. def add_years(date, years):
  39. return add_to_date(date, years=years)
  40. def date_diff(string_ed_date, string_st_date):
  41. return (getdate(string_ed_date) - getdate(string_st_date)).days
  42. def time_diff(string_ed_date, string_st_date):
  43. return get_datetime(string_ed_date) - get_datetime(string_st_date)
  44. def time_diff_in_seconds(string_ed_date, string_st_date):
  45. return time_diff(string_ed_date, string_st_date).total_seconds()
  46. def time_diff_in_hours(string_ed_date, string_st_date):
  47. return round(float(time_diff(string_ed_date, string_st_date).total_seconds()) / 3600, 6)
  48. def now_datetime():
  49. return convert_utc_to_user_timezone(datetime.datetime.utcnow())
  50. def get_user_time_zone():
  51. if getattr(frappe.local, "user_time_zone", None) is None:
  52. frappe.local.user_time_zone = frappe.cache().get_value("time_zone")
  53. if not frappe.local.user_time_zone:
  54. frappe.local.user_time_zone = frappe.db.get_default('time_zone') or 'Asia/Calcutta'
  55. frappe.cache().set_value("time_zone", frappe.local.user_time_zone)
  56. return frappe.local.user_time_zone
  57. def convert_utc_to_user_timezone(utc_timestamp):
  58. from pytz import timezone, UnknownTimeZoneError
  59. utcnow = timezone('UTC').localize(utc_timestamp)
  60. try:
  61. return utcnow.astimezone(timezone(get_user_time_zone()))
  62. except UnknownTimeZoneError:
  63. return utcnow
  64. def now():
  65. """return current datetime as yyyy-mm-dd hh:mm:ss"""
  66. if getattr(frappe.local, "current_date", None):
  67. return getdate(frappe.local.current_date).strftime("%Y-%m-%d") + " " + \
  68. now_datetime().strftime('%H:%M:%S.%f')
  69. else:
  70. return now_datetime().strftime('%Y-%m-%d %H:%M:%S.%f')
  71. def nowdate():
  72. """return current date as yyyy-mm-dd"""
  73. return now_datetime().strftime('%Y-%m-%d')
  74. def today():
  75. return nowdate()
  76. def nowtime():
  77. """return current time in hh:mm"""
  78. return now_datetime().strftime('%H:%M:%S.%f')
  79. def get_first_day(dt, d_years=0, d_months=0):
  80. """
  81. Returns the first day of the month for the date specified by date object
  82. Also adds `d_years` and `d_months` if specified
  83. """
  84. dt = getdate(dt)
  85. # d_years, d_months are "deltas" to apply to dt
  86. overflow_years, month = divmod(dt.month + d_months - 1, 12)
  87. year = dt.year + d_years + overflow_years
  88. return datetime.date(year, month + 1, 1)
  89. def get_last_day(dt):
  90. """
  91. Returns last day of the month using:
  92. `get_first_day(dt, 0, 1) + datetime.timedelta(-1)`
  93. """
  94. return get_first_day(dt, 0, 1) + datetime.timedelta(-1)
  95. def get_datetime(datetime_str):
  96. try:
  97. return datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S.%f')
  98. except TypeError:
  99. if isinstance(datetime_str, datetime.datetime):
  100. return datetime_str.replace(tzinfo=None)
  101. else:
  102. raise
  103. except ValueError:
  104. if datetime_str=='0000-00-00 00:00:00.000000':
  105. return None
  106. return datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
  107. def get_datetime_str(datetime_obj):
  108. if isinstance(datetime_obj, basestring):
  109. datetime_obj = get_datetime(datetime_obj)
  110. return datetime_obj.strftime('%Y-%m-%d %H:%M:%S.%f')
  111. def formatdate(string_date=None, format_string=None):
  112. """
  113. Convers the given string date to :data:`user_format`
  114. User format specified in defaults
  115. Examples:
  116. * dd-mm-yyyy
  117. * mm-dd-yyyy
  118. * dd/mm/yyyy
  119. """
  120. date = getdate(string_date) if string_date else now_datetime().date()
  121. if format_string:
  122. return babel.dates.format_date(date, format_string or "medium", locale=(frappe.local.lang or "").replace("-", "_"))
  123. else:
  124. if getattr(frappe.local, "user_format", None) is None:
  125. frappe.local.user_format = frappe.db.get_default("date_format")
  126. out = frappe.local.user_format or "yyyy-mm-dd"
  127. return out.replace("dd", date.strftime("%d"))\
  128. .replace("mm", date.strftime("%m"))\
  129. .replace("yyyy", date.strftime("%Y"))
  130. def global_date_format(date):
  131. """returns date as 1 January 2012"""
  132. formatted_date = getdate(date).strftime("%d %B %Y")
  133. return formatted_date.startswith("0") and formatted_date[1:] or formatted_date
  134. def has_common(l1, l2):
  135. """Returns truthy value if there are common elements in lists l1 and l2"""
  136. return set(l1) & set(l2)
  137. def flt(s, precision=None):
  138. """Convert to float (ignore commas)"""
  139. if isinstance(s, basestring):
  140. s = s.replace(',','')
  141. try:
  142. num = float(s)
  143. if precision is not None:
  144. num = rounded(num, precision)
  145. except Exception:
  146. num = 0
  147. return num
  148. def cint(s):
  149. """Convert to integer"""
  150. try: num = int(float(s))
  151. except: num = 0
  152. return num
  153. def cstr(s):
  154. if isinstance(s, unicode):
  155. return s
  156. elif s==None:
  157. return ''
  158. elif isinstance(s, basestring):
  159. return unicode(s, 'utf-8')
  160. else:
  161. return unicode(s)
  162. def rounded(num, precision=0):
  163. """round method for round halfs to nearest even algorithm"""
  164. precision = cint(precision)
  165. multiplier = 10 ** precision
  166. # avoid rounding errors
  167. num = round(num * multiplier if precision else num, 8)
  168. floor = math.floor(num)
  169. decimal_part = num - floor
  170. if decimal_part == 0.5:
  171. num = floor if (floor % 2 == 0) else floor + 1
  172. else:
  173. num = round(num)
  174. return (num / multiplier) if precision else num
  175. def encode(obj, encoding="utf-8"):
  176. if isinstance(obj, list):
  177. out = []
  178. for o in obj:
  179. if isinstance(o, unicode):
  180. out.append(o.encode(encoding))
  181. else:
  182. out.append(o)
  183. return out
  184. elif isinstance(obj, unicode):
  185. return obj.encode(encoding)
  186. else:
  187. return obj
  188. def parse_val(v):
  189. """Converts to simple datatypes from SQL query results"""
  190. if isinstance(v, (datetime.date, datetime.datetime)):
  191. v = unicode(v)
  192. elif isinstance(v, datetime.timedelta):
  193. v = ":".join(unicode(v).split(":")[:2])
  194. elif isinstance(v, long):
  195. v = int(v)
  196. return v
  197. def fmt_money(amount, precision=None, currency=None):
  198. """
  199. Convert to string with commas for thousands, millions etc
  200. """
  201. number_format = None
  202. if currency:
  203. number_format = frappe.db.get_value("Currency", currency, "number_format")
  204. if not number_format:
  205. number_format = frappe.db.get_default("number_format") or "#,###.##"
  206. decimal_str, comma_str, number_format_precision = get_number_format_info(number_format)
  207. if not precision:
  208. precision = number_format_precision
  209. amount = '%.*f' % (precision, flt(amount))
  210. if amount.find('.') == -1:
  211. decimals = ''
  212. else:
  213. decimals = amount.split('.')[1]
  214. parts = []
  215. minus = ''
  216. if flt(amount) < 0:
  217. minus = '-'
  218. amount = cstr(abs(flt(amount))).split('.')[0]
  219. if len(amount) > 3:
  220. parts.append(amount[-3:])
  221. amount = amount[:-3]
  222. val = number_format=="#,##,###.##" and 2 or 3
  223. while len(amount) > val:
  224. parts.append(amount[-val:])
  225. amount = amount[:-val]
  226. parts.append(amount)
  227. parts.reverse()
  228. amount = comma_str.join(parts) + ((precision and decimal_str) and (decimal_str + decimals) or "")
  229. amount = minus + amount
  230. if currency and frappe.defaults.get_global_default("hide_currency_symbol") != "Yes":
  231. symbol = frappe.db.get_value("Currency", currency, "symbol") or currency
  232. amount = symbol + " " + amount
  233. return amount
  234. number_format_info = {
  235. "#,###.##": (".", ",", 2),
  236. "#.###,##": (",", ".", 2),
  237. "# ###.##": (".", " ", 2),
  238. "# ###,##": (",", " ", 2),
  239. "#'###.##": (".", "'", 2),
  240. "#, ###.##": (".", ", ", 2),
  241. "#,##,###.##": (".", ",", 2),
  242. "#,###.###": (".", ",", 3),
  243. "#.###": ("", ".", 0),
  244. "#,###": ("", ",", 0)
  245. }
  246. def get_number_format_info(format):
  247. return number_format_info.get(format) or (".", ",", 2)
  248. #
  249. # convet currency to words
  250. #
  251. def money_in_words(number, main_currency = None, fraction_currency=None):
  252. """
  253. Returns string in words with currency and fraction currency.
  254. """
  255. from frappe.utils import get_defaults
  256. d = get_defaults()
  257. if not main_currency:
  258. main_currency = d.get('currency', 'INR')
  259. if not fraction_currency:
  260. fraction_currency = frappe.db.get_value("Currency", main_currency, "fraction") or "Cent"
  261. n = "%.2f" % flt(number)
  262. main, fraction = n.split('.')
  263. if len(fraction)==1: fraction += '0'
  264. number_format = frappe.db.get_value("Currency", main_currency, "number_format") or \
  265. frappe.db.get_default("number_format") or "#,###.##"
  266. in_million = True
  267. if number_format == "#,##,###.##": in_million = False
  268. out = main_currency + ' ' + in_words(main, in_million).title()
  269. if cint(fraction):
  270. out = out + ' and ' + in_words(fraction, in_million).title() + ' ' + fraction_currency
  271. return out + ' only.'
  272. #
  273. # convert number to words
  274. #
  275. def in_words(integer, in_million=True):
  276. """
  277. Returns string in words for the given integer.
  278. """
  279. n=int(integer)
  280. known = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
  281. 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
  282. 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'}
  283. def psn(n, known, xpsn):
  284. import sys;
  285. if n in known: return known[n]
  286. bestguess, remainder = str(n), 0
  287. if n<=20:
  288. frappe.errprint(sys.stderr)
  289. frappe.errprint(n)
  290. frappe.errprint("How did this happen?")
  291. assert 0
  292. elif n < 100:
  293. bestguess= xpsn((n//10)*10, known, xpsn) + '-' + xpsn(n%10, known, xpsn)
  294. return bestguess
  295. elif n < 1000:
  296. bestguess= xpsn(n//100, known, xpsn) + ' ' + 'hundred'
  297. remainder = n%100
  298. else:
  299. if in_million:
  300. if n < 1000000:
  301. bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
  302. remainder = n%1000
  303. elif n < 1000000000:
  304. bestguess= xpsn(n//1000000, known, xpsn) + ' ' + 'million'
  305. remainder = n%1000000
  306. else:
  307. bestguess= xpsn(n//1000000000, known, xpsn) + ' ' + 'billion'
  308. remainder = n%1000000000
  309. else:
  310. if n < 100000:
  311. bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
  312. remainder = n%1000
  313. elif n < 10000000:
  314. bestguess= xpsn(n//100000, known, xpsn) + ' ' + 'lakh'
  315. remainder = n%100000
  316. else:
  317. bestguess= xpsn(n//10000000, known, xpsn) + ' ' + 'crore'
  318. remainder = n%10000000
  319. if remainder:
  320. if remainder >= 100:
  321. comma = ','
  322. else:
  323. comma = ''
  324. return bestguess + comma + ' ' + xpsn(remainder, known, xpsn)
  325. else:
  326. return bestguess
  327. return psn(n, known, psn)
  328. def is_html(text):
  329. out = False
  330. for key in ["<br>", "<p", "<img", "<div"]:
  331. if key in text:
  332. out = True
  333. break
  334. return out
  335. # from Jinja2 code
  336. _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
  337. def strip_html(text):
  338. """removes anything enclosed in and including <>"""
  339. return _striptags_re.sub("", text)
  340. def escape_html(text):
  341. html_escape_table = {
  342. "&": "&amp;",
  343. '"': "&quot;",
  344. "'": "&apos;",
  345. ">": "&gt;",
  346. "<": "&lt;",
  347. }
  348. return "".join(html_escape_table.get(c,c) for c in text)
  349. def pretty_date(iso_datetime):
  350. """
  351. Takes an ISO time and returns a string representing how
  352. long ago the date represents.
  353. Ported from PrettyDate by John Resig
  354. """
  355. if not iso_datetime: return ''
  356. import math
  357. if isinstance(iso_datetime, basestring):
  358. iso_datetime = datetime.datetime.strptime(iso_datetime, '%Y-%m-%d %H:%M:%S.%f')
  359. now_dt = datetime.datetime.strptime(now(), '%Y-%m-%d %H:%M:%S.%f')
  360. dt_diff = now_dt - iso_datetime
  361. # available only in python 2.7+
  362. # dt_diff_seconds = dt_diff.total_seconds()
  363. dt_diff_seconds = dt_diff.days * 86400.0 + dt_diff.seconds
  364. dt_diff_days = math.floor(dt_diff_seconds / 86400.0)
  365. # differnt cases
  366. if dt_diff_seconds < 60.0:
  367. return 'just now'
  368. elif dt_diff_seconds < 120.0:
  369. return '1 minute ago'
  370. elif dt_diff_seconds < 3600.0:
  371. return '%s minutes ago' % cint(math.floor(dt_diff_seconds / 60.0))
  372. elif dt_diff_seconds < 7200.0:
  373. return '1 hour ago'
  374. elif dt_diff_seconds < 86400.0:
  375. return '%s hours ago' % cint(math.floor(dt_diff_seconds / 3600.0))
  376. elif dt_diff_days == 1.0:
  377. return 'Yesterday'
  378. elif dt_diff_days < 7.0:
  379. return '%s days ago' % cint(dt_diff_days)
  380. elif dt_diff_days < 31.0:
  381. return '%s week(s) ago' % cint(math.ceil(dt_diff_days / 7.0))
  382. elif dt_diff_days < 365.0:
  383. return '%s months ago' % cint(math.ceil(dt_diff_days / 30.0))
  384. else:
  385. return 'more than %s year(s) ago' % cint(math.floor(dt_diff_days / 365.0))
  386. def comma_or(some_list):
  387. return comma_sep(some_list, " or ")
  388. def comma_and(some_list):
  389. return comma_sep(some_list, " and ")
  390. def comma_sep(some_list, sep):
  391. if isinstance(some_list, (list, tuple)):
  392. # list(some_list) is done to preserve the existing list
  393. some_list = [unicode(s) for s in list(some_list)]
  394. if not some_list:
  395. return ""
  396. elif len(some_list) == 1:
  397. return some_list[0]
  398. else:
  399. some_list = ["'%s'" % s for s in some_list]
  400. return ", ".join(some_list[:-1]) + sep + some_list[-1]
  401. else:
  402. return some_list
  403. def filter_strip_join(some_list, sep):
  404. """given a list, filter None values, strip spaces and join"""
  405. return (cstr(sep)).join((cstr(a).strip() for a in filter(None, some_list)))
  406. def get_url(uri=None, full_address=False):
  407. """get app url from request"""
  408. host_name = frappe.local.conf.host_name
  409. if not host_name:
  410. if hasattr(frappe.local, "request") and frappe.local.request and frappe.local.request.host:
  411. protocol = 'https' == frappe.get_request_header('X-Forwarded-Proto', "") and 'https://' or 'http://'
  412. host_name = protocol + frappe.local.request.host
  413. elif frappe.local.site:
  414. host_name = "http://{}".format(frappe.local.site)
  415. else:
  416. host_name = frappe.db.get_value("Website Settings", "Website Settings",
  417. "subdomain")
  418. if host_name and "http" not in host_name:
  419. host_name = "http://" + host_name
  420. if not host_name:
  421. host_name = "http://localhost"
  422. if not uri and full_address:
  423. uri = frappe.get_request_header("REQUEST_URI", "")
  424. url = urllib.basejoin(host_name, uri) if uri else host_name
  425. return url
  426. def get_url_to_form(doctype, name, label=None):
  427. if not label: label = name
  428. return """<a href="/desk#!Form/%(doctype)s/%(name)s">%(label)s</a>""" % locals()
  429. operator_map = {
  430. # startswith
  431. "^": lambda (a, b): (a or "").startswith(b),
  432. # in or not in a list
  433. "in": lambda (a, b): operator.contains(b, a),
  434. "not in": lambda (a, b): not operator.contains(b, a),
  435. # comparison operators
  436. "=": lambda (a, b): operator.eq(a, b),
  437. "!=": lambda (a, b): operator.ne(a, b),
  438. ">": lambda (a, b): operator.gt(a, b),
  439. "<": lambda (a, b): operator.lt(a, b),
  440. ">=": lambda (a, b): operator.ge(a, b),
  441. "<=": lambda (a, b): operator.le(a, b),
  442. "not None": lambda (a, b): a and True or False,
  443. "None": lambda (a, b): (not a) and True or False
  444. }
  445. def compare(val1, condition, val2):
  446. ret = False
  447. if condition in operator_map:
  448. ret = operator_map[condition]((val1, val2))
  449. return ret
  450. def scrub_urls(html):
  451. html = expand_relative_urls(html)
  452. html = quote_urls(html)
  453. return html
  454. def expand_relative_urls(html):
  455. # expand relative urls
  456. url = get_url()
  457. if url.endswith("/"): url = url[:-1]
  458. def _expand_relative_urls(match):
  459. to_expand = list(match.groups())
  460. if not to_expand[2].startswith("/"):
  461. to_expand[2] = "/" + to_expand[2]
  462. to_expand.insert(2, url)
  463. return "".join(to_expand)
  464. return re.sub('(href|src){1}([\s]*=[\s]*[\'"]?)((?!http)[^\'" >]+)([\'"]?)', _expand_relative_urls, html)
  465. def quote_urls(html):
  466. def _quote_url(match):
  467. groups = list(match.groups())
  468. groups[2] = urllib.quote(groups[2], safe="~@#$&()*!+=:;,.?/'")
  469. return "".join(groups)
  470. return re.sub('(href|src){1}([\s]*=[\s]*[\'"]?)((?:http)[^\'">]+)([\'"]?)',
  471. _quote_url, html)
  472. def unique(seq):
  473. """use this instead of list(set()) to preserve order of the original list.
  474. Thanks to Stackoverflow: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
  475. seen = set()
  476. seen_add = seen.add
  477. return [ x for x in seq if not (x in seen or seen_add(x)) ]