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.
 
 
 
 
 
 

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