Ejemplo n.º 1
0
def validate_or_raise(SerializerCls, data):
    serializer = SerializerCls(data=data)
    if not serializer.is_valid():
        logger.error(f"cannot serializer: cls:{SerializerCls} data:{data}")
        raise APIException("server validation error logged")
    return serializer
Ejemplo n.º 2
0
    def post(self, request, organization):
        """
        Create a New Release for an Organization
        ````````````````````````````````````````
        Create a new release for the given Organization.  Releases are used by
        Sentry to improve its error reporting abilities by correlating
        first seen events with the release that might have introduced the
        problem.
        Releases are also necessary for sourcemaps and other debug features
        that require manual upload for functioning well.

        :pparam string organization_slug: the slug of the organization the
                                          release belongs to.
        :param string version: a version identifier for this release.  Can
                               be a version number, a commit hash etc.
        :param string ref: an optional commit reference.  This is useful if
                           a tagged version has been provided.
        :param url url: a URL that points to the release.  This can be the
                        path to an online interface to the sourcecode
                        for instance.
        :param array projects: a list of project slugs that are involved in
                               this release
        :param datetime dateReleased: an optional date that indicates when
                                      the release went live.  If not provided
                                      the current time is assumed.
        :param array commits: an optional list of commit data to be associated
                              with the release. Commits must include parameters
                              ``id`` (the sha of the commit), and can optionally
                              include ``repository``, ``message``, ``patch_set``,
                              ``author_name``, ``author_email``, and ``timestamp``.
                              See [release without integration example](/workflow/releases/).
        :param array refs: an optional way to indicate the start and end commits
                           for each repository included in a release. Head commits
                           must include parameters ``repository`` and ``commit``
                           (the HEAD sha). They can optionally include ``previousCommit``
                           (the sha of the HEAD of the previous release), which should
                           be specified if this is the first time you've sent commit data.
                           ``commit`` may contain a range in the form of ``previousCommit..commit``
        :auth: required
        """
        bind_organization_context(organization)
        serializer = ReleaseSerializerWithProjects(data=request.data)

        with configure_scope() as scope:
            if serializer.is_valid():
                result = serializer.validated_data
                scope.set_tag("version", result["version"])

                allowed_projects = {
                    p.slug: p
                    for p in self.get_projects(request, organization)
                }

                projects = []
                for slug in result["projects"]:
                    if slug not in allowed_projects:
                        return Response(
                            {"projects": ["Invalid project slugs"]},
                            status=400)
                    projects.append(allowed_projects[slug])

                new_status = result.get("status")

                # release creation is idempotent to simplify user
                # experiences
                try:
                    release, created = Release.objects.get_or_create(
                        organization_id=organization.id,
                        version=result["version"],
                        defaults={
                            "ref": result.get("ref"),
                            "url": result.get("url"),
                            "owner": result.get("owner"),
                            "date_released": result.get("dateReleased"),
                            "status": new_status or ReleaseStatus.OPEN,
                        },
                    )
                except IntegrityError:
                    raise APIException(
                        "Could not create the release it conflicts with existing data",
                        409)
                if created:
                    release_created.send_robust(release=release,
                                                sender=self.__class__)

                if not created and new_status is not None and new_status != release.status:
                    release.status = new_status
                    release.save()

                new_projects = []
                for project in projects:
                    created = release.add_project(project)
                    if created:
                        new_projects.append(project)

                if release.date_released:
                    for project in new_projects:
                        Activity.objects.create(
                            type=Activity.RELEASE,
                            project=project,
                            ident=Activity.get_version_ident(
                                result["version"]),
                            data={"version": result["version"]},
                            datetime=release.date_released,
                        )

                commit_list = result.get("commits")
                if commit_list:
                    release.set_commits(commit_list)

                refs = result.get("refs")
                if not refs:
                    refs = [{
                        "repository": r["repository"],
                        "previousCommit": r.get("previousId"),
                        "commit": r["currentId"],
                    } for r in result.get("headCommits", [])]
                scope.set_tag("has_refs", bool(refs))
                if refs:
                    if not request.user.is_authenticated():
                        scope.set_tag("failure_reason",
                                      "user_not_authenticated")
                        return Response(
                            {
                                "refs": [
                                    "You must use an authenticated API token to fetch refs"
                                ]
                            },
                            status=400,
                        )
                    fetch_commits = not commit_list
                    try:
                        release.set_refs(refs,
                                         request.user,
                                         fetch=fetch_commits)
                    except InvalidRepository as e:
                        scope.set_tag("failure_reason", "InvalidRepository")
                        return Response({"refs": [six.text_type(e)]},
                                        status=400)

                if not created and not new_projects:
                    # This is the closest status code that makes sense, and we want
                    # a unique 2xx response code so people can understand when
                    # behavior differs.
                    #   208 Already Reported (WebDAV; RFC 5842)
                    status = 208
                else:
                    status = 201

                analytics.record(
                    "release.created",
                    user_id=request.user.id
                    if request.user and request.user.id else None,
                    organization_id=organization.id,
                    project_ids=[project.id for project in projects],
                    user_agent=request.META.get("HTTP_USER_AGENT", ""),
                    created_status=status,
                )
                scope.set_tag("success_status", status)
                return Response(serialize(release, request.user),
                                status=status)
            scope.set_tag("failure_reason", "serializer_error")
            return Response(serializer.errors, status=400)
Ejemplo n.º 3
0
def appid_validate(data):
    if Users.objects.filter(appid=data).exists():
        return data
    else:
        raise APIException({'detail': 'User does not exists'})
Ejemplo n.º 4
0
 def create(self, request, pk):
     qs = self.get_object()
     if qs.openid != self.request.auth.openid:
         raise APIException(
             {"detail": "Cannot update data which not yours"})
     else:
         data = self.request.data
         if 'bin_name' not in data and 'move_to_bin' not in data:
             raise APIException({"detail": "Please Enter The Bin Name"})
         else:
             current_bin_detail = binset.objects.filter(
                 openid=self.request.auth.openid,
                 bin_name=str(data['bin_name'])).first()
             move_to_bin_detail = binset.objects.filter(
                 openid=self.request.auth.openid,
                 bin_name=str(data['move_to_bin'])).first()
             goods_qty_change = stocklist.objects.filter(
                 openid=self.request.auth.openid,
                 goods_code=str(data['goods_code'])).first()
             if int(data['move_qty']) <= 0:
                 raise APIException({"detail": "Move QTY Must > 0"})
             else:
                 bin_move_qty_res = qs.goods_qty - qs.pick_qty - qs.picked_qty - int(
                     data['move_qty'])
                 if bin_move_qty_res > 0:
                     qs.goods_qty = qs.goods_qty - qs.pick_qty - int(
                         data['move_qty'])
                     if current_bin_detail.bin_property == 'Damage':
                         if move_to_bin_detail.bin_property == 'Damage':
                             pass
                         elif move_to_bin_detail.bin_property == 'Inspection':
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                 data['move_qty'])
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Holding':
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                 data['move_qty'])
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                 data['move_qty'])
                         else:
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                 data['move_qty'])
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                 data['move_qty'])
                     elif current_bin_detail.bin_property == 'Inspection':
                         if move_to_bin_detail.bin_property == 'Damage':
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                 data['move_qty'])
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Inspection':
                             pass
                         elif move_to_bin_detail.bin_property == 'Holding':
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                 data['move_qty'])
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                 data['move_qty'])
                         else:
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                 data['move_qty'])
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                 data['move_qty'])
                     elif current_bin_detail.bin_property == 'Holding':
                         if move_to_bin_detail.bin_property == 'Damage':
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                 data['move_qty'])
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Inspection':
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                 data['move_qty'])
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Holding':
                             pass
                         else:
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                 data['move_qty'])
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                 data['move_qty'])
                     else:
                         if move_to_bin_detail.bin_property == 'Damage':
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                 data['move_qty'])
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Inspection':
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                 data['move_qty'])
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Holding':
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                 data['move_qty'])
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                 data['move_qty'])
                         else:
                             pass
                     StockBinModel.objects.create(
                         openid=self.request.auth.openid,
                         bin_name=str(data['move_to_bin']),
                         goods_code=str(data['goods_code']),
                         goods_desc=goods_qty_change.goods_desc,
                         goods_qty=int(data['move_qty']),
                         bin_size=move_to_bin_detail.bin_size,
                         bin_property=move_to_bin_detail.bin_property,
                         t_code=Md5.md5(str(data['goods_code'])),
                         create_time=qs.create_time)
                     if move_to_bin_detail.empty_label == True:
                         move_to_bin_detail.empty_label = False
                         move_to_bin_detail.save()
                     goods_qty_change.save()
                     qs.save()
                 elif bin_move_qty_res == 0:
                     qs.goods_qty = qs.picked_qty
                     if current_bin_detail.bin_property == 'Damage':
                         if move_to_bin_detail.bin_property == 'Damage':
                             pass
                         elif move_to_bin_detail.bin_property == 'Inspection':
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                 data['move_qty'])
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Holding':
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                 data['move_qty'])
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                 data['move_qty'])
                         else:
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                 data['move_qty'])
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                 data['move_qty'])
                     elif current_bin_detail.bin_property == 'Inspection':
                         if move_to_bin_detail.bin_property == 'Damage':
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                 data['move_qty'])
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Inspection':
                             pass
                         elif move_to_bin_detail.bin_property == 'Holding':
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                 data['move_qty'])
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                 data['move_qty'])
                         else:
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                 data['move_qty'])
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                 data['move_qty'])
                     elif current_bin_detail.bin_property == 'Holding':
                         if move_to_bin_detail.bin_property == 'Damage':
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                 data['move_qty'])
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Inspection':
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                 data['move_qty'])
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Holding':
                             pass
                         else:
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                 data['move_qty'])
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                 data['move_qty'])
                     else:
                         if move_to_bin_detail.bin_property == 'Damage':
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                 data['move_qty'])
                             goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Inspection':
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                 data['move_qty'])
                             goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                 data['move_qty'])
                         elif move_to_bin_detail.bin_property == 'Holding':
                             goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                 data['move_qty'])
                             goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                 data['move_qty'])
                         else:
                             pass
                     StockBinModel.objects.create(
                         openid=self.request.auth.openid,
                         bin_name=str(data['move_to_bin']),
                         goods_code=str(data['goods_code']),
                         goods_desc=goods_qty_change.goods_desc,
                         goods_qty=int(data['move_qty']),
                         bin_size=move_to_bin_detail.bin_size,
                         bin_property=move_to_bin_detail.bin_property,
                         t_code=Md5.md5(str(data['goods_code'])),
                         create_time=qs.create_time)
                     if move_to_bin_detail.empty_label == True:
                         move_to_bin_detail.empty_label = False
                         move_to_bin_detail.save()
                     goods_qty_change.save()
                     if qs.goods_qty == 0:
                         qs.delete()
                     else:
                         qs.save()
                     if StockBinModel.objects.filter(
                             openid=self.request.auth.openid,
                             bin_name=str(data['bin_name'])).exists():
                         pass
                     else:
                         current_bin_detail.empty_label = True
                     current_bin_detail.save()
                 elif bin_move_qty_res < 0:
                     raise APIException(
                         {"detail": "Move Qty must < Bin Goods Qty"})
                 else:
                     pass
             headers = self.get_success_headers(data)
             return Response(data, status=200, headers=headers)
