def warranty(request, warranty_id):
    user_profile = request.user.userprofile

    if request.method == "POST":
        try:
            image_types = {
                "PROOF": "proof of purchase",
                "IMAGE": "product image"
            }

            file_type = request.POST.get("file_type", "IMAGE")
            description = request.POST.get("image_description", "")
            warranty = Warranty.objects.get(pk=warranty_id)
            count = 0
            for afile in request.FILES.getlist('files'):
                count += 1
                warranty_image = WarrantyImage(warranty=warranty,
                                               type=file_type,
                                               description=description,
                                               file_path=afile)
                warranty_image.save()

                action = "Uploaded '{}' as {}".format(afile, image_types[file_type])
                warranty_history = WarrantyHistory(warranty=warranty, user_profile=user_profile, action=action)
                warranty_history.save()

            if count > 0:
                messages.success(request, "Successfully uploaded file(s)!")
            else:
                messages.error(request, "No files were uploaded!")
        except Exception as e:
            messages.error(request, "Error uploading images!")

    return render_page(request, "main/warranty.html", "WARRANTY", {"warranty_id": warranty_id})
def api_warranty_images_image(request, warranty_id, warranty_image_id):
    user_profile = request.user.userprofile

    return_object = {}

    try:
        warranty_image = WarrantyImage.objects.get(pk=warranty_image_id)
        warranty_image_dict = warranty_image.convert_to_dict()

        if request.method == "DELETE":
            action = "Removed '{}' image '{}'".format(warranty_image_dict["typeDescription"],
                                                      warranty_image_dict["fileName"])
            warranty_history = WarrantyHistory(warranty=warranty_image.warranty,
                                               user_profile=user_profile,
                                               action=action)
            warranty_history.save()

            warranty_image.delete()
            return_object = {"status": "deleted"}
        else:
            return_object = warranty_image_dict

    except Exception as e:
        logger.error("api_warranty_images_image: %s" % (e))
        return HttpResponseServerError("Error getting warranty images!")

    return HttpResponse(json.dumps(return_object), content_type="application/json")
def warranty_new(request):
    user_profile = request.user.userprofile

    warranty = Warranty()
    warranty.save()
    warranty.claim_number = "CWC-{:04d}".format(warranty.pk)
    warranty.save()

    warranty_history = WarrantyHistory(warranty=warranty, user_profile=user_profile, action="New Claim")
    warranty_history.save()

    return HttpResponseRedirect("/warranty/{}/".format(warranty.pk))
def api_warranty_status(request, warranty_id):
    user_profile = request.user.userprofile

    return_object = {}

    try:
        warranty = Warranty.objects.get(pk=warranty_id)
        warranty_dict = warranty.convert_to_dict()

        if request.method == "GET":

            return_object["status"] = warranty_dict["status"]

        if request.method == "POST":
            model_json = request.POST.get("model", None)
            model = json.loads(model_json)

            if warranty.status != model["status"]:
                from_status = warranty_dict["statusDescription"]

                warranty.status = model["status"]
                warranty.status_date = datetime.now()
                warranty.save()

                warranty_dict = warranty.convert_to_dict()

                action = "Changed status from '{}' to '{}'".format(from_status, warranty_dict["statusDescription"])
                warranty_history = WarrantyHistory(warranty=warranty, user_profile=user_profile, action=action)
                warranty_history.save()

            return_object = {
                "model": warranty_dict,
            }

    except Exception as e:
        logger.error("api_warranty_set_status: %s" % (e))
        return HttpResponseServerError("Error saving warranty status!")

    return HttpResponse(json.dumps(return_object), content_type="application/json")
