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.
 
 
 
 
 
 

168 lines
4.9 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. import webnotes
  23. import webnotes.model
  24. from webnotes.model.doc import Document
  25. class DocList(list):
  26. """DocList object as a wrapper around a list"""
  27. def get(self, filters, limit=0):
  28. """pass filters as:
  29. {"key": "val", "key": ["!=", "val"],
  30. "key": ["in", "val"], "key": ["not in", "val"], "key": "^val",
  31. "key" : True (exists), "key": False (does not exist) }"""
  32. out = []
  33. for doc in self:
  34. d = isinstance(getattr(doc, "fields", None), dict) and doc.fields or doc
  35. add = True
  36. for f in filters:
  37. fval = filters[f]
  38. if fval==True:
  39. fval = ["not None", fval]
  40. elif fval==False:
  41. fval = ["None", fval]
  42. elif not isinstance(fval, list):
  43. if isinstance(fval, basestring) and fval.startswith("^"):
  44. fval = ["^", fval[1:]]
  45. else:
  46. fval = ["=", fval]
  47. if not webnotes.compare(d.get(f), fval[0], fval[1]):
  48. add = False
  49. break
  50. if add:
  51. out.append(doc)
  52. if limit and (len(out)-1)==limit:
  53. break
  54. return DocList(out)
  55. def get_distinct_values(self, fieldname):
  56. return list(set(map(lambda d: d.fields.get(fieldname), self)))
  57. def remove_items(self, filters):
  58. for d in self.get(filters):
  59. self.remove(d)
  60. def getone(self, filters):
  61. return self.get(filters, limit=1)[0]
  62. def copy(self):
  63. out = []
  64. for d in self:
  65. if isinstance(d, dict):
  66. fielddata = d
  67. else:
  68. fielddata = d.fields
  69. fielddata.update({"name": None})
  70. out.append(Document(fielddata=fielddata))
  71. return DocList(out)
  72. def filter_valid_fields(self):
  73. import webnotes.model
  74. fieldnames = {}
  75. for d in self:
  76. remove = []
  77. for f in d:
  78. if f not in fieldnames.setdefault(d.doctype,
  79. webnotes.model.get_fieldnames(d.doctype)):
  80. remove.append(f)
  81. for f in remove:
  82. del d[f]
  83. def append(self, doc):
  84. if not isinstance(doc, Document):
  85. doc = Document(fielddata=doc)
  86. self._prepare_doc(doc)
  87. super(DocList, self).append(doc)
  88. def extend(self, doclist):
  89. doclist = objectify(doclist)
  90. for doc in doclist:
  91. self._prepare_doc(doc)
  92. super(DocList, self).extend(doclist)
  93. return self
  94. def _prepare_doc(self, doc):
  95. if not doc.name:
  96. doc.fields["__islocal"] = 1
  97. if doc.parentfield:
  98. if not doc.parenttype:
  99. doc.parenttype = self[0].doctype
  100. if not doc.parent:
  101. doc.parent = self[0].name
  102. def load(doctype, name):
  103. # load main doc
  104. return objectify(load_doclist(doctype, name))
  105. def load_doclist(doctype, name):
  106. doclist = DocList([load_main(doctype, name)])
  107. # load children
  108. table_fields = map(lambda f: (f.options, name, f.fieldname, doctype),
  109. webnotes.conn.get_table_fields(doctype))
  110. for args in table_fields:
  111. children = load_children(*args)
  112. if children: doclist += children
  113. return doclist
  114. def load_main(doctype, name):
  115. """retrieves doc from database"""
  116. if webnotes.conn.is_single(doctype):
  117. doc = webnotes.conn.sql("""select field, value from `tabSingles`
  118. where doctype=%s""", doctype, as_list=1)
  119. doc = dict(doc)
  120. doc["name"] = doctype
  121. else:
  122. doc = webnotes.conn.sql("""select * from `tab%s` where name = %s""" % \
  123. (doctype, "%s"), name, as_dict=1)
  124. if not doc:
  125. raise NameError, """%s: "%s" does not exist""" % (doctype, name)
  126. doc = doc[0]
  127. doc["doctype"] = doctype
  128. return doc
  129. def load_children(options, parent, parentfield, parenttype):
  130. """load children based on options, parentfield, parenttype and parent"""
  131. options = options.split("\n")[0].strip()
  132. return webnotes.conn.sql("""select *, "%s" as doctype from `tab%s` where parent = %s
  133. and parentfield = %s and parenttype = %s order by idx""" % (options, options, "%s", "%s", "%s"),
  134. (parent, parentfield, parenttype), as_dict=1)
  135. def objectify(doclist):
  136. from webnotes.model.doc import Document
  137. return map(lambda d: isinstance(d, Document) and d or Document(d), doclist)