Ejemplo n.º 5
0
 def perform_create(self, serializer):
     queryset = Participate.objects.filter(user=self.request.user,gathering=serializer.validated_data.get('gathering'))
     if queryset.exists():
         queryset.delete()
         raise APIException("You have signed up")
     instance = serializer.save(user=self.request.user)
Ejemplo n.º 6
0
def metrics_assessment(request, run_id):
    try:
        report_path = os.path.join(settings.MEDIA_ROOT, "user_" + run_id)

        run = Run.objects.get(run_id=run_id)
        use_case = "Gainsight" if run.gainsight else ""
        outcome_data = pd.read_csv(run.outcome_data.path, encoding="cp1252")
        history_data = pd.read_csv(run.scorecard_history.path, encoding="cp1252")
        company_data = None
        cols = run.metric_cols.split(",")

        if run.gainsight:
            company_data = pd.read_csv(run.account_details.path, encoding="cp1252")

        obj = HealthAssessment(
            ID="Account ID",
            churn_date=run.churn_date,
            snapshot_date=run.snapshot_date,
            target="Status",
            metrics_col=cols,
        )

        processed = obj.preprocess_data(outcome_data, history_data, company_data)
        model_record = obj.run_health_assessment(processed)
        model_record.fillna(0, inplace=True)
        model_record.model_status = model_record.model_status.apply(
            lambda x: 0 if x == "Active" else 1
        )
        ks_output_dict = get_insights(
            data=model_record, metrics_cols=cols, target_col="model_status"
        )

        output_ks_dict = dict()

        for key in ks_output_dict:
            output_ks_dict[key] = []
            for index in ks_output_dict[key]["kstable"].index:
                current_risk_value = ks_output_dict[key]["kstable"][
                    "Intensity of Risk"
                ][index]
                if math.isnan(current_risk_value):
                    output_ks_dict[key].append(
                        {"bin": str(index), "value": 0,}
                    )
                else:
                    output_ks_dict[key].append(
                        {"bin": str(index), "value": current_risk_value,}
                    )

        create_report_entry = True
        outcome_timeline_reportpath = os.path.join(report_path, "outcome_timeline.csv")

        if os.path.exists(outcome_timeline_reportpath):
            create_report_entry = False

        outcome_timeline = obj.get_outcome_timeline(
            outcome_data, "Inactivation Date"
        )  # OutCome Timeline Report
        outcome_timeline.to_csv(outcome_timeline_reportpath, header=True)

        if create_report_entry:
            report = Report(
                run_id=run,
                report_name="Monthly Target Distribution",
                report_path=outcome_timeline_reportpath,
            )
            report.save()

        return Response({"run_id": run_id, "ks_dict": output_ks_dict})
    except Exception as e:
        logger.exception(e)
        raise APIException(str(e))
Ejemplo n.º 7
0
 def update(self, request, *args, **kwargs):
     data = request.data
     if AsnListModel.objects.filter(openid=self.request.auth.openid,
                                    asn_code=str(data['asn_code']),
                                    asn_status=1,
                                    is_delete=False).exists():
         if supplier.objects.filter(openid=self.request.auth.openid,
                                    supplier_name=str(data['supplier']),
                                    is_delete=False).exists():
             for i in range(len(data['goods_code'])):
                 check_data = {
                     'openid': self.request.auth.openid,
                     'asn_code': str(data['asn_code']),
                     'supplier': str(data['supplier']),
                     'goods_code': str(data['goods_code'][i]),
                     'goods_qty': int(data['goods_qty'][i]),
                     'creater': str(data['creater'])
                 }
                 serializer = self.get_serializer(data=check_data)
                 serializer.is_valid(raise_exception=True)
             asn_detail_list = AsnDetailModel.objects.filter(
                 openid=self.request.auth.openid,
                 asn_code=str(data['asn_code']))
             for v in range(len(asn_detail_list)):
                 goods_qty_change = stocklist.objects.filter(
                     openid=self.request.auth.openid,
                     goods_code=str(asn_detail_list[v].goods_code)).first()
                 goods_qty_change.goods_qty = goods_qty_change.goods_qty - asn_detail_list[
                     v].goods_qty
                 if goods_qty_change.goods_qty < 0:
                     goods_qty_change.goods_qty = 0
                 goods_qty_change.asn_stock = goods_qty_change.asn_stock - asn_detail_list[
                     v].goods_qty
                 if goods_qty_change.asn_stock < 0:
                     goods_qty_change.asn_stock = 0
                 goods_qty_change.save()
             asn_detail_list.delete()
             post_data_list = []
             weight_list = []
             volume_list = []
             for j in range(len(data['goods_code'])):
                 goods_detail = goods.objects.filter(
                     openid=self.request.auth.openid,
                     goods_code=str(data['goods_code'][j]),
                     is_delete=False).first()
                 goods_weight = round(
                     goods_detail.goods_weight * int(data['goods_qty'][j]) /
                     1000, 8)
                 goods_volume = round(
                     goods_detail.unit_volume * int(data['goods_qty'][j]),
                     8)
                 if stocklist.objects.filter(
                         openid=self.request.auth.openid,
                         goods_code=str(data['goods_code'][j])).exists():
                     goods_qty_change = stocklist.objects.filter(
                         openid=self.request.auth.openid,
                         goods_code=str(data['goods_code'][j])).first()
                     goods_qty_change.goods_qty = goods_qty_change.goods_qty + int(
                         data['goods_qty'][j])
                     goods_qty_change.asn_stock = goods_qty_change.asn_stock + int(
                         data['goods_qty'][j])
                     goods_qty_change.save()
                 else:
                     stocklist.objects.create(
                         openid=self.request.auth.openid,
                         goods_code=str(data['goods_code'][j]),
                         goods_desc=goods_detail.goods_desc,
                         goods_qty=int(data['goods_qty'][j]),
                         asn_stock=int(data['goods_qty'][j]))
                 post_data = AsnDetailModel(
                     openid=self.request.auth.openid,
                     asn_code=str(data['asn_code']),
                     supplier=str(data['supplier']),
                     goods_code=str(data['goods_code'][j]),
                     goods_qty=int(data['goods_qty'][j]),
                     goods_weight=goods_weight,
                     goods_volume=goods_volume,
                     creater=str(data['creater']))
                 post_data_list.append(post_data)
                 weight_list.append(goods_weight)
                 volume_list.append(goods_volume)
             total_weight = sumOfList(weight_list, len(weight_list))
             total_volume = sumOfList(volume_list, len(volume_list))
             supplier_city = supplier.objects.filter(
                 openid=self.request.auth.openid,
                 supplier_name=str(data['supplier']),
                 is_delete=False).first().supplier_city
             warehouse_city = warehouse.objects.filter(
                 openid=self.request.auth.openid).first().warehouse_city
             transportation_fee = transportation.objects.filter(
                 Q(openid=self.request.auth.openid,
                   send_city__icontains=supplier_city,
                   receiver_city__icontains=warehouse_city,
                   is_delete=False)
                 | Q(openid='init_data',
                     send_city__icontains=supplier_city,
                     receiver_city__icontains=warehouse_city,
                     is_delete=False))
             transportation_res = {"detail": []}
             if len(transportation_fee) >= 1:
                 transportation_list = []
                 for k in range(len(transportation_fee)):
                     transportation_cost = transportation_calculate(
                         total_weight, total_volume,
                         transportation_fee[k].weight_fee,
                         transportation_fee[k].volume_fee,
                         transportation_fee[k].min_payment)
                     transportation_detail = {
                         "transportation_supplier":
                         transportation_fee[k].transportation_supplier,
                         "transportation_cost": transportation_cost
                     }
                     transportation_list.append(transportation_detail)
                 transportation_res['detail'] = transportation_list
             AsnDetailModel.objects.bulk_create(post_data_list,
                                                batch_size=100)
             AsnListModel.objects.filter(
                 openid=self.request.auth.openid,
                 asn_code=str(data['asn_code'])).update(
                     supplier=str(data['supplier']),
                     total_weight=total_weight,
                     total_volume=total_volume,
                     transportation_fee=transportation_res)
             return Response({"success": "Yes"}, status=200)
         else:
             raise APIException({"detail": "Supplier does not exists"})
     else:
         raise APIException(
             {"detail": "ASN Code has been deliveried or does not exists"})
