Exemple #1
0
class OrderRecordSerializer(serializers.ModelSerializer):
    project1 = ProjectSerializer()
    project2 = ProjectSerializer()
    project3 = ProjectSerializer()
    project4 = ProjectSerializer()

    class Meta:
        model = OrderRecord
        fields = [
            'id', 'order', 'project1', 'course_num1', 'project2',
            'course_num2', 'project3', 'course_num3', 'project4',
            'course_num4', 'all_amount'
        ]

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if data['course_num1']:
            data['project1']['course_number'] = data['course_num1']
            data['project1']['project_column'] = 'project1_id'
        if data['course_num2']:
            data['project2']['course_number'] = data['course_num2']
            data['project2']['project_column'] = 'project2_id'
        if data['course_num3']:
            data['project3']['course_number'] = data['course_num3']
            data['project3']['project_column'] = 'project3_id'
        if data['course_num4']:
            data['project4']['course_number'] = data['course_num4']
            data['project4']['project_column'] = 'project4_id'
        return data
Exemple #2
0
class CrawlerProjectDtSerializer(serializers.ModelSerializer):
    """
        项目详情
        """
    project = ProjectSerializer()

    class Meta:
        model = CrawlerProject
        fields = '__all__'
class RelationSerializer(serializers.Serializer):

    authors = PersonSerializer(many=True)
    keywords = LabelSerializer(many=True)
    parties = OrganisationSerializer(many=True)
    themes = LabelSerializer(many=True)
    projects = ProjectSerializer(many=True)
    children = serializers.ListField(child=serializers.CharField())
    parents = serializers.ListField(child=serializers.CharField())
