Ejemplo n.º 1
0
def edit_children(request, obj_type, obj_ref, obj_revi):
    """
    Manage html page which edits the chidren of the selected object.
    Possibility to modify the `.ParentChildLink.order`, the `.ParentChildLink.quantity` and to
    desactivate the `.ParentChildLink`
    It computes a context dictionnary based on
    
    .. include:: views_params.txt 
    """
    obj, ctx = get_generic_data(request, obj_type, obj_ref, obj_revi)
    
    if not hasattr(obj, "get_children"):
        # TODO
        raise TypeError()
    if request.method == "POST":
        formset = get_children_formset(obj, request.POST)
        if formset.is_valid():
            obj.update_children(formset)
            return HttpResponseRedirect("..")
    else:
        formset = get_children_formset(obj)
    extra_columns = []
    extra_fields = []
    for PCLE in models.get_PCLEs(obj.object):
        fields = PCLE.get_visible_fields()
        if fields:
            extra_columns.extend((f, PCLE._meta.get_field(f).verbose_name) 
                    for f in fields)
            prefix = PCLE._meta.module_name
            extra_fields.extend('%s_%s' % (prefix, f) for f in fields)
    ctx.update({'current_page':'BOM-child',
                'extra_columns' : extra_columns,
                'extra_fields' : extra_fields,
                'children_formset': formset, })
    return r2r('DisplayObjectChildEdit.htm', ctx, request)
Ejemplo n.º 2
0
    def modify_child(self, child, new_quantity, new_order, new_unit,
            **extension_data):
        """
        Modifies information about *child*.

        :param child: added child
        :type child: :class:`.Part`
        :param new_quantity: amount of *child*
        :type new_quantity: positive float
        :param new_order: order
        :type new_order: positive int
        
        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        :raises: :exc:`.PermissionError` if :attr:`object` is not editable.
        """
        
        self.check_permission("owner")
        self.check_editable()
        if isinstance(child, PLMObjectController):
            child = child.object
        if new_order < 0 or new_quantity < 0:
            raise ValueError("Quantity or order is negative")
        link = models.ParentChildLink.objects.get(parent=self.object,
                                                  child=child, end_time=None)
        original_extension_data = link.get_extension_data()

        if (link.quantity == new_quantity and link.order == new_order and
            link.unit == new_unit and original_extension_data == extension_data):
            # do not make an update if it is useless
            return
        link.end_time = datetime.datetime.today()
        link.save()
        # make a new link
        link2, extensions = link.clone(quantity=new_quantity, order=new_order,
                       unit=new_unit, end_time=None, extension_data=extension_data)
        details = ""
        if link.quantity != new_quantity:
            details += "quantity changes from %f to %f\n" % (link.quantity, new_quantity)
        if link.order != new_order:
            details += "order changes from %d to %d" % (link.order, new_order)
        if link.unit != new_unit:
            details += "unit changes from %s to %s" % (link.unit, new_unit)

        # TODO: details of extension changes

        self._save_histo("Modify - %s" % link.ACTION_NAME, details)
        link2.save(force_insert=True)
        # save cloned extensions
        for ext in extensions:
            ext.link = link2
            ext.save(force_insert=True)
        # add new extensions
        for PCLE in models.get_PCLEs(self.object):
            name = PCLE._meta.module_name
            if (name in extension_data and name not in original_extension_data
                and PCLE.one_per_link()):
                ext = PCLE(link=link2, **extension_data[name])
                ext.save()
Ejemplo n.º 3
0
 def __init__(self, parent, *args, **kwargs):
     super(AddChildForm, self).__init__(*args, **kwargs)
     self._PCLEs = defaultdict(list)
     for PCLE in m.get_PCLEs(parent):
         for field in PCLE.get_editable_fields():
             model_field = PCLE._meta.get_field(field)
             form_field = model_field.formfield()
             field_name = "%s_%s" % (PCLE._meta.module_name, field)
             self.fields[field_name] = form_field
             self._PCLEs[PCLE].append(field)