Ejemplo n.º 8
0
 def get(self, request):
     raise APIException('response')
Ejemplo n.º 9
0
 def get(self, request):
     raise APIException('with logging')
Ejemplo n.º 10
0
def save_facebook_token(request):
    """Save facebook token"""
    logger.debug("Facebook callback just landed")
    print(request.GET)
    error = request.query_params.get('error_code', False)
    error_description = request.query_params.get('error_message', '')
    if error:
        raise APIException("Facebook: " + error_description)

    original_payload = request.query_params.get('state', None)
    payload = request.query_params.get('state', None)
    if payload is None:
        raise ValidationError("No payload specified")
    else:
        try:
            payload = base64.b64decode(payload).decode("utf-8")
            payload = parse_qs(payload)
        except:
            raise ValidationError("Cannot decode payload in base64")

    if "url" not in payload:
        logger.exception(payload)
        raise ValidationError("No url specified from the slack payload")

    if "user" not in payload:
        logger.exception(payload)
        raise ValidationError("No user id specified from the slack payload")

    if "a" not in payload:
        logger.exception(payload)
        raise ValidationError("No academy id specified from the slack payload")

    try:
        academy = Academy.objects.get(id=payload["a"][0])
    except Exception as e:
        raise ValidationError("Not exist academy with that id") from e

    try:
        user = User.objects.get(id=payload["user"][0])
    except Exception as e:
        raise ValidationError("Not exist user with that id") from e

    # token = request.query_params.get('token', None)
    # if token == None:
    #     raise ValidationError("No facebook token specified")

    code = request.query_params.get('code', None)
    if code is None:
        raise ValidationError("No slack code specified")

    params = {
        'client_id': os.getenv('FACEBOOK_CLIENT_ID', ""),
        'client_secret': os.getenv('FACEBOOK_SECRET', ""),
        'redirect_uri': os.getenv('FACEBOOK_REDIRECT_URL', ""),
        'code': code,
    }
    resp = requests.post('https://graph.facebook.com/v8.0/oauth/access_token',
                         data=params)
    if resp.status_code == 200:

        logger.debug("Facebook responded with 200")

        facebook_data = resp.json()
        if 'access_token' not in facebook_data:
            logger.debug("Facebook response body")
            logger.debug(facebook_data)
            raise APIException("Facebook error status: " +
                               facebook_data['error_message'])

        # delete all previous credentials for the same team
        CredentialsFacebook.objects.filter(user_id=user.id).delete()

        utc_now = timezone.now()
        expires_at = utc_now + \
            timezone.timedelta(milliseconds=facebook_data['expires_in'])

        credentials = CredentialsFacebook(
            user=user,
            academy=academy,
            expires_at=expires_at,
            token=facebook_data['access_token'],
        )
        credentials.save()

        params = {
            'access_token': facebook_data['access_token'],
            'fields': 'id,email',
        }
        resp = requests.post('https://graph.facebook.com/me', data=params)
        if resp.status_code == 200:
            logger.debug("Facebook responded with 200")
            facebook_data = resp.json()
            if "email" in facebook_data:
                credentials.email = facebook_data['email']
            if "id" in facebook_data:
                credentials.facebook_id = facebook_data['id']
            credentials.save()

        return HttpResponseRedirect(redirect_to=payload["url"][0])
Ejemplo n.º 11
0
def raise_api_exception(code, msg):
    e = APIException()
    e.status_code = code
    e.detail = msg
    raise e
Ejemplo n.º 12
0
def save_slack_token(request):
    """Get Slack token and redirect to authorization route"""
    logger.debug("Slack callback just landed")

    error = request.query_params.get('error', False)
    error_description = request.query_params.get('error_description', '')
    if error:
        raise APIException("Slack: " + error_description)

    original_payload = request.query_params.get('payload', None)
    payload = request.query_params.get('payload', None)
    if payload is None:
        raise ValidationError("No payload specified")
    else:
        try:
            payload = base64.b64decode(payload).decode("utf-8")
            payload = parse_qs(payload)
        except:
            raise ValidationError("Cannot decode payload in base64")

    if "url" not in payload:
        logger.exception(payload)
        raise ValidationError("No url specified from the slack payload")

    if "user" not in payload:
        logger.exception(payload)
        raise ValidationError("No user id specified from the slack payload")

    if "a" not in payload:
        logger.exception(payload)
        raise ValidationError("No academy id specified from the slack payload")

    try:
        academy = Academy.objects.get(id=payload["a"][0])
    except Exception as e:
        raise ValidationError("Not exist academy with that id") from e

    user = None
    try:
        user = User.objects.get(id=payload["user"][0])
    except Exception as e:
        raise ValidationError("Not exist user with that id") from e

    code = request.query_params.get('code', None)
    if code is None:
        raise ValidationError("No slack code specified")

    params = {
        'client_id': os.getenv('SLACK_CLIENT_ID', ""),
        'client_secret': os.getenv('SLACK_SECRET', ""),
        'redirect_uri':
        os.getenv('SLACK_REDIRECT_URL', "") + "?payload=" + original_payload,
        'code': code,
    }
    # print("params", params)
    resp = requests.post('https://slack.com/api/oauth.v2.access', data=params)
    if resp.status_code == 200:

        logger.debug("Slack responded with 200")

        slack_data = resp.json()
        if 'access_token' not in slack_data:
            print("Slack response body", slack_data)
            raise APIException("Slack error status: " + slack_data['error'])

        slack_data = resp.json()
        logger.debug(slack_data)

        # delete all previous credentials for the same team and cohort
        CredentialsSlack.objects.filter(app_id=slack_data['app_id'],
                                        team_id=slack_data['team']['id'],
                                        user__id=user.id).delete()
        credentials = CredentialsSlack(
            user=user,
            app_id=slack_data['app_id'],
            bot_user_id=slack_data['bot_user_id'],
            token=slack_data['access_token'],
            team_id=slack_data['team']['id'],
            team_name=slack_data['team']['name'],
            authed_user=slack_data['authed_user']['id'],
        )
        credentials.save()

        team = SlackTeam.objects.filter(
            academy__id=academy.id, slack_id=slack_data['team']['id']).first()
        if team is None:
            team = SlackTeam(slack_id=slack_data['team']['id'],
                             owner=user,
                             academy=academy)

        team.name = slack_data['team']['name']
        team.save()

        return HttpResponseRedirect(redirect_to=payload["url"][0])
