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.
 
 
 
 
 
 

678 lines
20 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. """
  5. Contains the Document class representing an object / record
  6. """
  7. _toc = ["webnotes.model.doc.Document"]
  8. import webnotes
  9. import webnotes.model.meta
  10. from webnotes.utils import *
  11. valid_fields_map = {}
  12. class Document:
  13. """
  14. The wn(meta-data)framework equivalent of a Database Record.
  15. Stores,Retrieves,Updates the record in the corresponding table.
  16. Runs the triggers required.
  17. The `Document` class represents the basic Object-Relational Mapper (ORM). The object type is defined by
  18. `DocType` and the object ID is represented by `name`::
  19. Please note the anamoly in the Web Notes Framework that `ID` is always called as `name`
  20. If both `doctype` and `name` are specified in the constructor, then the object is loaded from the database.
  21. If only `doctype` is given, then the object is not loaded
  22. If `fielddata` is specfied, then the object is created from the given dictionary.
  23. **Note 1:**
  24. The getter and setter of the object are overloaded to map to the fields of the object that
  25. are loaded when it is instantiated.
  26. For example: doc.name will be the `name` field and doc.owner will be the `owner` field
  27. **Note 2 - Standard Fields:**
  28. * `name`: ID / primary key
  29. * `owner`: creator of the record
  30. * `creation`: datetime of creation
  31. * `modified`: datetime of last modification
  32. * `modified_by` : last updating user
  33. * `docstatus` : Status 0 - Saved, 1 - Submitted, 2- Cancelled
  34. * `parent` : if child (table) record, this represents the parent record
  35. * `parenttype` : type of parent record (if any)
  36. * `parentfield` : table fieldname of parent record (if any)
  37. * `idx` : Index (sequence) of the child record
  38. """
  39. def __init__(self, doctype = None, name = None, fielddata = None, prefix='tab'):
  40. self._roles = []
  41. self._perms = []
  42. self._user_defaults = {}
  43. self._prefix = prefix
  44. if isinstance(doctype, dict):
  45. fielddata = doctype
  46. doctype = None
  47. if fielddata:
  48. self.fields = webnotes._dict(fielddata)
  49. else:
  50. self.fields = webnotes._dict()
  51. if not self.fields.has_key('name'):
  52. self.fields['name']='' # required on save
  53. if not self.fields.has_key('doctype'):
  54. self.fields['doctype']='' # required on save
  55. if not self.fields.has_key('owner'):
  56. self.fields['owner']='' # required on save
  57. if doctype:
  58. self.fields['doctype'] = doctype
  59. if name:
  60. self.fields['name'] = name
  61. self.__initialized = 1
  62. if (doctype and name):
  63. self._loadfromdb(doctype, name)
  64. else:
  65. if not fielddata:
  66. self.fields['__islocal'] = 1
  67. if not self.fields.docstatus:
  68. self.fields.docstatus = 0
  69. def __nonzero__(self):
  70. return True
  71. def __str__(self):
  72. return str(self.fields)
  73. def __repr__(self):
  74. return repr(self.fields)
  75. def __unicode__(self):
  76. return unicode(self.fields)
  77. def __eq__(self, other):
  78. if isinstance(other, Document):
  79. return self.fields == other.fields
  80. else:
  81. return False
  82. def __getstate__(self):
  83. return self.fields
  84. def __setstate__(self, d):
  85. self.fields = d
  86. def encode(self, encoding='utf-8'):
  87. """convert all unicode values to utf-8"""
  88. for key in self.fields:
  89. if isinstance(self.fields[key], unicode):
  90. self.fields[key] = self.fields[key].encode(encoding)
  91. def _loadfromdb(self, doctype = None, name = None):
  92. if name: self.name = name
  93. if doctype: self.doctype = doctype
  94. is_single = False
  95. try:
  96. is_single = webnotes.model.meta.is_single(self.doctype)
  97. except Exception, e:
  98. pass
  99. if is_single:
  100. self._loadsingle()
  101. else:
  102. dataset = webnotes.conn.sql('select * from `%s%s` where name="%s"' % (self._prefix, self.doctype, self.name.replace('"', '\"')))
  103. if not dataset:
  104. raise Exception, '[WNF] %s %s does not exist' % (self.doctype, self.name)
  105. self._load_values(dataset[0], webnotes.conn.get_description())
  106. def _load_values(self, data, description):
  107. if '__islocal' in self.fields:
  108. del self.fields['__islocal']
  109. for i in range(len(description)):
  110. v = data[i]
  111. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  112. def _merge_values(self, data, description):
  113. for i in range(len(description)):
  114. v = data[i]
  115. if v: # only if value, over-write
  116. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  117. def _loadsingle(self):
  118. self.name = self.doctype
  119. self.fields.update(getsingle(self.doctype))
  120. def __setattr__(self, name, value):
  121. # normal attribute
  122. if not self.__dict__.has_key('_Document__initialized'):
  123. self.__dict__[name] = value
  124. elif self.__dict__.has_key(name):
  125. self.__dict__[name] = value
  126. else:
  127. # field attribute
  128. f = self.__dict__['fields']
  129. f[name] = value
  130. def __getattr__(self, name):
  131. if self.__dict__.has_key(name):
  132. return self.__dict__[name]
  133. elif self.fields.has_key(name):
  134. return self.fields[name]
  135. else:
  136. return ''
  137. def _get_amended_name(self):
  138. am_id = 1
  139. am_prefix = self.amended_from
  140. if webnotes.conn.sql('select amended_from from `tab%s` where name = "%s"' % (self.doctype, self.amended_from))[0][0] or '':
  141. am_id = cint(self.amended_from.split('-')[-1]) + 1
  142. am_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen
  143. self.name = am_prefix + '-' + str(am_id)
  144. def _set_name(self, autoname, istable):
  145. self.localname = self.name
  146. # get my object
  147. import webnotes.model.code
  148. so = webnotes.model.code.get_server_obj(self, [])
  149. # amendments
  150. if self.amended_from:
  151. self._get_amended_name()
  152. # by method
  153. elif so and hasattr(so, 'autoname'):
  154. r = webnotes.model.code.run_server_obj(so, 'autoname')
  155. if r: return r
  156. # based on a field
  157. elif autoname and autoname.startswith('field:'):
  158. n = self.fields[autoname[6:]]
  159. if not n:
  160. raise Exception, 'Name is required'
  161. self.name = n.strip()
  162. elif autoname and autoname.startswith("naming_series:"):
  163. self.set_naming_series()
  164. if not self.naming_series:
  165. webnotes.msgprint(webnotes._("Naming Series mandatory"), raise_exception=True)
  166. self.name = make_autoname(self.naming_series+'.#####')
  167. # based on expression
  168. elif autoname and autoname.startswith('eval:'):
  169. doc = self # for setting
  170. self.name = eval(autoname[5:])
  171. # call the method!
  172. elif autoname and autoname!='Prompt':
  173. self.name = make_autoname(autoname, self.doctype)
  174. # given
  175. elif self.fields.get('__newname',''):
  176. self.name = self.fields['__newname']
  177. # default name for table
  178. elif istable:
  179. self.name = make_autoname('#########', self.doctype)
  180. # unable to determine a name, use a serial number!
  181. if not self.name:
  182. self.name = make_autoname('#########', self.doctype)
  183. def set_naming_series(self):
  184. if not self.naming_series:
  185. # pick default naming series
  186. from webnotes.model.doctype import get_property
  187. self.naming_series = get_property(self.doctype, "options", "naming_series")
  188. if self.naming_series:
  189. self.naming_series = self.naming_series.split("\n")
  190. self.naming_series = self.naming_series[0] or self.naming_series[1]
  191. def _insert(self, autoname, istable, case='', make_autoname=1, keep_timestamps=False):
  192. # set name
  193. if make_autoname:
  194. self._set_name(autoname, istable)
  195. # validate name
  196. self.name = validate_name(self.doctype, self.name, case)
  197. # insert!
  198. if not keep_timestamps:
  199. if not self.owner:
  200. self.owner = webnotes.session['user']
  201. self.modified_by = webnotes.session['user']
  202. if not self.creation:
  203. self.creation = self.modified = now()
  204. else:
  205. self.modified = now()
  206. webnotes.conn.sql("insert into `tab%(doctype)s`" % self.fields \
  207. + """ (name, owner, creation, modified, modified_by)
  208. values (%(name)s, %(owner)s, %(creation)s, %(modified)s,
  209. %(modified_by)s)""", self.fields)
  210. def _update_single(self, link_list):
  211. self.modified = now()
  212. update_str, values = [], []
  213. webnotes.conn.sql("delete from tabSingles where doctype='%s'" % self.doctype)
  214. for f in self.fields.keys():
  215. if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\
  216. and (not f.startswith('__')): # fields not saved
  217. # validate links
  218. if link_list and link_list.get(f):
  219. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  220. if self.fields[f]==None:
  221. update_str.append("(%s,%s,NULL)")
  222. values.append(self.doctype)
  223. values.append(f)
  224. else:
  225. update_str.append("(%s,%s,%s)")
  226. values.append(self.doctype)
  227. values.append(f)
  228. values.append(self.fields[f])
  229. webnotes.conn.sql("insert into tabSingles(doctype, field, value) values %s" % (', '.join(update_str)), values)
  230. def validate_links(self, link_list):
  231. err_list = []
  232. for f in self.fields.keys():
  233. # validate links
  234. old_val = self.fields[f]
  235. if link_list and link_list.get(f):
  236. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  237. if old_val and not self.fields[f]:
  238. s = link_list[f][1] + ': ' + old_val
  239. err_list.append(s)
  240. return err_list
  241. def make_link_list(self):
  242. res = webnotes.model.meta.get_link_fields(self.doctype)
  243. link_list = {}
  244. for i in res: link_list[i[0]] = (i[1], i[2]) # options, label
  245. return link_list
  246. def _validate_link(self, dt, dn):
  247. if not dt: return dn
  248. if not dn: return None
  249. if dt=="[Select]": return dn
  250. if dt.lower().startswith('link:'):
  251. dt = dt[5:]
  252. if '\n' in dt:
  253. dt = dt.split('\n')[0]
  254. tmp = webnotes.conn.sql("""SELECT name FROM `tab%s`
  255. WHERE name = %s""" % (dt, '%s'), dn)
  256. return tmp and tmp[0][0] or ''# match case
  257. def _update_values(self, issingle, link_list, ignore_fields=0, keep_timestamps=False):
  258. if issingle:
  259. self._update_single(link_list)
  260. else:
  261. update_str, values = [], []
  262. # set modified timestamp
  263. if self.modified and not keep_timestamps:
  264. self.modified = now()
  265. self.modified_by = webnotes.session['user']
  266. fields_list = ignore_fields and self.get_valid_fields() or self.fields.keys()
  267. for f in fields_list:
  268. if (not (f in ('doctype', 'name', 'perm', 'localname',
  269. 'creation','_user_tags', "file_list"))) and (not f.startswith('__')):
  270. # fields not saved
  271. # validate links
  272. if link_list and link_list.get(f):
  273. self.fields[f] = self._validate_link(link_list[f][0],
  274. self.fields.get(f))
  275. if self.fields.get(f) is None or self.fields.get(f)=='':
  276. update_str.append("`%s`=NULL" % f)
  277. else:
  278. values.append(self.fields.get(f))
  279. update_str.append("`%s`=%s" % (f, '%s'))
  280. if values:
  281. values.append(self.name)
  282. r = webnotes.conn.sql("update `tab%s` set %s where name=%s" % \
  283. (self.doctype, ', '.join(update_str), "%s"), values)
  284. def get_valid_fields(self):
  285. global valid_fields_map
  286. if not valid_fields_map.get(self.doctype):
  287. import webnotes.model.doctype
  288. if cint(webnotes.conn.get_value("DocType", self.doctype, "issingle")):
  289. doctypelist = webnotes.model.doctype.get(self.doctype)
  290. valid_fields_map[self.doctype] = doctypelist.get_fieldnames({
  291. "fieldtype": ["not in", webnotes.model.no_value_fields]})
  292. else:
  293. valid_fields_map[self.doctype] = \
  294. webnotes.conn.get_table_columns(self.doctype)
  295. return valid_fields_map.get(self.doctype)
  296. def save(self, new=0, check_links=1, ignore_fields=0, make_autoname=1,
  297. keep_timestamps=False):
  298. res = webnotes.model.meta.get_dt_values(self.doctype,
  299. 'autoname, issingle, istable, name_case', as_dict=1)
  300. res = res and res[0] or {}
  301. if new:
  302. self.fields["__islocal"] = 1
  303. # add missing parentinfo (if reqd)
  304. if self.parent and not (self.parenttype and self.parentfield):
  305. self.update_parentinfo()
  306. if self.parent and not self.idx:
  307. self.set_idx()
  308. # if required, make new
  309. if self.fields.get('__islocal') and (not res.get('issingle')):
  310. r = self._insert(res.get('autoname'), res.get('istable'), res.get('name_case'),
  311. make_autoname, keep_timestamps = keep_timestamps)
  312. if r:
  313. return r
  314. else:
  315. if not res.get('issingle') and not webnotes.conn.exists(self.doctype, self.name):
  316. webnotes.msgprint("""This document was updated before your change. Please refresh before saving.""", raise_exception=1)
  317. # save the values
  318. self._update_values(res.get('issingle'),
  319. check_links and self.make_link_list() or {}, ignore_fields=ignore_fields,
  320. keep_timestamps=keep_timestamps)
  321. self._clear_temp_fields()
  322. def insert(self):
  323. self.fields['__islocal'] = 1
  324. self.save()
  325. return self
  326. def update_parentinfo(self):
  327. """update parent type and parent field, if not explicitly specified"""
  328. tmp = webnotes.conn.sql("""select parent, fieldname from tabDocField
  329. where fieldtype='Table' and options=%s""", self.doctype)
  330. if len(tmp)==0:
  331. raise Exception, 'Incomplete parent info in child table (%s, %s)' \
  332. % (self.doctype, self.fields.get('name', '[new]'))
  333. elif len(tmp)>1:
  334. raise Exception, 'Ambiguous parent info (%s, %s)' \
  335. % (self.doctype, self.fields.get('name', '[new]'))
  336. else:
  337. self.parenttype = tmp[0][0]
  338. self.parentfield = tmp[0][1]
  339. def set_idx(self):
  340. """set idx"""
  341. self.idx = (webnotes.conn.sql("""select max(idx) from `tab%s`
  342. where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'),
  343. (self.parent, self.parentfield))[0][0] or 0) + 1
  344. def _clear_temp_fields(self):
  345. # clear temp stuff
  346. keys = self.fields.keys()
  347. for f in keys:
  348. if f.startswith('__'):
  349. del self.fields[f]
  350. def clear_table(self, doclist, tablefield, save=0):
  351. """
  352. Clears the child records from the given `doclist` for a particular `tablefield`
  353. """
  354. from webnotes.model.utils import getlist
  355. table_list = getlist(doclist, tablefield)
  356. delete_list = [d.name for d in table_list]
  357. if delete_list:
  358. #filter doclist
  359. doclist = filter(lambda d: d.name not in delete_list, doclist)
  360. # delete from db
  361. webnotes.conn.sql("""\
  362. delete from `tab%s`
  363. where parent=%s and parenttype=%s"""
  364. % (table_list[0].doctype, '%s', '%s'),
  365. (self.name, self.doctype))
  366. self.fields['__unsaved'] = 1
  367. return webnotes.doclist(doclist)
  368. def addchild(self, fieldname, childtype = '', doclist=None):
  369. """
  370. Returns a child record of the give `childtype`.
  371. * if local is set, it does not save the record
  372. * if doclist is passed, it append the record to the doclist
  373. """
  374. from webnotes.model.doc import Document
  375. d = Document()
  376. d.parent = self.name
  377. d.parenttype = self.doctype
  378. d.parentfield = fieldname
  379. d.doctype = childtype
  380. d.docstatus = 0;
  381. d.name = ''
  382. d.owner = webnotes.session['user']
  383. d.fields['__islocal'] = 1 # for Client to identify unsaved doc
  384. if doclist != None:
  385. doclist.append(d)
  386. return d
  387. def get_values(self):
  388. """get non-null fields dict withouth standard fields"""
  389. from webnotes.model import default_fields
  390. ret = {}
  391. for key in self.fields:
  392. if key not in default_fields and self.fields[key]:
  393. ret[key] = self.fields[key]
  394. return ret
  395. def addchild(parent, fieldname, childtype = '', doclist=None):
  396. """
  397. Create a child record to the parent doc.
  398. Example::
  399. c = Document('Contact','ABC')
  400. d = addchild(c, 'contact_updates', 'Contact Update')
  401. d.last_updated = 'Phone call'
  402. d.save(1)
  403. """
  404. return parent.addchild(fieldname, childtype, doclist)
  405. def make_autoname(key, doctype=''):
  406. """
  407. Creates an autoname from the given key:
  408. **Autoname rules:**
  409. * The key is separated by '.'
  410. * '####' represents a series. The string before this part becomes the prefix:
  411. Example: ABC.#### creates a series ABC0001, ABC0002 etc
  412. * 'MM' represents the current month
  413. * 'YY' and 'YYYY' represent the current year
  414. *Example:*
  415. * DE/./.YY./.MM./.##### will create a series like
  416. DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
  417. """
  418. if not "#" in key:
  419. key = key + ".#####"
  420. n = ''
  421. l = key.split('.')
  422. series_set = False
  423. today = now_datetime()
  424. for e in l:
  425. en = ''
  426. if e.startswith('#'):
  427. if not series_set:
  428. digits = len(e)
  429. en = getseries(n, digits, doctype)
  430. series_set = True
  431. elif e=='YY':
  432. en = today.strftime('%y')
  433. elif e=='MM':
  434. en = today.strftime('%m')
  435. elif e=='DD':
  436. en = today.strftime("%d")
  437. elif e=='YYYY':
  438. en = today.strftime('%Y')
  439. else: en = e
  440. n+=en
  441. return n
  442. def getseries(key, digits, doctype=''):
  443. # series created ?
  444. if webnotes.conn.sql("select name from tabSeries where name='%s'" % key):
  445. # yes, update it
  446. webnotes.conn.sql("update tabSeries set current = current+1 where name='%s'" % key)
  447. # find the series counter
  448. r = webnotes.conn.sql("select current from tabSeries where name='%s'" % key)
  449. n = r[0][0]
  450. else:
  451. # no, create it
  452. webnotes.conn.sql("insert into tabSeries (name, current) values ('%s', 1)" % key)
  453. n = 1
  454. return ('%0'+str(digits)+'d') % n
  455. def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'):
  456. import webnotes
  457. from webnotes.model.doclist import DocList
  458. condition = ""
  459. values = []
  460. if field:
  461. condition += ' and parentfield=%s '
  462. values.append(field)
  463. if parenttype:
  464. condition += ' and parenttype=%s '
  465. values.append(parenttype)
  466. dataset = webnotes.conn.sql("""select * from `%s%s` where parent=%s %s order by idx""" \
  467. % (prefix, childtype, "%s", condition), tuple([name]+values))
  468. desc = webnotes.conn.get_description()
  469. l = DocList()
  470. for i in dataset:
  471. d = Document()
  472. d.doctype = childtype
  473. d._load_values(i, desc)
  474. l.append(d)
  475. return l
  476. def check_page_perm(doc):
  477. if doc.name=='Login Page':
  478. return
  479. if doc.publish:
  480. return
  481. if not webnotes.conn.sql("select name from `tabPage Role` where parent=%s and role='Guest'", doc.name):
  482. webnotes.response['403'] = 1
  483. raise webnotes.PermissionError, '[WNF] No read permission for %s %s' % ('Page', doc.name)
  484. def get(dt, dn='', with_children = 1, from_controller = 0, prefix = 'tab'):
  485. """
  486. Returns a doclist containing the main record and all child records
  487. """
  488. import webnotes
  489. import webnotes.model
  490. from webnotes.model.doclist import DocList
  491. dn = dn or dt
  492. # load the main doc
  493. doc = Document(dt, dn, prefix=prefix)
  494. if dt=='Page' and webnotes.session['user'] == 'Guest':
  495. check_page_perm(doc)
  496. if not with_children:
  497. # done
  498. return DocList([doc,])
  499. # get all children types
  500. tablefields = webnotes.model.meta.get_table_fields(dt)
  501. # load chilren
  502. doclist = DocList([doc,])
  503. for t in tablefields:
  504. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  505. return doclist
  506. def getsingle(doctype):
  507. """get single doc as dict"""
  508. dataset = webnotes.conn.sql("select field, value from tabSingles where doctype=%s", doctype)
  509. return dict(dataset)
  510. def copy_common_fields(from_doc, to_doc):
  511. from webnotes.model import default_fields
  512. doctype_list = webnotes.get_doctype(to_doc.doctype)
  513. for fieldname, value in from_doc.fields.items():
  514. if fieldname in default_fields:
  515. continue
  516. if doctype_list.get_field(fieldname) and to_doc.fields[fieldname] != value:
  517. to_doc.fields[fieldname] = value
  518. def validate_name(doctype, name, case=None, merge=False):
  519. if not merge:
  520. if webnotes.conn.sql('select name from `tab%s` where name=%s' % (doctype,'%s'), name):
  521. raise NameError, 'Name %s already exists' % name
  522. # no name
  523. if not name: return 'No Name Specified for %s' % doctype
  524. # new..
  525. if name.startswith('New '+doctype):
  526. raise NameError, 'There were some errors setting the name, please contact the administrator'
  527. if case=='Title Case': name = name.title()
  528. if case=='UPPER CASE': name = name.upper()
  529. name = name.strip() # no leading and trailing blanks
  530. forbidden = ['%', "'", '"', '#', '*', '?', '`']
  531. for f in forbidden:
  532. if f in name:
  533. webnotes.msgprint('%s not allowed in ID (name)' % f, raise_exception =1)
  534. return name