示例#1
0
def get_device(request, sn):
    if len(sn) < 1:
        return Device(sn=sn)

    key = 'checkin-device-%s' % sn
    device = cache.get(key, get_local_device(request, sn))
    set_cache_device(device)
    return device
示例#2
0
def get_remote_device(request, sn):
    try:
        apple_sn_validator(sn)
    except ValidationError:
        return Device(sn=sn,
                      image_url='https://static.servoapp.com/images/na.gif')

    get_gsx_connection(request)

    return Device.from_gsx(sn)
示例#3
0
def prep_detail_view(request, pk, product_line=None, model=None):
    if pk is None:
        device = Device()
    else:
        device = get_object_or_404(Device, pk=pk)

    data = prep_list_view(request, product_line, model)

    data['device'] = device
    data['title'] = device.description

    return data
示例#4
0
def find_device(request):
    device = Device(sn=request.GET['sn'])
    device.description = _('Other Device')
    device_form = DeviceForm(instance=device)

    try:
        apple_sn_validator(device.sn)
    except Exception as e:  # not an Apple serial number
        return render(request, "checkin/device_form.html", locals())

    try:
        device = get_device(request, device.sn)
        device_form = DeviceForm(instance=device)
    except GsxError as e:
        error = e

    return render(request, "checkin/device_form.html", locals())
示例#5
0
def edit_device(request, pk=None, product_line=None, model=None):
    """
    Edits an existing device or adds a new one
    """
    device = Device()
    device.sn = request.GET.get('sn', '')

    if product_line is not None:
        device.product_line = product_line

    if model is not None:
        device.product_line = product_line
        device.description = model_from_slug(product_line, model)

    if pk is not None:
        device = get_object_or_404(Device, pk=pk)

    form = DeviceForm(instance=device)

    if request.method == "POST":

        form = DeviceForm(request.POST, request.FILES, instance=device)

        if form.is_valid():
            device = form.save()
            messages.success(request, _(u"%s saved") % device.description)
            device.add_tags(request.POST.getlist('tag'))

            return redirect(view_device,
                            pk=device.pk,
                            product_line=device.product_line,
                            model=device.slug)
        else:
            messages.error(request, form.errors)

    data = prep_detail_view(request, pk, product_line, model)
    data['form'] = form

    return render(request, 'devices/form.html', data)
示例#6
0
def index(request):
    """
    Render the checkin homepage.

    @FIXME: would be nice to break this into smaller chunks...
    """
    if request.method == 'GET':
        try:
            init_session(request)
        except ConfigurationError as e:
            error = {'message': e}
            return render(request, 'checkin/error.html', error)

    title = _('Service Order Check-In')
    dcat = request.GET.get('d', 'mac')
    dmap = {
        'mac': _('Mac'),
        'iphone': _('iPhone'),
        'ipad': _('iPad'),
        'ipod': _('iPod'),
        'acc': _('Apple Accessory'),
        'beats': _('Beats Products'),
        'other': _('Other Devices'),
    }

    issue_form = IssueForm()
    device = Device(description=dmap[dcat])

    if dcat in ('mac', 'iphone', 'ipad', 'ipod'):
        sn_form = AppleSerialNumberForm()
    else:
        sn_form = SerialNumberForm()

    tags = Tag.objects.filter(type="order")
    device_form = DeviceForm(instance=device)
    customer_form = CustomerForm(request)

    if request.method == 'POST':

        if not request.session.test_cookie_worked():
            error = {
                'message': _('Please enable cookies to use this application.')
            }
            return render(request, 'checkin/error.html', error)
        else:
            request.session.delete_test_cookie()

        sn_form = SerialNumberForm(request.POST)
        issue_form = IssueForm(request.POST, request.FILES)
        customer_form = CustomerForm(request, request.POST)
        device_form = DeviceForm(request.POST, request.FILES)

        if device_form.is_valid() and issue_form.is_valid(
        ) and customer_form.is_valid():

            user = get_object_or_404(User, pk=request.session['checkin_user'])

            idata = issue_form.cleaned_data
            ddata = device_form.cleaned_data
            cdata = customer_form.cleaned_data
            customer_id = request.session.get('checkin_customer')

            if customer_id:
                customer = get_object_or_404(Customer, pk=customer_id)
            else:
                customer = Customer()

            name = u'{0} {1}'.format(cdata['fname'], cdata['lname'])

            if len(cdata['company']):
                name += ', ' + cdata['company']

            customer.name = name
            customer.city = cdata['city']
            customer.phone = cdata['phone']
            customer.email = cdata['email']
            customer.phone = cdata['phone']
            customer.zip_code = cdata['postal_code']
            customer.street_address = cdata['address']
            customer.save()

            order = Order(customer=customer, created_by=user)
            order.location_id = request.session['checkin_location']
            order.checkin_location = cdata['checkin_location']
            order.checkout_location = cdata['checkout_location']

            order.save()
            order.check_in(user)

            try:
                device = get_device(request, ddata['sn'])
            except GsxError as e:
                pass

            device.username = ddata['username']
            device.password = ddata['password']
            device.description = ddata['description']
            device.purchased_on = ddata['purchased_on']
            device.purchase_country = ddata['purchase_country']
            device.save()

            order.add_device(device, user)

            note = Note(created_by=user, body=idata['issue_description'])
            note.is_reported = True
            note.order = order
            note.save()

            # Proof of purchase was supplied
            if ddata.get('pop'):
                f = {'content_type': Attachment.get_content_type('note').pk}
                f['object_id'] = note.pk
                a = AttachmentForm(f, {'content': ddata['pop']})
                a.save()

            if request.POST.get('tags'):
                order.set_tags(request.POST.getlist('tags'), request.user)

            # Check checklists early for validation
            answers = []

            # @FIXME: should try to move this to a formset...
            for k, v in request.POST.items():
                if k.startswith('__cl__'):
                    answers.append('- **' + k[6:] + '**: ' + v)

            if len(answers) > 0:
                note = Note(created_by=user, body="\r\n".join(answers))

                if Configuration.true('checkin_report_checklist'):
                    note.is_reported = True

                note.order = order
                note.save()

            # mark down internal notes (only if logged in)
            if len(idata.get('notes')):
                note = Note(created_by=user, body=idata['notes'])
                note.is_reported = False
                note.order = order
                note.save()

            # mark down condition of device
            if len(ddata.get('condition')):
                note = Note(created_by=user, body=ddata['condition'])
                note.is_reported = True
                note.order = order
                note.save()

            # mark down supplied accessories
            if len(ddata.get('accessories')):
                accs = ddata['accessories'].strip().split("\n")
                order.set_accessories(accs, device)

            redirect_to = thanks
            """
            if request.user.is_authenticated():
                if request.user.autoprint:
                    redirect_to = print_confirmation
            """
            return redirect(redirect_to, order.url_code)

    try:
        pk = Configuration.conf('checkin_checklist')
        questions = ChecklistItem.objects.filter(checklist_id=pk)
    except ValueError:
        # Checklists probably not configured
        pass

    if request.GET.get('phone'):
        return find_customer(request, request.GET['phone'])

    if request.GET.get('sn'):
        return find_device(request)

    return render(request, "checkin/newindex.html", locals())
