コード例 #1
0
class EditPart(Base):
    template_name = 'assets/edit_part.html'

    def get_context_data(self, **kwargs):
        ret = super(EditPart, self).get_context_data(**kwargs)
        status_history = AssetHistoryChange.objects.all().filter(
            asset=kwargs.get('asset_id'),
            field_name__exact='status').order_by('-date')
        ret.update({
            'asset_form': self.asset_form,
            'office_info_form': self.office_info_form,
            'part_info_form': self.part_info_form,
            'form_id': 'edit_part_form',
            'edit_mode': True,
            'status_history': status_history,
            'history_link': self.get_history_link(),
            'parent_link': self.get_parent_link(),
        })
        return ret

    def get(self, *args, **kwargs):
        self.asset = get_object_or_404(Asset.admin_objects,
                                       id=kwargs.get('asset_id'))
        if self.asset.device_info:  # it isn't part asset
            raise Http404()
        mode = _get_mode(self.request)
        self.asset_form = EditPartForm(instance=self.asset, mode=mode)
        self.office_info_form = OfficeForm(instance=self.asset.office_info)
        self.part_info_form = BasePartForm(
            instance=self.asset.part_info,
            mode=mode,
        )
        return super(EditPart, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        self.asset = get_object_or_404(Asset.admin_objects,
                                       id=kwargs.get('asset_id'))
        mode = _get_mode(self.request)
        self.asset_form = EditPartForm(self.request.POST,
                                       instance=self.asset,
                                       mode=mode)
        self.office_info_form = OfficeForm(self.request.POST,
                                           self.request.FILES)
        self.part_info_form = BasePartForm(self.request.POST, mode=mode)
        if all((self.asset_form.is_valid(), self.office_info_form.is_valid(),
                self.part_info_form.is_valid())):
            modifier_profile = self.request.user.get_profile()
            self.asset = _update_asset(modifier_profile, self.asset,
                                       self.asset_form.cleaned_data)
            self.asset = _update_office_info(
                modifier_profile.user, self.asset,
                self.office_info_form.cleaned_data)
            self.asset = _update_part_info(modifier_profile.user, self.asset,
                                           self.part_info_form.cleaned_data)
            self.asset.save(user=self.request.user)
            messages.success(self.request, _("Part of asset was edited."))
            cat = self.request.path.split('/')[2]
            return HttpResponseRedirect('/assets/%s/edit/part/%s/' %
                                        (cat, self.asset.id))
        else:
            messages.error(self.request, _("Please correct the errors."))
            messages.error(self.request, self.asset_form.non_field_errors())
        return super(EditPart, self).get(*args, **kwargs)

    def get_parent_link(self):
        mode = _get_mode(self.request)
        asset = self.asset.part_info.source_device
        url = ''
        if asset:
            if mode == 'dc':
                url = reverse('dc_device_edit', args=[
                    asset.id,
                ])
            elif mode == 'back_office':
                url = reverse('back_office_device_edit', args=[
                    asset.id,
                ])
        return url

    def get_history_link(self):
        mode = _get_mode(self.request)
        asset_id = self.asset.id
        if mode == 'dc':
            url = reverse('dc_part_history', args=[
                asset_id,
            ])
        elif mode == 'back_office':
            url = reverse('back_office_part_history', args=[
                asset_id,
            ])
        return url
コード例 #2
0
ファイル: device.py プロジェクト: xliiv/ralph_assets
class AddDevice(AssetsBase):
    template_name = 'assets/add_device.html'
    sidebar_selected = 'add device'

    def get_context_data(self, **kwargs):
        ret = super(AddDevice, self).get_context_data(**kwargs)
        ret.update({
            'asset_form': self.asset_form,
            'additional_info': self.additional_info,
            'form_id': 'add_device_asset_form',
            'edit_mode': False,
            'multivalue_fields': ['sn', 'barcode', 'imei'],
        })
        return ret

    def _set_additional_info_form(self):
        if self.mode == 'dc':
            # XXX: how to clean it?
            if self.request.method == 'POST':
                self.additional_info = DeviceForm(
                    self.request.POST,
                    mode=self.mode,
                    exclude='create_stock',
                )
            else:
                self.additional_info = DeviceForm(
                    mode=self.mode,
                    exclude='create_stock',
                )
        elif self.mode == 'back_office':
            if self.request.method == 'POST':
                self.additional_info = OfficeForm(self.request.POST)
            else:
                self.additional_info = OfficeForm()

    def get(self, *args, **kwargs):
        self.asset_form = AddDeviceForm(mode=self.mode)
        device_form_class = self.form_dispatcher('AddDevice')
        self.asset_form = device_form_class(mode=self.mode)
        self._set_additional_info_form()
        return super(AddDevice, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        device_form_class = self.form_dispatcher('AddDevice')
        self.asset_form = device_form_class(self.request.POST, mode=self.mode)
        self._set_additional_info_form()
        if self.asset_form.is_valid() and self.additional_info.is_valid():
            creator_profile = self.request.user.get_profile()
            asset_data = {}
            for f_name, f_value in self.asset_form.cleaned_data.items():
                if f_name not in {
                    "barcode", "category", "company", "cost_center",
                    "department", "employee_id", "imei", "licences", "manager",
                    "sn", "profit_center", "supports",
                }:
                    asset_data[f_name] = f_value
            sns = self.asset_form.cleaned_data.get('sn', [])
            barcodes = self.asset_form.cleaned_data.get('barcode', [])
            imeis = (
                self.asset_form.cleaned_data.pop('imei')
                if 'imei' in self.asset_form.cleaned_data else None
            )
            ids = []
            for index in range(len(sns or barcodes)):
                asset_data['sn'] = sns[index] if sns else None
                asset_data['barcode'] = barcodes[index] if barcodes else None
                if imeis:
                    self.additional_info.cleaned_data['imei'] = imeis[index]
                device = _create_device(
                    creator_profile,
                    asset_data,
                    self.additional_info.cleaned_data,
                    self.mode,
                )
                ids.append(device.id)
            messages.success(self.request, _("Assets saved."))
            cat = self.request.path.split('/')[2]
            if len(ids) == 1:
                return HttpResponseRedirect(
                    '/assets/%s/edit/device/%s/' % (cat, ids[0])
                )
            else:
                return HttpResponseRedirect(
                    '/assets/%s/bulkedit/?select=%s' % (
                        cat, '&select='.join(["%s" % id for id in ids]))
                )
        else:
            messages.error(self.request, _("Please correct the errors."))
        return super(AddDevice, self).get(*args, **kwargs)
コード例 #3
0
class EditDevice(Base):
    template_name = 'assets/edit_device.html'

    def initialize_vars(self):
        self.parts = []
        self.office_info_form = None
        self.asset = None

    def get_context_data(self, **kwargs):
        ret = super(EditDevice, self).get_context_data(**kwargs)
        status_history = AssetHistoryChange.objects.all().filter(
            asset=kwargs.get('asset_id'),
            field_name__exact='status').order_by('-date')
        ret.update({
            'asset_form': self.asset_form,
            'device_info_form': self.device_info_form,
            'office_info_form': self.office_info_form,
            'part_form': MoveAssetPartForm(),
            'form_id': 'edit_device_asset_form',
            'edit_mode': True,
            'status_history': status_history,
            'parts': self.parts,
            'asset': self.asset,
            'history_link': self.get_history_link(),
        })
        return ret

    def get(self, *args, **kwargs):
        self.initialize_vars()
        self.asset = get_object_or_404(Asset.admin_objects,
                                       id=kwargs.get('asset_id'))
        if not self.asset.device_info:  # it isn't device asset
            raise Http404()
        mode = _get_mode(self.request)
        self.asset_form = EditDeviceForm(instance=self.asset, mode=mode)
        if self.asset.type in AssetType.BO.choices:
            self.office_info_form = OfficeForm(instance=self.asset.office_info)
        self.device_info_form = DeviceForm(
            instance=self.asset.device_info,
            mode=mode,
        )
        self.parts = Asset.objects.filter(part_info__device=self.asset)
        return super(EditDevice, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        self.initialize_vars()
        post_data = self.request.POST
        self.asset = get_object_or_404(Asset.admin_objects,
                                       id=kwargs.get('asset_id'))
        mode = _get_mode(self.request)
        self.asset_form = EditDeviceForm(
            post_data,
            instance=self.asset,
            mode=mode,
        )
        self.device_info_form = DeviceForm(
            post_data,
            mode=mode,
            instance=self.asset.device_info,
        )
        self.part_form = MoveAssetPartForm(post_data)
        if 'move_parts' in post_data.keys():
            destination_asset = post_data.get('new_asset')
            if not destination_asset or not Asset.objects.filter(
                    id=destination_asset, ):
                messages.error(
                    self.request,
                    _("Source device asset does not exist"),
                )
            elif kwargs.get('asset_id') == destination_asset:
                messages.error(
                    self.request,
                    _("You can't move parts to the same device"),
                )
            else:
                for part_id in post_data.get('part_ids'):
                    info_part = PartInfo.objects.get(asset=part_id)
                    info_part.device_id = destination_asset
                    info_part.save()
                messages.success(self.request, _("Selected parts was moved."))
        elif 'asset' in post_data.keys():
            if self.asset.type in AssetType.BO.choices:
                self.office_info_form = OfficeForm(
                    post_data,
                    self.request.FILES,
                )
            if all(
                (self.asset_form.is_valid(), self.device_info_form.is_valid(),
                 self.asset.type not in AssetType.BO.choices
                 or self.office_info_form.is_valid())):
                modifier_profile = self.request.user.get_profile()
                self.asset = _update_asset(modifier_profile, self.asset,
                                           self.asset_form.cleaned_data)
                if self.asset.type in AssetType.BO.choices:
                    self.asset = _update_office_info(
                        modifier_profile.user, self.asset,
                        self.office_info_form.cleaned_data)
                self.asset = _update_device_info(
                    modifier_profile.user, self.asset,
                    self.device_info_form.cleaned_data)
                if self.device_info_form.cleaned_data.get('create_stock'):
                    self.asset.create_stock_device()
                self.asset.save(user=self.request.user)
                messages.success(self.request, _("Assets edited."))
                cat = self.request.path.split('/')[2]
                return HttpResponseRedirect('/assets/%s/edit/device/%s/' %
                                            (cat, self.asset.id))
            else:
                messages.error(self.request, _("Please correct the errors."))
                messages.error(
                    self.request,
                    self.asset_form.non_field_errors(),
                )
        return super(EditDevice, self).get(*args, **kwargs)

    def get_history_link(self):
        mode = _get_mode(self.request)
        asset_id = self.asset.id
        if mode == 'dc':
            url = reverse('dc_device_history', args=[
                asset_id,
            ])
        elif mode == 'back_office':
            url = reverse('back_office_device_history', args=[
                asset_id,
            ])
        return url
コード例 #4
0
ファイル: views.py プロジェクト: deejay1/ralph_assets
class EditPart(Base):
    template_name = 'assets/edit_part.html'

    def get_context_data(self, **kwargs):
        ret = super(EditPart, self).get_context_data(**kwargs)
        status_history = AssetHistoryChange.objects.all().filter(
            asset=kwargs.get('asset_id'), field_name__exact='status'
        ).order_by('-date')
        ret.update({
            'asset_form': self.asset_form,
            'office_info_form': self.office_info_form,
            'part_info_form': self.part_info_form,
            'form_id': 'edit_part_form',
            'edit_mode': True,
            'status_history': status_history,
            'history_link': self.get_history_link(),
            'parent_link': self.get_parent_link(),
        })
        return ret

    def get(self, *args, **kwargs):
        self.asset = get_object_or_404(
            Asset.admin_objects,
            id=kwargs.get('asset_id')
        )
        if self.asset.device_info:  # it isn't part asset
            raise Http404()
        mode = _get_mode(self.request)
        self.asset_form = EditPartForm(instance=self.asset, mode=mode)
        self.office_info_form = OfficeForm(instance=self.asset.office_info)
        self.part_info_form = BasePartForm(
            instance=self.asset.part_info, mode=mode,
        )
        return super(EditPart, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        self.asset = get_object_or_404(
            Asset.admin_objects,
            id=kwargs.get('asset_id')
        )
        mode = _get_mode(self.request)
        self.asset_form = EditPartForm(
            self.request.POST,
            instance=self.asset,
            mode=mode
        )
        self.office_info_form = OfficeForm(
            self.request.POST, self.request.FILES)
        self.part_info_form = BasePartForm(self.request.POST, mode=mode)
        if all((
            self.asset_form.is_valid(),
            self.office_info_form.is_valid(),
            self.part_info_form.is_valid()
        )):
            modifier_profile = self.request.user.get_profile()
            self.asset = _update_asset(
                modifier_profile, self.asset,
                self.asset_form.cleaned_data
            )
            self.asset = _update_office_info(
                modifier_profile.user, self.asset,
                self.office_info_form.cleaned_data
            )
            self.asset = _update_part_info(
                modifier_profile.user, self.asset,
                self.part_info_form.cleaned_data
            )
            self.asset.save(user=self.request.user)
            messages.success(self.request, _("Part of asset was edited."))
            cat = self.request.path.split('/')[2]
            return HttpResponseRedirect(
                '/assets/%s/edit/part/%s/' % (cat, self.asset.id)
            )
        else:
            messages.error(self.request, _("Please correct the errors."))
            messages.error(self.request, self.asset_form.non_field_errors())
        return super(EditPart, self).get(*args, **kwargs)

    def get_parent_link(self):
        mode = _get_mode(self.request)
        asset = self.asset.part_info.source_device
        url = ''
        if asset:
            if mode == 'dc':
                url = reverse('dc_device_edit', args=[asset.id, ])
            elif mode == 'back_office':
                url = reverse('back_office_device_edit', args=[asset.id, ])
        return url

    def get_history_link(self):
        mode = _get_mode(self.request)
        asset_id = self.asset.id
        if mode == 'dc':
            url = reverse('dc_part_history', args=[asset_id, ])
        elif mode == 'back_office':
            url = reverse('back_office_part_history', args=[asset_id, ])
        return url
コード例 #5
0
ファイル: device.py プロジェクト: xliiv/ralph_assets
class EditDevice(AssetsBase):
    template_name = 'assets/edit_device.html'
    sidebar_selected = 'edit device'

    def initialize_vars(self, *args, **kwargs):
        self.asset = get_object_or_404(
            Asset.admin_objects,
            id=kwargs.get('asset_id'),
        )
        self.parts = Asset.objects.filter(part_info__device=self.asset)
        device_form_class = self.form_dispatcher('EditDevice')
        self.asset_form = device_form_class(
            self.request.POST or None,
            instance=self.asset,
            mode=self.mode,
        )
        self.part_form = MoveAssetPartForm(self.request.POST or None)
        self._set_additional_info_form()

    def get_context_data(self, **kwargs):
        ret = super(EditDevice, self).get_context_data(**kwargs)
        status_history = AssetHistoryChange.objects.all().filter(
            asset=kwargs.get('asset_id'), field_name__exact='status'
        ).order_by('-date')
        ret.update({
            'asset_form': self.asset_form,
            'additional_info': self.additional_info,
            'part_form': self.part_form,
            'form_id': 'edit_device_asset_form',
            'edit_mode': True,
            'status_history': status_history,
            'parts': self.parts,
            'asset': self.asset,
            'history_link': self.get_history_link(),
        })
        return ret

    def _update_additional_info(self, modifier):
        if self.asset.type in AssetType.DC.choices:
            self.asset = _update_device_info(
                modifier, self.asset, self.additional_info.cleaned_data
            )
            if self.additional_info.cleaned_data.get('create_stock'):
                self.asset.create_stock_device()
        elif self.asset.type in AssetType.BO.choices:
            new_src, new_dst = _move_data(
                self.asset_form.cleaned_data,
                self.additional_info.cleaned_data,
                ['imei', 'purpose'],
            )
            self.asset_form.cleaned_data = new_src
            self.additional_info.cleaned_data = new_dst
            self.asset = _update_office_info(
                modifier, self.asset, self.additional_info.cleaned_data
            )

    def _set_additional_info_form(self):
        if self.mode == 'dc':
            # XXX: how do it better, differ only by one arg?
            if self.request.method == 'POST':
                self.additional_info = DeviceForm(
                    self.request.POST,
                    instance=self.asset.device_info,
                    mode=self.mode,
                )
            else:
                self.additional_info = DeviceForm(
                    instance=self.asset.device_info,
                    mode=self.mode,
                )
        elif self.mode == 'back_office':
            # XXX: how do it better, differ only by one arg?
            if self.request.method == 'POST':
                self.additional_info = OfficeForm(
                    self.request.POST,
                    instance=self.asset.office_info,
                )
            else:
                self.additional_info = OfficeForm(
                    instance=self.asset.office_info,
                )
                fields = ['imei', 'purpose']
                for field in fields:
                    if field in self.asset_form.fields:
                        self.asset_form.fields[field].initial = (
                            getattr(self.asset.office_info, field, '')
                        )

    def get(self, *args, **kwargs):
        self.initialize_vars(*args, **kwargs)
        return super(EditDevice, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        post_data = self.request.POST
        self.initialize_vars(*args, **kwargs)
        self.part_form = MoveAssetPartForm(post_data or None)
        if 'move_parts' in post_data.keys():
            destination_asset = post_data.get('new_asset')
            if not destination_asset or not Asset.objects.filter(
                id=destination_asset,
            ):
                messages.error(
                    self.request,
                    _("Source device asset does not exist"),
                )
            elif kwargs.get('asset_id') == destination_asset:
                messages.error(
                    self.request,
                    _("You can't move parts to the same device"),
                )
            else:
                if post_data.getlist('part_ids'):
                    for part_id in post_data.getlist('part_ids'):
                        info_part = PartInfo.objects.get(asset=part_id)
                        info_part.device_id = destination_asset
                        info_part.save()
                    messages.success(
                        self.request, _("Selected parts was moved."),
                    )
                    self.part_form = MoveAssetPartForm()
                else:
                    messages.error(
                        self.request, _("Please select one or more parts."),
                    )
        elif 'asset' in post_data.keys():
            if all((
                self.asset_form.is_valid(),
                self.additional_info.is_valid(),
            )):
                modifier_profile = self.request.user.get_profile()
                self.asset = _update_asset(
                    modifier_profile, self.asset, self.asset_form.cleaned_data
                )
                self._update_additional_info(modifier_profile.user)
                self.asset.save(user=self.request.user)
                self.asset.licence_set.clear()
                for licence in self.asset_form.cleaned_data.get(
                    'licences', []
                ):
                    self.asset.licence_set.add(licence)
                self.asset.supports.clear()
                for support in self.asset_form.cleaned_data.get(
                    'supports', []
                ):
                    self.asset.supports.add(support)
                messages.success(self.request, _("Assets edited."))
                cat = self.request.path.split('/')[2]
                return HttpResponseRedirect(
                    '/assets/%s/edit/device/%s/' % (cat, self.asset.id)
                )
            else:
                messages.error(self.request, _("Please correct the errors."))
                messages.error(
                    self.request, self.asset_form.non_field_errors(),
                )
        return super(EditDevice, self).get(*args, **kwargs)

    def get_history_link(self):
        asset_id = self.asset.id
        url = reverse('device_history', kwargs={
            'asset_id': asset_id,
            'mode': self.mode,
        })
        return url
コード例 #6
0
ファイル: part.py プロジェクト: xliiv/ralph_assets
class EditPart(AssetsBase):
    template_name = 'assets/edit_part.html'

    def initialize_vars(self):
        self.office_info_form = None

    def get_context_data(self, **kwargs):
        ret = super(EditPart, self).get_context_data(**kwargs)
        status_history = AssetHistoryChange.objects.all().filter(
            asset=kwargs.get('asset_id'), field_name__exact='status'
        ).order_by('-date')
        ret.update({
            'asset_form': self.asset_form,
            'office_info_form': self.office_info_form,
            'part_info_form': self.part_info_form,
            'form_id': 'edit_part_form',
            'edit_mode': True,
            'status_history': status_history,
            'history_link': self.get_history_link(),
            'parent_link': self.get_parent_link(),
            'asset': self.asset,
        })
        return ret

    def get(self, *args, **kwargs):
        self.initialize_vars()
        self.asset = get_object_or_404(
            Asset.admin_objects,
            id=kwargs.get('asset_id')
        )
        if self.asset.device_info:  # it isn't part asset
            raise Http404()
        self.asset_form = EditPartForm(instance=self.asset, mode=self.mode)
        self.write_office_info2asset_form()
        self.part_info_form = BasePartForm(
            instance=self.asset.part_info, mode=self.mode,
        )
        return super(EditPart, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        self.asset = get_object_or_404(
            Asset.admin_objects,
            id=kwargs.get('asset_id')
        )
        mode = self.mode
        self.asset_form = EditPartForm(
            self.request.POST,
            instance=self.asset,
            mode=mode
        )
        self.office_info_form = OfficeForm(
            self.request.POST, self.request.FILES)
        self.part_info_form = BasePartForm(self.request.POST, mode=mode)
        if all((
            self.asset_form.is_valid(),
            self.office_info_form.is_valid(),
            self.part_info_form.is_valid()
        )):
            modifier_profile = self.request.user.get_profile()
            self.asset = _update_asset(
                modifier_profile, self.asset,
                self.asset_form.cleaned_data
            )
            new_src, new_dst = _move_data(
                self.asset_form.cleaned_data,
                self.office_info_form.cleaned_data,
                ['imei'],
            )
            self.asset_form.cleaned_data = new_src
            self.office_info_form.cleaned_data = new_dst
            self.asset = _update_office_info(
                modifier_profile.user, self.asset,
                self.office_info_form.cleaned_data
            )
            self.asset = _update_part_info(
                modifier_profile.user, self.asset,
                self.part_info_form.cleaned_data
            )
            self.asset.save(user=self.request.user)
            self.asset.supports.clear()
            for support in self.asset_form.cleaned_data.get(
                'supports', []
            ):
                self.asset.supports.add(support)
            messages.success(self.request, _("Part of asset was edited."))
            cat = self.request.path.split('/')[2]
            return HttpResponseRedirect(
                '/assets/%s/edit/part/%s/' % (cat, self.asset.id)
            )
        else:
            messages.error(self.request, _("Please correct the errors."))
            messages.error(self.request, self.asset_form.non_field_errors())
        return super(EditPart, self).get(*args, **kwargs)

    def get_parent_link(self):
        asset = self.asset.part_info.source_device
        if asset:
            return reverse('device_edit', kwargs={
                'asset_id': asset.id,
                'mode': self.mode,
            })

    def get_history_link(self):
        return reverse('part_history', kwargs={
            'asset_id': self.asset.id,
            'mode': self.mode,
        })
コード例 #7
0
ファイル: views.py プロジェクト: deejay1/ralph_assets
class EditDevice(Base):
    template_name = 'assets/edit_device.html'

    def initialize_vars(self):
        self.parts = []
        self.office_info_form = None
        self.asset = None

    def get_context_data(self, **kwargs):
        ret = super(EditDevice, self).get_context_data(**kwargs)
        status_history = AssetHistoryChange.objects.all().filter(
            asset=kwargs.get('asset_id'), field_name__exact='status'
        ).order_by('-date')
        ret.update({
            'asset_form': self.asset_form,
            'device_info_form': self.device_info_form,
            'office_info_form': self.office_info_form,
            'part_form': MoveAssetPartForm(),
            'form_id': 'edit_device_asset_form',
            'edit_mode': True,
            'status_history': status_history,
            'parts': self.parts,
            'asset': self.asset,
            'history_link': self.get_history_link(),
        })
        return ret

    def get(self, *args, **kwargs):
        self.initialize_vars()
        self.asset = get_object_or_404(
            Asset.admin_objects,
            id=kwargs.get('asset_id')
        )
        if not self.asset.device_info:  # it isn't device asset
            raise Http404()
        mode = _get_mode(self.request)
        self.asset_form = EditDeviceForm(instance=self.asset, mode=mode)
        if self.asset.type in AssetType.BO.choices:
            self.office_info_form = OfficeForm(instance=self.asset.office_info)
        self.device_info_form = DeviceForm(
            instance=self.asset.device_info,
            mode=mode
        )
        self.parts = Asset.objects.filter(part_info__device=self.asset)
        return super(EditDevice, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        self.initialize_vars()
        post_data = self.request.POST
        self.asset = get_object_or_404(
            Asset.admin_objects,
            id=kwargs.get('asset_id')
        )
        mode = _get_mode(self.request)
        self.asset_form = EditDeviceForm(
            post_data,
            instance=self.asset,
            mode=mode,
        )
        self.device_info_form = DeviceForm(
            post_data,
            mode=mode,
            instance=self.asset.device_info,
        )
        self.part_form = MoveAssetPartForm(post_data)
        if 'move_parts' in post_data.keys():
            destination_asset = post_data.get('new_asset')
            if not destination_asset or not Asset.objects.filter(
                id=destination_asset,
            ):
                messages.error(
                    self.request,
                    _("Source device asset does not exist"),
                )
            elif kwargs.get('asset_id') == destination_asset:
                messages.error(
                    self.request,
                    _("You can't move parts to the same device"),
                )
            else:
                for part_id in post_data.get('part_ids'):
                    info_part = PartInfo.objects.get(asset=part_id)
                    info_part.device_id = destination_asset
                    info_part.save()
                messages.success(self.request, _("Selected parts was moved."))
        elif 'asset' in post_data.keys():
            if self.asset.type in AssetType.BO.choices:
                self.office_info_form = OfficeForm(
                    post_data, self.request.FILES,
                )
            if all((
                self.asset_form.is_valid(),
                self.device_info_form.is_valid(),
                self.asset.type not in AssetType.BO.choices or
                self.office_info_form.is_valid()
            )):
                modifier_profile = self.request.user.get_profile()
                self.asset = _update_asset(
                    modifier_profile, self.asset, self.asset_form.cleaned_data
                )
                if self.asset.type in AssetType.BO.choices:
                    self.asset = _update_office_info(
                        modifier_profile.user, self.asset,
                        self.office_info_form.cleaned_data
                    )
                self.asset = _update_device_info(
                    modifier_profile.user, self.asset,
                    self.device_info_form.cleaned_data
                )
                self.asset.save(user=self.request.user)
                messages.success(self.request, _("Assets edited."))
                cat = self.request.path.split('/')[2]
                return HttpResponseRedirect(
                    '/assets/%s/edit/device/%s/' % (cat, self.asset.id)
                )
            else:
                messages.error(self.request, _("Please correct the errors."))
                messages.error(
                    self.request, self.asset_form.non_field_errors(),
                )
        return super(EditDevice, self).get(*args, **kwargs)

    def get_history_link(self):
        mode = _get_mode(self.request)
        asset_id = self.asset.id
        if mode == 'dc':
            url = reverse('dc_device_history', args=[asset_id, ])
        elif mode == 'back_office':
            url = reverse('back_office_device_history', args=[asset_id, ])
        return url
コード例 #8
0
ファイル: device.py プロジェクト: allegro/ralph_assets
class AddDevice(HardwareModeMixin, SubmoduleModeMixin, AssetsBase):
    active_sidebar_item = 'add device'
    template_name = 'assets/add_device.html'

    def get_context_data(self, **kwargs):
        ret = super(AddDevice, self).get_context_data(**kwargs)
        ret.update({
            'asset_form': self.asset_form,
            'additional_info': self.additional_info,
            'form_id': 'add_device_asset_form',
            'edit_mode': False,
            'multivalue_fields': ['sn', 'barcode', 'imei'],
        })
        return ret

    def _set_additional_info_form(self):
        if self.mode == 'dc':
            # XXX: how to clean it?
            if self.request.method == 'POST':
                self.additional_info = DeviceForm(
                    self.request.POST,
                    mode=self.mode,
                    exclude='create_stock',
                )
            else:
                self.additional_info = DeviceForm(
                    mode=self.mode,
                    exclude='create_stock',
                )
        elif self.mode == 'back_office':
            if self.request.method == 'POST':
                self.additional_info = OfficeForm(self.request.POST)
            else:
                self.additional_info = OfficeForm()

    def get(self, *args, **kwargs):
        device_form_class = self.form_dispatcher('AddDevice')
        self.asset_form = device_form_class(mode=self.mode)
        self._set_additional_info_form()
        return super(AddDevice, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        device_form_class = self.form_dispatcher('AddDevice')
        self.asset_form = device_form_class(self.request.POST, mode=self.mode)
        self._set_additional_info_form()
        if self.asset_form.is_valid() and self.additional_info.is_valid():
            try:
                self.validate_forms_dependency()
            except ValidationError as e:
                return super(AddDevice, self).get(*args, **kwargs)

            force_unlink = self.additional_info.cleaned_data.get(
                'force_unlink', None,
            )
            if self.validate_barcodes(
                self.asset_form.cleaned_data['barcode'],
            ) and not force_unlink:
                msg = _(
                    "Device with barcode already exist, check"
                    " 'force unlink' option to relink it."
                )
                messages.error(self.request, msg)
                return super(AddDevice, self).get(*args, **kwargs)
            try:
                ids = _create_assets(
                    self.request.user.get_profile(),
                    self.asset_form,
                    self.additional_info,
                    self.mode
                )
            except ValueError as e:
                messages.error(self.request, e.message)
                return super(AddDevice, self).get(*args, **kwargs)
            messages.success(self.request, _("Assets saved."))
            cat = self.request.path.split('/')[2]
            if len(ids) == 1:
                return HttpResponseRedirect(
                    '/assets/%s/edit/device/%s/' % (cat, ids[0])
                )
            else:
                return HttpResponseRedirect(
                    '/assets/%s/bulkedit/?select=%s' % (
                        cat, '&select='.join(["%s" % id for id in ids]))
                )
        else:
            messages.error(self.request, _("Please correct the errors."))
        return super(AddDevice, self).get(*args, **kwargs)
コード例 #9
0
ファイル: device.py プロジェクト: allegro/ralph_assets
class EditDevice(HardwareModeMixin, SubmoduleModeMixin, AssetsBase):
    detect_changes = True
    template_name = 'assets/edit_device.html'
    sidebar_selected = 'edit device'

    def initialize_vars(self, *args, **kwargs):
        self.asset = get_object_or_404(
            Asset.objects,
            id=kwargs.get('asset_id'),
        )
        self.parts = Asset.objects.filter(part_info__device=self.asset)
        device_form_class = self.form_dispatcher('EditDevice')
        self.asset_form = device_form_class(
            self.request.POST or None,
            instance=self.asset,
            mode=self.mode,
        )
        self.part_form = MoveAssetPartForm(self.request.POST or None)
        self._set_additional_info_form()

    def get_context_data(self, **kwargs):
        context = super(EditDevice, self).get_context_data(**kwargs)
        context.update({
            'asset_form': self.asset_form,
            'additional_info': self.additional_info,
            'part_form': self.part_form,
            'form_id': 'edit_device_asset_form',
            'edit_mode': True,
            'parts': self.parts,
            'asset': self.asset,
        })
        return context

    def _update_additional_info(self, modifier):
        if self.asset.type in AssetType.DC.choices:
            self.asset = _update_device_info(
                modifier, self.asset, self.additional_info.cleaned_data
            )
            if self.additional_info.cleaned_data.get('create_stock'):
                self.asset.create_stock_device()
        elif self.asset.type in AssetType.BO.choices:
            new_src, new_dst = _move_data(
                self.asset_form.cleaned_data,
                self.additional_info.cleaned_data,
                ['imei', 'purpose'],
            )
            self.asset_form.cleaned_data = new_src
            self.additional_info.cleaned_data = new_dst
            self.asset = _update_office_info(
                modifier, self.asset, self.additional_info.cleaned_data
            )

    def _set_additional_info_form(self):
        if self.mode == 'dc':
            # XXX: how do it better, differ only by one arg?
            if self.request.method == 'POST':
                self.additional_info = DeviceForm(
                    self.request.POST,
                    instance=self.asset.device_info,
                    mode=self.mode,
                )
            else:
                self.additional_info = DeviceForm(
                    instance=self.asset.device_info,
                    mode=self.mode,
                )
        elif self.mode == 'back_office':
            # XXX: how do it better, differ only by one arg?
            if self.request.method == 'POST':
                self.additional_info = OfficeForm(
                    self.request.POST,
                    instance=self.asset.office_info,
                )
            else:
                self.additional_info = OfficeForm(
                    instance=self.asset.office_info,
                )
                fields = ['imei', 'purpose']
                for field in fields:
                    if field in self.asset_form.fields:
                        self.asset_form.fields[field].initial = (
                            getattr(self.asset.office_info, field, '')
                        )

    def get(self, *args, **kwargs):
        self.initialize_vars(*args, **kwargs)
        return super(EditDevice, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        post_data = self.request.POST
        self.initialize_vars(*args, **kwargs)
        self.part_form = MoveAssetPartForm(post_data or None)
        if 'move_parts' in post_data.keys():
            destination_asset = post_data.get('new_asset')
            if not destination_asset or not Asset.objects.filter(
                id=destination_asset,
            ):
                messages.error(
                    self.request,
                    _("Source device asset does not exist"),
                )
            elif kwargs.get('asset_id') == destination_asset:
                messages.error(
                    self.request,
                    _("You can't move parts to the same device"),
                )
            else:
                if post_data.getlist('part_ids'):
                    for part_id in post_data.getlist('part_ids'):
                        info_part = PartInfo.objects.get(asset=part_id)
                        info_part.device_id = destination_asset
                        info_part.save()
                    messages.success(
                        self.request, _("Selected parts was moved."),
                    )
                    self.part_form = MoveAssetPartForm()
                else:
                    messages.error(
                        self.request, _("Please select one or more parts."),
                    )
        elif (
            'asset' in post_data.keys() or
            'transition_type' in post_data.keys()
        ):
            if all((
                self.asset_form.is_valid(),
                self.additional_info.is_valid(),
            )):
                try:
                    self.validate_forms_dependency()
                except ValidationError:
                    return super(EditDevice, self).get(*args, **kwargs)

                force_unlink = self.additional_info.cleaned_data.get(
                    'force_unlink', None,
                )
                modifier_profile = self.request.user.get_profile()
                self.asset = _update_asset(
                    modifier_profile, self.asset, self.asset_form.cleaned_data
                )
                self._update_additional_info(modifier_profile.user)
                self.asset.save(
                    user=self.request.user, force_unlink=force_unlink,
                )
                self.asset.licences.clear()
                for licence in self.asset_form.cleaned_data.get(
                    'licences', []
                ):
                    Licence.objects.get(pk=licence).assign(self.asset)
                self.asset.supports.clear()
                for support in self.asset_form.cleaned_data.get(
                    'supports', []
                ):
                    self.asset.supports.add(support)
                messages.success(self.request, _("Assets edited."))
                transition_type = post_data.get('transition_type')
                if transition_type:
                    redirect_url = get_transition_url(
                        transition_type, [self.asset.id], self.mode
                    )
                else:
                    redirect_url = reverse(
                        'device_edit', args=[self.mode, self.asset.id, ],
                    )
                return HttpResponseRedirect(redirect_url)
            else:
                messages.error(self.request, _("Please correct the errors."))
                messages.error(
                    self.request, self.asset_form.non_field_errors(),
                )
        return super(EditDevice, self).get(*args, **kwargs)
コード例 #10
0
class EditPart(HardwareModeMixin, SubmoduleModeMixin, AssetsBase):
    detect_changes = True
    template_name = 'assets/edit_part.html'

    def initialize_vars(self):
        self.office_info_form = None

    def get_context_data(self, **kwargs):
        context = super(EditPart, self).get_context_data(**kwargs)
        context.update({
            'asset_form': self.asset_form,
            'office_info_form': self.office_info_form,
            'part_info_form': self.part_info_form,
            'form_id': 'edit_part_form',
            'edit_mode': True,
            'parent_link': self.get_parent_link(),
            'asset': self.asset,
        })
        return context

    def get(self, *args, **kwargs):
        self.initialize_vars()
        self.asset = get_object_or_404(Asset.admin_objects,
                                       id=kwargs.get('asset_id'))
        if self.asset.device_info:  # it isn't part asset
            raise Http404()
        self.asset_form = EditPartForm(instance=self.asset, mode=self.mode)
        self.write_office_info2asset_form()
        self.part_info_form = BasePartForm(
            instance=self.asset.part_info,
            mode=self.mode,
        )
        return super(EditPart, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        self.asset = get_object_or_404(Asset.admin_objects,
                                       id=kwargs.get('asset_id'))
        mode = self.mode
        self.asset_form = EditPartForm(self.request.POST,
                                       instance=self.asset,
                                       mode=mode)
        self.office_info_form = OfficeForm(self.request.POST,
                                           self.request.FILES)
        self.part_info_form = BasePartForm(self.request.POST, mode=mode)
        if all((self.asset_form.is_valid(), self.office_info_form.is_valid(),
                self.part_info_form.is_valid())):
            modifier_profile = self.request.user.get_profile()
            self.asset = _update_asset(modifier_profile, self.asset,
                                       self.asset_form.cleaned_data)
            new_src, new_dst = _move_data(
                self.asset_form.cleaned_data,
                self.office_info_form.cleaned_data,
                ['imei'],
            )
            self.asset_form.cleaned_data = new_src
            self.office_info_form.cleaned_data = new_dst
            self.asset = _update_office_info(
                modifier_profile.user, self.asset,
                self.office_info_form.cleaned_data)
            self.asset = _update_part_info(modifier_profile.user, self.asset,
                                           self.part_info_form.cleaned_data)
            self.asset.save(user=self.request.user)
            self.asset.supports.clear()
            for support in self.asset_form.cleaned_data.get('supports', []):
                self.asset.supports.add(support)
            messages.success(self.request, _("Part of asset was edited."))
            cat = self.request.path.split('/')[2]
            return HttpResponseRedirect('/assets/%s/edit/part/%s/' %
                                        (cat, self.asset.id))
        else:
            messages.error(self.request, _("Please correct the errors."))
            messages.error(self.request, self.asset_form.non_field_errors())
        return super(EditPart, self).get(*args, **kwargs)

    def get_parent_link(self):
        asset = self.asset.part_info.source_device
        if asset:
            return reverse('device_edit',
                           kwargs={
                               'asset_id': asset.id,
                               'mode': self.mode,
                           })
コード例 #11
0
class AddDevice(HardwareModeMixin, SubmoduleModeMixin, AssetsBase):
    active_sidebar_item = 'add device'
    template_name = 'assets/add_device.html'

    def get_context_data(self, **kwargs):
        ret = super(AddDevice, self).get_context_data(**kwargs)
        ret.update({
            'asset_form': self.asset_form,
            'additional_info': self.additional_info,
            'form_id': 'add_device_asset_form',
            'edit_mode': False,
            'multivalue_fields': ['sn', 'barcode', 'imei'],
        })
        return ret

    def _set_additional_info_form(self):
        if self.mode == 'dc':
            # XXX: how to clean it?
            if self.request.method == 'POST':
                self.additional_info = DeviceForm(
                    self.request.POST,
                    mode=self.mode,
                    exclude='create_stock',
                )
            else:
                self.additional_info = DeviceForm(
                    mode=self.mode,
                    exclude='create_stock',
                )
        elif self.mode == 'back_office':
            if self.request.method == 'POST':
                self.additional_info = OfficeForm(self.request.POST)
            else:
                self.additional_info = OfficeForm()

    def get(self, *args, **kwargs):
        self.asset_form = AddDeviceForm(mode=self.mode)
        device_form_class = self.form_dispatcher('AddDevice')
        self.asset_form = device_form_class(mode=self.mode)
        self._set_additional_info_form()
        return super(AddDevice, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        device_form_class = self.form_dispatcher('AddDevice')
        self.asset_form = device_form_class(self.request.POST, mode=self.mode)
        self._set_additional_info_form()
        if self.asset_form.is_valid() and self.additional_info.is_valid():
            force_unlink = self.additional_info.cleaned_data.get(
                'force_unlink', None,
            )
            if self.validate_barcodes(
                self.asset_form.cleaned_data['barcode'],
            ) and not force_unlink:
                msg = _(
                    "Device with barcode already exist, check"
                    " 'force unlink' option to relink it."
                )
                messages.error(self.request, msg)
                return super(AddDevice, self).get(*args, **kwargs)
            try:
                ids = _create_assets(
                    self.request.user.get_profile(),
                    self.asset_form,
                    self.additional_info,
                    self.mode
                )
            except ValueError as e:
                messages.error(self.request, e.message)
                return super(AddDevice, self).get(*args, **kwargs)
            messages.success(self.request, _("Assets saved."))
            cat = self.request.path.split('/')[2]
            if len(ids) == 1:
                return HttpResponseRedirect(
                    '/assets/%s/edit/device/%s/' % (cat, ids[0])
                )
            else:
                return HttpResponseRedirect(
                    '/assets/%s/bulkedit/?select=%s' % (
                        cat, '&select='.join(["%s" % id for id in ids]))
                )
        else:
            messages.error(self.request, _("Please correct the errors."))
        return super(AddDevice, self).get(*args, **kwargs)
コード例 #12
0
class EditDevice(HardwareModeMixin, SubmoduleModeMixin, AssetsBase):
    detect_changes = True
    template_name = 'assets/edit_device.html'
    sidebar_selected = 'edit device'

    def initialize_vars(self, *args, **kwargs):
        self.asset = get_object_or_404(
            Asset.admin_objects,
            id=kwargs.get('asset_id'),
        )
        self.parts = Asset.objects.filter(part_info__device=self.asset)
        device_form_class = self.form_dispatcher('EditDevice')
        self.asset_form = device_form_class(
            self.request.POST or None,
            instance=self.asset,
            mode=self.mode,
        )
        self.part_form = MoveAssetPartForm(self.request.POST or None)
        self._set_additional_info_form()

    def get_context_data(self, **kwargs):
        context = super(EditDevice, self).get_context_data(**kwargs)
        context.update({
            'asset_form': self.asset_form,
            'additional_info': self.additional_info,
            'part_form': self.part_form,
            'form_id': 'edit_device_asset_form',
            'edit_mode': True,
            'parts': self.parts,
            'asset': self.asset,
        })
        return context

    def _update_additional_info(self, modifier):
        if self.asset.type in AssetType.DC.choices:
            self.asset = _update_device_info(
                modifier, self.asset, self.additional_info.cleaned_data
            )
            if self.additional_info.cleaned_data.get('create_stock'):
                self.asset.create_stock_device()
        elif self.asset.type in AssetType.BO.choices:
            new_src, new_dst = _move_data(
                self.asset_form.cleaned_data,
                self.additional_info.cleaned_data,
                ['imei', 'purpose'],
            )
            self.asset_form.cleaned_data = new_src
            self.additional_info.cleaned_data = new_dst
            self.asset = _update_office_info(
                modifier, self.asset, self.additional_info.cleaned_data
            )

    def _set_additional_info_form(self):
        if self.mode == 'dc':
            # XXX: how do it better, differ only by one arg?
            if self.request.method == 'POST':
                self.additional_info = DeviceForm(
                    self.request.POST,
                    instance=self.asset.device_info,
                    mode=self.mode,
                )
            else:
                self.additional_info = DeviceForm(
                    instance=self.asset.device_info,
                    mode=self.mode,
                )
        elif self.mode == 'back_office':
            # XXX: how do it better, differ only by one arg?
            if self.request.method == 'POST':
                self.additional_info = OfficeForm(
                    self.request.POST,
                    instance=self.asset.office_info,
                )
            else:
                self.additional_info = OfficeForm(
                    instance=self.asset.office_info,
                )
                fields = ['imei', 'purpose']
                for field in fields:
                    if field in self.asset_form.fields:
                        self.asset_form.fields[field].initial = (
                            getattr(self.asset.office_info, field, '')
                        )

    def get(self, *args, **kwargs):
        self.initialize_vars(*args, **kwargs)
        return super(EditDevice, self).get(*args, **kwargs)

    def post(self, *args, **kwargs):
        post_data = self.request.POST
        self.initialize_vars(*args, **kwargs)
        self.part_form = MoveAssetPartForm(post_data or None)
        if 'move_parts' in post_data.keys():
            destination_asset = post_data.get('new_asset')
            if not destination_asset or not Asset.objects.filter(
                id=destination_asset,
            ):
                messages.error(
                    self.request,
                    _("Source device asset does not exist"),
                )
            elif kwargs.get('asset_id') == destination_asset:
                messages.error(
                    self.request,
                    _("You can't move parts to the same device"),
                )
            else:
                if post_data.getlist('part_ids'):
                    for part_id in post_data.getlist('part_ids'):
                        info_part = PartInfo.objects.get(asset=part_id)
                        info_part.device_id = destination_asset
                        info_part.save()
                    messages.success(
                        self.request, _("Selected parts was moved."),
                    )
                    self.part_form = MoveAssetPartForm()
                else:
                    messages.error(
                        self.request, _("Please select one or more parts."),
                    )
        elif 'asset' in post_data.keys():
            if all((
                self.asset_form.is_valid(),
                self.additional_info.is_valid(),
            )):
                force_unlink = self.additional_info.cleaned_data.get(
                    'force_unlink', None,
                )
                modifier_profile = self.request.user.get_profile()
                self.asset = _update_asset(
                    modifier_profile, self.asset, self.asset_form.cleaned_data
                )
                self._update_additional_info(modifier_profile.user)
                self.asset.save(
                    user=self.request.user, force_unlink=force_unlink,
                )
                self.asset.licence_set.clear()
                for licence in self.asset_form.cleaned_data.get(
                    'licences', []
                ):
                    self.asset.licence_set.add(licence)
                self.asset.supports.clear()
                for support in self.asset_form.cleaned_data.get(
                    'supports', []
                ):
                    self.asset.supports.add(support)
                messages.success(self.request, _("Assets edited."))
                cat = self.request.path.split('/')[2]
                return HttpResponseRedirect(
                    '/assets/%s/edit/device/%s/' % (cat, self.asset.id)
                )
            else:
                messages.error(self.request, _("Please correct the errors."))
                messages.error(
                    self.request, self.asset_form.non_field_errors(),
                )
        return super(EditDevice, self).get(*args, **kwargs)