Ejemplo n.º 4
0
def edit_children(request, obj_type, obj_ref, obj_revi):
    """
    View to edit a BOM.

    :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/bom-child/edit/`

    .. include:: views_params.txt

    **Template:**

    :file:`parts/bom_edit.html`

    **Context:**

    ``RequestContext``

    ``children_formset``
        a formset to edit the BOM

    ``extra_columns``
        a list of extra columns that are displayed

    ``extra_fields``
        a list of extra fields that are editable

    """
    obj, ctx = get_generic_data(request, obj_type, obj_ref, obj_revi)

    if not hasattr(obj, "get_children"):
        return HttpResponseBadRequest("object must be a part")
    if request.method == "POST":
        formset = forms.get_children_formset(obj, request.POST)
        if formset.is_valid():
            obj.update_children(formset)
            return HttpResponseRedirect("..")
    else:
        formset = forms.get_children_formset(obj)
    extra_columns = []
    extra_fields = []
    for PCLE in models.get_PCLEs(obj.object):
        fields = PCLE.get_visible_fields()
        if fields:
            extra_columns.extend(
                (f, PCLE._meta.get_field(f).verbose_name) for f in fields)
            prefix = PCLE._meta.module_name
            extra_fields.extend('%s_%s' % (prefix, f) for f in fields)
    ctx.update({
        'current_page': 'BOM-child',
        'extra_columns': extra_columns,
        'extra_fields': extra_fields,
        'children_formset': formset,
    })
    return r2r('parts/bom_edit.html', ctx, request)
Ejemplo n.º 5
0
def edit_children(request, obj_type, obj_ref, obj_revi):
    """
    View to edit a BOM.

    :url: :samp:`/object/{obj_type}/{obj_ref}/{obj_revi}/bom-child/edit/`

    .. include:: views_params.txt

    **Template:**

    :file:`parts/bom_edit.html`

    **Context:**

    ``RequestContext``

    ``children_formset``
        a formset to edit the BOM

    ``extra_columns``
        a list of extra columns that are displayed

    ``extra_fields``
        a list of extra fields that are editable

    """
    obj, ctx = get_generic_data(request, obj_type, obj_ref, obj_revi)

    if not hasattr(obj, "get_children"):
        return HttpResponseBadRequest("object must be a part")
    if request.method == "POST":
        formset = forms.get_children_formset(obj, request.POST)
        if formset.is_valid():
            obj.update_children(formset)
            return HttpResponseRedirect("..")
    else:
        formset = forms.get_children_formset(obj)
    extra_columns = []
    extra_fields = []
    for PCLE in models.get_PCLEs(obj.object):
        fields = PCLE.get_visible_fields()
        if fields:
            extra_columns.extend((f, PCLE._meta.get_field(f).verbose_name)
                    for f in fields)
            prefix = PCLE._meta.module_name
            extra_fields.extend('%s_%s' % (prefix, f) for f in fields)
    ctx.update({'current_page':'BOM-child',
                'extra_columns' : extra_columns,
                'extra_fields' : extra_fields,
                'children_formset': formset, })
    return r2r('parts/bom_edit.html', ctx, request)
Ejemplo n.º 6
0
def display_object_child(request, obj_type, obj_ref, obj_revi):
    """
    Manage html page which displays the chidren of the selected object.
    It computes a context dictionnary based on
    
    .. include:: views_params.txt 
    """
    obj, ctx = get_generic_data(request, obj_type, obj_ref, obj_revi)
    
    if not hasattr(obj, "get_children"):
        # TODO
        raise TypeError()
    date = None
    level = "first"
    if request.GET:
        display_form = DisplayChildrenForm(request.GET)
        if display_form.is_valid():
            date = display_form.cleaned_data["date"]
            level = display_form.cleaned_data["level"]
    else:
        display_form = DisplayChildrenForm(initial={"date" : datetime.datetime.now(),
                                                    "level" : "first"})
    max_level = 1 if level == "first" else -1
    children = obj.get_children(max_level, date=date)
    if level == "last" and children:
        maximum = max(children, key=attrgetter("level")).level
        children = (c for c in children if c.level == maximum)
    children = list(children)
    extra_columns = []
    extension_data = defaultdict(dict)
    for PCLE in models.get_PCLEs(obj.object):
        fields = PCLE.get_visible_fields()
        if fields:
            extra_columns.extend((f, PCLE._meta.get_field(f).verbose_name) 
                    for f in fields)
            for child in children:
                link = child.link
                for field in fields:
                    try:
                        e = PCLE.objects.get(link=link)
                        extension_data[link][field] = getattr(e, field)
                    except PCLE.DoesNotExist:
                        extension_data[link][field] = ""
    ctx.update({'current_page':'BOM-child',
                'children': children,
                'extra_columns' : extra_columns,
                'extension_data': extension_data,
                "display_form" : display_form})
    return r2r('DisplayObjectChild.htm', ctx, request)
Ejemplo n.º 7
0
    def __init__(self, parent, *args, **kwargs):
        super(AddChildForm, self).__init__(*args, **kwargs)
        self._PCLEs = defaultdict(list)
        initial = kwargs.get("initial")
        if not self.is_bound and (initial is None or "order" not in initial):
            orders = list(parent.parentchildlink_parent.values_list('order', flat=True))
            initial_order = max(orders) + 10 if orders else 10
            self.fields["order"].initial = initial_order

        for PCLE in m.get_PCLEs(parent):
            for field in PCLE.get_editable_fields():
                model_field = PCLE._meta.get_field(field)
                form_field = model_field.formfield()
                field_name = "%s_%s" % (PCLE._meta.module_name, field)
                self.fields[field_name] = form_field
                self._PCLEs[PCLE].append(field)
