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.
 
 
 
 
 
 

727 rivejä
20 KiB

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