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

Revision 662, 7.9 KB checked in by pcosquer, 9 years ago (diff)

3D branch: merge changes from trunk (rev [661])

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(str(r) for r in 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                           form.cleaned_data["unit"])
143            return {"result" : "ok"}
144        else:
145            data["result"] = "error"
146            data["error"] = "invalid form"
147    for field in ("type", "reference", "revision"):
148        form.fields[field].widget.attrs['readonly'] = 'on'
149    data.update({
150            "parent" : {
151                "id" : part.id,
152                "type" : part.type,
153                "reference" : part.reference,
154                "revision" : part.revision,
155                },
156            "form" : form.as_table()
157           })
158    return data
159
160@login_required
161@json_view
162def ajax_can_add_child(request, part_id):
163    part = get_obj_by_id(part_id, request.user)
164    data = {"can_add" : False}
165    if part.is_part and request.GET:
166        form = forms.AddRelPartForm(request.GET)
167        if form.is_valid():
168            child = get_obj_from_form(form, request.user)
169            data["can_add"] = part.can_add_child(child)
170    return data
171
172@login_required
173@json_view
174def ajax_attach(request, plmobject_id):
175    plmobject = get_obj_by_id(plmobject_id, request.user)
176    data = {}
177    if request.GET:
178        form = forms.AddRelPartForm(initial=request.GET)
179    else:
180        form = forms.AddRelPartForm(request.POST)
181        if form.is_valid():
182            attached = get_obj_from_form(form, request.user)
183            if hasattr(plmobject, "attach_to_document"):
184                plmobject.attach_to_document(attached)
185            elif hasattr(plmobject, "attach_to_part"):
186                plmobject.attach_to_part(attached)
187            return {"result" : "ok"}
188        else:
189            data["result"] = "error"
190            data["error"] = "invalid form"
191    for field in ("type", "reference", "revision"):
192        form.fields[field].widget.attrs['readonly'] = 'on'
193    data.update({
194            "plmobject" : {
195                "id" : plmobject.id,
196                "type" : plmobject.type,
197                "reference" : plmobject.reference,
198                "revision" : plmobject.revision,
199                },
200            "form" : form.as_table()
201           })
202    return data
203
204@login_required
205@json_view
206def ajax_can_attach(request, plmobject_id):
207    plmobject = get_obj_by_id(plmobject_id, request.user)
208    data = {"can_attach" : False}
209    if isinstance(plmobject, PLMObjectController) and request.GET:
210        form = forms.AddRelPartForm(request.GET)
211        if form.is_valid():
212            attached = get_obj_from_form(form, request.user)
213            if attached.check_readable(False):
214                if hasattr(plmobject, "can_attach_document"):
215                    data["can_attach"] = plmobject.can_attach_document(attached)
216                elif hasattr(plmobject, "can_attach_part"):
217                    data["can_attach"] = plmobject.can_attach_part(attached)
218    return data
219
Note: See TracBrowser for help on using the repository browser.