Exemple #4
0
    def create(self, request, *args, **kwargs):
        serializer = ProjectSaveSerializer(request, data=request.data)

        if serializer.is_valid():
            project = serializer.save()
            project_object = ProjectSerializer(project)
            if project_object:
                return Response(project_object.data,
                                status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #5
0
class ProjectBugSerializer(serializers.ModelSerializer):
    handler = UserSerializer()
    tester = UserSerializer()
    checker = UserSerializer()
    project = ProjectSerializer()
    task = ProjectTaskSerializer()

    class Meta:
        model = ProjectBug
        depth = 1
        fields = "__all__"
Exemple #6
0
class CrawlerDtSerializer(serializers.ModelSerializer):
    # 格式化时间输出
    add_time = serializers.DateTimeField(format="%Y-%m-%d ", read_only=True, default='')
    built_at = serializers.DateTimeField(format="%Y-%m-%d", read_only=True, default='')
    generated_at = serializers.DateTimeField(format="%Y-%m-%d", read_only=True, default='')

    server = ServerSerializer(many=True)
    project = ProjectSerializer(many=True)

    class Meta:
        model = Crawler
        fields = '__all__'
Exemple #7
0
    def patch_title(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        new_title = request.data.get('title')
        if not new_title:
            return Response({}, status=status.HTTP_400_BAD_REQUEST)

        project.title = new_title
        project.save()

        serializer = ProjectSerializer(project)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #8
0
    def get(self, request, pk, *args, **kwargs):

        project = Project.objects.get(id=pk)
        serializer = ProjectSerializer(project)

        return Response(
            {
                'status': '200',
                'msg': 'showing data',
                'data': serializer.data,
            },
            status.HTTP_200_OK,
        )
Exemple #9
0
 def put(self, request, pk, format=None):
     project = project.objects.get(id=pk)
     serializer = ProjectSerializer(project, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(
             {
                 'status': '200',
                 'msg': 'showing data',
                 'data': serializer.data,
             },
             status.HTTP_200_OK,
         )
Exemple #10
0
    def list(self, request, format=None):

        queryset = Project.objects.all()
        serializer = ProjectSerializer(queryset, many=True)

        return Response(
            {
                'status': '200',
                'msg': 'showing data',
                'data': serializer.data,
            },
            status.HTTP_200_OK,
        )
Exemple #11
0
    def remove_keyword(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        keyword = get_object_or_404(project.keywords,
                                    id=kwargs.get('keyword_id'))

        new_count = keyword.count - 1
        keyword.count = new_count
        keyword.save()
        project.keywords.remove(keyword)

        serializer = ProjectSerializer(project)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #12
0
    def remove_ability(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        ability = get_object_or_404(project.abilities,
                                    id=kwargs.get('ability_id'))

        new_count = ability.count - 1
        ability.count = new_count
        ability.save()
        project.abilities.remove(ability)

        serializer = ProjectSerializer(project)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #13
0
    def patch_date(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        new_started_at = request.data.get('started_at')
        new_ends_at = request.data.get('ends_at')
        if not new_started_at or not new_ends_at:
            return Response({}, status=status.HTTP_400_BAD_REQUEST)

        project.started_at = new_started_at
        project.ends_at = new_ends_at
        project.save()

        serializer = ProjectSerializer(project)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #14
0
def indexViewAll(request, sig_name):
    projects = {}
    if sig_name=='Catalyst':
        start_year = 2019
    else:
        start_year = 2018
    for year in range(start_year,datetime.today().year+1):
        projects_obj = Project.objects.filter(
            sigs__name=sig_name,
            year=year
        ).order_by('name')
        projects_data = ProjectSerializer(projects_obj,many=True).data
        projects[str(year)+'-'+str(year+1)[2:]] = projects_data
    return Response(projects)
Exemple #15
0
def indexViewCurrent(request, sig_name):
    this_year = datetime.now().year
    this_month = datetime.now().month
    if this_month<7:
        this_year = this_year-1
    sig = SIG.objects.get(
        name=sig_name
    )
    projects_obj = Project.objects.filter(
        sigs__name=sig.name,
        year=this_year
    ).order_by('name')
    projects_data = ProjectSerializer(projects_obj,many=True).data
    return Response(projects_data)
Exemple #16
0
 def patch_schedules(self, request, *args, **kwargs):
     project = get_object_or_404(Project, id=kwargs.get('project_id'))
     self.check_object_permissions(request, project)
     schedule_data = request.data.get('schedule')
     schedule = project.schedule
     project_serializer = ProjectSerializer(project)
     schedule_serializer = ProjectScheduleSaveSerializer(schedule,
                                                         data=schedule_data)
     if schedule_serializer.is_valid():
         schedule_serializer.save()
         return Response(project_serializer.data, status=status.HTTP_200_OK)
     else:
         return Response(schedule_serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Exemple #17
0
    def patch_location(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        new_location_code = request.data.get('location_code')
        if not new_location_code:
            return Response({}, status=status.HTTP_400_BAD_REQUEST)

        new_location = get_object_or_404(Location,
                                         address_1_code=new_location_code,
                                         address_2_code__isnull=True)
        project.location = new_location
        project.save()

        serializer = ProjectSerializer(project)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #18
0
    def patch_descriptions(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        descriptions_data = request.data.get('descriptions')
        ProjectDescription.objects.filter(project=project).delete()
        for description_data in descriptions_data:
            description = ProjectDescription(
                project=project,
                question_id=description_data.get('question'),
                answer=description_data.get('answer'),
            )
            description.save()

        serializer = ProjectSerializer(project)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #19
0
 def mutate(root, info, data):
     # TODO : Add can  update or not
     try:
         instance = Project.objects.get(id=data['id'])
     except Project.DoesNotExist:
         return UpdateClient(errors=[
             CustomErrorType(field='nonFieldErrors',
                             messages=gettext('Project Does not exist'))
         ])
     serializer = ProjectSerializer(instance=instance,
                                    data=data,
                                    context={'request': info.context},
                                    partial=True)
     if errors := mutation_is_not_valid(serializer):
         return UpdateProject(errors=errors, ok=False)
class TaskDetailSerializer(serializers.ModelSerializer):
    assignee = UserSerializer()
    initiator = UserSerializer()
    project = ProjectSerializer()
    release = ReleaseSerializer()
    sprint = SprintSerializer()
    parent_task = TaskSerializer()
    sub_tasks = TaskSerializer(many=True)

    class Meta:
        model = Task
        fields = '__all__'

        extra_kwargs = {
            'status': {'default': 0, },
        }
Exemple #21
0
    def update(self, request, pk=None, *args, **kwargs):
        try:
            params = request.data if request.data else request.POST
            kw = {}
            assigned_to = params.get('assigned_to', [])
            project = Project.objects.filter(pk=pk)

            for key, val in params.items():
                if key in ['name', 'description']:
                    if val.strip():
                        kw[key] = val
                    else:
                        return JsonResponse(
                            {'message': 'Project {} is not valid'.format(key)},
                            status=400)

                if key in ['start_date', 'end_date', 'completed_on']:
                    if val.strip():
                        kw[key] = datetime.strptime(val, '%d-%m-%Y')
                    else:
                        return JsonResponse(
                            {'message': 'Project {} is not valid'.format(key)},
                            status=400)

                kw['is_completed'] = True if params.get(
                    'is_completed', '') == 'true' else False

            kw['modified_by'] = request.user
            project.update(**kw)
            project = project.first()

            if assigned_to:
                for x in assigned_to:
                    project.assigned_to.add(Employee.objects.get(id=x))
                project.assigned_by = request.user.employee
                project.assigned_on = datetime.now()
                project.save()

            return JsonResponse(
                {
                    "Message": 'Data Updated Successfully....',
                    "data": ProjectSerializer(project).data
                },
                status=200)

        except Exception as e:
            return JsonResponse({"Message": str(e)}, status=400)
Exemple #22
0
    def patch_media(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        media_data = request.data.get('media')
        project.medai.all().delete()
        for media_data_object in media_data:
            type_data = media_data_object.get('type')
            url_data = media_data_object.get('url')
            media = Media(
                type_id=type_data,
                url=url_data,
            )
            media.save()
            project.media.add(media)

        serializer = ProjectSerializer(project)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #23
0
    def patch_contacts(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        contacts_data = request.data.get('contacts')
        project.contacts.all().delete()
        for contact_data in contacts_data:
            type_data = contact_data.get('type')
            information_data = contact_data.get('information')
            contact = Contact(
                type_id=type_data,
                information=information_data,
            )
            contact.save()
            project.contacts.add(contact)

        serializer = ProjectSerializer(project)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #24
0
    def add_ability(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        ability_string = request.data.get('ability')
        try:
            project.abilities.get(name=ability_string)
            return Response({}, status=status.HTTP_409_CONFLICT)
        except ObjectDoesNotExist:
            ability, created = Ability.objects.get_or_create(
                name=ability_string)
            new_count = ability.count + 1
            ability.count = new_count
            ability.save()
            project.abilities.add(ability)

            serializer = ProjectSerializer(project)
            return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #25
0
    def add_keyword(self, request, *args, **kwargs):
        project = get_object_or_404(Project, id=kwargs.get('project_id'))
        self.check_object_permissions(request, project)
        keyword_string = request.data.get('keyword')
        try:
            project.keywords.get(name=keyword_string)
            return Response({}, status=status.HTTP_409_CONFLICT)
        except ObjectDoesNotExist:
            keyword, created = Keyword.objects.get_or_create(
                name=keyword_string)
            new_count = keyword.count + 1
            keyword.count = new_count
            keyword.save()
            project.keywords.add(keyword)

            serializer = ProjectSerializer(project)
            return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #26
0
    def test_retrieve_project_list(self):
        """Test retrieving a list of projects"""
        project1 = Project.objects.create(
            project_name='test 1',
            project_description='description 1',
        )
        project2 = Project.objects.create(
            project_name='test 2',
            project_description='description 2',
        )
        project1.users.add(self.user)
        project2.users.add(self.user)

        res = self.client.get(PROJECTS_URL)

        projects = Project.objects.all().order_by('-project_name')
        serializer = ProjectSerializer(projects, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)
Exemple #27
0
def suite_init(request, pk):
    try:
        suite = TestSuite.objects.get(id=pk)
    except TestSuite.DoesNotExist:
        return Http404
    cases = ApiTestCases.objects.filter(suite_id=pk).all()
    project = Projects.objects.get(id=suite.project_id)
    suite_log = SuiteChangeLog.objects.filter(test_suite_id=pk).last()
    old_coding = suite_log.code_content if suite_log != None else None
    if not os.path.exists(project.project_root):
        os.makedirs(project.project_root)
    suite_file_path = os.path.join(project.project_root,
                                   '{}.py'.format(suite.suite_name))
    if request.method == "GET":
        suite_content = CaseBuilder(suite_file_path).suite_build(
            suite.suite_name, suite.suite_desc)
        for case in cases:
            cases_content = CaseBuilder(suite_file_path).case_build(
                case.func_name, case.description)
            suite_content += cases_content
        data = {
            'suite': testSuiteSerializers(suite).data,
            'project': ProjectSerializer(suite.project).data,
            'file_path': suite_file_path,
            'file_content': suite_content,
            'last': old_coding
        }
        return Response(data)
    elif request.method == "POST":
        if request.data.get("active") == "save":
            coding = request.data.get("coding")
            log = SuiteChangeLog.objects.create(test_suite_id=suite.id,
                                                code_content=coding)
            log.save()
            try:
                with open(suite_file_path, 'wb') as f:
                    f.write(coding)
                    f.close()
            except IOError as e:
                return Response({"status": "fail"},
                                status=status.HTTP_204_NO_CONTENT)
            return Response({"status": "ok"},
                            status=status.HTTP_204_NO_CONTENT)
Exemple #28
0
class UserOrderCourseSerializer(serializers.ModelSerializer):
    project = ProjectSerializer()

    class Meta:
        model = Order
        fields = [
            'id', 'user', 'project', 'currency', 'payment', 'create_time',
            'status', 'course_num', 'standard_fee', 'pay_fee', 'project',
            'remark'
        ]

    def to_representation(self, instance):
        data = super().to_representation(instance)
        user_course = Course.objects.filter(
            usercourse__order=instance,
            usercourse__user=self.context['request'].user)
        user_course_data = OrderCourseSerializer(
            user_course, many=True).data if user_course else None
        data['user_course'] = user_course_data
        return data
Exemple #29
0
class ExtensionPropertiesSerializer(serializers.Serializer):

    external_id = serializers.CharField()
    state = serializers.ChoiceField(required=False,
                                    choices=Document.States.choices)
    title = serializers.CharField(required=False)
    description = serializers.CharField(required=False)
    language = serializers.CharField(required=False, max_length=2)
    published_at = serializers.DateField(required=False)
    copyright = serializers.ChoiceField(required=False,
                                        choices=settings.COPYRIGHT_VALUES)

    authors = PersonSerializer(many=True, required=False)
    parties = OrganisationSerializer(many=True, required=False)
    projects = ProjectSerializer(many=True, required=False)
    themes = LabelSerializer(many=True, required=False)
    keywords = LabelSerializer(many=True, required=False)

    parents = serializers.ListField(child=serializers.CharField(),
                                    required=False)
    children = serializers.ListField(child=serializers.CharField(),
                                     required=False)
Exemple #30
0
class ExtensionSerializer(DocumentBaseSerializer,
                          ExtensionPropertiesSerializer):

    id = serializers.CharField(read_only=True)
    is_addition = serializers.BooleanField(required=False, default=False)
    properties = ExtensionPropertiesSerializer(read_only=True)

    external_id = serializers.CharField(write_only=True)
    state = serializers.CharField(write_only=True, required=False)
    title = serializers.CharField(write_only=True, required=False)
    description = serializers.CharField(write_only=True, required=False)
    language = serializers.CharField(write_only=True,
                                     required=False,
                                     max_length=2)
    published_at = serializers.DateField(write_only=True, required=False)
    copyright = serializers.ChoiceField(write_only=True,
                                        required=False,
                                        choices=settings.COPYRIGHT_VALUES)

    authors = PersonSerializer(many=True, write_only=True, required=False)
    parties = OrganisationSerializer(many=True,
                                     write_only=True,
                                     required=False)
    projects = ProjectSerializer(many=True, write_only=True, required=False)
    themes = LabelSerializer(many=True, write_only=True, required=False)
    keywords = LabelSerializer(many=True, write_only=True, required=False)

    parents = serializers.ListField(child=serializers.CharField(),
                                    write_only=True,
                                    required=False)
    children = serializers.ListField(child=serializers.CharField(),
                                     write_only=True,
                                     required=False)

    def validate_external_id(self, external_id):
        path_external_id = self.context["view"].kwargs.get("external_id")
        if path_external_id and path_external_id != external_id:
            raise ValidationError("External id in path and body do not match.")
        return external_id

    def validate_published_at(self, published_at):
        return published_at.strftime("%Y-%m-%d")

    def validate_relation_ids(self, ids):
        if not len(ids):
            return
        document_ids = {
            external_id
            for external_id in Document.objects.filter(
                reference__in=ids).values_list("reference", flat=True)
        }
        extension_ids = {
            external_id
            for external_id in Extension.objects.filter(
                id__in=ids).values_list("id", flat=True)
        }
        for external_id in ids:
            if external_id not in document_ids and external_id not in extension_ids:
                raise ValidationError(
                    f"Document or Extension with id '{external_id}' does not exist."
                )

    def validate_parents(self, parents):
        self.validate_relation_ids(parents)
        return parents

    def validate_children(self, children):
        self.validate_relation_ids(children)
        return children

    def validate(self, attrs):
        external_id = attrs["external_id"]
        if not attrs.get("is_addition", False):
            if not Document.objects.filter(reference=external_id).exists():
                raise ValidationError(
                    f"Could not find Document with external_id '{external_id}'. Did you mean to create an addition?"
                )
            addition_properties = ["language", "published_at", "copyright"]
            for prop in addition_properties:
                if prop in attrs:
                    raise ValidationError(
                        f"Can't set {prop} property for anything but an addition extension."
                    )
        if self.context["request"].method == "POST":
            if Extension.objects.filter(id=external_id,
                                        deleted_at__isnull=True).exists():
                raise ValidationError(
                    f"Extension with id '{external_id}' already exists. Try to PUT the extension instead."
                )
        return super().validate(attrs)

    def create(self, validated_data):
        external_id = validated_data["external_id"]
        is_addition = validated_data.pop("is_addition")
        # Detect whether a deleted addition extension exists and permanently delete it before creation
        if is_addition:
            Extension.objects.filter(id=external_id,
                                     deleted_at__isnull=False).delete()
        # Create the extension
        extension = super().create({
            "id": external_id,
            "is_addition": is_addition,
            "reference": external_id,
            "properties": validated_data
        })
        if not is_addition:
            Document.objects.filter(reference=external_id).update(
                modified_at=now(), extension=extension)
        return extension

    def update(self, instance, validated_data):
        is_addition = validated_data.pop("is_addition", None)
        if not is_addition:
            Document.objects.filter(
                reference=validated_data["external_id"]).update(
                    modified_at=now())
        instance.properties.update(validated_data)
        instance.save()
        return super().update(instance, validated_data)

    class Meta:
        model = Extension
        fields = ("id", "created_at", "modified_at", "properties",
                  "is_addition", "external_id", "state", "title",
                  "description", "language", "published_at", "copyright",
                  "authors", "parties", "projects", "themes", "keywords",
                  "parents", "children")