示例#7
0
def get_gsx_search_results(request, what, param, query):
    """
    The second phase of a GSX search.
    There should be an active GSX session open at this stage.
    """
    data = {}
    results = []
    query = query.upper()
    device = Device(sn=query)
    error_template = "search/results/gsx_error.html"

    # @TODO: this isn't a GSX search. Move it somewhere else.
    if what == "orders":
        try:
            if param == 'serialNumber':
                device = Device.objects.get(sn__exact=query)
            if param == 'alternateDeviceId':
                device = Device.objects.get(imei__exact=query)
        except (
                Device.DoesNotExist,
                ValueError,
        ):
            return render(request, "search/results/gsx_notfound.html")

        orders = device.order_set.all()
        return render(request, "orders/list.html", locals())

    if what == "warranty":
        # Update wty info if device has been serviced before
        try:
            device = Device.objects.get(sn__exact=query)
            device.update_gsx_details()
        except Exception:
            try:
                device = Device.from_gsx(query, user=request.user)
            except Exception as e:
                return render(request, error_template, {'message': e})

        results.append(device)

        # maybe it's a device we've already replaced...
        try:
            soi = ServiceOrderItem.objects.get(sn__iexact=query)
            results[0].repeat_service = soi.order
        except ServiceOrderItem.DoesNotExist:
            pass

    if what == "parts":
        # looking for parts
        if param == "partNumber":
            # ... with a part number
            part = gsxws.Part(partNumber=query)

            try:
                partinfo = part.lookup()
            except gsxws.GsxError as e:
                return render(request, error_template, {'message': e})

            product = Product.from_gsx(partinfo)
            cache.set(query, product)
            results.append(product)

        if param == "serialNumber":
            try:
                dev = Device.from_gsx(query)
                products = dev.get_parts()
                return render(request, "devices/parts.html", locals())
            except gsxws.GsxError as message:
                return render(request, "search/results/gsx_error.html",
                              locals())

        if param == "productName":
            product = gsxws.Product(productName=query)
            parts = product.parts()
            for p in parts:
                results.append(Product.from_gsx(p))

    if what == "repairs":
        # Looking for GSX repairs
        if param == "serialNumber":
            # ... with a serial number
            try:
                device = gsxws.Product(query)
                #results = device.repairs()
                for i, p in enumerate(device.repairs()):
                    d = {'purchaseOrderNumber': p.purchaseOrderNumber}
                    d['repairConfirmationNumber'] = p.repairConfirmationNumber
                    d['createdOn'] = p.createdOn
                    # @TODO: move the encoding hack to py-gsxws
                    d['customerName'] = p.customerName.encode('utf-8')
                    d['repairStatus'] = p.repairStatus
                    results.append(d)
            except gsxws.GsxError as e:
                return render(request, "search/results/gsx_notfound.html")

        elif param == "dispatchId":
            # ... with a repair confirmation number
            repair = gsxws.Repair(number=query)
            try:
                results = repair.lookup()
            except gsxws.GsxError as message:
                return render(request, error_template, locals())

    return render(request, "devices/search_gsx_%s.html" % what, locals())