Ejemplo n.º 13
0
def save_github_token(request):

    logger.debug("Github callback just landed")
    logger.debug(request.query_params)

    error = request.query_params.get('error', False)
    error_description = request.query_params.get('error_description', '')
    if error:
        raise APIException("Github: " + error_description)

    url = request.query_params.get('url', None)
    if url == None:
        raise ValidationError("No callback URL specified")
    code = request.query_params.get('code', None)
    if code == None:
        raise ValidationError("No github code specified")

    payload = {
        'client_id': os.getenv('GITHUB_CLIENT_ID', ""),
        'client_secret': os.getenv('GITHUB_SECRET', ""),
        'redirect_uri': os.getenv('GITHUB_REDIRECT_URL', ""),
        'code': code,
    }
    headers = {'Accept': 'application/json'}
    resp = requests.post('https://github.com/login/oauth/access_token',
                         data=payload,
                         headers=headers)
    if resp.status_code == 200:

        logger.debug("Github responded with 200")

        body = resp.json()
        if 'access_token' not in body:
            raise APIException(body['error_description'])

        github_token = body['access_token']
        resp = requests.get('https://api.github.com/user',
                            headers={'Authorization': 'token ' + github_token})
        if resp.status_code == 200:
            github_user = resp.json()
            logger.debug(github_user)
            if github_user['email'] is None:
                resp = requests.get(
                    'https://api.github.com/user/emails',
                    headers={'Authorization': 'token ' + github_token})
                if resp.status_code == 200:
                    emails = resp.json()
                    primary_emails = [
                        x for x in emails if x["primary"] == True
                    ]
                    if len(primary_emails) > 0:
                        github_user['email'] = primary_emails[0]["email"]
                    elif len(emails) > 0:
                        github_user['email'] = emails[0]["email"]

            if github_user['email'] is None:
                raise ValidationError("Imposible to retrieve user email")

            # TODO: if user_id: User.objects.filter(id=user_id).first()

            user = User.objects.filter(
                Q(credentialsgithub__github_id=github_user['id'])
                | Q(email__iexact=github_user['email'])).first()
            if user is None:
                user = User(username=github_user['email'],
                            email=github_user['email'])
                user.save()

            CredentialsGithub.objects.filter(
                github_id=github_user['id']).delete()
            github_credentials = CredentialsGithub(
                github_id=github_user['id'],
                user=user,
                token=github_token,
                username=github_user['login'],
                email=github_user['email'],
                avatar_url=github_user['avatar_url'],
                name=github_user['name'],
                blog=github_user['blog'],
                bio=github_user['bio'],
                company=github_user['company'],
                twitter_username=github_user['twitter_username'])
            github_credentials.save()

            profile = Profile.objects.filter(user=user).first()
            if profile is None:
                profile = Profile(
                    user=user,
                    avatar_url=github_user['avatar_url'],
                    blog=github_user['blog'],
                    bio=github_user['bio'],
                    twitter_username=github_user['twitter_username'])
                profile.save()

            student_role = Role.objects.get(slug="student")
            cus = CohortUser.objects.filter(user=user, role="STUDENT")
            for cu in cus:
                profile_academy = ProfileAcademy.objects.filter(
                    user=cu.user, academy=cu.cohort.academy).first()
                if profile_academy is None:
                    profile_academy = ProfileAcademy(
                        user=cu.user,
                        academy=cu.cohort.academy,
                        role=student_role,
                        email=cu.user.email,
                        first_name=cu.user.first_name,
                        last_name=cu.user.last_name,
                        status='ACTIVE')
                    profile_academy.save()

            token, created = Token.objects.get_or_create(user=user,
                                                         token_type='login')

            return HttpResponseRedirect(redirect_to=url + '?token=' +
                                        token.key)
        else:
            # print("Github error: ", resp.status_code)
            # print("Error: ", resp.json())
            raise APIException("Error from github")
