Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

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