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.
 
 
 
 
 
 

683 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)
  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)
  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, link_list, f):
  247. dt = link_list[f][0]
  248. dn = self.fields.get(f)
  249. if not dt:
  250. webnotes.throw("Options not set for link field: " + f)
  251. if not dt: return dn
  252. if not dn: return None
  253. if dt=="[Select]": return dn
  254. if dt.lower().startswith('link:'):
  255. dt = dt[5:]
  256. if '\n' in dt:
  257. dt = dt.split('\n')[0]
  258. tmp = webnotes.conn.sql("""SELECT name FROM `tab%s`
  259. WHERE name = %s""" % (dt, '%s'), dn)
  260. return tmp and tmp[0][0] or ''# match case
  261. def _update_values(self, issingle, link_list, ignore_fields=0, keep_timestamps=False):
  262. if issingle:
  263. self._update_single(link_list)
  264. else:
  265. update_str, values = [], []
  266. # set modified timestamp
  267. if self.modified and not keep_timestamps:
  268. self.modified = now()
  269. self.modified_by = webnotes.session['user']
  270. fields_list = ignore_fields and self.get_valid_fields() or self.fields.keys()
  271. for f in fields_list:
  272. if (not (f in ('doctype', 'name', 'perm', 'localname',
  273. 'creation','_user_tags', "file_list"))) and (not f.startswith('__')):
  274. # fields not saved
  275. # validate links
  276. if link_list and link_list.get(f):
  277. self.fields[f] = self._validate_link(link_list, f)
  278. if self.fields.get(f) is None or self.fields.get(f)=='':
  279. update_str.append("`%s`=NULL" % f)
  280. else:
  281. values.append(self.fields.get(f))
  282. update_str.append("`%s`=%s" % (f, '%s'))
  283. if values:
  284. values.append(self.name)
  285. r = webnotes.conn.sql("update `tab%s` set %s where name=%s" % \
  286. (self.doctype, ', '.join(update_str), "%s"), values)
  287. def get_valid_fields(self):
  288. global valid_fields_map
  289. if not valid_fields_map.get(self.doctype):
  290. import webnotes.model.doctype
  291. if cint(webnotes.conn.get_value("DocType", self.doctype, "issingle")):
  292. doctypelist = webnotes.model.doctype.get(self.doctype)
  293. valid_fields_map[self.doctype] = doctypelist.get_fieldnames({
  294. "fieldtype": ["not in", webnotes.model.no_value_fields]})
  295. else:
  296. valid_fields_map[self.doctype] = \
  297. webnotes.conn.get_table_columns(self.doctype)
  298. return valid_fields_map.get(self.doctype)
  299. def save(self, new=0, check_links=1, ignore_fields=0, make_autoname=1,
  300. keep_timestamps=False):
  301. res = webnotes.model.meta.get_dt_values(self.doctype,
  302. 'autoname, issingle, istable, name_case', as_dict=1)
  303. res = res and res[0] or {}
  304. if new:
  305. self.fields["__islocal"] = 1
  306. # add missing parentinfo (if reqd)
  307. if self.parent and not (self.parenttype and self.parentfield):
  308. self.update_parentinfo()
  309. if self.parent and not self.idx:
  310. self.set_idx()
  311. # if required, make new
  312. if self.fields.get('__islocal') and (not res.get('issingle')):
  313. r = self._insert(res.get('autoname'), res.get('istable'), res.get('name_case'),
  314. make_autoname, keep_timestamps = keep_timestamps)
  315. if r:
  316. return r
  317. else:
  318. if not res.get('issingle') and not webnotes.conn.exists(self.doctype, self.name):
  319. webnotes.msgprint("""This document was updated before your change. Please refresh before saving.""", raise_exception=1)
  320. # save the values
  321. self._update_values(res.get('issingle'),
  322. check_links and self.make_link_list() or {}, ignore_fields=ignore_fields,
  323. keep_timestamps=keep_timestamps)
  324. self._clear_temp_fields()
  325. def insert(self):
  326. self.fields['__islocal'] = 1
  327. self.save()
  328. return self
  329. def update_parentinfo(self):
  330. """update parent type and parent field, if not explicitly specified"""
  331. tmp = webnotes.conn.sql("""select parent, fieldname from tabDocField
  332. where fieldtype='Table' and options=%s""", self.doctype)
  333. if len(tmp)==0:
  334. raise Exception, 'Incomplete parent info in child table (%s, %s)' \
  335. % (self.doctype, self.fields.get('name', '[new]'))
  336. elif len(tmp)>1:
  337. raise Exception, 'Ambiguous parent info (%s, %s)' \
  338. % (self.doctype, self.fields.get('name', '[new]'))
  339. else:
  340. self.parenttype = tmp[0][0]
  341. self.parentfield = tmp[0][1]
  342. def set_idx(self):
  343. """set idx"""
  344. self.idx = (webnotes.conn.sql("""select max(idx) from `tab%s`
  345. where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'),
  346. (self.parent, self.parentfield))[0][0] or 0) + 1
  347. def _clear_temp_fields(self):
  348. # clear temp stuff
  349. keys = self.fields.keys()
  350. for f in keys:
  351. if f.startswith('__'):
  352. del self.fields[f]
  353. def clear_table(self, doclist, tablefield, save=0):
  354. """
  355. Clears the child records from the given `doclist` for a particular `tablefield`
  356. """
  357. from webnotes.model.utils import getlist
  358. table_list = getlist(doclist, tablefield)
  359. delete_list = [d.name for d in table_list]
  360. if delete_list:
  361. #filter doclist
  362. doclist = filter(lambda d: d.name not in delete_list, doclist)
  363. # delete from db
  364. webnotes.conn.sql("""\
  365. delete from `tab%s`
  366. where parent=%s and parenttype=%s"""
  367. % (table_list[0].doctype, '%s', '%s'),
  368. (self.name, self.doctype))
  369. self.fields['__unsaved'] = 1
  370. return webnotes.doclist(doclist)
  371. def addchild(self, fieldname, childtype = '', doclist=None):
  372. """
  373. Returns a child record of the give `childtype`.
  374. * if local is set, it does not save the record
  375. * if doclist is passed, it append the record to the doclist
  376. """
  377. from webnotes.model.doc import Document
  378. d = Document()
  379. d.parent = self.name
  380. d.parenttype = self.doctype
  381. d.parentfield = fieldname
  382. d.doctype = childtype
  383. d.docstatus = 0;
  384. d.name = ''
  385. d.owner = webnotes.session['user']
  386. d.fields['__islocal'] = 1 # for Client to identify unsaved doc
  387. if doclist != None:
  388. doclist.append(d)
  389. return d
  390. def get_values(self):
  391. """get non-null fields dict withouth standard fields"""
  392. from webnotes.model import default_fields
  393. ret = {}
  394. for key in self.fields:
  395. if key not in default_fields and self.fields[key]:
  396. ret[key] = self.fields[key]
  397. return ret
  398. def addchild(parent, fieldname, childtype = '', doclist=None):
  399. """
  400. Create a child record to the parent doc.
  401. Example::
  402. c = Document('Contact','ABC')
  403. d = addchild(c, 'contact_updates', 'Contact Update')
  404. d.last_updated = 'Phone call'
  405. d.save(1)
  406. """
  407. return parent.addchild(fieldname, childtype, doclist)
  408. def make_autoname(key, doctype=''):
  409. """
  410. Creates an autoname from the given key:
  411. **Autoname rules:**
  412. * The key is separated by '.'
  413. * '####' represents a series. The string before this part becomes the prefix:
  414. Example: ABC.#### creates a series ABC0001, ABC0002 etc
  415. * 'MM' represents the current month
  416. * 'YY' and 'YYYY' represent the current year
  417. *Example:*
  418. * DE/./.YY./.MM./.##### will create a series like
  419. DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
  420. """
  421. if not "#" in key:
  422. key = key + ".#####"
  423. n = ''
  424. l = key.split('.')
  425. series_set = False
  426. today = now_datetime()
  427. for e in l:
  428. en = ''
  429. if e.startswith('#'):
  430. if not series_set:
  431. digits = len(e)
  432. en = getseries(n, digits, doctype)
  433. series_set = True
  434. elif e=='YY':
  435. en = today.strftime('%y')
  436. elif e=='MM':
  437. en = today.strftime('%m')
  438. elif e=='DD':
  439. en = today.strftime("%d")
  440. elif e=='YYYY':
  441. en = today.strftime('%Y')
  442. else: en = e
  443. n+=en
  444. return n
  445. def getseries(key, digits, doctype=''):
  446. # series created ?
  447. if webnotes.conn.sql("select name from tabSeries where name='%s'" % key):
  448. # yes, update it
  449. webnotes.conn.sql("update tabSeries set current = current+1 where name='%s'" % key)
  450. # find the series counter
  451. r = webnotes.conn.sql("select current from tabSeries where name='%s'" % key)
  452. n = r[0][0]
  453. else:
  454. # no, create it
  455. webnotes.conn.sql("insert into tabSeries (name, current) values ('%s', 1)" % key)
  456. n = 1
  457. return ('%0'+str(digits)+'d') % n
  458. def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'):
  459. import webnotes
  460. from webnotes.model.doclist import DocList
  461. condition = ""
  462. values = []
  463. if field:
  464. condition += ' and parentfield=%s '
  465. values.append(field)
  466. if parenttype:
  467. condition += ' and parenttype=%s '
  468. values.append(parenttype)
  469. dataset = webnotes.conn.sql("""select * from `%s%s` where parent=%s %s order by idx""" \
  470. % (prefix, childtype, "%s", condition), tuple([name]+values))
  471. desc = webnotes.conn.get_description()
  472. l = DocList()
  473. for i in dataset:
  474. d = Document()
  475. d.doctype = childtype
  476. d._load_values(i, desc)
  477. l.append(d)
  478. return l
  479. def check_page_perm(doc):
  480. if doc.name=='Login Page':
  481. return
  482. if doc.publish:
  483. return
  484. if not webnotes.conn.sql("select name from `tabPage Role` where parent=%s and role='Guest'", doc.name):
  485. webnotes.response['403'] = 1
  486. raise webnotes.PermissionError, '[WNF] No read permission for %s %s' % ('Page', doc.name)
  487. def get(dt, dn='', with_children = 1, from_controller = 0, prefix = 'tab'):
  488. """
  489. Returns a doclist containing the main record and all child records
  490. """
  491. import webnotes
  492. import webnotes.model
  493. from webnotes.model.doclist import DocList
  494. dn = dn or dt
  495. # load the main doc
  496. doc = Document(dt, dn, prefix=prefix)
  497. if dt=='Page' and webnotes.session['user'] == 'Guest':
  498. check_page_perm(doc)
  499. if not with_children:
  500. # done
  501. return DocList([doc,])
  502. # get all children types
  503. tablefields = webnotes.model.meta.get_table_fields(dt)
  504. # load chilren
  505. doclist = DocList([doc,])
  506. for t in tablefields:
  507. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  508. return doclist
  509. def getsingle(doctype):
  510. """get single doc as dict"""
  511. dataset = webnotes.conn.sql("select field, value from tabSingles where doctype=%s", doctype)
  512. return dict(dataset)
  513. def copy_common_fields(from_doc, to_doc):
  514. from webnotes.model import default_fields
  515. doctype_list = webnotes.get_doctype(to_doc.doctype)
  516. for fieldname, value in from_doc.fields.items():
  517. if fieldname in default_fields:
  518. continue
  519. if doctype_list.get_field(fieldname) and to_doc.fields[fieldname] != value:
  520. to_doc.fields[fieldname] = value
  521. def validate_name(doctype, name, case=None, merge=False):
  522. if not merge:
  523. if webnotes.conn.sql('select name from `tab%s` where name=%s' % (doctype,'%s'), name):
  524. raise NameError, 'Name %s already exists' % name
  525. # no name
  526. if not name: return 'No Name Specified for %s' % doctype
  527. # new..
  528. if name.startswith('New '+doctype):
  529. raise NameError, 'There were some errors setting the name, please contact the administrator'
  530. if case=='Title Case': name = name.title()
  531. if case=='UPPER CASE': name = name.upper()
  532. name = name.strip() # no leading and trailing blanks
  533. forbidden = ['%', "'", '"', '#', '*', '?', '`']
  534. for f in forbidden:
  535. if f in name:
  536. webnotes.msgprint('%s not allowed in ID (name)' % f, raise_exception =1)
  537. return name