Ejemplo n.º 14
0
    def put(self, request, pk, file_id):
        """
        Update a resource file's metadata

        Accepts application/json encoding.

        ## Parameters
        * `id` - alphanumeric uuid of the resource, i.e. cde01b3898c94cdab78a2318330cf795
        * `file_id` - integer id of the resource file. You can use the `/hsapi/resource/{id}/files`
        to get these
        * `data` - see the "returns" section for formatting

        ## Returns
        ```
        {
            "keywords": [
                "keyword1",
                "keyword2"
            ],
            "spatial_coverage": {
                "units": "Decimal degrees",
                "east": -84.0465,
                "north": 49.6791,
                "name": "12232",
                "projection": "WGS 84 EPSG:4326"
            },
            "extra_metadata": {
                "extended1": "one"
            },
            "temporal_coverage": {
                "start": "2018-02-22",
                "end": "2018-02-24"
            },
            "title": "File Metadata Title"
        }
        ```
        """

        file_serializer = FileMetaDataSerializer(request.data)

        try:
            title = file_serializer.data.pop("title", "")
            resource_file = ResourceFile.objects.get(id=file_id)
            resource_file.metadata.logical_file.dataset_name = title
            resource_file.metadata.logical_file.save()

            spatial_coverage = file_serializer.data.pop("spatial_coverage", None)
            if spatial_coverage is not None:
                if resource_file.metadata.spatial_coverage is not None:
                    cov_id = resource_file.metadata.spatial_coverage.id
                    resource_file.metadata.update_element('coverage',
                                                          cov_id,
                                                          type='point',
                                                          value=spatial_coverage)
                elif resource_file.metadata.spatial_coverage is None:
                    resource_file.metadata.create_element('coverage', type="point",
                                                          value=spatial_coverage)

            temporal_coverage = file_serializer.data.pop("temporal_coverage", None)
            if temporal_coverage is not None:
                if resource_file.metadata.temporal_coverage is not None:
                    cov_id = resource_file.metadata.temporal_coverage.id
                    resource_file.metadata.update_element('coverage',
                                                          cov_id,
                                                          type='period',
                                                          value=temporal_coverage)
                elif resource_file.metadata.temporal_coverage is None:
                    resource_file.metadata.create_element('coverage', type="period",
                                                          value=temporal_coverage)

            keywords = file_serializer.data.pop("keywords", None)
            if keywords is not None:
                resource_file.metadata.keywords = keywords

            extra_metadata = file_serializer.data.pop("extra_metadata", None)
            if extra_metadata is not None:
                resource_file.metadata.extra_metadata = extra_metadata

            resource_file.metadata.save()
        except Exception as e:
            raise APIException(e)

        # TODO: How to leverage serializer for this?
        title = resource_file.metadata.logical_file.dataset_name \
            if resource_file.metadata.logical_file else ""
        keywords = resource_file.metadata.keywords \
            if resource_file.metadata else []
        spatial_coverage = resource_file.metadata.spatial_coverage.value \
            if resource_file.metadata.spatial_coverage else {}
        extra_metadata = resource_file.metadata.extra_metadata \
            if resource_file.metadata else {}
        temporal_coverage = resource_file.metadata.temporal_coverage.value if \
            resource_file.metadata.temporal_coverage else {}

        return Response({
            "title": title,
            "keywords": keywords,
            "spatial_coverage": spatial_coverage,
            "extra_metadata": extra_metadata,
            "temporal_coverage": temporal_coverage
        })
    def set_geonode_map(self, caller, serializer, map_obj=None, data=None, attributes=None):

        def decode_base64(data):
            """Decode base64, padding being optional.

            :param data: Base64 data as an ASCII byte string
            :returns: The decoded byte string.

            """
            _thumbnail_format = 'png'
            _invalid_padding = data.find(';base64,')
            if _invalid_padding:
                _thumbnail_format = data[data.find('image/') + len('image/'):_invalid_padding]
                data = data[_invalid_padding + len(';base64,'):]
            missing_padding = len(data) % 4
            if missing_padding != 0:
                data += b'=' * (4 - missing_padding)
            return (base64.b64decode(data), _thumbnail_format)

        _map_name = None
        _map_title = None
        _map_abstract = None
        _map_thumbnail = None
        _map_thumbnail_format = 'png'
        if attributes:
            for _a in attributes:
                if _a['name'] == 'name' and 'value' in _a:
                    _map_name = _a['value']
                if _a['name'] == 'title' and 'value' in _a:
                    _map_title = _a['value']
                if _a['name'] == 'abstract' and 'value' in _a:
                    _map_abstract = _a['value']
                if 'thumb' in _a['name'] and 'value' in _a:
                    try:
                        (_map_thumbnail, _map_thumbnail_format) = decode_base64(_a['value'])
                    except Exception:
                        if _a['value']:
                            _map_thumbnail = _a['value']
                            _map_thumbnail_format = 'link'
        elif map_obj:
            _map_title = map_obj.title
            _map_abstract = map_obj.abstract

        _map_name = _map_name or None
        if not _map_name and 'name' in serializer.validated_data:
            _map_name = serializer.validated_data['name']
        _map_title = _map_title or _map_name
        _map_abstract = _map_abstract or ""
        if data:
            try:
                _map_conf = dict(data)
                _map_conf["about"] = {
                    "name": _map_name,
                    "title": _map_title,
                    "abstract": _map_abstract}
                _map_conf['sources'] = {}
                from geonode.layers.views import layer_detail
                _map_obj = data.pop('map', None)
                if _map_obj:
                    _map_bbox = []
                    for _lyr in _map_obj['layers']:
                        _lyr_context = {}
                        _lyr_store = _lyr['store'] if 'store' in _lyr else None
                        if not _lyr_store:
                            try:
                                _url = urlparse(_lyr['catalogURL'])
                                _lyr_store = Layer.objects.get(
                                    uuid=parse_qs(_url.query)['id'][0]).store
                            except Exception:
                                try:
                                    _lyr_store = Layer.objects.get(
                                        alternate=_lyr['name'],
                                        remote_service__base_url=_lyr['url']).store
                                except Exception:
                                    _lyr_store = None

                        _lyr_name = "%s:%s" % (_lyr_store, _lyr['name']) if _lyr_store else _lyr['name']
                        try:
                            # Retrieve the Layer Params back from GeoNode
                            _gn_layer = layer_detail(
                                caller.request,
                                _lyr_name)
                            if _gn_layer and _gn_layer.context_data:
                                _context_data = json.loads(_gn_layer.context_data['viewer'])
                                for _gn_layer_ctx in _context_data['map']['layers']:
                                    if 'name' in _gn_layer_ctx and _gn_layer_ctx['name'] == _lyr['name']:
                                        _lyr['store'] = _lyr_store
                                        if 'style' in _lyr:
                                            _lyr_context['style'] = _lyr['style']
                                            if 'capability' in _gn_layer_ctx:
                                                # Add selected style to capability in layer_params
                                                _gn_layer_ctx['capability']['style'] = _lyr['style']
                                        _lyr_context = _gn_layer_ctx
                                        _src_idx = _lyr_context['source']
                                        _map_conf['sources'][_src_idx] = _context_data['sources'][_src_idx]
                        except Http404:
                            tb = traceback.format_exc()
                            logger.debug(tb)
                        except Exception:
                            raise
                        # Store ms2 layer idq
                        if "id" in _lyr and _lyr["id"]:
                            _lyr['extraParams'] = {"msId": _lyr["id"]}

                        # Store the Capabilities Document into the Layer Params of GeoNode
                        if _lyr_context:
                            if 'ftInfoTemplate' in _lyr_context:
                                _lyr['ftInfoTemplate'] = _lyr_context['ftInfoTemplate']
                            if 'getFeatureInfo' in _lyr_context:
                                _lyr['getFeatureInfo'] = _lyr_context['getFeatureInfo']
                            if 'capability' in _lyr_context:
                                _lyr['capability'] = _lyr_context['capability']
                                if 'bbox' in _lyr_context['capability']:
                                    _lyr_bbox = _lyr_context['capability']['bbox']
                                    if _map_obj['projection'] in _lyr_bbox:
                                        x0 = _lyr_bbox[_map_obj['projection']]['bbox'][0]
                                        x1 = _lyr_bbox[_map_obj['projection']]['bbox'][2]
                                        y0 = _lyr_bbox[_map_obj['projection']]['bbox'][1]
                                        y1 = _lyr_bbox[_map_obj['projection']]['bbox'][3]

                                        if len(_map_bbox) == 0:
                                            _map_bbox = [x0, x1, y0, y1]
                                        else:
                                            from geonode.utils import bbox_to_wkt
                                            from django.contrib.gis.geos import GEOSGeometry

                                            _l_wkt = bbox_to_wkt(x0, x1, y0, y1,
                                                                 srid=_map_obj['projection'])
                                            _m_wkt = bbox_to_wkt(_map_bbox[0], _map_bbox[2],
                                                                 _map_bbox[1], _map_bbox[3],
                                                                 srid=_map_obj['projection'])
                                            _map_srid = int(_map_obj['projection'][5:])
                                            _l_poly = GEOSGeometry(_l_wkt, srid=_map_srid)
                                            _m_poly = GEOSGeometry(_m_wkt, srid=_map_srid).union(_l_poly)
                                            _map_bbox = _m_poly.extent

                            if 'source' in _lyr_context:
                                _source = _map_conf['sources'][_lyr_context['source']]
                                if 'remote' in _source and _source['remote'] is True:
                                    _lyr['source'] = _lyr_context['source']
                        elif 'source' in _lyr:
                            _map_conf['sources'][_lyr['source']] = {}
                    event_type = None
                    if is_analytics_enabled:
                        event_type = EventType.EVENT_CHANGE

                    if not map_obj:
                        # Update Map BBox
                        if 'bbox' not in _map_obj and (not _map_bbox or len(_map_bbox) != 4):
                            _map_bbox = _map_obj['maxExtent']
                            # Must be in the form : [x0, x1, y0, y1]
                            _map_obj['bbox'] = [_map_bbox[0], _map_bbox[1],
                                                _map_bbox[2], _map_bbox[3]]
                        # Create a new GeoNode Map
                        from geonode.maps.models import Map
                        map_obj = Map(
                            title=_map_title,
                            owner=caller.request.user,
                            center_x=_map_obj['center']['x'],
                            center_y=_map_obj['center']['y'],
                            projection=_map_obj['projection'],
                            zoom=_map_obj['zoom'],
                            srid=_map_obj['projection'])
                        if 'bbox' in _map_obj:
                            if hasattr(map_obj, 'bbox_polygon'):
                                map_obj.bbox_polygon = BBOXHelper.from_xy(_map_obj['bbox']).as_polygon()
                            else:
                                map_obj.bbox_x0 = _map_obj['bbox'][0]
                                map_obj.bbox_y0 = _map_obj['bbox'][1]
                                map_obj.bbox_x1 = _map_obj['bbox'][2]
                                map_obj.bbox_y1 = _map_obj['bbox'][3]
                        map_obj.save()

                        if is_analytics_enabled:
                            event_type = EventType.EVENT_CREATE

                    # Dumps thumbnail from MapStore2 Interface
                    if _map_thumbnail:
                        # note: dumping a thumbnail should be performed before update_from_viewer(), to remove
                        # a race hazard. update_from_viewer() saves an existing map without a thumbnail,
                        # triggering asynchronous generation of a default thumbnail, which may overwrite uploaded thumb
                        if _map_thumbnail_format == 'link':
                            map_obj.thumbnail_url = _map_thumbnail
                        else:
                            _map_thumbnail_filename = "map-%s-thumb.%s" % (map_obj.uuid, _map_thumbnail_format)
                            map_obj.save_thumbnail(_map_thumbnail_filename, _map_thumbnail)

                    # Update GeoNode Map
                    _map_conf['map'] = _map_obj
                    map_obj.update_from_viewer(
                        _map_conf,
                        context={'config': _map_conf})

                    if is_analytics_enabled:
                        register_event(caller.request, event_type, map_obj)

                    serializer.validated_data['id'] = map_obj.id
                    serializer.save(user=caller.request.user)
            except Exception as e:
                tb = traceback.format_exc()
                logger.error(tb)
                raise APIException(e)
        else:
            raise APIException("Map Configuration (data) is Mandatory!")
Ejemplo n.º 16
0
 def to_internal_value(self, data):
     if data.get('token') and data.get('zone_name') and data.get('time'):
         return data
     else:
         raise APIException({'error': 'Invalid data sended.'})
Ejemplo n.º 17
0
    def request(self,
                method,
                url,
                params=None,
                data=None,
                headers=None,
                cookies=None,
                files=None,
                auth=None,
                timeout=None,
                allow_redirects=True,
                proxies=None,
                hooks=None,
                stream=None,
                verify=None,
                cert=None,
                json=None,
                **kwargs):
        site_id = kwargs.pop('site_id', None)
        force_json = kwargs.pop('force_json', True)
        raise_on_exception = kwargs.pop('raise_on_exception', True)
        raise_to_front = kwargs.pop('raise_to_front', True)
        return_json = kwargs.pop('return_json', True)

        if isinstance(url, (tuple, list)):
            url = get_service_url(url[0], *url[1:], **kwargs)
        if data:
            if isinstance(data, unicode):
                data = data.encode('utf-8')
            elif force_json and not isinstance(data, six.string_types):
                data = json_utils.to_json(data)

        if site_id is not None:
            headers = headers or {}
            headers[settings.SITE_ID_HEADER_NAME] = str(site_id)

        self._log('request', method.upper(), url)
        self._debug(data)

        response = super(BackendAPISession,
                         self).request(method, url, params, data, headers,
                                       cookies, files, auth, timeout,
                                       allow_redirects, proxies, hooks, stream,
                                       verify, cert, json)

        self._log('response', response.status_code, response.url)
        if not stream:
            self._debug(response.text)

        if raise_on_exception:
            try:
                response.raise_for_status()
            except HTTPError:
                if raise_to_front:
                    raise APIException(response.text, response.reason)
                raise

        if return_json:
            return response.json()

        return response
Ejemplo n.º 18
0
 def authenticate(self, request):
     token = request.query_params.get('token')
     user = models.Userinfo.objects.filter(token=token).first()
     if user:
         return (user.name, 'aaaaaa')
     raise APIException('认证失败')
Ejemplo n.º 19
0
def bulk_products(request):
    products = Product.objects.filter(order_details__quantity__gte=8)
    if not products:
        raise APIException("Not found products")

    return Response(BulkProductSerializer(products, many=True).data, status=HTTP_200_OK)
