You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 21 KiB

13 jaren geleden
13 jaren geleden
13 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
14 jaren geleden
14 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
12 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. # util __init__.py
  23. from __future__ import unicode_literals
  24. import webnotes
  25. user_time_zone = None
  26. user_format = None
  27. no_value_fields = ['Section Break', 'Column Break', 'HTML', 'Table', 'FlexTable',
  28. 'Button', 'Image', 'Graph']
  29. default_fields = ['doctype', 'name', 'owner', 'creation', 'modified', 'modified_by',
  30. 'parent', 'parentfield', 'parenttype', 'idx', 'docstatus']
  31. # used in import_docs.py
  32. # TODO: deprecate it
  33. def getCSVelement(v):
  34. """
  35. Returns the CSV value of `v`, For example:
  36. * apple becomes "apple"
  37. * hi"there becomes "hi""there"
  38. """
  39. v = cstr(v)
  40. if not v: return ''
  41. if (',' in v) or ('\n' in v) or ('"' in v):
  42. if '"' in v: v = v.replace('"', '""')
  43. return '"'+v+'"'
  44. else: return v or ''
  45. def get_fullname(profile):
  46. """get the full name (first name + last name) of the user from Profile"""
  47. p = webnotes.conn.sql("""select first_name, last_name from `tabProfile`
  48. where name=%s""", profile, as_dict=1)
  49. if p:
  50. profile = " ".join(filter(None,
  51. [p[0].get('first_name'), p[0].get('last_name')])) or profile
  52. return profile
  53. def get_formatted_email(user):
  54. """get email id of user formatted as: John Doe <johndoe@example.com>"""
  55. if user == "Administrator":
  56. return user
  57. from email.utils import formataddr
  58. fullname = get_fullname(user)
  59. return formataddr((fullname, user))
  60. def extract_email_id(email):
  61. """fetch only the email part of the email id"""
  62. from email.utils import parseaddr
  63. if ',' in email and email.count("@")==1:
  64. email = email.split(",")[-1]
  65. fullname, email_id = parseaddr(email)
  66. return email_id
  67. def validate_email_add(email_str):
  68. """Validates the email string"""
  69. email = extract_email_id(email_str)
  70. import re
  71. return re.match("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", email.lower())
  72. def get_request_site_address(full_address=False):
  73. """get app url from request"""
  74. import os
  75. try:
  76. return 'HTTPS' in os.environ.get('SERVER_PROTOCOL') and 'https://' or 'http://' \
  77. + os.environ.get('HTTP_HOST')\
  78. + (full_address and (os.environ.get("REQUEST_URI")) or "")
  79. except TypeError:
  80. return 'http://localhost'
  81. def random_string(length):
  82. """generate a random string"""
  83. import string
  84. from random import choice
  85. return ''.join([choice(string.letters + string.digits) for i in range(length)])
  86. def load_json(arg):
  87. # already a dictionary?
  88. if not isinstance(arg, basestring):
  89. return arg
  90. import json
  91. return json.loads(arg, encoding='utf-8')
  92. # Get Traceback
  93. # ==============================================================================
  94. def getTraceback():
  95. """
  96. Returns the traceback of the Exception
  97. """
  98. import sys, traceback
  99. exc_type, value, tb = sys.exc_info()
  100. trace_list = traceback.format_tb(tb, None) + \
  101. traceback.format_exception_only(exc_type, value)
  102. body = "Traceback (innermost last):\n" + "%-20s %s" % \
  103. (unicode((b"").join(trace_list[:-1]), 'utf-8'), unicode(trace_list[-1], 'utf-8'))
  104. if webnotes.logger:
  105. webnotes.logger.error('Db:'+(webnotes.conn and webnotes.conn.cur_db_name or '') \
  106. + ' - ' + body)
  107. return body
  108. def log(event, details):
  109. webnotes.logger.info(details)
  110. # datetime functions
  111. def getdate(string_date):
  112. """
  113. Coverts string date (yyyy-mm-dd) to datetime.date object
  114. """
  115. import datetime
  116. if isinstance(string_date, datetime.date):
  117. return string_date
  118. elif isinstance(string_date, datetime.datetime):
  119. return datetime.date()
  120. if " " in string_date:
  121. string_date = string_date.split(" ")[0]
  122. try:
  123. return datetime.datetime.strptime(string_date, "%Y-%m-%d").date()
  124. except ValueError:
  125. webnotes.msgprint("Cannot understand date - '%s'" % \
  126. (string_date,), raise_exception=1)
  127. def add_to_date(date, years=0, months=0, days=0):
  128. """Adds `days` to the given date"""
  129. format = isinstance(date, basestring)
  130. if date:
  131. date = getdate(date)
  132. else:
  133. raise Exception, "Start date required"
  134. from dateutil.relativedelta import relativedelta
  135. date += relativedelta(years=years, months=months, days=days)
  136. if format:
  137. return date.strftime("%Y-%m-%d")
  138. else:
  139. return date
  140. def add_days(date, days):
  141. return add_to_date(date, days=days)
  142. def add_months(date, months):
  143. return add_to_date(date, months=months)
  144. def add_years(date, years):
  145. return add_to_date(date, years=years)
  146. def date_diff(string_ed_date, string_st_date):
  147. return (getdate(string_ed_date) - getdate(string_st_date)).days
  148. def time_diff(string_ed_date, string_st_date):
  149. return get_datetime(string_ed_date) - get_datetime(string_st_date)
  150. def time_diff_in_seconds(string_ed_date, string_st_date):
  151. return time_diff(string_ed_date, string_st_date).seconds
  152. def time_diff_in_hours(string_ed_date, string_st_date):
  153. return round(float(time_diff(string_ed_date, string_st_date).seconds) / 3600, 6)
  154. def now_datetime():
  155. from datetime import datetime
  156. return convert_utc_to_user_timezone(datetime.utcnow())
  157. def get_user_time_zone():
  158. global user_time_zone
  159. if not user_time_zone:
  160. user_time_zone = webnotes.conn.get_value('Control Panel', None, 'time_zone') \
  161. or 'Asia/Calcutta'
  162. return user_time_zone
  163. def convert_utc_to_user_timezone(utc_timestamp):
  164. from pytz import timezone
  165. utcnow = timezone('UTC').localize(utc_timestamp)
  166. return utcnow.astimezone(timezone(get_user_time_zone()))
  167. def now():
  168. """return current datetime as yyyy-mm-dd hh:mm:ss"""
  169. return now_datetime().strftime('%Y-%m-%d %H:%M:%S')
  170. def nowdate():
  171. """return current date as yyyy-mm-dd"""
  172. return now_datetime().strftime('%Y-%m-%d')
  173. def today():
  174. return nowdate()
  175. def nowtime():
  176. """return current time in hh:mm"""
  177. return now_datetime().strftime('%H:%M')
  178. def get_first_day(dt, d_years=0, d_months=0):
  179. """
  180. Returns the first day of the month for the date specified by date object
  181. Also adds `d_years` and `d_months` if specified
  182. """
  183. import datetime
  184. dt = getdate(dt)
  185. # d_years, d_months are "deltas" to apply to dt
  186. overflow_years, month = divmod(dt.month + d_months - 1, 12)
  187. year = dt.year + d_years + overflow_years
  188. return datetime.date(year, month + 1, 1)
  189. def get_last_day(dt):
  190. """
  191. Returns last day of the month using:
  192. `get_first_day(dt, 0, 1) + datetime.timedelta(-1)`
  193. """
  194. import datetime
  195. return get_first_day(dt, 0, 1) + datetime.timedelta(-1)
  196. def get_datetime(datetime_str):
  197. from datetime import datetime
  198. if isinstance(datetime_str, datetime):
  199. return datetime_str.replace(microsecond=0, tzinfo=None)
  200. return datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
  201. def get_datetime_str(datetime_obj):
  202. if isinstance(datetime_obj, basestring):
  203. datetime_obj = get_datetime(datetime_obj)
  204. return datetime_obj.strftime('%Y-%m-%d %H:%M:%S')
  205. def formatdate(string_date=None):
  206. """
  207. Convers the given string date to :data:`user_format`
  208. User format specified in :term:`Control Panel`
  209. Examples:
  210. * dd-mm-yyyy
  211. * mm-dd-yyyy
  212. * dd/mm/yyyy
  213. """
  214. if string_date:
  215. string_date = getdate(string_date)
  216. else:
  217. string_date = now_datetime().date()
  218. global user_format
  219. if not user_format:
  220. user_format = webnotes.conn.get_default("date_format")
  221. out = user_format
  222. return out.replace("dd", string_date.strftime("%d"))\
  223. .replace("mm", string_date.strftime("%m"))\
  224. .replace("yyyy", string_date.strftime("%Y"))
  225. def global_date_format(date):
  226. """returns date as 1 January 2012"""
  227. formatted_date = getdate(date).strftime("%d %B %Y")
  228. return formatted_date.startswith("0") and formatted_date[1:] or formatted_date
  229. def dict_to_str(args, sep='&'):
  230. """
  231. Converts a dictionary to URL
  232. """
  233. import urllib
  234. t = []
  235. for k in args.keys():
  236. t.append(str(k)+'='+urllib.quote(str(args[k] or '')))
  237. return sep.join(t)
  238. def timestamps_equal(t1, t2):
  239. """Returns true if same the two string timestamps are same"""
  240. scrub = lambda x: x.replace(':', ' ').replace('-',' ').split()
  241. t1, t2 = scrub(t1), scrub(t2)
  242. if len(t1) != len(t2):
  243. return
  244. for i in range(len(t1)):
  245. if t1[i]!=t2[i]:
  246. return
  247. return 1
  248. def has_common(l1, l2):
  249. """Returns truthy value if there are common elements in lists l1 and l2"""
  250. return set(l1) & set(l2)
  251. def flt(s, precision=None):
  252. """Convert to float (ignore commas)"""
  253. if isinstance(s, basestring):
  254. s = s.replace(',','')
  255. try:
  256. num = float(s)
  257. if precision:
  258. num = round(num, precision)
  259. except Exception:
  260. num = 0
  261. return num
  262. def cint(s):
  263. """Convert to integer"""
  264. try: num = int(float(s))
  265. except: num = 0
  266. return num
  267. def cstr(s):
  268. if isinstance(s, unicode):
  269. return s
  270. elif s==None:
  271. return ''
  272. elif isinstance(s, basestring):
  273. return unicode(s, 'utf-8')
  274. else:
  275. return unicode(s)
  276. def encode(obj, encoding="utf-8"):
  277. if isinstance(obj, list):
  278. out = []
  279. for o in obj:
  280. if isinstance(o, unicode):
  281. out.append(o.encode(encoding))
  282. else:
  283. out.append(o)
  284. return out
  285. elif isinstance(obj, unicode):
  286. return obj.encode(encoding)
  287. else:
  288. return obj
  289. def parse_val(v):
  290. """Converts to simple datatypes from SQL query results"""
  291. import datetime
  292. if isinstance(v, (datetime.date, datetime.datetime)):
  293. v = unicode(v)
  294. elif isinstance(v, datetime.timedelta):
  295. v = ":".join(unicode(v).split(":")[:2])
  296. elif isinstance(v, long):
  297. v = int(v)
  298. return v
  299. def fmt_money(amount, precision=None):
  300. """
  301. Convert to string with commas for thousands, millions etc
  302. """
  303. import webnotes
  304. from webnotes import _
  305. number_format = webnotes.conn.get_default("number_format") or "#,###.##"
  306. decimal_str, comma_str, precision = get_number_format_info(number_format)
  307. val = 2
  308. if number_format == "#,##,###.##": val = 3
  309. amount = '%.*f' % (precision, flt(amount))
  310. if amount.find('.') == -1:
  311. decimals = ''
  312. else:
  313. decimals = amount.split('.')[1]
  314. l = []
  315. minus = ''
  316. if flt(amount) < 0: minus = '-'
  317. amount = cstr(abs(flt(amount))).split('.')[0]
  318. # main logic
  319. if len(amount) > 3:
  320. nn = amount[len(amount)-3:]
  321. l.append(nn)
  322. amount = amount[0:len(amount)-3]
  323. while len(amount) > val:
  324. nn = amount[len(amount)-val:]
  325. l.insert(0,nn)
  326. amount = amount[0:len(amount)-val]
  327. if len(amount) > 0: l.insert(0,amount)
  328. amount = comma_str.join(l) + decimal_str + decimals
  329. amount = minus + amount
  330. return amount
  331. def get_number_format_info(format):
  332. if format=="#.###":
  333. return "", ".", 0
  334. elif format=="#,###":
  335. return "", ",", 0
  336. elif format=="#,###.##" or format=="#,##,###.##":
  337. return ".", ",", 2
  338. elif format=="#.###,##":
  339. return ",", ".", 2
  340. elif format=="# ###.##":
  341. return ".", " ", 2
  342. else:
  343. return ".", ",", 2
  344. #
  345. # convet currency to words
  346. #
  347. def money_in_words(number, main_currency = None, fraction_currency=None):
  348. """
  349. Returns string in words with currency and fraction currency.
  350. """
  351. d = get_defaults()
  352. if not main_currency:
  353. main_currency = d.get('currency', 'INR')
  354. if not fraction_currency:
  355. fraction_currency = webnotes.conn.get_value("Currency", main_currency, "fraction") or "Cent"
  356. n = "%.2f" % flt(number)
  357. main, fraction = n.split('.')
  358. if len(fraction)==1: fraction += '0'
  359. number_format = webnotes.conn.get_value("Currency", main_currency, "number_format") or \
  360. webnotes.conn.get_default("number_format") or "#,###.##"
  361. in_million = True
  362. if number_format == "#,##,###.##": in_million = False
  363. out = main_currency + ' ' + in_words(main, in_million).title()
  364. if cint(fraction):
  365. out = out + ' and ' + in_words(fraction, in_million).title() + ' ' + fraction_currency
  366. return out + ' only.'
  367. #
  368. # convert number to words
  369. #
  370. def in_words(integer, in_million=True):
  371. """
  372. Returns string in words for the given integer.
  373. """
  374. n=int(integer)
  375. known = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
  376. 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
  377. 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'}
  378. def psn(n, known, xpsn):
  379. import sys;
  380. if n in known: return known[n]
  381. bestguess, remainder = str(n), 0
  382. if n<=20:
  383. webnotes.errprint(sys.stderr)
  384. webnotes.errprint(n)
  385. webnotes.errprint("How did this happen?")
  386. assert 0
  387. elif n < 100:
  388. bestguess= xpsn((n//10)*10, known, xpsn) + '-' + xpsn(n%10, known, xpsn)
  389. return bestguess
  390. elif n < 1000:
  391. bestguess= xpsn(n//100, known, xpsn) + ' ' + 'hundred'
  392. remainder = n%100
  393. else:
  394. if in_million:
  395. if n < 1000000:
  396. bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
  397. remainder = n%1000
  398. elif n < 1000000000:
  399. bestguess= xpsn(n//1000000, known, xpsn) + ' ' + 'million'
  400. remainder = n%1000000
  401. else:
  402. bestguess= xpsn(n//1000000000, known, xpsn) + ' ' + 'billion'
  403. remainder = n%1000000000
  404. else:
  405. if n < 100000:
  406. bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
  407. remainder = n%1000
  408. elif n < 10000000:
  409. bestguess= xpsn(n//100000, known, xpsn) + ' ' + 'lakh'
  410. remainder = n%100000
  411. else:
  412. bestguess= xpsn(n//10000000, known, xpsn) + ' ' + 'crore'
  413. remainder = n%10000000
  414. if remainder:
  415. if remainder >= 100:
  416. comma = ','
  417. else:
  418. comma = ''
  419. return bestguess + comma + ' ' + xpsn(remainder, known, xpsn)
  420. else:
  421. return bestguess
  422. return psn(n, known, psn)
  423. # Get Defaults
  424. # ==============================================================================
  425. def get_defaults(key=None):
  426. """
  427. Get dictionary of default values from the :term:`Control Panel`, or a value if key is passed
  428. """
  429. return webnotes.conn.get_defaults(key)
  430. def set_default(key, val):
  431. """
  432. Set / add a default value to :term:`Control Panel`
  433. """
  434. return webnotes.conn.set_default(key, val)
  435. def remove_blanks(d):
  436. """
  437. Returns d with empty ('' or None) values stripped
  438. """
  439. empty_keys = []
  440. for key in d:
  441. if d[key]=='' or d[key]==None:
  442. # del d[key] raises runtime exception, using a workaround
  443. empty_keys.append(key)
  444. for key in empty_keys:
  445. del d[key]
  446. return d
  447. def pprint_dict(d, level=1, no_blanks=True):
  448. """
  449. Pretty print a dictionary with indents
  450. """
  451. if no_blanks:
  452. remove_blanks(d)
  453. # make indent
  454. indent, ret = '', ''
  455. for i in range(0,level): indent += '\t'
  456. # add lines
  457. comment, lines = '', []
  458. kl = d.keys()
  459. kl.sort()
  460. # make lines
  461. for key in kl:
  462. if key != '##comment':
  463. tmp = {key: d[key]}
  464. lines.append(indent + str(tmp)[1:-1] )
  465. # add comment string
  466. if '##comment' in kl:
  467. ret = ('\n' + indent) + '# ' + d['##comment'] + '\n'
  468. # open
  469. ret += indent + '{\n'
  470. # lines
  471. ret += indent + ',\n\t'.join(lines)
  472. # close
  473. ret += '\n' + indent + '}'
  474. return ret
  475. def get_common(d1,d2):
  476. """
  477. returns (list of keys) the common part of two dicts
  478. """
  479. return [p for p in d1 if p in d2 and d1[p]==d2[p]]
  480. def get_common_dict(d1, d2):
  481. """
  482. return common dictionary of d1 and d2
  483. """
  484. ret = {}
  485. for key in d1:
  486. if key in d2 and d2[key]==d1[key]:
  487. ret[key] = d1[key]
  488. return ret
  489. def get_diff_dict(d1, d2):
  490. """
  491. return common dictionary of d1 and d2
  492. """
  493. diff_keys = set(d2.keys()).difference(set(d1.keys()))
  494. ret = {}
  495. for d in diff_keys: ret[d] = d2[d]
  496. return ret
  497. def get_file_timestamp(fn):
  498. """
  499. Returns timestamp of the given file
  500. """
  501. import os
  502. from webnotes.utils import cint
  503. try:
  504. return str(cint(os.stat(fn).st_mtime))
  505. except OSError, e:
  506. if e.args[0]!=2:
  507. raise e
  508. else:
  509. return None
  510. # to be deprecated
  511. def make_esc(esc_chars):
  512. """
  513. Function generator for Escaping special characters
  514. """
  515. return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
  516. # esc / unescape characters -- used for command line
  517. def esc(s, esc_chars):
  518. """
  519. Escape special characters
  520. """
  521. if not s:
  522. return ""
  523. for c in esc_chars:
  524. esc_str = '\\' + c
  525. s = s.replace(c, esc_str)
  526. return s
  527. def unesc(s, esc_chars):
  528. """
  529. UnEscape special characters
  530. """
  531. for c in esc_chars:
  532. esc_str = '\\' + c
  533. s = s.replace(esc_str, c)
  534. return s
  535. def strip_html(text):
  536. """
  537. removes anything enclosed in and including <>
  538. """
  539. import re
  540. return re.compile(r'<.*?>').sub('', text)
  541. def escape_html(text):
  542. html_escape_table = {
  543. "&": "&amp;",
  544. '"': "&quot;",
  545. "'": "&apos;",
  546. ">": "&gt;",
  547. "<": "&lt;",
  548. }
  549. return "".join(html_escape_table.get(c,c) for c in text)
  550. def get_doctype_label(dt=None):
  551. """
  552. Gets label of a doctype
  553. """
  554. if dt:
  555. res = webnotes.conn.sql("""\
  556. SELECT name, dt_label FROM `tabDocType Label`
  557. WHERE name=%s""", dt)
  558. return res and res[0][0] or dt
  559. else:
  560. res = webnotes.conn.sql("SELECT name, dt_label FROM `tabDocType Label`")
  561. dt_label_dict = {}
  562. for r in res:
  563. dt_label_dict[r[0]] = r[1]
  564. return dt_label_dict
  565. def get_label_doctype(label):
  566. """
  567. Gets doctype from its label
  568. """
  569. res = webnotes.conn.sql("""\
  570. SELECT name FROM `tabDocType Label`
  571. WHERE dt_label=%s""", label)
  572. return res and res[0][0] or label
  573. def pretty_date(iso_datetime):
  574. """
  575. Takes an ISO time and returns a string representing how
  576. long ago the date represents.
  577. Ported from PrettyDate by John Resig
  578. """
  579. if not iso_datetime: return ''
  580. from datetime import datetime
  581. import math
  582. if isinstance(iso_datetime, basestring):
  583. iso_datetime = datetime.strptime(iso_datetime, '%Y-%m-%d %H:%M:%S')
  584. now_dt = datetime.strptime(now(), '%Y-%m-%d %H:%M:%S')
  585. dt_diff = now_dt - iso_datetime
  586. # available only in python 2.7+
  587. # dt_diff_seconds = dt_diff.total_seconds()
  588. dt_diff_seconds = dt_diff.days * 86400.0 + dt_diff.seconds
  589. dt_diff_days = math.floor(dt_diff_seconds / 86400.0)
  590. # differnt cases
  591. if dt_diff_seconds < 60.0:
  592. return 'just now'
  593. elif dt_diff_seconds < 120.0:
  594. return '1 minute ago'
  595. elif dt_diff_seconds < 3600.0:
  596. return '%s minutes ago' % cint(math.floor(dt_diff_seconds / 60.0))
  597. elif dt_diff_seconds < 7200.0:
  598. return '1 hour ago'
  599. elif dt_diff_seconds < 86400.0:
  600. return '%s hours ago' % cint(math.floor(dt_diff_seconds / 3600.0))
  601. elif dt_diff_days == 1.0:
  602. return 'Yesterday'
  603. elif dt_diff_days < 7.0:
  604. return '%s days ago' % cint(dt_diff_days)
  605. elif dt_diff_days < 31.0:
  606. return '%s week(s) ago' % cint(math.ceil(dt_diff_days / 7.0))
  607. elif dt_diff_days < 365.0:
  608. return '%s months ago' % cint(math.ceil(dt_diff_days / 30.0))
  609. else:
  610. return 'more than %s year(s) ago' % cint(math.floor(dt_diff_days / 365.0))
  611. def execute_in_shell(cmd, verbose=0):
  612. # using Popen instead of os.system - as recommended by python docs
  613. from subprocess import Popen
  614. import tempfile
  615. with tempfile.TemporaryFile() as stdout:
  616. with tempfile.TemporaryFile() as stderr:
  617. p = Popen(cmd, shell=True, stdout=stdout, stderr=stderr)
  618. p.wait()
  619. stdout.seek(0)
  620. out = stdout.read()
  621. stderr.seek(0)
  622. err = stderr.read()
  623. if verbose:
  624. if err: print err
  625. if out: print out
  626. return err, out
  627. def comma_or(some_list):
  628. return comma_sep(some_list, " or ")
  629. def comma_and(some_list):
  630. return comma_sep(some_list, " and ")
  631. def comma_sep(some_list, sep):
  632. if isinstance(some_list, (list, tuple)):
  633. # list(some_list) is done to preserve the existing list
  634. some_list = [unicode(s) for s in list(some_list)]
  635. if not some_list:
  636. return ""
  637. elif len(some_list) == 1:
  638. return some_list[0]
  639. else:
  640. some_list = ["'%s'" % s for s in some_list]
  641. return ", ".join(some_list[:-1]) + sep + some_list[-1]
  642. else:
  643. return some_list
  644. def get_base_path():
  645. import conf
  646. import os
  647. return os.path.dirname(os.path.abspath(conf.__file__))
  648. def get_url_to_form(doctype, name, base_url=None, label=None):
  649. if not base_url:
  650. try:
  651. from startup import get_url
  652. base_url = get_url()
  653. except ImportError:
  654. base_url = get_request_site_address()
  655. if not label: label = name
  656. return """<a href="%(base_url)s/app.html#!Form/%(doctype)s/%(name)s">%(label)s</a>""" % locals()
  657. import operator
  658. operator_map = {
  659. # startswith
  660. "^": lambda (a, b): (a or "").startswith(b),
  661. # in or not in a list
  662. "in": lambda (a, b): operator.contains(b, a),
  663. "not in": lambda (a, b): not operator.contains(b, a),
  664. # comparison operators
  665. "=": lambda (a, b): operator.eq(a, b),
  666. "!=": lambda (a, b): operator.ne(a, b),
  667. ">": lambda (a, b): operator.gt(a, b),
  668. "<": lambda (a, b): operator.lt(a, b),
  669. ">=": lambda (a, b): operator.ge(a, b),
  670. "<=": lambda (a, b): operator.le(a, b),
  671. }
  672. def compare(val1, condition, val2):
  673. if condition in operator_map:
  674. return operator_map[condition]((val1, val2))
  675. return False