forked from Morphnus-IT-Solutions/cimworks
/
__init__.py
executable file
·641 lines (513 loc) · 15.6 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
# util __init__.py
import webnotes
user_time_zone = None
month_name = ['','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
month_name_full = ['','January','February','March','April','May','June','July','August','September','October','November','December']
no_value_fields = ['Section Break', 'Column Break', 'HTML', 'Table', 'FlexTable', 'Button', 'Image', 'Graph']
default_fields = ['doctype','name','owner','creation','modified','modified_by','parent','parentfield','parenttype','idx','docstatus']
def getCSVelement(v):
"""
Returns the CSV value of `v`, For example:
* apple becomes "apple"
* hi"there becomes "hi""there"
"""
v = cstr(v)
if not v: return ''
if (',' in v) or ('\n' in v) or ('"' in v):
if '"' in v: v = v.replace('"', '""')
return '"'+v+'"'
else: return v or ''
def extract_email_id(s):
"""
Extract email id from email header format
"""
if '<' in s:
s = s.split('<')[1].split('>')[0]
if s:
s = s.strip().lower()
return s
def validate_email_add(email_str):
"""
Validates the email string
"""
s = extract_email_id(email_str)
import re
#return re.match("^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", email_str)
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])?", s)
def sendmail(recipients, sender='', msg='', subject='[No Subject]', parts=[], cc=[], attach=[]):
"""
Send an email. For more details see :func:`email_lib.sendmail`
"""
import webnotes.utils.email_lib
return email_lib.sendmail(recipients, sender, msg, subject, parts, cc, attach)
def generate_hash():
"""
Generates random hash for session id
"""
import hashlib, time
return hashlib.sha224(str(time.time())).hexdigest()
def db_exists(dt, dn):
return webnotes.conn.sql('select name from `tab%s` where name="%s"' % (dt, dn))
def load_json(arg):
# already a dictionary?
if type(arg)!=str:
return arg
try: import json
except: import simplejson as json
#return json.loads(unicode(arg, 'iso-8859-15'))
return json.loads(arg)
# Get Traceback
# ==============================================================================
def getTraceback():
"""
Returns the traceback of the Exception
"""
import sys, traceback, string
type, value, tb = sys.exc_info()
body = "Traceback (innermost last):\n"
list = traceback.format_tb(tb, None) + traceback.format_exception_only(type, value)
body = body + "%-20s %s" % (string.join(list[:-1], ""), list[-1])
if webnotes.logger:
webnotes.logger.error('Db:'+(webnotes.conn and webnotes.conn.cur_db_name or '') + ' - ' + body)
return body
# Log
# ==============================================================================
def log(event, details):
webnotes.logger.info(details)
# Date and Time
# ==============================================================================
def getdate(string_date):
"""
Coverts string date (yyyy-mm-dd) to datetime.date object
"""
import datetime
if type(string_date)==unicode:
string_date = str(string_date)
if type(string_date) in (datetime.datetime, datetime.date):
return string_date
if ' ' in string_date:
string_date = string_date.split(' ')[0]
t = string_date.split('-')
if len(t)==3:
return datetime.date(cint(t[0]), cint(t[1]), cint(t[2]))
else:
return ''
def add_days(date, days, format='string'):
"""
Adds `days` to the given `string_date`
"""
import datetime
if not date:
date = now_datetime()
if type(date) not in (datetime.datetime, datetime.date):
date = getdate(date)
dt = date + datetime.timedelta(days)
if format=='string':
return dt.strftime('%Y-%m-%d')
else:
return dt
def add_months(string_date, months):
import datetime
return webnotes.conn.sql("select DATE_ADD('%s',INTERVAL '%s' MONTH)" % (getdate(string_date),months))[0][0]
def add_years(string_date, years):
import datetime
return webnotes.conn.sql("select DATE_ADD('%s',INTERVAL '%s' YEAR)" % (getdate(string_date),years))[0][0]
def date_diff(string_ed_date, string_st_date=None):
import datetime
return webnotes.conn.sql("SELECT DATEDIFF('%s','%s')" %(getdate(string_ed_date), getdate(string_st_date)))[0][0]
def now_datetime():
global user_time_zone
from datetime import datetime
from pytz import timezone
# get localtime
if not user_time_zone:
user_time_zone = webnotes.conn.get_value('Control Panel', None, 'time_zone') or 'Asia/Calcutta'
# convert to UTC
utcnow = timezone('UTC').localize(datetime.utcnow())
# convert to user time zone
return utcnow.astimezone(timezone(user_time_zone))
def now():
"""
Returns `time.strftime('%Y-%m-%d %H:%M:%S')`
"""
return now_datetime().strftime('%Y-%m-%d %H:%M:%S')
def nowdate():
"""
Returns time.strftime('%Y-%m-%d')
"""
return now_datetime().strftime('%Y-%m-%d')
def get_first_day(dt, d_years=0, d_months=0):
"""
Returns the first day of the month for the date specified by date object
Also adds `d_years` and `d_months` if specified
"""
import datetime
# d_years, d_months are "deltas" to apply to dt
y, m = dt.year + d_years, dt.month + d_months
a, m = divmod(m-1, 12)
return datetime.date(y+a, m+1, 1)
def get_last_day(dt):
"""
Returns last day of the month using:
`get_first_day(dt, 0, 1) + datetime.timedelta(-1)`
"""
import datetime
return get_first_day(dt, 0, 1) + datetime.timedelta(-1)
user_format = None
"""
User format specified in :term:`Control Panel`
Examples:
* dd-mm-yyyy
* mm-dd-yyyy
* dd/mm/yyyy
"""
def formatdate(string_date):
"""
Convers the given string date to :data:`user_format`
"""
global user_format
if not user_format:
user_format = webnotes.conn.get_value('Control Panel', None, 'date_format')
d = string_date.split('-');
out = user_format
return out.replace('dd', ('%.2i' % cint(d[2]))).replace('mm', ('%.2i' % cint(d[1]))).replace('yyyy', d[0])
def dict_to_str(args, sep='&'):
"""
Converts a dictionary to URL
"""
import urllib
t = []
for k in args.keys():
t.append(str(k)+'='+urllib.quote(str(args[k] or '')))
return sep.join(t)
def timestamps_equal(t1, t2):
"""Returns true if same the two string timestamps are same"""
scrub = lambda x: x.replace(':', ' ').replace('-',' ').split()
t1, t2 = scrub(t1), scrub(t2)
if len(t1) != len(t2):
return
for i in range(len(t1)):
if t1[i]!=t2[i]:
return
return 1
def global_date_format(date):
import datetime
if type(date) in (str, unicode):
date = getdate(date)
return date.strftime('%d') + ' ' + month_name_full[int(date.strftime('%m'))] + ' ' + date.strftime('%Y')
# Datatype
# ==============================================================================
def isNull(v):
"""
Returns true if v='' or v is `None`
"""
return (v=='' or v==None)
def has_common(l1, l2):
"""
Returns true if there are common elements in lists l1 and l2
"""
for l in l1:
if l in l2:
return 1
return 0
def flt(s):
"""
Convert to float (ignore commas)
"""
if type(s)==str: # if string
s = s.replace(',','')
try: tmp = float(s)
except: tmp = 0
return tmp
def cint(s):
"""
Convert to integer
"""
try: tmp = int(float(s))
except: tmp = 0
return tmp
def cstr(s):
"""
Convert to string
"""
if type(s) in (str, unicode):
return s
elif s==None:
return ''
else:
return str(s)
def str_esc_quote(s):
"""
Escape quotes
"""
if s==None:return ''
return s.replace("'","\'")
def replace_newlines(s):
"""
Replace newlines by '<br>'
"""
if s==None:return ''
return s.replace("\n","<br>")
# ==============================================================================
def parse_val(v):
"""
Converts to simple datatypes from SQL query results
"""
import datetime
try: import decimal # for decimal Python 2.5 (?)
except: pass
if type(v)==datetime.date:
v = str(v)
elif type(v)==datetime.timedelta:
v = ':'.join(str(v).split(':')[:2])
elif type(v)==datetime.datetime:
v = str(v)
elif type(v)==long: v=int(v)
try:
if type(v)==decimal.Decimal: v=float(v)
except: pass
return v
# ==============================================================================
def fmt_money(amount, fmt = '%.2f'):
"""
Convert to string with commas for thousands, millions etc
"""
curr = webnotes.conn.get_value('Control Panel', None, 'currency_format') or 'Millions'
val = 2
if curr == 'Millions': val = 3
if cstr(amount).find('.') == -1: temp = '00'
else: temp = cstr(amount).split('.')[1]
l = []
minus = ''
if flt(amount) < 0: minus = '-'
amount = ''.join(cstr(amount).split(','))
amount = cstr(abs(flt(amount))).split('.')[0]
# main logic
if len(cstr(amount)) > 3:
nn = amount[len(amount)-3:]
l.append(nn)
amount = amount[0:len(amount)-3]
while len(cstr(amount)) > val:
nn = amount[len(amount)-val:]
l.insert(0,nn)
amount = amount[0:len(amount)-val]
if len(amount) > 0: l.insert(0,amount)
amount = ','.join(l)+'.'+temp
amount = minus + amount
return amount
#
# convet currency to words
#
def money_in_words(number, main_currency = None, fraction_currency=None):
"""
Returns string in words with currency and fraction currency.
"""
d = get_defaults()
if not main_currency:
main_currency = d.get('currency', 'INR')
if not fraction_currency:
fraction_currency = d.get('fraction_currency', 'paise')
n = str(flt(number))
main, fraction = n.split('.')
if len(fraction)==1: fraction += '0'
out = main_currency + ' ' + in_words(main).title()
if cint(fraction):
out = out + ' and ' + in_words(fraction).title() + ' ' + fraction_currency
return out + ' only.'
#
# convert number to words
#
def in_words(integer):
"""
Returns string in words for the given integer.
"""
in_million = webnotes.conn.get_value('Control Panel',None,'currency_format')=='Millions' and 1 or 0
n=int(integer)
known = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'}
def psn(n, known, xpsn):
import sys;
if n in known: return known[n]
bestguess, remainder = str(n), 0
if n<=20:
print >>sys.stderr, n, "How did this happen?"
assert 0
elif n < 100:
bestguess= xpsn((n//10)*10, known, xpsn) + '-' + xpsn(n%10, known, xpsn)
return bestguess
elif n < 1000:
bestguess= xpsn(n//100, known, xpsn) + ' ' + 'hundred'
remainder = n%100
else:
if in_million:
if n < 1000000:
bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
remainder = n%1000
elif n < 1000000000:
bestguess= xpsn(n//1000000, known, xpsn) + ' ' + 'million'
remainder = n%1000000
else:
bestguess= xpsn(n//1000000000, known, xpsn) + ' ' + 'billion'
remainder = n%1000000000
else:
if n < 100000:
bestguess= xpsn(n//1000, known, xpsn) + ' ' + 'thousand'
remainder = n%1000
elif n < 10000000:
bestguess= xpsn(n//100000, known, xpsn) + ' ' + 'lakh'
remainder = n%100000
else:
bestguess= xpsn(n//10000000, known, xpsn) + ' ' + 'crore'
remainder = n%10000000
if remainder:
if remainder >= 100:
comma = ','
else:
comma = ''
return bestguess + comma + ' ' + xpsn(remainder, known, xpsn)
else:
return bestguess
return psn(n, known, psn)
# Get Defaults
# ==============================================================================
def get_defaults(key=None):
"""
Get dictionary of default values from the :term:`Control Panel`, or a value if key is passed
"""
if key:
res = webnotes.conn.sql('select defvalue from `tabDefaultValue` where parent = "Control Panel" and defkey=%s', key)
return res and res[0][0] or None
else:
res = webnotes.conn.sql('select defkey, defvalue from `tabDefaultValue` where parent = "Control Panel"')
d = {}
for rec in res:
d[rec[0]] = rec[1] or ''
return d
def set_default(key, val):
"""
Set / add a default value to :term:`Control Panel`
"""
res = webnotes.conn.sql('select defkey from `tabDefaultValue` where defkey="%s" and parent = "Control Panel"' % key)
if res:
webnotes.conn.sql('update `tabDefaultValue` set defvalue="%s" where parent = "Control Panel" and defkey="%s"' % (val, key))
else:
from webnotes.model.doc import Document
d = Document('DefaultValue')
d.parent = 'Control Panel'
d.parenttype = 'Control Panel'
d.parentfield = 'system_defaults'
d.defkey = key
d.defvalue = val
d.save(1)
#
# Clear recycle bin
#
def clear_recycle_bin():
sql = webnotes.conn.sql
tl = sql('show tables')
total_deleted = 0
for t in tl:
fl = [i[0] for i in sql('desc `%s`' % t[0])]
if 'name' in fl:
total_deleted += sql("select count(*) from `%s` where name like '__overwritten:%%'" % t[0])[0][0]
sql("delete from `%s` where name like '__overwritten:%%'" % t[0])
if 'parent' in fl:
total_deleted += sql("select count(*) from `%s` where parent like '__oldparent:%%'" % t[0])[0][0]
sql("delete from `%s` where parent like '__oldparent:%%'" % t[0])
total_deleted += sql("select count(*) from `%s` where parent like 'oldparent:%%'" % t[0])[0][0]
sql("delete from `%s` where parent like 'oldparent:%%'" % t[0])
total_deleted += sql("select count(*) from `%s` where parent like 'old_parent:%%'" % t[0])[0][0]
sql("delete from `%s` where parent like 'old_parent:%%'" % t[0])
return "%s records deleted" % str(int(total_deleted))
# Send Error Report
# ==============================================================================
def send_error_report():
sql = webnotes.conn.sql
m = ''
acc_id = webnotes.conn.get_value('Control Panel',None,'account_id') or ''
if acc_id: m = 'Account Id : '+acc_id
form = webnotes.form
err_msg = '''
%s <br>
Comment: %s
Err Msg : %s
''' % (m, form.getvalue('msg') or '', form.getvalue('err_msg'))
sendmail([webnotes.conn.get_value('Control Panel',None,'support_email_id') or 'support@iwebnotes.com'], sender=webnotes.session['user'], msg=err_msg, subject='Error Report '+m)
# Dictionary utils
# ==============================================================================
def remove_blanks(d):
"""
Returns d with empty ('' or None) values stripped
"""
empty_keys = []
for key in d:
if d[key]=='' or d[key]==None:
# del d[key] raises runtime exception, using a workaround
empty_keys.append(key)
for key in empty_keys:
del d[key]
return d
def pprint_dict(d, level=1, no_blanks=True):
"""
Pretty print a dictionary with indents
"""
if no_blanks:
remove_blanks(d)
# make indent
indent, ret = '', ''
for i in range(0,level): indent += '\t'
# add lines
comment, lines = '', []
kl = d.keys()
kl.sort()
# make lines
for key in kl:
if key != '##comment':
tmp = {key: d[key]}
lines.append(indent + str(tmp)[1:-1] )
# add comment string
if '##comment' in kl:
ret = ('\n' + indent) + '# ' + d['##comment'] + '\n'
# open
ret += indent + '{\n'
# lines
ret += indent + ',\n\t'.join(lines)
# close
ret += '\n' + indent + '}'
return ret
def get_common(d1,d2):
"""
returns (list of keys) the common part of two dicts
"""
return [p for p in d1 if p in d2 and d1[p]==d2[p]]
def get_common_dict(d1, d2):
"""
return common dictionary of d1 and d2
"""
ret = {}
for key in d1:
if key in d2 and d2[key]==d1[key]:
ret[key] = d1[key]
return ret
def get_diff_dict(d1, d2):
"""
return common dictionary of d1 and d2
"""
diff_keys = set(d2.keys()).difference(set(d1.keys()))
ret = {}
for d in diff_keys: ret[d] = d2[d]
return ret
def get_file_timestamp(fn):
"""
Returns timestamp of the given file
"""
import os
from webnotes.utils import cint
try:
return str(cint(os.stat(fn).st_mtime))
except OSError, e:
if e.args[0]!=2:
raise e
else:
return None