Example #1
0
class CreateMessageSerializer(serializers.ModelSerializer):
    files = UploadedFileSerializer(many=True, required=False)

    class Meta:
        model = Message
        fields = ['message', 'files']

    def create(self, validated_data):
        conversation = validated_data.get('conversation')
        message = conversation.add_message(
            user_from=validated_data.get('user_from'),
            message=validated_data.get('message'))
        for data in validated_data.get('files', []):
            UploadedFile.create(created_by=validated_data.get('user_from'),
                                filename=data.get('filename'),
                                mimetype=data.get('mimetype'),
                                filestack_url=data.get('url'),
                                filestack_status=data.get('filestack_status'),
                                related_to=message)
        return message
Example #2
0
class StartConversationSerializer(serializers.Serializer):
    files = UploadedFileSerializer(many=True, required=False)
    message = serializers.CharField()

    def validate(self, data):
        user_from = self.context.get('view').request.user
        user_to = self.context.get('view').get_object()
        if user_from == user_to:
            raise serializers.ValidationError(
                'User can not start conversation himself')
        return data

    def create(self, validated_data):
        user_from = validated_data.get('user_from')
        user_to = validated_data.get('user_to')
        files = validated_data.get('files', [])
        message = validated_data.get('message')
        start_conversation(user_from=user_from,
                           user_to=user_to,
                           files=files,
                           message=message)
        return validated_data
Example #3
0
class OpportunitySerializer(OpportunityMixin, OpportunityUserMixin,
                            serializers.ModelSerializer):

    userBy = serializers.SerializerMethodField()
    keywords = KeywordSerializer(many=True, required=False)
    languages = LanguageSerializer(many=True, required=False)
    userStatus = serializers.SerializerMethodField()
    userActions = serializers.SerializerMethodField()
    numApplicants = serializers.SerializerMethodField()
    alreadyVisited = serializers.SerializerMethodField()
    isNew = serializers.SerializerMethodField()
    questions = QuestionSerializer(many=True, required=False)
    comment = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=True,
    )
    send_notification = serializers.BooleanField(required=False)
    budgets = BudgetSerializer(required=False, many=True)
    users_tagged = UserTaggedSerializer(required=False, many=True)
    duration_unity = serializers.ChoiceField(
        required=False, choices=settings.OPPORTUNITIES_DURATION_UNITY_CHOICES)
    duration_value = serializers.IntegerField(required=False)
    exo_role = serializers.SlugRelatedField(queryset=ExORole.objects.all(),
                                            slug_field='code',
                                            required=True)
    certification_required = serializers.SlugRelatedField(
        queryset=CertificationRole.objects.all(),
        slug_field='code',
        required=False,
        allow_null=True)
    files = UploadedFileSerializer(many=True, required=False)
    group = serializers.PrimaryKeyRelatedField(
        queryset=OpportunityGroup.objects.all(), required=False)

    class Meta:
        model = Opportunity
        fields = [
            'pk',
            'slug',
            'uuid',
            'comment',
            'send_notification',
            'title',
            'description',
            'keywords',
            'languages',
            'mode',
            'location',
            'place_id',
            'location_url',
            'start_date',
            'modified',
            'entity',
            'exo_role',
            'certification_required',
            'other_role_name',
            'userStatus',
            'userBy',
            'other_category_name',
            'budgets',
            'alreadyVisited',
            'isNew',
            'userActions',
            'numApplicants',
            'questions',
            'num_positions',
            'deadline_date',
            'users_tagged',
            'target',
            'duration_unity',
            'duration_value',
            'files',
            'group',
            'context_object_uuid',
            'context_content_type',
        ]
        read_only_fields = ['slug', 'modified', 'uuid']
        extra_kwargs = {
            'description': {
                'allow_blank': False,
                'required': True,
                'allow_null': False,
            },
        }

    def validate(self, data):
        action = self.context.get('view').action
        group = data.get('group')
        user = self.context.get('request').user

        if action == 'update':
            opportunity = self.context.get('view').get_object()
            can_update_opportunity = opportunity.can_do_actions(
                user, settings.OPPORTUNITIES_ACTION_CH_EDIT)
            if not can_update_opportunity:
                raise serializers.ValidationError(
                    "You can't update this opportunity")
        if group:
            if action in ['create', 'preview']:
                previous_opp = None
            else:
                previous_opp = self.instance
            position_availables = group.has_positions_availables(
                data.get('num_positions'),
                previous_opp,
            )
            if not position_availables:
                raise serializers.ValidationError("No positions availables")

        if 'other_category_name' not in data and \
                data['exo_role'].categories.first().code == settings.EXO_ROLE_CATEGORY_OTHER:
            raise serializers.ValidationError(
                detail='Other Category name is required')

        if 'other_category_name' in data and data['other_category_name'] and \
                data['exo_role'].categories.first().code != settings.EXO_ROLE_CATEGORY_OTHER:
            raise serializers.ValidationError(detail='Invalid Category')

        return data

    def create(self, validated_data):
        keywords = Keyword.objects.update_keywords(
            user_from=validated_data.get('user_from'),
            keywords_name=[k['name'] for k in validated_data.get('keywords')],
        )
        validated_data['keywords'] = keywords
        languages = Language.objects.update_languages(
            user_from=validated_data.get('user_from'),
            languages_name=set(
                [k['name'] for k in validated_data.get('languages', [])]),
        )
        validated_data['languages'] = languages
        validated_data['users_tagged'] = [
            u['user'] for u in validated_data.get('users_tagged', [])
        ]
        group = validated_data.pop('group', None)
        if group:
            return Opportunity.objects.create_opportunity_in_group(
                user_from=validated_data.pop('user_from'),
                group=group,
                **validated_data)
        else:
            return Opportunity.objects.create_opportunity(
                user_from=validated_data.pop('user_from'), **validated_data)

    def add_id_to_questions(self, validated_data):
        validated_data['questions'] = self.initial_data.get('questions')

    def update(self, instance, validated_data):
        keywords = Keyword.objects.update_keywords(
            user_from=validated_data.get('user_from'),
            keywords_name=[k['name'] for k in validated_data.get('keywords')],
        )
        validated_data['keywords'] = keywords
        languages = Language.objects.update_languages(
            user_from=validated_data.get('user_from'),
            languages_name=set(
                [k['name'] for k in validated_data.get('languages', [])]),
        )
        validated_data['languages'] = languages
        self.add_id_to_questions(validated_data)
        validated_data['users_tagged'] = [
            u['user'].uuid for u in validated_data.get('users_tagged', [])
        ]
        opportunity = Opportunity.objects.update_opportunity(
            user_from=validated_data.pop('user_from'),
            opportunity=instance,
            **validated_data)
        instance.refresh_from_db()
        return opportunity