Ejemplo n.º 20
0
    def update(self, request, *args, **kwargs):  # pragma: no cover
        serializer = RepositoryTranslatedExporterSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        for_language = serializer.data.get("language", None)

        workbook = openpyxl.load_workbook(filename=request.data.get("file"))
        worksheet = workbook.get_sheet_by_name("Translate")
        columns = ["ID", "Repository Version", "Language"]

        examples_success = []

        find = False
        for count, row in enumerate(worksheet.iter_rows(), start=1):
            if (row[1].value in columns and row[2].value in columns
                    and row[3].value in columns):
                find = True
                continue
            if find:
                example_id = int(re.sub("[^0-9]", "", row[1].value))
                repository_version = int(row[2].value)
                text_translated = row[5].value

                if not int(kwargs.get("pk")) == repository_version:
                    raise APIException(  # pragma: no cover
                        {
                            "detail": "Import version is different from the selected version"
                        },
                        code=400,
                    )

                if text_translated:
                    example = RepositoryExample.objects.filter(
                        pk=example_id,
                        repository_version_language__repository_version=
                        repository_version,
                        repository_version_language__repository_version__repository
                        =kwargs.get("repository__uuid"),
                    )
                    if example.count() == 0:
                        worksheet.cell(row=count,
                                       column=7,
                                       value="Sentence does not exist")
                        continue

                    example = example.first()

                    entity_validation = False

                    for entity in utils.find_entities_in_example(
                            text_translated):
                        original_text_count_entity = (
                            RepositoryExampleEntity.objects.filter(
                                repository_example=example,
                                entity__repository_version=kwargs.get("pk"),
                                entity__value=entity.get("entity"),
                            ).count())

                        if original_text_count_entity == 0:
                            entity_validation = True
                            worksheet.cell(row=count,
                                           column=7,
                                           value="Entities must match")
                            break

                    if entity_validation:
                        continue

                    translated_examples = RepositoryTranslatedExample.objects.filter(
                        original_example=example, language=for_language)

                    if translated_examples.count() > 0:
                        translated_examples.delete()

                    version_language = example.repository_version_language.repository_version.get_version_language(
                        language=for_language)

                    translated = RepositoryTranslatedExample.objects.create(
                        repository_version_language=version_language,
                        original_example=example,
                        language=for_language,
                        text=utils.get_without_entity(text_translated),
                        clone_repository=True,
                    )

                    for translated_entity in utils.find_entities_in_example(
                            text_translated):
                        RepositoryTranslatedExampleEntity.objects.create(
                            repository_translated_example=translated,
                            start=translated_entity["start"],
                            end=translated_entity["end"],
                            entity=translated_entity["entity"],
                        )

                examples_success.append(count)

        for r in reversed(examples_success):
            worksheet.delete_rows(r)

        response = HttpResponse(
            content=save_virtual_workbook(workbook),
            content_type=
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        )
        response["Content-Disposition"] = "attachment; filename=bothub.xlsx"
        return response
Ejemplo n.º 21
0
 def create(self, request, pk):
     qs = self.get_object()
     if qs.openid != self.request.auth.openid:
         raise APIException(
             {"detail": "Cannot delete data which not yours"})
     else:
         if qs.asn_status != 4:
             raise APIException({
                 "detail":
                 "ASN Status does not correct , Can not Move To Bin"
             })
         else:
             data = request.data
             if 'bin_name' not in data:
                 raise APIException({"detail": "Please Enter the Bin Name"})
             else:
                 bin_detail = binset.objects.filter(
                     openid=self.request.auth.openid,
                     bin_name=str(data['bin_name'])).first()
                 asn_detail = AsnListModel.objects.filter(
                     openid=self.request.auth.openid,
                     asn_code=str(data['asn_code'])).first()
                 goods_qty_change = stocklist.objects.filter(
                     openid=self.request.auth.openid,
                     goods_code=str(data['goods_code'])).first()
                 move_qty = qs.goods_actual_qty - qs.sorted_qty - int(
                     data['qty'])
                 if move_qty > 0:
                     qs.sorted_qty = qs.sorted_qty + int(data['qty'])
                     goods_qty_change.sorted_stock = goods_qty_change.sorted_stock - int(
                         data['qty'])
                     goods_qty_change.onhand_stock = goods_qty_change.onhand_stock + int(
                         data['qty'])
                     if bin_detail.bin_property == 'Damage':
                         goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                             data['qty'])
                         qs.goods_damage_qty = qs.goods_damage_qty + int(
                             data['qty'])
                     elif bin_detail.bin_property == 'Inspection':
                         goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                             data['qty'])
                     elif bin_detail.bin_property == 'Holding':
                         goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                             data['qty'])
                     else:
                         goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                             data['qty'])
                     qs.save()
                     goods_qty_change.save()
                     stockbin.objects.create(
                         openid=self.request.auth.openid,
                         bin_name=str(data['bin_name']),
                         goods_code=str(data['goods_code']),
                         goods_desc=goods_qty_change.goods_desc,
                         goods_qty=int(data['qty']),
                         bin_size=bin_detail.bin_size,
                         bin_property=bin_detail.bin_property)
                     if bin_detail.empty_label == True:
                         bin_detail.empty_label = False
                         bin_detail.save()
                 elif move_qty == 0:
                     qs.sorted_qty = qs.sorted_qty + int(data['qty'])
                     qs.asn_status = 5
                     asn_detail.asn_status = 5
                     goods_qty_change.sorted_stock = goods_qty_change.sorted_stock - int(
                         data['qty'])
                     goods_qty_change.onhand_stock = goods_qty_change.onhand_stock + int(
                         data['qty'])
                     if bin_detail.bin_property == 'Damage':
                         goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                             data['qty'])
                         qs.goods_damage_qty = qs.goods_damage_qty + int(
                             data['qty'])
                     elif bin_detail.bin_property == 'Inspection':
                         goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                             data['qty'])
                     elif bin_detail.bin_property == 'Holding':
                         goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                             data['qty'])
                     else:
                         goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                             data['qty'])
                     qs.save()
                     goods_qty_change.save()
                     stockbin.objects.create(
                         openid=self.request.auth.openid,
                         bin_name=str(data['bin_name']),
                         goods_code=str(data['goods_code']),
                         goods_desc=goods_qty_change.goods_desc,
                         goods_qty=int(data['qty']),
                         bin_size=bin_detail.bin_size,
                         bin_property=bin_detail.bin_property)
                     if bin_detail.empty_label == True:
                         bin_detail.empty_label = False
                         bin_detail.save()
                 elif move_qty < 0:
                     raise APIException(
                         {"detail": "Move Qty must < Actual Arrive Qty"})
                 else:
                     pass
                 return Response({"success": "Yes"}, status=200)
Ejemplo n.º 22
0
 def partial_update(self, request, pk):
     qs = self.get_object()
     if qs.openid != request.auth.openid:
         raise APIException(
             {"detail": "Cannot partial_update data which not yours"})
     else:
         data = request.data
         if supplier.objects.filter(openid=self.request.auth.openid,
                                    supplier_name=data['goods_supplier'],
                                    is_delete=False).exists():
             if goods_unit.objects.filter(openid=self.request.auth.openid,
                                          goods_unit=data['goods_unit'],
                                          is_delete=False).exists():
                 if goods_class.objects.filter(
                         openid=self.request.auth.openid,
                         goods_class=data['goods_class'],
                         is_delete=False).exists():
                     if goods_brand.objects.filter(
                             openid=self.request.auth.openid,
                             goods_brand=data['goods_brand'],
                             is_delete=False).exists():
                         if goods_color.objects.filter(
                                 openid=self.request.auth.openid,
                                 goods_color=data['goods_color'],
                                 is_delete=False).exists():
                             if goods_shape.objects.filter(
                                     openid=self.request.auth.openid,
                                     goods_shape=data['goods_shape'],
                                     is_delete=False).exists():
                                 if goods_specs.objects.filter(
                                         openid=self.request.auth.openid,
                                         goods_specs=data['goods_specs'],
                                         is_delete=False).exists():
                                     if goods_origin.objects.filter(
                                             openid=self.request.auth.
                                             openid,
                                             goods_origin=data[
                                                 'goods_origin'],
                                             is_delete=False).exists():
                                         serializer = self.get_serializer(
                                             qs, data=data, partial=True)
                                         serializer.is_valid(
                                             raise_exception=True)
                                         serializer.save()
                                         headers = self.get_success_headers(
                                             serializer.data)
                                         return Response(serializer.data,
                                                         status=200,
                                                         headers=headers)
                                     else:
                                         raise APIException({
                                             "detail":
                                             "Goods Origin does not exists or it has been changed"
                                         })
                                 else:
                                     raise APIException({
                                         "detail":
                                         "Goods Specs does not exists or it has been changed"
                                     })
                             else:
                                 raise APIException({
                                     "detail":
                                     "Goods Shape does not exists or it has been changed"
                                 })
                         else:
                             raise APIException({
                                 "detail":
                                 "Goods Color does not exists or it has been changed"
                             })
                     else:
                         raise APIException({
                             "detail":
                             "Goods Brand does not exists or it has been changed"
                         })
                 else:
                     raise APIException({
                         "detail":
                         "Goods Class does not exists or it has been changed"
                     })
             else:
                 raise APIException({
                     "detail":
                     "Goods Unit does not exists or it has been changed"
                 })
         else:
             raise APIException({
                 "detail":
                 "Supplier does not exists or it has been changed"
             })
