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.

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