def api_warranty_create_claims(request):
    user_profile = request.user.userprofile

    count = int(request.GET.get("count", "10"))

    statuses = ["NEW", "PREAUTHORIZED", "RECEIVED", "AUTHORIZED", "NOTAUTHORIZED", "CLOSED"]
    styles = ["Afina", "Bachelor", "Cali", "Dakota", "Eden", "Faux Nias", "Grace", "Huntington", "Ivana", "Jaida"]
    colors = ["Africa", "Black", "Camo", "Denim", "Emerald", "Flannel", "Gray", "Hope Brown", "Java", "Kameleon"]
    damages = ["Broken Strap", "Crushed", "Curled", "Delaminated Layers", "Discolored", "Toe Post Pulled Out",
               "Torn Strap", "Worn / Cracked Top Sole"]

    return_list = []
    for i in range(1, count + 1):
        year = random.randint(2015, 2016)
        month = 1
        day = random.randint(1, 17)
        if year == 2015:
            month = random.randint(1, 12)
            day = random.randint(1, 28)

        status = statuses[random.randint(0, 5)]
        status_date = datetime.strptime("{}/{}/{}".format(month, day, year), '%m/%d/%Y')
        name = "Name {}".format(i)
        email = "*****@*****.**"
        phone = "Phone {}".format(i)
        address = "Address {}".format(i)
        style = styles[random.randint(0, 9)]
        color = colors[random.randint(0, 9)]
        damage = damages[random.randint(0, 7)]

        warranty = Warranty()
        warranty.save()

        warranty.claim_number = "CWC-{:04d}".format(warranty.pk)
        warranty.status = status
        warranty.status_date = status_date
        warranty.name = name
        warranty.email = email
        warranty.phone = phone
        warranty.address = address
        warranty.style = style
        warranty.color = color
        warranty.damage = damage
        warranty.save()

        warranty_dict = warranty.convert_to_dict()
        return_list.append(warranty_dict)

        warranty_history = WarrantyHistory(warranty=warranty, user_profile=user_profile, action="New claim")
        warranty_history.save()

        if status != "NEW":
            warranty_history = WarrantyHistory(warranty=warranty,
                                               user_profile=user_profile,
                                               action="Set status to {}".format(warranty_dict["statusDescription"]))
            warranty_history.save()

    return HttpResponse(json.dumps(return_list), content_type="application/json")
def api_warranty(request, warranty_id):
    user_profile = request.user.userprofile

    return_object = {}

    try:
        warranty = Warranty.objects.get(pk=warranty_id)
        warranty_dict = warranty.convert_to_dict()

        if request.method == "GET":
            return_object = warranty.convert_to_dict()

        if request.method == "POST":
            return_status = "success"
            actions = []
            before_status = warranty.status
            before_status_description = None
            model_json = request.POST.get("model", None)
            model = json.loads(model_json)
            if warranty.status != model["status"]:
                before_status_description = warranty_dict["statusDescription"]
                warranty.status = model["status"]
                warranty.status_date = datetime.now()

            if warranty.name != model["name"]:
                actions.append("Changed name '{}' to '{}'".format(warranty.name, model["name"]))
                warranty.name = model["name"]

            if warranty.email != model["email"]:
                actions.append("Changed email '{}' to '{}'".format(warranty.email, model["email"]))
                warranty.email = model["email"]

            if warranty.phone != model["phone"]:
                actions.append("Changed phone '{}' to '{}'".format(warranty.phone, model["phone"]))
                warranty.phone = model["phone"]

            if warranty.address != model["address"]:
                actions.append("Changed address '{}' to '{}'".format(warranty.address, model["address"]))
                warranty.address = model["address"]

            if warranty.style != model["style"]:
                actions.append("Changed style '{}' to '{}'".format(warranty.style, model["style"]))
                warranty.style = model["style"]

            if warranty.color != model["color"]:
                actions.append("Changed color '{}' to '{}'".format(warranty.color, model["color"]))
                warranty.color = model["color"]

            if warranty.damage != model["damage"]:
                actions.append("Changed damage '{}' to '{}'".format(warranty.damage, model["damage"]))
                warranty.damage = model["damage"]

            warranty.notes = model["notes"]
            if model["imageOverride"]:
                if not warranty.image_override:
                    actions.append("Set 'Image Override' to True")
                    warranty.image_override = True
            else:
                if warranty.image_override:
                    actions.append("Set 'Image Override' to False")
                    warranty.image_override = False

            warranty.save()
            warranty_dict = warranty.convert_to_dict()

            if before_status_description:
                actions.append("Changed status '{}' to '{}'".format(before_status_description,
                                                                    warranty_dict["statusDescription"]))

            if warranty.status == "PREAUTHORIZED" and not warranty.email_sent:
                if send_pre_authorized_email(request, warranty):
                    warranty.email_sent = True
                    warranty.save()
                    actions.append("Pre-authorized email sent")
                else:
                    return_status = "Error sending email, status not changed"
                    warranty.status = before_status
                    warranty.save()
                    actions.append("ERROR Sending Pre-authorized email!")

            for action in actions:
                warranty_history = WarrantyHistory(warranty=warranty, user_profile=user_profile, action=action)
                warranty_history.save()

            return_object = {
                "returnStatus": return_status,
                "model": warranty_dict,
            }

        if request.method == "DELETE":
            warranty.delete()
            return_object = {"status": "deleted"}

    except Exception as e:
        logger.error("api_warranty: {}".format(e))
        return HttpResponseServerError("Error getting warranty data!")

    return HttpResponse(json.dumps(return_object), content_type="application/json")