Ejemplo n.º 8
0
    def __init__(self, parent, *args, **kwargs):
        super(AddChildForm, self).__init__(*args, **kwargs)
        self._PCLEs = defaultdict(list)
        initial = kwargs.get("initial")
        if not self.is_bound and (initial is None or "order" not in initial):
            orders = list(
                parent.parentchildlink_parent.values_list('order', flat=True))
            initial_order = max(orders) + 10 if orders else 10
            self.fields["order"].initial = initial_order

        for PCLE in m.get_PCLEs(parent):
            for field in PCLE.get_editable_fields():
                model_field = PCLE._meta.get_field(field)
                form_field = model_field.formfield()
                field_name = "%s_%s" % (PCLE._meta.module_name, field)
                self.fields[field_name] = form_field
                self._PCLEs[PCLE].append(field)
Ejemplo n.º 9
0
    def add_child(self, child, quantity, order, unit=DEFAULT_UNIT, **extension_data):
        """
        Adds *child* to *self*.

        :param child: added child
        :type child: :class:`.Part`
        :param quantity: amount of *child*
        :type quantity: positive float
        :param order: order
        :type order: positive int
        :param unit: a valid unit
        
        :raises: :exc:`ValueError` if *child* is already a child or a parent.
        :raises: :exc:`ValueError` if *quantity* or *order* are negative.
        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
            :attr:`object`.
        :raises: :exc:`.PermissionError` if :attr:`object` is not editable.
        """

        if isinstance(child, PLMObjectController):
            child = child.object
        self.check_add_child(child)
        # check if child is not already a direct child
        if child.pk in (c.link.child.pk for c in self.get_children(1)):
            raise ValueError("%s is already a child of %s" % (child, self.object))
        if order < 0 or quantity < 0:
            raise ValueError("Quantity or order is negative")
        # data are valid : create the link
        link = models.ParentChildLink()
        link.parent = self.object
        link.child = child
        link.quantity = quantity
        link.order = order
        link.unit = unit
        link.save()
        # handle plces
        for PCLE in models.get_PCLEs(self.object):
            name = PCLE._meta.module_name
            if name in extension_data and PCLE.one_per_link():
                ext = PCLE(link=link, **extension_data[name])
                ext.save()
        # records creation in history
        self._save_histo(link.ACTION_NAME,
                         "parent : %s\nchild : %s" % (self.object, child))
Ejemplo n.º 10
0
 def add_fields(self, form, index):
     super(BaseChildrenFormSet, self).add_fields(form, index)
     form.PCLEs = defaultdict(list)
     parent = form.instance.parent.get_leaf_object()
     for PCLE in m.get_PCLEs(parent):
         if not PCLE.one_per_link():
             continue
         try:
             ext = PCLE.objects.get(link=form.instance)
         except PCLE.DoesNotExist:
             ext = None
         for field in PCLE.get_editable_fields():
             initial = getattr(ext, field, None)
             model_field = PCLE._meta.get_field(field)
             form_field = model_field.formfield(initial=initial)
             field_name = "%s_%s" % (PCLE._meta.module_name, field)
             if isinstance(form_field.widget, forms.TextInput):
                 form_field.widget.attrs["size"] = 10
             form.fields[field_name] = form_field
             form.PCLEs[PCLE].append(field)
Ejemplo n.º 11
0
 def add_fields(self, form, index):
     super(BaseChildrenFormSet, self).add_fields(form, index)
     form.PCLEs = defaultdict(list)
     try:
         pcles = self.pcle_cache[form.instance.parent_id]
     except KeyError:
         parent = form.instance.parent.get_leaf_object()
         pcles = [p for p in m.get_PCLEs(parent) if p.one_per_link()]
         self.pcle_cache[parent.id] = pcles
     for PCLE in pcles:
         try:
             ext = PCLE.objects.get(link=form.instance)
         except PCLE.DoesNotExist:
             ext = None
         for field in PCLE.get_editable_fields():
             initial = getattr(ext, field, None)
             model_field = PCLE._meta.get_field(field)
             form_field = model_field.formfield(initial=initial)
             field_name = "%s_%s" % (PCLE._meta.module_name, field)
             if isinstance(form_field.widget, forms.TextInput):
                 form_field.widget.attrs["size"] = 10
             form.fields[field_name] = form_field
             form.PCLEs[PCLE].append(field)