Ejemplo n.º 23
0
 def get_serializer_class(self):
     if self.type == ScoreboardType.monthly:
         return MonthlyScoreboardUserSerializer
     if self.type == ScoreboardType.forever:
         return ForeverScoreboardUserSerializer
     raise APIException(f"Invalid type: '{self.type}'")
Ejemplo n.º 24
0
 def create(self, request, *args, **kwargs):
     data = request.data
     data['openid'] = self.request.auth.openid
     data['unit_volume'] = round(
         (float(data['goods_w']) * float(data['goods_d']) *
          float(data['goods_h'])) / 1000000000, 4)
     if self.queryset.filter(openid=data['openid'],
                             goods_code=data['goods_code'],
                             is_delete=False).exists():
         raise APIException({"detail": "Data exists"})
     else:
         if supplier.objects.filter(openid=data['openid'],
                                    supplier_name=data['goods_supplier'],
                                    is_delete=False).exists():
             if goods_unit.objects.filter(openid=data['openid'],
                                          goods_unit=data['goods_unit'],
                                          is_delete=False).exists():
                 if goods_class.objects.filter(
                         openid=data['openid'],
                         goods_class=data['goods_class'],
                         is_delete=False).exists():
                     if goods_brand.objects.filter(
                             openid=data['openid'],
                             goods_brand=data['goods_brand'],
                             is_delete=False).exists():
                         if goods_color.objects.filter(
                                 openid=data['openid'],
                                 goods_color=data['goods_color'],
                                 is_delete=False).exists():
                             if goods_shape.objects.filter(
                                     openid=data['openid'],
                                     goods_shape=data['goods_shape'],
                                     is_delete=False).exists():
                                 if goods_specs.objects.filter(
                                         openid=data['openid'],
                                         goods_specs=data['goods_specs'],
                                         is_delete=False).exists():
                                     if goods_origin.objects.filter(
                                             openid=data['openid'],
                                             goods_origin=data[
                                                 'goods_origin'],
                                             is_delete=False).exists():
                                         serializer = self.get_serializer(
                                             data=data)
                                         serializer.is_valid(
                                             raise_exception=True)
                                         serializer.save()
                                         headers = self.get_success_headers(
                                             serializer.data)
                                         return Response(serializer.data,
                                                         status=200,
                                                         headers=headers)
                                     else:
                                         raise APIException({
                                             "detail":
                                             "Goods Origin does not exists or it has been changed"
                                         })
                                 else:
                                     raise APIException({
                                         "detail":
                                         "Goods Specs does not exists or it has been changed"
                                     })
                             else:
                                 raise APIException({
                                     "detail":
                                     "Goods Shape does not exists or it has been changed"
                                 })
                         else:
                             raise APIException({
                                 "detail":
                                 "Goods Color does not exists or it has been changed"
                             })
                     else:
                         raise APIException({
                             "detail":
                             "Goods Brand does not exists or it has been changed"
                         })
                 else:
                     raise APIException({
                         "detail":
                         "Goods Class does not exists or it has been changed"
                     })
             else:
                 raise APIException({
                     "detail":
                     "Goods Unit does not exists or it has been changed"
                 })
         else:
             raise APIException({
                 "detail":
                 "Supplier does not exists or it has been changed"
             })
Ejemplo n.º 25
0
 def put(self, request, *args, **kwargs):
     obj = self.get_object()
     if obj.status in ["canceled", "delivered"]:
         raise APIException(
             "Canceled order Or Delivered Order Can't Be Updated")
     return self.update(request, *args, **kwargs)
Ejemplo n.º 26
0
    def _get_account_information(self, api_output):
        """
        Create a dict with account information based on the json response from Dataprovider.
        """
        phone_number_limit = 5
        email_limit = 5
        address_limit = 3

        # Expected API output is json.
        api_output_json = json.loads(api_output)

        # Return 404 when the api returned an error.
        if api_output_json.get('error'):
            raise Http404(api_output_json.get('error'))

        # Return error message when nothing was found.
        if api_output_json.get('total') == 0:
            raise APIException(
                _('I\'m so sorry, I couldn\'t find any data for this website.')
            )

        # Filter useful data.
        result = api_output_json['data'][0]

        # Get the keywords and convert to list.
        tags = result.get('keywords')
        if tags:
            tags = result.get('keywords').strip().rstrip(',').split(',')

        # Get email addresses as a list.
        emails = list(result.get('emailaddresses', []))

        # Determine primary email since Dataprovider doesn't provide it.
        primary_email = None
        if emails:
            primary_email = self._get_primary_email(emails)

            # Set primary email to the first in the list.
            emails.index(primary_email)
            emails.remove(primary_email)
            emails.insert(0, primary_email)

        phone_numbers = []

        # Get primary phone number and convert to a nicer representation.
        phone_number = result.get('phonenumber')

        if phone_number:
            phone_number = parse_phone_number(phone_number)
            phone_numbers.append(phone_number)

        # Get phone numbers as a list.
        raw_phone_numbers = list(result.get('phonenumbers', []))

        # Convert all phone numbers to a nicer representation.
        for raw_phone_number in raw_phone_numbers:
            phone_numbers.append(parse_phone_number(raw_phone_number))

        # Try to parse the address.
        address = result.get('address')
        address_line = ''
        if address:
            # Construct address_line, instead of assigning address to address_line directly,
            # because parse_address() also santizes the result.
            street, street_number, complement = parse_address(address)
            if street:
                address_line = street
            if street_number:
                address_line += ' ' + street_number
            if complement:
                address_line += complement

        # Make the full address.
        addresses = []
        if address or result.get('city') or result.get(
                'zipcode') or result.get('country'):
            addresses = [{
                'address': address_line,
                'city': result.get('city'),
                'country': result.get('country'),
                'postal_code': result.get('zipcode'),
            }]

        # Get social media profiles.
        social_profiles = result.get('socialprofiles')

        # Group profiles by platform.
        # Disregards the other platforms provided by Dataprovider: Facebook, Google Plus and Pinterest.
        social_media = {}
        for profile in social_profiles:
            if profile.startswith('twitter.com/'):
                if 'twitter' not in social_media:
                    social_media['twitter'] = []
                social_media['twitter'].append(profile)
            elif profile.startswith('www.linkedin.com/in/'):
                if 'linkedin' not in social_media:
                    social_media['linkedin'] = []
                social_media['linkedin'].append(profile)

        primary_twitter = ''
        if 'twitter' in social_media:
            primary_twitter = self._get_primary_profile(
                social_media['twitter'], result.get('company'))

        primary_linkedin = ''
        if 'linkedin' in social_media:
            primary_linkedin = self._get_primary_profile(
                social_media['linkedin'], result.get('company'))

        # Build dict with account information.
        account_information = {
            'name': result.get('company'),
            'description': result.get('description'),
            'tags': tags,
            'email_addresses': emails[:email_limit],
            'primary_email': primary_email,
            'phone_numbers': phone_numbers[:phone_number_limit],
            'phone_number': phone_number,
            'addresses': addresses[:address_limit],
            'legalentity': result.get('legalentity'),
            'taxnumber': result.get('taxnumber'),
            'bankaccountnumber': result.get('bankaccountnumber'),
            'cocnumber': result.get('cocnumber'),
            'iban': result.get('iban'),
            'bic': result.get('bic'),
            'social_media_profiles': social_media,
            'twitter': primary_twitter,
            'linkedin': primary_linkedin,
        }

        return account_information
