def test_import_bom_valid(self): """ Tests an import of a valid bom. """ self.import_csv(PLMObjectsImporter, self.get_valid_rows()) csv_rows = self.get_valid_bom() objects = self.import_csv(BOMImporter, csv_rows) # objects should be [parent1, child1, ...] self.assertEquals((len(csv_rows) - 1) * 2, len(objects)) # first row parent = get_obj("Part", "p1", "a", self.user) child = get_obj("SinglePart", "sp1", "s", self.user) c = parent.get_children()[0] self.assertEquals(c.link.parent.id, parent.id) self.assertEquals(c.link.child.id, child.id) self.assertEquals(c.link.quantity, 10) self.assertEquals(c.link.order, 15) # second row parent = get_obj("SinglePart", "sp1", "s", self.user) child = get_obj("SinglePart", "sp2", "s", self.user) c = parent.get_children()[0] self.assertEquals(c.link.parent.id, parent.id) self.assertEquals(c.link.child.id, child.id) self.assertEquals(c.link.quantity, 10.5) self.assertEquals(c.link.order, 16)
def download_archive(request, obj_type, obj_ref, obj_revi): """ View to download all files from a document/part. .. include:: views_params.txt """ obj = get_obj(obj_type, obj_ref, obj_revi, request.user) obj.check_readable() d_o_u = "document__owner__username" if obj.is_document: files = obj.files.select_related(d_o_u) elif obj.is_part and "cad" in request.GET: files = obj.get_cad_files() elif obj.is_part: links = obj.get_attached_documents() docs = (link.document for link in links) files = itertools.chain(*(doc.files.select_related(d_o_u) for doc in docs)) else: return HttpResponseForbidden() archive_format = request.GET.get("format") if archive_format in ARCHIVE_FORMATS: name = "%s_%s.%s" % (obj_ref, obj_revi, archive_format) content_type = guess_type(name, False)[0] if not content_type: content_type = 'application/octet-stream' content = generate_archive(files, archive_format) response = StreamingHttpResponse(content, content_type=content_type) response['Content-Disposition'] = 'attachment; filename="%s"' % name return response return HttpResponseForbidden()
def test_view_csv_all(self): """ Complex test that simulate an upload of a csv file (complete process). """ # upload a csv file csv_file = StringIO.StringIO() csv_file.name = "data.csv" UnicodeWriter(csv_file).writerows(self.get_valid_rows()) csv_file.seek(0) response = self.client.post("/import/csv/", {"encoding":"utf_8", "filename":"data.csv", "file":csv_file}, follow=True) csv_file.close() # load the second page url = response.redirect_chain[0][0] response2 = self.client.get(url) self.assertEquals(2, response2.context["step"]) preview = response2.context["preview"] self.assertFalse(None in preview.guessed_headers) formset = response2.context["headers_formset"] # validate and import the file data = {} for key, value in formset.management_form.initial.iteritems(): data["form-" + key] = value or "" for i, d in enumerate(formset.initial): for key, value in d.iteritems(): data["form-%d-%s" % (i, key)] = value data['form-%d-ORDER' % i] = str(i) response3 = self.client.post(url, data, follow=True) url_done = response3.redirect_chain[-1][0] self.assertEquals("http://testserver/import/done/", url_done) # check an item sp1 = get_obj("SinglePart", "sp1", "s", self.user) self.assertEquals("SP1", sp1.name)
def ajax_thumbnails(request, obj_type, obj_ref, obj_revi, date=None): """ Ajax view to get files and thumbnails of a document. :param request: :class:`django.http.QueryDict` :param obj_type: :attr:`.PLMObject.type` :type obj_type: str :param obj_ref: :attr:`.PLMObject.reference` :type obj_ref: str :param obj_revi: :attr:`.PLMObject.revision` :type obj_revi: str """ obj = get_obj(obj_type, obj_ref, obj_revi, request.user) files = [] doc = "|".join((obj_type, obj_ref, obj_revi)) if date: d = datetime.datetime(*time.strptime(date, TIME_FORMAT)[:6]) fileset = obj.documentfile_set.filter(ctime__lte=d).exclude(end_time__gt=d) else: fileset = obj.files missing_url = urlparse.urljoin(settings.STATIC_URL, "img/image-missing.png") for f in fileset: if f.thumbnail: img = f.thumbnail.url else: img = missing_url files.append({ "name": f.filename, "url": "/file/%d/" % f.id, "img": img, "revision" : f.revision, "deleted" : f.deleted, "deprecated" : f.deprecated, }) return dict(files=files, doc=doc)
def test_import_valid(self): csv_rows = self.get_valid_rows() objects = self.import_csv(PLMObjectsImporter, csv_rows) self.assertEquals(len(csv_rows) - 1, len(objects)) sp1 = get_obj("SinglePart", "sp1", "s", self.user) self.assertEquals("SP1", sp1.name) self.assertEqual(0, len(mail.outbox)) self.assertEqual(1, len(self.sent_tasks["openPLM.plmapp.tasks.update_indexes"]))
def get_doc(self, path): p = path.strip("/").split("/") if len(p) >= 3: try: return get_obj(p[0], p[1], p[2], self.user), p[3:] except: raise BackendResourceNotFoundException(path) return None, p
def test_import_valid(self): csv_rows = self.get_valid_rows() objects = self.import_csv(PLMObjectsImporter, csv_rows) self.assertEquals(len(csv_rows) - 1, len(objects)) sp1 = get_obj("SinglePart", "sp1", "s", self.user) self.assertEquals("SP1", sp1.name) self.assertEqual(0, len(mail.outbox)) self.assertEqual( 1, len(self.sent_tasks["openPLM.plmapp.tasks.update_indexes"]))
def parse_row(self, line, row): from openPLM.plmapp.views.base import get_obj ptype, preference, prevision = self.get_values(row, *["parent-" + h for h in ("type", "reference", "revision")]) parent = get_obj(ptype, preference, prevision, self.user) ctype, creference, crevision = self.get_values(row, *["child-" + h for h in ("type", "reference", "revision")]) child = get_obj(ctype, creference, crevision, self.user) parent.block_mails() parent.object.no_index = True child.block_mails() child.object.no_index = True self.objects.append(parent) self.objects.append(child) qty = self.get_value(row, "quantity").replace(",", ".").replace(" ", "") quantity = float(qty) order = int(self.get_value(row, "order").replace(" ", "")) parent.add_child(child, quantity, order)
def checkout_file(request, obj_type, obj_ref, obj_revi, docfile_id): """ Manage html page for the files (:class:`DocumentFile`) checkout from the selected object. It locks the :class:`DocumentFile` and, after, calls :func:`.views.download` .. include:: views_params.txt :param docfile_id: :attr:`.DocumentFile.id` :type docfile_id_value: str """ obj = get_obj(obj_type, obj_ref, obj_revi, request.user) doc_file = models.DocumentFile.objects.get(id=docfile_id) obj.lock(doc_file) return download(request, docfile_id)
def attributes(request, obj_type, obj_ref, obj_revi): """ View that returns the object's attributes as a PDF file. """ obj = get_obj(obj_type, obj_ref, obj_revi, request.user) if hasattr(obj, "check_readable"): obj.check_readable(raise_=True) ctx = {"obj" : obj,} attributes = render_attributes(obj, obj.attributes) if hasattr(obj, "state"): attributes.append((obj.get_verbose_name("state"), obj.state.name, False)) ctx['attributes'] = attributes filename = u"%s_%s_%s.pdf" % (obj_type, obj_ref, obj_revi) return render_to_pdf('attributes.xhtml', ctx, filename)
def ajax_richtext_preview(request, obj_type, obj_ref, obj_revi): """ Ajax view to get an HTML preview of a raw content (in richtext syntax). GET paramerer: ``content`` raw content to be rendered This view returns a JSON response with one key, ``html``, the rendered content that can be included in a div element. """ content = request.GET["content"] if obj_type in ("create", "object"): return {"html": richtext(content, None)} obj = get_obj(obj_type, obj_ref, obj_revi, request.user) obj.check_readable() return {"html": richtext(content, obj)}
def test_view_csv_all(self): """ Complex test that simulate an upload of a csv file (complete process). """ # upload a csv file csv_file = StringIO.StringIO() csv_file.name = "data.csv" UnicodeWriter(csv_file).writerows(self.get_valid_rows()) csv_file.seek(0) response = self.client.post("/import/csv/", { "encoding": "utf_8", "filename": "data.csv", "file": csv_file }, follow=True) csv_file.close() # load the second page url = response.redirect_chain[0][0] response2 = self.client.get(url) self.assertEquals(2, response2.context["step"]) preview = response2.context["preview"] self.assertFalse(None in preview.guessed_headers) formset = response2.context["headers_formset"] # validate and import the file data = {} for key, value in formset.management_form.initial.iteritems(): data["form-" + key] = value or "" for i, d in enumerate(formset.initial): for key, value in d.iteritems(): data["form-%d-%s" % (i, key)] = value data['form-%d-ORDER' % i] = str(i) response3 = self.client.post(url, data, follow=True) url_done = response3.redirect_chain[-1][0] self.assertEquals("http://testserver/import/done/", url_done) # check an item sp1 = get_obj("SinglePart", "sp1", "s", self.user) self.assertEquals("SP1", sp1.name)
def display_public_3d(request, obj_ref, obj_revi): obj = get_obj("Document3D", obj_ref, obj_revi, request.user) if not obj.published and request.user.is_anonymous(): return redirect_to_login(request.get_full_path()) elif not obj.published and not obj.check_restricted_readable(False): raise Http404 ctx = init_ctx("Document3D", obj_ref, obj_revi) ctx['stl'] = False try: doc_file = obj.files.filter(models.is_stp)[0] except IndexError: doc_file = None javascript_arborescense="" try: doc_file = obj.files.filter(models.is_stl)[0] ctx["stl"] = True ctx["stl_file"] = doc_file except IndexError: pass else: product = obj.get_product(doc_file, True) javascript_arborescense = JSGenerator(product).get_js() ctx.update({ 'is_readable' : True, 'is_contributor': False, # disable the menu and the navigation_history 'object_menu' : [], 'navigation_history' : [], 'obj' : obj, 'javascript_arborescense' : javascript_arborescense, }) return r2r("public_3d_view.html", ctx, request)
def delete_management(request, obj_type, obj_ref, obj_revi, reader=False, level=None): """ View to remove a notified user or a restricted user. :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/management/delete/` The request must be a POST request containing the key ``link_id``. It should be the id of one of the :class:`.PLMObjectUserLink` related to the object. The role of this link must be :const:`.ROLE_NOTIFIED` or :class:`.ROLE_READER`. Redirects to :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/management/lifecycle/` in case of a success. """ obj = get_obj(obj_type, obj_ref, obj_revi, request.user) if request.method == "POST": try: link_id = int(request.POST["link_id"]) link = obj.users.now().get(id=link_id) obj.remove_user(link) messages.info(request, _(u"The user you have selected has been successfully deleted.")) except (KeyError, ValueError, ControllerError): return HttpResponseForbidden() return HttpResponseRedirect("../../lifecycle/")
def public(request, obj_type, obj_ref, obj_revi, template="public.html"): """ .. versionadded:: 1.1 Public view of the given object, this view is accessible to anonymous users. The object must be a published part or document. Redirects to the login page if the object is not published and the user is not authenticated. :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/public/` .. include:: views_params.txt **Template:** :file:`public.html` **Context:** ``RequestContext`` ``obj`` the controller ``object_attributes`` list of tuples(verbose attribute name, value) ``revisions`` list of published related revisions ``attached`` list of published attached documents and parts """ # do not call get_generic_data to avoid the overhead due # to a possible search and the update of the navigation history obj = get_obj(obj_type, obj_ref, obj_revi, request.user) if not (obj.is_part or obj.is_document): raise Http404 if not obj.published and request.user.is_anonymous(): return redirect_to_login(request.get_full_path()) elif not obj.published and not obj.check_restricted_readable(False): raise Http404 ctx = init_ctx(obj_type, obj_ref, obj_revi) object_attributes = render_attributes(obj, obj.published_attributes) object_attributes.insert( 4, (obj.get_verbose_name("state"), obj.state.name, False)) if request.user.is_anonymous(): test = lambda x: x.published is_contributor = False else: is_contributor = request.user.profile.is_contributor readable = request.user.plmobjectuserlink_user.now().filter(role=models.ROLE_READER)\ .values_list("plmobject_id", flat=True) test = lambda x: x.published or x.id in readable revisions = [rev for rev in obj.get_all_revisions() if test(rev)] if obj.is_part: attached = [ d.document for d in obj.get_attached_documents() if test(d.document) ] else: attached = [d.part for d in obj.get_attached_parts() if test(d.part)] ctx.update({ 'is_readable': True, 'is_contributor': is_contributor, # disable the menu and the navigation_history 'object_menu': [], 'navigation_history': [], 'obj': obj, 'object_attributes': object_attributes, 'revisions': revisions, 'attached': attached, }) return r2r(template, ctx, request)
def public(request, obj_type, obj_ref, obj_revi, template="public.html"): """ .. versionadded:: 1.1 Public view of the given object, this view is accessible to anonymous users. The object must be a published part or document. Redirects to the login page if the object is not published and the user is not authenticated. :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/public/` .. include:: views_params.txt **Template:** :file:`public.html` **Context:** ``RequestContext`` ``obj`` the controller ``object_attributes`` list of tuples(verbose attribute name, value) ``revisions`` list of published related revisions ``attached`` list of published attached documents and parts """ # do not call get_generic_data to avoid the overhead due # to a possible search and the update of the navigation history obj = get_obj(obj_type, obj_ref, obj_revi, request.user) if not (obj.is_part or obj.is_document): raise Http404 if not obj.published and request.user.is_anonymous(): return redirect_to_login(request.get_full_path()) elif not obj.published and not obj.check_restricted_readable(False): raise Http404 ctx = init_ctx(obj_type, obj_ref, obj_revi) object_attributes = render_attributes(obj, obj.published_attributes) object_attributes.insert(4, (obj.get_verbose_name("state"), obj.state.name, False)) if request.user.is_anonymous(): test = lambda x: x.published is_contributor = False else: is_contributor = request.user.profile.is_contributor readable = request.user.plmobjectuserlink_user.now().filter(role=models.ROLE_READER)\ .values_list("plmobject_id", flat=True) test = lambda x: x.published or x.id in readable revisions = [rev for rev in obj.get_all_revisions() if test(rev)] if obj.is_part: attached = [d.document for d in obj.get_attached_documents() if test(d.document)] else: attached = [d.part for d in obj.get_attached_parts() if test(d.part)] ctx.update({ 'is_readable' : True, 'is_contributor': is_contributor, # disable the menu and the navigation_history 'object_menu' : [], 'navigation_history' : [], 'obj' : obj, 'object_attributes': object_attributes, 'revisions' : revisions, 'attached' : attached, }) return r2r(template, ctx, request)
def get_object(self, request, obj_type, obj_ref, obj_revi): obj = get_obj(obj_type, obj_ref, obj_revi, request.user) obj.check_readable() return obj