def handle(self, *args, **options): if len(args) < 1: print "Usage: updateprices username [start:finish]" sys.exit(1) start, counter = 0, 0 finish = 999999999999 if len(args) == 2: start, finish = args[1].split(':') GsxAccount.default(User.objects.get(username=args[0])) products = Product.objects.filter(pk__gt=start, pk__lt=finish) products = products.exclude(part_type='SERVICE') products = products.exclude(fixed_price=True) for i in products.order_by('id'): logging.debug('Updating product %d' % i.pk) try: i.update_price() i.save() counter += 1 except Exception as e: logging.debug(e) print '%d product prices updated' % counter
def run_test(self, test_id, request): """Run diagnostics on this device.""" GsxAccount.default(request.user) diags = diagnostics.Diagnostics(self.sn) diags.shipTo = request.user.location.gsx_shipto diags.diagnosticSuiteId = test_id return diags.run_test()
def diagnostics(request, pk): """ Fetches MRI diagnostics or initiates iOS diags from GSX """ device = get_object_or_404(Device, pk=pk) if request.GET.get('a') == 'init': if request.method == 'POST': from gsxws import diagnostics order = request.POST.get('order') order = device.order_set.get(pk=order) email = request.POST.get('email') diag = diagnostics.Diagnostics(serialNumber=device.sn) diag.emailAddress = email diag.shipTo = order.location.gsx_shipto try: GsxAccount.default(request.user) res = diag.initiate() msg = _('Diagnostics initiated - diags://%s') % res order.notify("init_diags", msg, request.user) messages.success(request, msg) except gsxws.GsxError, e: messages.error(request, e) return redirect(order) order = request.GET.get('order') order = device.order_set.get(pk=order) customer = order.customer url = request.path return render(request, "devices/diagnostic_init.html", locals())
def search_gsx(request, what, param, query): """ The first phase of a GSX search """ title = _(u'Search results for "%s"') % query try: act = request.session.get("gsx_account") act = None if act is None: GsxAccount.default(user=request.user) else: act.connect(request.user) except gsxws.GsxError as message: return render(request, "devices/search_gsx_error.html", locals()) if request.is_ajax(): if what == "parts": 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()) return get_gsx_search_results(request, what, param, query) return render(request, "devices/search_gsx.html", locals())
def choose(request, order_id): """ Choosing a device from within an SRO Does GSX lookup in case device is not found locally """ context = {'order': order_id} if request.method == "POST": query = request.POST.get('q').upper() results = Device.objects.filter(Q(sn__iexact=query) | Q(imei=query)) if len(results) < 1: try: current_order = request.session.get("current_order_id") current_order = Order.objects.get(pk=current_order) if current_order and current_order.queue: GsxAccount.default(request.user, current_order.queue) else: GsxAccount.default(request.user) results = [Device.from_gsx(query)] except Exception as e: context['error'] = e return render(request, "devices/choose-error.html", context) context['results'] = results return render(request, "devices/choose-list.html", context) return render(request, "devices/choose.html", context)
def handle(self, *args, **options): if len(args) < 1: print "Usage: updateprices username [start:finish]" sys.exit(1) start, counter = 0, 0 finish = 999999999999 if len(args) == 2: start, finish = args[1].split(':') GsxAccount.default(User.objects.get(username=args[0])) products = Product.objects.filter(pk__gt=start, pk__lt=finish) products = products.exclude(part_type='SERVICE') products = products.exclude(fixed_price=True) for i in products.order_by('id'): logging.debug('Updating product %d' % i.pk) try: i.update_price() i.save() counter += 1 except Exception, e: logging.debug(e)
def update_price(request, pk): product = Product.objects.get(pk=pk) try: GsxAccount.default(request.user) product.update_price() messages.success(request, _('Price info updated from GSX')) except Exception, e: messages.error(request, _('Failed to update price from GSX'))
def return_label(request, code, return_order): GsxAccount.default(request.user) try: label = gsxws.Returns(return_order) return HttpResponse(label.returnLabelFileData, content_type="application/pdf") except Exception as e: messages.add_message(request, messages.ERROR, e) return redirect('products-list')
def fetch_dc_url(request): from gsxws.diagnostics import Diagnostics GsxAccount.default(request.user) ship_to = request.user.location.gsx_shipto diags = Diagnostics(shipTo=ship_to) try: return redirect(diags.fetch_dc_url()) except Exception as e: return messages.error(request, e)
def handle(self, *args, **options): u = User.objects.get(username='******') GsxAccount.default(u) for p in Product.objects.filter(component_code='').exclude(labour_tier=''): try: info = ServicePart(part_number=p.code).lookup() p.component_code = info.componentCode.strip() p.save() except Exception, e: print e
def run_test(request, device, test_id): device = get_object_or_404(Device, pk=device) GsxAccount.default(request.user) try: result = device.run_test(test_id, request) messages.success(request, result.responseMessage) except Exception as e: messages.error(request, e) return redirect(request.session['return_to'])
def update_gsx_details(request, pk): """ Updates devices GSX warranty details """ device = get_object_or_404(Device, pk=pk) try: GsxAccount.default(request.user) device.update_gsx_details() messages.success(request, _("Warranty status updated successfully")) except Exception, e: messages.error(request, e)
def search_gsx_repairs(request, pk): """ Performs async GSX search for this device's GSX repairs """ device = get_object_or_404(Device, pk=pk) try: GsxAccount.default(request.user) results = {'results': device.get_gsx_repairs()} return render(request, "devices/search_gsx_repairs.html", results) except gsxws.GsxError as message: return render(request, "search/results/gsx_error.html", locals())
def update_price(request, pk): """ Updates the price info from GSX """ product = get_object_or_404(Product, pk=pk) try: GsxAccount.default(request.user) product.update_price() messages.success(request, _('Price info updated from GSX')) except Exception as e: messages.error(request, _('Failed to update price from GSX')) return redirect(product)
def get_diagnostics(self, user): """ Fetch GSX iOS or Repair diagnostics based on device type """ GsxAccount.default(user) from gsxws.diagnostics import Diagnostics if len(self.imei): diags = Diagnostics(alternateDeviceId=self.imei) else: diags = Diagnostics(serialNumber=self.sn) diags.shipTo = user.location.gsx_shipto return diags.fetch()
def handle(self, *args, **options): try: act = GsxAccount.fallback() except Exception as e: print >> sys.stderr, 'Failed to connect to GSX (%s)' % e sys.exit(-1) if 'articles' in options['verb']: # Update GSX articles articles = gsxws.comms.fetch() for a in articles: try: article = Article.from_gsx(a) try: content = gsxws.comms.content(article.gsx_id) article.content = content.articleContent except Exception as e: pass article.save() except ValueError as e: pass if 'comptia' in options['verb']: # Update raw CompTIA data (all product groups) try: codes = gsxws.comptia.fetch() caches['comptia'].set('codes', codes) except Exception as e: print >> sys.stderr, 'Failed to fetch CompTIA codes (%s)' % e sys.exit(-1) exit(0)
def update_gsx_details(request, pk): """ Updates devices GSX warranty details """ device = get_object_or_404(Device, pk=pk) try: GsxAccount.default(request.user) device.update_gsx_details() messages.success(request, _("Warranty status updated successfully")) except Exception as e: messages.error(request, e) if request.session.get('return_to'): return redirect(request.session['return_to']) return redirect(device)
def handle(self, *args, **options): try: act = GsxAccount.fallback() except Exception as e: print >> sys.stderr, 'Failed to connect to GSX (%s)' % e sys.exit(-1) if 'articles' in options['verb']: # Update GSX articles articles = gsxws.comms.fetch() for a in articles: try: article = Article.from_gsx(a) try: content = gsxws.comms.content(article.gsx_id) article.content = content.articleContent except Exception as e: pass article.save() except ValueError as e: pass if 'comptia' in options[ 'verb']: # Update raw CompTIA data (all product groups) try: codes = gsxws.comptia.fetch() caches['comptia'].set('codes', codes) except Exception as e: print >> sys.stderr, 'Failed to fetch CompTIA codes (%s)' % e sys.exit(-1) exit(0)
def create_repair(request, order_id, device_id, type): """ Creates a GSX repair for the specified SRO and device and redirects to the repair's edit page. """ from datetime import timedelta from django.utils import timezone order = get_object_or_404(Order, pk=order_id) device = order.devices.get(pk=device_id) repair = Repair(order=order, created_by=request.user, device=device) timediff = timezone.now() - order.created_at if timediff.seconds <= 3600: repair.unit_received_at = order.created_at - timedelta(hours=1) else: repair.unit_received_at = order.created_at repair.reference = request.user.gsx_poprefix + order.code try: repair.gsx_account = GsxAccount.default(request.user, order.queue) except Exception, e: messages.error(request, e) return redirect(order)
def order_stock(request, po_id): """ Submits the PO as a GSX Stocking Order Using the default GSX account. """ po = PurchaseOrder.objects.get(pk=po_id) if request.method == "POST": if po.submitted_at: messages.error(request, _(u'Purchase Order %s has already been submitted') % po.pk) return list_pos(request) act = GsxAccount.default(request.user) stock_order = gsxws.StockingOrder( shipToCode=act.ship_to, purchaseOrderNumber=po.id ) for i in po.purchaseorderitem_set.all(): stock_order.add_part(i.code, i.amount) try: result = stock_order.submit() po.supplier = "Apple" po.confirmation = result.confirmationNumber po.submit(request.user) msg = _("Products ordered with confirmation %s" % po.confirmation) messages.success(request, msg) except gsxws.GsxError, e: messages.error(request, e) return redirect(list_pos)
def order_stock(request, po_id): """ Submits the PO as a GSX Stocking Order Using the default GSX account. """ po = get_object_or_404(PurchaseOrder, pk=po_id) if request.method == "POST": if po.submitted_at: msg = _(u'Purchase Order %s has already been submitted') % po.pk messages.error(request, msg) return list_pos(request) act = GsxAccount.default(request.user) stock_order = gsxws.StockingOrder(shipToCode=act.ship_to, purchaseOrderNumber=po.id) for i in po.purchaseorderitem_set.all(): stock_order.add_part(i.code, i.amount) try: result = stock_order.submit() po.supplier = "Apple" po.confirmation = result.confirmationNumber po.submit(request.user) msg = _("Products ordered with confirmation %s" % po.confirmation) messages.success(request, msg) except gsxws.GsxError as e: messages.error(request, e) return redirect(list_pos) data = {'action': request.path} return render(request, "purchases/order_stock.html", data)
def parts(request, pk, order_id, queue_id): """ Lists available parts for this device/order taking into account the order's queues GSX Sold-To and the Location's corresponding GSX account """ from decimal import InvalidOperation device = get_object_or_404(Device, pk=pk) order = device.order_set.get(pk=order_id) try: # remember the right GSX account act = GsxAccount.default(request.user, order.queue) request.session['gsx_account'] = act.pk products = device.get_parts() except gsxws.GsxError as message: return render(request, "search/results/gsx_error.html", locals()) except AttributeError: message = _('Invalid serial number for parts lookup') return render(request, "search/results/gsx_error.html", locals()) except InvalidOperation: message = _( 'Error calculating prices. Please check your system settings.') return render(request, "search/results/gsx_error.html", locals()) return render(request, "devices/parts.html", locals())
def parts(request, pk, order_id, queue_id): """ Lists available parts for this device/order taking into account the order's queues GSX Sold-To and the Location's corresponding GSX account """ from decimal import InvalidOperation device = get_object_or_404(Device, pk=pk) order = device.order_set.get(pk=order_id) try: # remember the right GSX account act = GsxAccount.default(request.user, order.queue) request.session['gsx_account'] = act.pk products = device.get_parts() except gsxws.GsxError as message: return render(request, "search/results/gsx_error.html", locals()) except AttributeError: message = _('Invalid serial number for parts lookup') return render(request, "search/results/gsx_error.html", locals()) except InvalidOperation: message = _('Error calculating prices. Please check your system settings.') return render(request, "search/results/gsx_error.html", locals()) return render(request, "devices/parts.html", locals())
def create_repair(request, order_id, device_id, type): """ Creates a GSX repair for the specified SRO and device and redirects to the repair's edit page. """ from datetime import timedelta from django.utils import timezone order = get_object_or_404(Order, pk=order_id) device = order.devices.get(pk=device_id) repair = Repair(order=order, created_by=request.user, device=device) timediff = timezone.now() - order.created_at if timediff.seconds <= 3600: repair.unit_received_at = order.created_at - timedelta(hours=1) else: repair.unit_received_at = order.created_at repair.reference = request.user.gsx_poprefix + order.code try: repair.gsx_account = GsxAccount.default(request.user, order.queue) except Exception as e: messages.error(request, e) return redirect(order) repair.repair_type = type repair.tech_id = request.user.tech_id repair.save() return redirect(edit_repair, order.pk, repair.pk)
def search_gsx(request, what, param, query): """ The first phase of a GSX search. Sets up the GSX connection. @TODO: Should this be in Device.from_gsx()? """ title = _(u'Search results for "%s"') % query try: act = request.session.get("gsx_account") act = None if act is None: GsxAccount.default(user=request.user) else: act.connect(request.user) except gsxws.GsxError as message: return render(request, "devices/search_gsx_error.html", locals()) return render(request, "devices/search_gsx.html", locals())
def get_remote_symptom_codes(group): """ Remote lookup for symptom codes """ symptoms = {} cache = caches['comptia'] # First, try to load from global cache (updated every 24h) data = cache.get('codes') or {} if not data: # ... then try to fetch from GSX GsxAccount.fallback() data = gsxws.comptia.fetch() cache.set('codes', data) for k, v in data.get(group): symptoms[k] = v return symptoms
def upload_devices(request): """ User uploads device DB as tab-delimited CSV file SN USERNAME PASSWORD NOTES """ gsx_account = None form = DeviceUploadForm() if request.method == "POST": form = DeviceUploadForm(request.POST, request.FILES) if form.is_valid(): i = 0 df = form.cleaned_data['datafile'].read() if form.cleaned_data.get('do_warranty_check'): gsx_account = GsxAccount.default(request.user) for l in df.split("\r"): l = l.decode("latin-1").encode("utf-8") row = l.strip().split("\t") if gsx_account: try: device = Device.from_gsx(row[0]) except Exception, e: messages.error(request, e) break else: device = Device.objects.get_or_create(sn=row[0])[0] try: device.username = row[1] device.password = row[2] device.notes = row[3] except IndexError: pass device.save() i += 1 if form.cleaned_data.get("customer"): customer = form.cleaned_data['customer'] customer.devices.add(device) messages.success(request, _("%d devices imported") % i) return redirect(index)
def get_gsx_connection(request): act = GsxAccount.get_default_account() user = User.objects.get(pk=request.session['checkin_user']) location = Location.objects.get(pk=request.session['checkin_location']) return act.connect(user, location)
def from_gsx(cls, sn, device=None, cached=True, user=None): """ Initialize new Device with warranty info from GSX Or update existing one """ sn = sn.upper() cache_key = 'device-%s' % sn # Only cache unsaved devices if cached and device is None: if cache.get(cache_key): return cache.get(cache_key) arg = gsxws.validate(sn) if arg not in ("serialNumber", "alternateDeviceId",): raise ValueError(_(u"Invalid input for warranty check: %s") % sn) product = gsxws.Product(sn) if user and user.location: ship_to = user.location.gsx_shipto else: gsx_act = GsxAccount.get_default_account() ship_to = gsx_act.ship_to wty = product.warranty(ship_to=ship_to) model = product.model() if device is None: # serialNumber may sometimes come back empty serial_number = wty.serialNumber or sn device = Device(sn=serial_number) from servo.lib.utils import empty if empty(device.notes): device.notes = wty.notes or '' device.notes += wty.csNotes or '' device.has_onsite = product.has_onsite device.is_vintage = product.is_vintage device.description = product.description device.fmip_active = product.fmip_is_active device.slug = slugify(device.description) device.configuration = wty.configDescription or '' device.purchase_country = countries.by_name(wty.purchaseCountry) device.config_code = model.configCode device.product_line = model.productLine.replace(" ", "") device.parts_and_labor_covered = product.parts_and_labor_covered device.sla_description = wty.slaGroupDescription or '' device.contract_start_date = wty.contractCoverageStartDate device.contract_end_date = wty.contractCoverageEndDate device.onsite_start_date = wty.onsiteStartDate device.onsite_end_date = wty.onsiteEndDate if wty.estimatedPurchaseDate: device.purchased_on = wty.estimatedPurchaseDate device.image_url = wty.imageURL or '' device.manual_url = wty.manualURL or '' device.exploded_view_url = wty.explodedViewURL or '' if wty.warrantyStatus: device.set_wty_status(wty.warrantyStatus) if product.is_ios: ad = device.get_activation() device.imei = ad.imeiNumber or '' device.unlocked = product.is_unlocked(ad) device.applied_activation_policy = ad.appliedActivationDetails or '' device.initial_activation_policy = ad.initialActivationPolicyDetails or '' device.next_tether_policy = ad.nextTetherPolicyDetails or '' cache.set(cache_key, device) return device
def get_diagnostics(self, user): """ Fetch GSX iOS or Repair diagnostics based on device type """ GsxAccount.default(user) return self.to_gsx().diagnostics()
def fetch_tests(self, request): """Return applicable test suites.""" GsxAccount.default(request.user) diags = diagnostics.Diagnostics(self.sn) diags.shipTo = request.user.location.gsx_shipto return diags.fetch_suites()
def upload_devices(request): """ User uploads device DB as tab-delimited CSV file SN USERNAME PASSWORD NOTES """ gsx_account = None form = DeviceUploadForm() title = _('Upload devices') if request.GET.get('c'): customer = Customer.objects.get(pk=request.GET['c']) title = _('Upload devices for %s') % customer.name form.fields['customer'].initial = request.GET['c'] if request.method == "POST": form = DeviceUploadForm(request.POST, request.FILES) if form.is_valid(): import django_excel as excel import pyexcel.ext.xls # import it to handle xls file import pyexcel.ext.xlsx # import it to handle xlsx file counter, errors = 0, 0 datafile = form.cleaned_data['datafile'] sheet = datafile.get_sheet() if sheet.row[0][0] == 'SN': del (sheet.row[0]) # skip header row if form.cleaned_data.get('do_warranty_check'): gsx_account = GsxAccount.default(request.user) for row in sheet: if not len(row[0]): continue # skip empty rows if gsx_account: try: device = Device.from_gsx(row[0]) except Exception as e: messages.error(request, e) break else: device = Device.objects.get_or_create(sn=row[0])[0] device.username = row[1] device.password = row[2] device.notes = row[3] device.save() counter += 1 if form.cleaned_data.get("customer"): cid = form.cleaned_data['customer'] customer = Customer.objects.get(pk=cid) customer.devices.add(device) messages.success(request, _("%d devices imported") % counter) return redirect(index) data = {'form': form, 'action': request.path, 'title': title} return render(request, "devices/upload_devices.html", data)
def upload_devices(request): """ User uploads device DB as tab-delimited CSV file SN USERNAME PASSWORD NOTES """ gsx_account = None form = DeviceUploadForm() title = _('Upload devices') if request.GET.get('c'): customer = Customer.objects.get(pk=request.GET['c']) title = _('Upload devices for %s') % customer.name form.fields['customer'].initial = request.GET['c'] if request.method == "POST": form = DeviceUploadForm(request.POST, request.FILES) if form.is_valid(): import django_excel as excel import pyexcel.ext.xls # import it to handle xls file import pyexcel.ext.xlsx # import it to handle xlsx file counter, errors = 0, 0 datafile = form.cleaned_data['datafile'] sheet = datafile.get_sheet() if sheet.row[0][0] == 'SN': del(sheet.row[0]) # skip header row if form.cleaned_data.get('do_warranty_check'): gsx_account = GsxAccount.default(request.user) for row in sheet: if not len(row[0]): continue # skip empty rows if gsx_account: try: device = Device.from_gsx(row[0]) except Exception as e: messages.error(request, e) break else: device = Device.objects.get_or_create(sn=row[0])[0] device.username = row[1] device.password = row[2] device.notes = row[3] device.save() counter += 1 if form.cleaned_data.get("customer"): cid = form.cleaned_data['customer'] customer = Customer.objects.get(pk=cid) customer.devices.add(device) messages.success(request, _("%d devices imported") % counter) return redirect(index) data = {'form': form, 'action': request.path, 'title': title} return render(request, "devices/upload_devices.html", data)