Ejemplo n.º 27
0
def register_new_lead(form_entry=None):
    if form_entry is None:
        raise Exception('You need to specify the form entry data')

    if 'location' not in form_entry or form_entry['location'] is None:
        raise Exception('Missing location information')

    ac_academy = ActiveCampaignAcademy.objects.filter(
        academy__slug=form_entry['location']).first()
    if ac_academy is None:
        raise Exception(f"No academy found with slug {form_entry['location']}")

    automations = get_lead_automations(ac_academy, form_entry)

    if automations:
        logger.debug("found automations")
        logger.debug(automations)
    else:
        logger.debug("automations not found")

    tags = get_lead_tags(ac_academy, form_entry)
    logger.debug("found tags")
    logger.debug(set(t.slug for t in tags))
    LEAD_TYPE = tags[0].tag_type
    if (automations is None or len(automations) == 0) and len(tags) > 0:
        if tags[0].automation is None:
            raise Exception(
                'No automation was specified and the the specified tag has no automation either'
            )

        automations = [tags[0].automation.acp_id]

    if not 'email' in form_entry:
        raise Exception('The email doesn\'t exist')

    if not 'first_name' in form_entry:
        raise Exception('The first name doesn\'t exist')

    if not 'last_name' in form_entry:
        raise Exception('The last name doesn\'t exist')

    if not 'phone' in form_entry:
        raise Exception('The phone doesn\'t exist')

    if not 'id' in form_entry:
        raise Exception('The id doesn\'t exist')

    contact = {
        "email": form_entry["email"],
        "first_name": form_entry["first_name"],
        "last_name": form_entry["last_name"],
        "phone": form_entry["phone"]
    }
    contact = set_optional(contact, 'utm_url', form_entry)
    contact = set_optional(contact, 'utm_location', form_entry, "location")
    contact = set_optional(contact, 'course', form_entry)
    contact = set_optional(contact, 'utm_language', form_entry, "language")
    contact = set_optional(contact, 'utm_country', form_entry, "country")
    contact = set_optional(contact, 'client_comments', form_entry,
                           "client_comments")
    contact = set_optional(contact, 'gclid', form_entry)
    contact = set_optional(contact, 'referral_key', form_entry)

    entry = FormEntry.objects.filter(id=form_entry['id']).first()

    if not entry:
        raise Exception('FormEntry not found (id: ' + str(form_entry['id']) +
                        ')')

    # save geolocalization info
    # save_get_geolocal(entry, form_enty)

    if 'contact-us' == tags[0].slug:
        send_email_message(
            'new_contact',
            ac_academy.academy.marketing_email,
            {
                "subject":
                f"New contact from the website {form_entry['first_name']} {form_entry['last_name']}",
                "full_name":
                form_entry['first_name'] + " " + form_entry['last_name'],
                "client_comments":
                form_entry['client_comments'],
                "data": {
                    **form_entry
                },
                # "data": { **form_entry, **address },
            })

    # ENV Variable to fake lead storage
    if SAVE_LEADS == 'FALSE':
        logger.debug(
            "Ignoring leads because SAVE_LEADS is FALSE on the env variables")
        return form_entry

    logger.debug("ready to send contact with following details: ", contact)
    old_client = AC_Old_Client(ac_academy.ac_url, ac_academy.ac_key)
    response = old_client.contacts.create_contact(contact)
    contact_id = response['subscriber_id']
    if 'subscriber_id' not in response:
        logger.error("error adding contact", response)
        raise APIException('Could not save contact in CRM')

    client = Client(ac_academy.ac_url, ac_academy.ac_key)
    if automations:
        for automation_id in automations:
            data = {
                "contactAutomation": {
                    "contact": contact_id,
                    "automation": automation_id
                }
            }
            response = client.contacts.add_a_contact_to_an_automation(data)
            if 'contacts' not in response:
                logger.error(
                    f"error triggering automation with id {str(automation_id)}",
                    response)
                raise APIException('Could not add contact to Automation')
            else:
                logger.debug(
                    f"Triggered automation with id {str(automation_id)}",
                    response)
                auto = Automation.objects.filter(
                    acp_id=automation_id, ac_academy=ac_academy).first()
                entry.automation_objects.add(auto)

    for t in tags:
        data = {"contactTag": {"contact": contact_id, "tag": t.acp_id}}
        response = client.contacts.add_a_tag_to_contact(data)
        if 'contacts' in response:
            entry.tag_objects.add(t.id)

    entry.storage_status = 'PERSISTED'
    entry.save()

    form_entry['storage_status'] = 'PERSISTED'

    return entry
Ejemplo n.º 28
0
 def destroy(self, request, *args, **kwargs):
     try:
         return super(DeployEnvViewSet, self).destroy(request, *args, **kwargs)
     except ProtectedError:
         raise APIException(detail='请先删除其他关联', code=500)
Ejemplo n.º 29
0
def predict(request):
    """
    This endpoint handles predicting the data for a specific area over some number
    of days in the future. The expected query params are "country", "state" and "days", 
    and the response is a list of data points, each represented as custom objects containing 
    the date of infection, the value, and source (a string indicating whether this data point was
    predicted by our model or is from observed data) in a given number of future days.
    """
    country = request.query_params.get("country")
    state = request.query_params.get("state")
    days = int(request.query_params.get("days"))

    true_vals = ['True', 'true']
    distancing_on = request.query_params.get("distancingOn", None) in true_vals
    distancing_off = request.query_params.get("distancingOff",
                                              None) in true_vals

    # Get the models from the URl query parameters.
    # Django expects it to be of the form: 'models=foo&models=bar&...'
    models = request.GET.getlist("models[]", [])

    # Get the area and raise an API exception if we can't.
    try:
        area = Area.objects.get(country=country, state=state)
    except Area.DoesNotExist:
        msg = "Could not find the area for country '{0}'".format(country)
        if state:
            msg += " and state '{0}'".format(state)
        raise APIException(msg)
    except Area.MultipleObjectsReturned:
        msg = "Found multiple areas for country '{0}'".format(country)
        if state:
            msg += " and state '{0}'".format(state)
        msg += ". This is most likely an error with data cleansing."
        raise APIException(msg)

    # Response data type. Predictions is an array that should hold objects of
    # the following type:
    # {
    #   model_name: "...",
    #   distancing: true/false,
    #   time_series: [
    #     {
    #       date,
    #       val
    #     }
    #   ]
    # }
    response = {
        "observed": [],
        "predictions": [],
    }

    # Pull observed data from database.
    observed = Covid19DataPoint.objects.filter(area=area)
    for d in observed:
        response["observed"].append({
            "date": d.date,
            "value": d.val,
        })

    # Determine the time range for predictions.
    prediction_start_date = max([d.date for d in observed]) + timedelta(days=1)
    prediction_end_date = prediction_start_date + timedelta(days=days)

    for model_name in models:
        model = Covid19Model.objects.get(name=model_name)

        if distancing_on:
            qs = Covid19PredictionDataPoint.objects.filter(
                model=model,
                social_distancing=True,
                area=area,
                date__range=(prediction_start_date, prediction_end_date))

            response["predictions"].append({
                "model": {
                    "name": model.name,
                    "description": model.description
                },
                "distancing":
                True,
                "time_series": [{
                    "date": d.date,
                    "value": d.val,
                } for d in qs]
            })

        if distancing_off:
            qs = Covid19PredictionDataPoint.objects.filter(
                model=model,
                social_distancing=False,
                area=area,
                date__range=(prediction_start_date, prediction_end_date))

            response["predictions"].append({
                "model": {
                    "name": model.name,
                    "description": model.description
                },
                "distancing":
                False,
                "time_series": [{
                    "date": d.date,
                    "value": d.val,
                } for d in qs]
            })

    return Response(response)
Ejemplo n.º 30
0
    def create(self, validated_data):

        clienteCpf = validated_data['cliente']
        codServico = validated_data['servico']

        #Verifica se existe cliente ===================================================================================================
        url = 'http://127.0.0.1:8000/cliente_service/v1/clientes/?nome=&email=&cpf=' + str(
            clienteCpf)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response = requests.get(url, headers=headers)

        if response.status_code != 200 or response.json()['count'] == 0:
            raise APIException(
                "Cliente não cadastrado. Para cadastrar um novo cliente acesse: http://127.0.0.1:8000/cliente_service/v1/clientes/?format=api"
            )

        # Verifica se existe o serviço ===================================================================================================
        url = 'http://127.0.0.1:8000/servicos/?cod_servico=' + str(codServico)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response = requests.get(url, headers=headers)

        data_servico = response.json()
        if response.status_code != 200 or data_servico['count'] == 0:
            raise APIException(
                "Serviço não cadastrado. Para cadastrar um novo serviço acesse: http://127.0.0.1:8000/servicos/?format=api"
            )

        # Verifica se ja bateo o valor ===================================================================================================
        results = data_servico['results']
        #quantidade de entrada para contemplação
        qtdEntradas = results[0]['entradas']
        #validade da promoção
        validade = datetime.strptime(results[0]['validade'], '%Y-%m-%d').date()

        present = datetime.now().date()
        #present = datetime.strptime(validated_data['data'], '%Y-%m-%d')

        if (present > validade):
            raise APIException(
                "Não é possível inserir o registro. A promoção expirou em: " +
                validade.strftime('%d/%m/%Y'))

        #url = 'http://127.0.0.1:8000/registros/?cliente=' + str(clienteCpf)+'&servico='+ str(codServico)
        url = 'http://127.0.0.1:8000/registros/?data=&status=true&cliente=' + str(
            clienteCpf) + '&servico=' + str(codServico)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response = requests.get(url, headers=headers)

        if response.json()['count'] >= qtdEntradas:
            raise APIException(
                "Este cartão já alconçou o numero de entradas, seu prêmio já pode ser resgatado em: http://127.0.0.1:8000/premios/?format=api"
            )

        #raise APIException(validated_data)
        registro = Registros.objects.create(**validated_data)
        return registro