Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

304 rindas
8.9 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import frappe
  5. from frappe import _
  6. import frappe.model
  7. import frappe.utils
  8. import json, os
  9. from six import iteritems, string_types
  10. '''
  11. Handle RESTful requests that are mapped to the `/api/resource` route.
  12. Requests via FrappeClient are also handled here.
  13. '''
  14. @frappe.whitelist()
  15. def get_list(doctype, fields=None, filters=None, order_by=None,
  16. limit_start=None, limit_page_length=20):
  17. '''Returns a list of records by filters, fields, ordering and limit
  18. :param doctype: DocType of the data to be queried
  19. :param fields: fields to be returned. Default is `name`
  20. :param filters: filter list by this dict
  21. :param order_by: Order by this fieldname
  22. :param limit_start: Start at this index
  23. :param limit_page_length: Number of records to be returned (default 20)'''
  24. return frappe.get_list(doctype, fields=fields, filters=filters, order_by=order_by,
  25. limit_start=limit_start, limit_page_length=limit_page_length, ignore_permissions=False)
  26. @frappe.whitelist()
  27. def get(doctype, name=None, filters=None):
  28. '''Returns a document by name or filters
  29. :param doctype: DocType of the document to be returned
  30. :param name: return document of this `name`
  31. :param filters: If name is not set, filter by these values and return the first match'''
  32. if filters and not name:
  33. name = frappe.db.get_value(doctype, json.loads(filters))
  34. if not name:
  35. frappe.throw(_("No document found for given filters"))
  36. doc = frappe.get_doc(doctype, name)
  37. if not doc.has_permission("read"):
  38. raise frappe.PermissionError
  39. return frappe.get_doc(doctype, name).as_dict()
  40. @frappe.whitelist()
  41. def get_value(doctype, fieldname, filters=None, as_dict=True, debug=False):
  42. '''Returns a value form a document
  43. :param doctype: DocType to be queried
  44. :param fieldname: Field to be returned (default `name`)
  45. :param filters: dict or string for identifying the record'''
  46. if not frappe.has_permission(doctype):
  47. frappe.throw(_("Not permitted"), frappe.PermissionError)
  48. try:
  49. filters = json.loads(filters)
  50. except (TypeError, ValueError):
  51. # filters are not passesd, not json
  52. pass
  53. try:
  54. fieldname = json.loads(fieldname)
  55. except (TypeError, ValueError):
  56. # name passed, not json
  57. pass
  58. # check whether the used filters were really parseable and usable
  59. # and did not just result in an empty string or dict
  60. if not filters:
  61. filters = None
  62. return frappe.db.get_value(doctype, filters, fieldname, as_dict=as_dict, debug=debug)
  63. @frappe.whitelist()
  64. def set_value(doctype, name, fieldname, value=None):
  65. '''Set a value using get_doc, group of values
  66. :param doctype: DocType of the document
  67. :param name: name of the document
  68. :param fieldname: fieldname string or JSON / dict with key value pair
  69. :param value: value if fieldname is JSON / dict'''
  70. if fieldname!="idx" and fieldname in frappe.model.default_fields:
  71. frappe.throw(_("Cannot edit standard fields"))
  72. if not value:
  73. values = fieldname
  74. if isinstance(fieldname, string_types):
  75. try:
  76. values = json.loads(fieldname)
  77. except ValueError:
  78. values = {fieldname: ''}
  79. else:
  80. values = {fieldname: value}
  81. doc = frappe.db.get_value(doctype, name, ["parenttype", "parent"], as_dict=True)
  82. if doc and doc.parent and doc.parenttype:
  83. doc = frappe.get_doc(doc.parenttype, doc.parent)
  84. child = doc.getone({"doctype": doctype, "name": name})
  85. child.update(values)
  86. else:
  87. doc = frappe.get_doc(doctype, name)
  88. doc.update(values)
  89. doc.save()
  90. return doc.as_dict()
  91. @frappe.whitelist()
  92. def insert(doc=None):
  93. '''Insert a document
  94. :param doc: JSON or dict object to be inserted'''
  95. if isinstance(doc, string_types):
  96. doc = json.loads(doc)
  97. if doc.get("parent") and doc.get("parenttype"):
  98. # inserting a child record
  99. parent = frappe.get_doc(doc.get("parenttype"), doc.get("parent"))
  100. parent.append(doc.get("parentfield"), doc)
  101. parent.save()
  102. return parent.as_dict()
  103. else:
  104. doc = frappe.get_doc(doc).insert()
  105. return doc.as_dict()
  106. @frappe.whitelist()
  107. def insert_many(docs=None):
  108. '''Insert multiple documents
  109. :param docs: JSON or list of dict objects to be inserted in one request'''
  110. if isinstance(docs, string_types):
  111. docs = json.loads(docs)
  112. out = []
  113. if len(docs) > 200:
  114. frappe.throw(_('Only 200 inserts allowed in one request'))
  115. for doc in docs:
  116. if doc.get("parent") and doc.get("parenttype"):
  117. # inserting a child record
  118. parent = frappe.get_doc(doc.get("parenttype"), doc.get("parent"))
  119. parent.append(doc.get("parentfield"), doc)
  120. parent.save()
  121. out.append(parent.name)
  122. else:
  123. doc = frappe.get_doc(doc).insert()
  124. out.append(doc.name)
  125. return out
  126. @frappe.whitelist()
  127. def save(doc):
  128. '''Update (save) an existing document
  129. :param doc: JSON or dict object with the properties of the document to be updated'''
  130. if isinstance(doc, string_types):
  131. doc = json.loads(doc)
  132. doc = frappe.get_doc(doc).save()
  133. return doc.as_dict()
  134. @frappe.whitelist()
  135. def rename_doc(doctype, old_name, new_name, merge=False):
  136. '''Rename document
  137. :param doctype: DocType of the document to be renamed
  138. :param old_name: Current `name` of the document to be renamed
  139. :param new_name: New `name` to be set'''
  140. new_name = frappe.rename_doc(doctype, old_name, new_name, merge=merge)
  141. return new_name
  142. @frappe.whitelist()
  143. def submit(doc):
  144. '''Submit a document
  145. :param doc: JSON or dict object to be submitted remotely'''
  146. if isinstance(doc, string_types):
  147. doc = json.loads(doc)
  148. doc = frappe.get_doc(doc)
  149. doc.submit()
  150. return doc.as_dict()
  151. @frappe.whitelist()
  152. def cancel(doctype, name):
  153. '''Cancel a document
  154. :param doctype: DocType of the document to be cancelled
  155. :param name: name of the document to be cancelled'''
  156. wrapper = frappe.get_doc(doctype, name)
  157. wrapper.cancel()
  158. return wrapper.as_dict()
  159. @frappe.whitelist()
  160. def delete(doctype, name):
  161. '''Delete a remote document
  162. :param doctype: DocType of the document to be deleted
  163. :param name: name of the document to be deleted'''
  164. frappe.delete_doc(doctype, name)
  165. @frappe.whitelist()
  166. def set_default(key, value, parent=None):
  167. """set a user default value"""
  168. frappe.db.set_default(key, value, parent or frappe.session.user)
  169. frappe.clear_cache(user=frappe.session.user)
  170. @frappe.whitelist()
  171. def make_width_property_setter(doc):
  172. '''Set width Property Setter
  173. :param doc: Property Setter document with `width` property'''
  174. if isinstance(doc, string_types):
  175. doc = json.loads(doc)
  176. if doc["doctype"]=="Property Setter" and doc["property"]=="width":
  177. frappe.get_doc(doc).insert(ignore_permissions = True)
  178. @frappe.whitelist()
  179. def bulk_update(docs):
  180. '''Bulk update documents
  181. :param docs: JSON list of documents to be updated remotely. Each document must have `docname` property'''
  182. docs = json.loads(docs)
  183. failed_docs = []
  184. for doc in docs:
  185. try:
  186. ddoc = {key: val for key, val in iteritems(doc) if key not in ['doctype', 'docname']}
  187. doctype = doc['doctype']
  188. docname = doc['docname']
  189. doc = frappe.get_doc(doctype, docname)
  190. doc.update(ddoc)
  191. doc.save()
  192. except:
  193. failed_docs.append({
  194. 'doc': doc,
  195. 'exc': frappe.utils.get_traceback()
  196. })
  197. return {'failed_docs': failed_docs}
  198. @frappe.whitelist()
  199. def has_permission(doctype, docname, perm_type="read"):
  200. '''Returns a JSON with data whether the document has the requested permission
  201. :param doctype: DocType of the document to be checked
  202. :param docname: `name` of the document to be checked
  203. :param perm_type: one of `read`, `write`, `create`, `submit`, `cancel`, `report`. Default is `read`'''
  204. # perm_type can be one of read, write, create, submit, cancel, report
  205. return {"has_permission": frappe.has_permission(doctype, perm_type.lower(), docname)}
  206. @frappe.whitelist()
  207. def get_password(doctype, name, fieldname):
  208. '''Return a password type property. Only applicable for System Managers
  209. :param doctype: DocType of the document that holds the password
  210. :param name: `name` of the document that holds the password
  211. :param fieldname: `fieldname` of the password property
  212. '''
  213. frappe.only_for("System Manager")
  214. return frappe.get_doc(doctype, name).get_password(fieldname)
  215. @frappe.whitelist()
  216. def get_js(items):
  217. '''Load JS code files. Will also append translations
  218. and extend `frappe._messages`
  219. :param items: JSON list of paths of the js files to be loaded.'''
  220. items = json.loads(items)
  221. out = []
  222. for src in items:
  223. src = src.strip("/").split("/")
  224. if ".." in src or src[0] != "assets":
  225. frappe.throw(_("Invalid file path: {0}").format("/".join(src)))
  226. contentpath = os.path.join(frappe.local.sites_path, *src)
  227. with open(contentpath, "r") as srcfile:
  228. code = frappe.utils.cstr(srcfile.read())
  229. if frappe.local.lang != "en":
  230. messages = frappe.get_lang_dict("jsfile", contentpath)
  231. messages = json.dumps(messages)
  232. code += "\n\n$.extend(frappe._messages, {})".format(messages)
  233. out.append(code)
  234. return out
  235. @frappe.whitelist(allow_guest=True)
  236. def get_time_zone():
  237. '''Returns default time zone'''
  238. return {"time_zone": frappe.defaults.get_defaults().get("time_zone")}