source: main/branches/3D/openPLM/plmapp/views/ajax.py @ 595

Revision 595, 7.8 KB checked in by pcosquer, 9 years ago (diff)

3D branch: merge changes from trunk rev 594

Line 
1#-!- coding:utf-8 -!-
2
3############################################################################
4# openPLM - open source PLM
5# Copyright 2010 Philippe Joulaud, Pierre Cosquer
6#
7# This file is part of openPLM.
8#
9#    openPLM is free software: you can redistribute it and/or modify
10#    it under the terms of the GNU General Public License as published by
11#    the Free Software Foundation, either version 3 of the License, or
12#    (at your option) any later version.
13#
14#    openPLM is distributed in the hope that it will be useful,
15#    but WITHOUT ANY WARRANTY; without even the implied warranty of
16#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17#    GNU General Public License for more details.
18#
19#    You should have received a copy of the GNU General Public License
20#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
21#
22# Contact :
23#    Philippe Joulaud : ninoo.fr@gmail.com
24#    Pierre Cosquer : pierre.cosquer@insa-rennes.fr
25################################################################################
26
27import urlparse
28
29from django.conf import settings
30from django.contrib.auth.decorators import login_required
31from django.utils.simplejson import JSONEncoder
32from django.views.decorators.cache import cache_page
33from django.http import HttpResponse, HttpResponseForbidden
34
35import openPLM.plmapp.models as models
36from openPLM.plmapp.controllers import PLMObjectController
37import openPLM.plmapp.forms as forms
38from openPLM.plmapp.base_views import get_obj, get_obj_by_id, get_obj_from_form, \
39        json_view, get_navigate_data
40
41
42@login_required
43def ajax_search_form(request):
44    """
45    Simple view which returns the html of a search form with the data
46    of :attr:`request.GET` as initial values.
47   
48    The request must contains a get parameter *type* with a valid type,
49    otherwise, a :class:`.HttpResponseForbidden` is returned.
50    """
51    tf = forms.TypeForm(request.GET)
52    if tf.is_valid():
53        cls = models.get_all_users_and_plmobjects()[tf.cleaned_data["type"]]
54        form = forms.get_search_form(cls, request.GET)
55        return HttpResponse(form.as_table())
56    else:
57        return HttpResponseForbidden()
58
59@login_required
60@cache_page(60 * 60)
61def ajax_autocomplete(request, obj_type, field):
62    """
63    Simple ajax view for JQquery.UI.autocomplete. This returns the possible
64    completions (in JSON format) for *field*. The request must contains
65    a get parameter named *term* which should be the string used to filter
66    the results. *obj_type* must be a valid typename.
67
68    :param str obj_type: a valid typename (like ``"part"``)
69    :param str field: a valid field (like ``"name"``)
70    """
71    if not request.GET.get('term'):
72       return HttpResponse(mimetype='text/plain')
73    term = request.GET.get('term')
74    limit = 50
75    try:
76        cls = models.get_all_users_and_plmobjects()[obj_type]
77    except KeyError:
78        return HttpResponseForbidden()
79    if field not in cls._meta.get_all_field_names():
80        return HttpResponseForbidden()
81    results = cls.objects.filter(**{"%s__icontains" % field : term})
82    results = results.values_list(field, flat=True).order_by(field).distinct()
83    json = JSONEncoder().encode(list(results[:limit])) 
84    return HttpResponse(json, mimetype='application/json')
85
86@login_required
87@json_view
88def ajax_thumbnails(request, obj_type, obj_ref, obj_revi):
89    """
90    Ajax view to get files and thumbnails of a document.
91
92    :param request: :class:`django.http.QueryDict`
93    :param obj_type: :attr:`.PLMObject.type`
94    :type obj_type: str
95    :param obj_ref: :attr:`.PLMObject.reference`
96    :type obj_ref: str
97    :param obj_revi: :attr:`.PLMObject.revision`
98    :type obj_revi: str
99    """
100    obj = get_obj(obj_type, obj_ref, obj_revi, request.user)
101    files = []
102    doc = "|".join((obj_type, obj_ref, obj_revi))
103    for f in obj.files:
104        if f.thumbnail:
105            img = f.thumbnail.url
106        else:
107            img = urlparse.urljoin(settings.MEDIA_URL, "img/image-missing.png")
108        files.append((f.filename, "/file/%d/" % f.id, img))
109    return dict(files=files, doc=doc)
110
111
112@login_required
113@json_view
114def ajax_navigate(request, obj_type, obj_ref, obj_revi):
115    context = get_navigate_data(request, obj_type, obj_ref, obj_revi)
116    data = {
117            "img" : context["picture_path"],
118            "width" : context["img_width"],
119            "height" : context["img_height"],
120            "divs" : context["map_areas"],
121            "left" : context["x_img_position"],
122            "top" : context["y_img_position"],
123            "form" : context["filter_object_form"].as_ul(),
124            "center_x" : context["center_x"],
125            "center_y" : context["center_y"],
126            }
127    return data
128
129@login_required
130@json_view
131def ajax_add_child(request, part_id):
132    part = get_obj_by_id(part_id, request.user)
133    data = {}
134    if request.GET:
135        form = forms.AddChildForm(initial=request.GET)
136    else:
137        form = forms.AddChildForm(request.POST)
138        if form.is_valid():
139            child = get_obj_from_form(form, request.user)
140            part.add_child(child, form.cleaned_data["quantity"],
141                           form.cleaned_data["order"])
142            return {"result" : "ok"}
143        else:
144            data["result"] = "error"
145            data["error"] = "invalid form"
146    for field in ("type", "reference", "revision"):
147        form.fields[field].widget.attrs['readonly'] = 'on'
148    data.update({
149            "parent" : {
150                "id" : part.id,
151                "type" : part.type,
152                "reference" : part.reference,
153                "revision" : part.revision,
154                },
155            "form" : form.as_table()
156           })
157    return data
158
159@login_required
160@json_view
161def ajax_can_add_child(request, part_id):
162    part = get_obj_by_id(part_id, request.user)
163    data = {"can_add" : False}
164    if part.is_part and request.GET:
165        form = forms.AddRelPartForm(request.GET)
166        if form.is_valid():
167            child = get_obj_from_form(form, request.user)
168            data["can_add"] = part.can_add_child(child)
169    return data
170
171@login_required
172@json_view
173def ajax_attach(request, plmobject_id):
174    plmobject = get_obj_by_id(plmobject_id, request.user)
175    data = {}
176    if request.GET:
177        form = forms.AddRelPartForm(initial=request.GET)
178    else:
179        form = forms.AddRelPartForm(request.POST)
180        if form.is_valid():
181            attached = get_obj_from_form(form, request.user)
182            if hasattr(plmobject, "attach_to_document"):
183                plmobject.attach_to_document(attached)
184            elif hasattr(plmobject, "attach_to_part"):
185                plmobject.attach_to_part(attached)
186            return {"result" : "ok"}
187        else:
188            data["result"] = "error"
189            data["error"] = "invalid form"
190    for field in ("type", "reference", "revision"):
191        form.fields[field].widget.attrs['readonly'] = 'on'
192    data.update({
193            "plmobject" : {
194                "id" : plmobject.id,
195                "type" : plmobject.type,
196                "reference" : plmobject.reference,
197                "revision" : plmobject.revision,
198                },
199            "form" : form.as_table()
200           })
201    return data
202
203@login_required
204@json_view
205def ajax_can_attach(request, plmobject_id):
206    plmobject = get_obj_by_id(plmobject_id, request.user)
207    data = {"can_attach" : False}
208    if isinstance(plmobject, PLMObjectController) and request.GET:
209        form = forms.AddRelPartForm(request.GET)
210        if form.is_valid():
211            attached = get_obj_from_form(form, request.user)
212            if attached.check_readable(False):
213                if hasattr(plmobject, "can_attach_document"):
214                    data["can_attach"] = plmobject.can_attach_document(attached)
215                elif hasattr(plmobject, "can_attach_part"):
216                    data["can_attach"] = plmobject.can_attach_part(attached)
217    return data
218
Note: See TracBrowser for help on using the repository browser.