<commit_before>from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.contrib.auth.models import User
from django.db import connection
from django.http import HttpResponse

from rest_framework import viewsets, serializers, mixins
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse

from isisdata.models import *

from django.template import RequestContext, loader
from django.http import HttpResponse

from collections import defaultdict

class ReadOnlyLowerField(serializers.ReadOnlyField):
    """
    Coerces value to lowercase.
    """
    def to_representation(self, obj):
        return obj.lower()

class GenericHyperlink(serializers.HyperlinkedRelatedField):
    """
    Handles generic relations.
    """
    view_name = 'generic-detail'

    def get_url(self, obj, v, request, format):
        view_name = type(obj).__name__.lower() + '-detail'
        return super(GenericHyperlink, self).get_url(obj, view_name,
                                                     request, format)

# class ValueHyperlink(serializers.HyperlinkedRelatedField):
#     view_name = 'value-detail'
#
#     def get_url(self, obj, v, request, format):
#         view_name = obj.child_class.lower() + '-detail'
#         print view_name
#         return super(ValueHyperlink, self).get_url(obj, view_name,
#                                                    request, format)

class ValueSerializer(serializers.HyperlinkedModelSerializer):
    value = serializers.ReadOnlyField(source='cvalue')
    value_type = ReadOnlyLowerField(source='child_class')

    class Meta:
        model = Value
        fields = ('value', 'value_type')

class ContentTypeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ContentType
        fields = ('url', 'model')

class AttributeTypeSerializer(serializers.HyperlinkedModelSerializer):
    content_type = ContentTypeSerializer(source='value_content_type')

    class Meta:
        model = AttributeType
        fields = ('url', 'id', 'name', 'content_type')

class AttributeSerializer(serializers.HyperlinkedModelSerializer):
    type_controlled = AttributeTypeSerializer(many=False)
    source = GenericHyperlink(many=False, read_only=True)
    value = ValueSerializer(many=False, read_only=True)

    class Meta:
        model = Attribute
        fields = ('uri', 'url', 'id',
                  'type_controlled',
                  'type_controlled_broad',
                  'source',
                  'value',
                  'value_freeform')

class LanguageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Language
        fields = ('url', 'id', 'name')

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User

class LinkedDataTypeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = LinkedDataType

class LinkedDataSerializer(serializers.HyperlinkedModelSerializer):
    type_controlled = LinkedDataTypeSerializer(many=False)
    class Meta:
        model = LinkedData
        fields = ('universal_resource_name', 'description', 'type_controlled')

class CCRelationSerializer(serializers.HyperlinkedModelSerializer):
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')

    class Meta:
        model = CCRelation

        fields = ('uri', 'url', 'id',
                  'subject', 'object',
                  'name',
                  'description',
                  'type_controlled',
                  'attributes',
                  'linked_data')

class CCRelationSparseSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = CCRelation

        fields = ('uri', 'url', 'id',
                  'subject', 'object',
                  'name',
                  'type_controlled')

class ACRelationSerializer(serializers.HyperlinkedModelSerializer):
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')

    class Meta:
        model = ACRelation

        fields = ('uri', 'url', 'id',
                  'citation', 'authority',
                  'name',
                  'description',
                  'type_controlled',
                  'attributes',
                  'linked_data')

class ACRelationSparseSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ACRelation

        fields = ('uri', 'url', 'id',
                  'citation', 'authority',
                  'name',
                  'type_controlled')

class AARelationSerializer(serializers.HyperlinkedModelSerializer):
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')

    class Meta:
        model = AARelation

        fields = ('uri', 'url', 'id',
                  'subject', 'object',
                  'name',
                  'description',
                  'type_controlled',
                  'attributes',
                  'linked_data')

class AARelationSparseSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = AARelation

        fields = ('uri', 'url', 'id',
                  'subject', 'object',
                  'name',
                  'type_controlled')

class AuthoritySerializer(serializers.HyperlinkedModelSerializer):
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')
    related_citations = ACRelationSparseSerializer(read_only=True, many=True,
                                                   source='acrelations')
    related_authorities = AARelationSparseSerializer(read_only=True, many=True,
                                                     source='aarelations')

    class Meta:
        model = Authority
        fields = ('uri', 'url', 'name',
                  'description',
                  'type_controlled',
                  'classification_system',
                  'classification_code',
                  'classification_hierarchy',
                  'redirect_to',
                  'attributes',
                  'linked_data',
                  'related_citations',
                  'related_authorities')

    def to_representation(self, obj):
        """
        Add Person-specific fields to the instance representation.

        TODO: make this more general.
        """

        repr = super(AuthoritySerializer, self).to_representation(obj)
        if hasattr(obj, 'person'):
            obj = obj.person
            for fname in ['personal_name_last',
                          'personal_name_first',
                          'personal_name_suffix']:
                repr[fname] = getattr(obj, fname)
        return repr

class CitationSerializer(serializers.HyperlinkedModelSerializer):
    language = LanguageSerializer(many=True, read_only=True)
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')
    related_citations = CCRelationSparseSerializer(read_only=True, many=True,
                                                   source='ccrelations')
    related_authorities = ACRelationSparseSerializer(read_only=True, many=True,
                                               source='acrelations')

    class Meta:
        model = Citation
        fields = ('uri', 'url', 'id',
                  'title',
                  'description',
                  'language',
                  'type_controlled',
                  'abstract',
                  'edition_details',
                  'physical_details',
                  'attributes',
                  'linked_data',
                  'related_citations',
                  'related_authorities')

class PartDetailsSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = PartDetails

class AuthorityViewSet(mixins.ListModelMixin,
                       mixins.RetrieveModelMixin,
                       viewsets.GenericViewSet):
    queryset = Authority.objects.all()
    serializer_class = AuthoritySerializer

class UserViewSet(mixins.ListModelMixin,
                  mixins.RetrieveModelMixin,
                  viewsets.GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class CitationViewSet(mixins.ListModelMixin,
                      mixins.RetrieveModelMixin,
                      viewsets.GenericViewSet):
    queryset = Citation.objects.all()
    serializer_class = CitationSerializer

class ACRelationViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = ACRelation.objects.all()
    serializer_class = ACRelationSerializer

class CCRelationViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = CCRelation.objects.all()
    serializer_class = CCRelationSerializer

class AARelationViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = AARelation.objects.all()
    serializer_class = AARelationSerializer

class AttributeTypeViewSet(mixins.ListModelMixin,
                           mixins.RetrieveModelMixin,
                           viewsets.GenericViewSet):
    queryset = AttributeType.objects.all()
    serializer_class = AttributeTypeSerializer

class ContentTypeViewSet(mixins.ListModelMixin,
                         mixins.RetrieveModelMixin,
                         viewsets.GenericViewSet):
    queryset = ContentType.objects.all()
    serializer_class = ContentTypeSerializer

class ValueViewSet(mixins.ListModelMixin,
                   mixins.RetrieveModelMixin,
                   viewsets.GenericViewSet):
    queryset = Value.objects.all()
    serializer_class = ValueSerializer

class LanguageViewSet(mixins.ListModelMixin,
                      mixins.RetrieveModelMixin,
                      viewsets.GenericViewSet):
    queryset = Language.objects.all()
    serializer_class = LanguageSerializer

# class ReferencedEntityRelatedField(serializers.HyperlinkedRelatedField):
#     view_name = ''
#
#     def to_representation(self, value):
#         print self.view_name
#         if hasattr(value, 'citation'):
#             self.view_name = 'citation-detail'
#             value = value.citation
#         if hasattr(value, 'authority'):
#             self.view_name = 'authority-detail'
#             value = value.citation
#         return super(ReferencedEntityRelatedField, self).to_representation(value)

class AttributeViewSet(mixins.ListModelMixin,
                       mixins.RetrieveModelMixin,
                       viewsets.GenericViewSet):

    queryset = Attribute.objects.all()
    serializer_class = AttributeSerializer
    # source = ReferencedEntityRelatedField(read_only=True)

class LinkedDataViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = LinkedData.objects.all()
    serializer_class = LinkedDataSerializer

class LinkedDataTypeViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = LinkedDataType.objects.all()
    serializer_class = LinkedDataTypeSerializer

class PartDetailsViewSet(mixins.ListModelMixin,
                         mixins.RetrieveModelMixin,
                         viewsets.GenericViewSet):
    queryset = PartDetails.objects.all()
    serializer_class = PartDetailsSerializer

@api_view(('GET',))
def api_root(request, format=None):
    return Response({
        'authority': reverse('authority-list', request=request, format=format),
        'citation': reverse('citation-list', request=request, format=format),
        'acrelation': reverse('acrelation-list', request=request, format=format),
        'ccrelation': reverse('ccrelation-list', request=request, format=format),
        'aarelation': reverse('aarelation-list', request=request, format=format),
        'attribute': reverse('attribute-list', request=request, format=format),
        'linkeddata': reverse('linkeddata-list', request=request, format=format),
    })

def index(request):
    template = loader.get_template('isisdata/index.html')
    context = RequestContext(request, {
        'test': False,
    })
    return HttpResponse(template.render(context))

def index(request, obj_id):
    template = loader.get_template('isisdata/index.html')
    try:
        object = Authority.objects.get(id=obj_id)
    except Authority.DoesNotExist:
        object = None
    if object != None:
        return redirect('authority', authority_id = obj_id)

    return redirect('citation', citation_id = obj_id)

    #context = RequestContext(request, {
    #    'test': False,
    #})
    #return HttpResponse(template.render(context))

def authority(request, authority_id):
    template = loader.get_template('isisdata/authority.html')
    authority = Authority.objects.get(id=authority_id)
    citations_by_list = ACRelation.objects.filter(authority=authority,type_broad_controlled='PR')
    citations_about_list = ACRelation.objects.filter(authority=authority,type_broad_controlled='SC')
    citations_other_list = ACRelation.objects.filter(authority=authority,type_broad_controlled__in=['IH', 'PH'])

    citations_by_paginator = Paginator(citations_by_list, 30)
    citations_about_paginator = Paginator(citations_about_list, 30)
    citations_other_paginator = Paginator(citations_other_list, 30)

    page = request.GET.get('page-about')
    try:
        citations_about = citations_about_paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        citations_about = citations_about_paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        citations_about = citations_about_paginator.page(paginator.num_pages)

    page_other = request.GET.get('page-other')
    try:
        citations_other = citations_other_paginator.page(page_other)
    except PageNotAnInteger:
        citations_other = citations_other_paginator.page(1)
    except EmptyPage:
        citations_other = citations_other_paginator.page(paginator.num_pages)

    page_by = request.GET.get('page-by')
    try:
        citations_by = citations_by_paginator.page(page_other)
    except PageNotAnInteger:
        citations_by = citations_by_paginator.page(1)
    except EmptyPage:
        citations_by = citations_by_paginator.page(paginator.num_pages)

    context = RequestContext(request, {
        'authority_id': authority_id,
        'authority': authority,
        'citations_by': citations_by,
        'citations_about': citations_about,
        'citations_other': citations_other
    })
    return HttpResponse(template.render(context))

def citation(request, citation_id):
    template = loader.get_template('isisdata/citation.html')
    citation = get_object_or_404(Citation, pk=citation_id)
    authors = citation.acrelation_set.filter(type_controlled__in=['AU', 'CO'])
    subjects = citation.acrelation_set.filter(type_controlled__in=['SU'])
    persons = citation.acrelation_set.filter(type_broad_controlled__in=['PR'])
    categories = citation.acrelation_set.filter(type_controlled__in=['CA'])
    time_periods = citation.acrelation_set.filter(type_controlled__in=['TI'])

    properties = citation.acrelation_set.exclude(type_controlled__in=['AU', 'CO', 'SU', 'CA'])
    properties_map = defaultdict(list)
    for prop in properties:
        properties_map[prop.type_controlled] += [prop]

    context = RequestContext(request, {
        'citation_id': citation_id,
        'citation': citation,
        'authors': authors,
        'properties_map': properties,
        'subjects': subjects,
        'persons': persons,
        'categories': categories,
        'time_periods': time_periods,
    })
    return HttpResponse(template.render(context))
<commit_msg>cleanup<commit_after>from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.contrib.auth.models import User
from django.db import connection
from django.http import HttpResponse

from rest_framework import viewsets, serializers, mixins
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse

from isisdata.models import *

from django.template import RequestContext, loader
from django.http import HttpResponse

from collections import defaultdict

class ReadOnlyLowerField(serializers.ReadOnlyField):
    """
    Coerces value to lowercase.
    """
    def to_representation(self, obj):
        return obj.lower()

class GenericHyperlink(serializers.HyperlinkedRelatedField):
    """
    Handles generic relations.
    """
    view_name = 'generic-detail'

    def get_url(self, obj, v, request, format):
        view_name = type(obj).__name__.lower() + '-detail'
        return super(GenericHyperlink, self).get_url(obj, view_name,
                                                     request, format)

# class ValueHyperlink(serializers.HyperlinkedRelatedField):
#     view_name = 'value-detail'
#
#     def get_url(self, obj, v, request, format):
#         view_name = obj.child_class.lower() + '-detail'
#         print view_name
#         return super(ValueHyperlink, self).get_url(obj, view_name,
#                                                    request, format)

class ValueSerializer(serializers.HyperlinkedModelSerializer):
    value = serializers.ReadOnlyField(source='cvalue')
    value_type = ReadOnlyLowerField(source='child_class')

    class Meta:
        model = Value
        fields = ('value', 'value_type')

class ContentTypeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ContentType
        fields = ('url', 'model')

class AttributeTypeSerializer(serializers.HyperlinkedModelSerializer):
    content_type = ContentTypeSerializer(source='value_content_type')

    class Meta:
        model = AttributeType
        fields = ('url', 'id', 'name', 'content_type')

class AttributeSerializer(serializers.HyperlinkedModelSerializer):
    type_controlled = AttributeTypeSerializer(many=False)
    source = GenericHyperlink(many=False, read_only=True)
    value = ValueSerializer(many=False, read_only=True)

    class Meta:
        model = Attribute
        fields = ('uri', 'url', 'id',
                  'type_controlled',
                  'type_controlled_broad',
                  'source',
                  'value',
                  'value_freeform')

class LanguageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Language
        fields = ('url', 'id', 'name')

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User

class LinkedDataTypeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = LinkedDataType

class LinkedDataSerializer(serializers.HyperlinkedModelSerializer):
    type_controlled = LinkedDataTypeSerializer(many=False)
    class Meta:
        model = LinkedData
        fields = ('universal_resource_name', 'description', 'type_controlled')

class CCRelationSerializer(serializers.HyperlinkedModelSerializer):
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')

    class Meta:
        model = CCRelation

        fields = ('uri', 'url', 'id',
                  'subject', 'object',
                  'name',
                  'description',
                  'type_controlled',
                  'attributes',
                  'linked_data')

class CCRelationSparseSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = CCRelation

        fields = ('uri', 'url', 'id',
                  'subject', 'object',
                  'name',
                  'type_controlled')

class ACRelationSerializer(serializers.HyperlinkedModelSerializer):
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')

    class Meta:
        model = ACRelation

        fields = ('uri', 'url', 'id',
                  'citation', 'authority',
                  'name',
                  'description',
                  'type_controlled',
                  'attributes',
                  'linked_data')

class ACRelationSparseSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ACRelation

        fields = ('uri', 'url', 'id',
                  'citation', 'authority',
                  'name',
                  'type_controlled')

class AARelationSerializer(serializers.HyperlinkedModelSerializer):
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')

    class Meta:
        model = AARelation

        fields = ('uri', 'url', 'id',
                  'subject', 'object',
                  'name',
                  'description',
                  'type_controlled',
                  'attributes',
                  'linked_data')

class AARelationSparseSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = AARelation

        fields = ('uri', 'url', 'id',
                  'subject', 'object',
                  'name',
                  'type_controlled')

class AuthoritySerializer(serializers.HyperlinkedModelSerializer):
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')
    related_citations = ACRelationSparseSerializer(read_only=True, many=True,
                                                   source='acrelations')
    related_authorities = AARelationSparseSerializer(read_only=True, many=True,
                                                     source='aarelations')

    class Meta:
        model = Authority
        fields = ('uri', 'url', 'name',
                  'description',
                  'type_controlled',
                  'classification_system',
                  'classification_code',
                  'classification_hierarchy',
                  'redirect_to',
                  'attributes',
                  'linked_data',
                  'related_citations',
                  'related_authorities')

    def to_representation(self, obj):
        """
        Add Person-specific fields to the instance representation.

        TODO: make this more general.
        """

        repr = super(AuthoritySerializer, self).to_representation(obj)
        if hasattr(obj, 'person'):
            obj = obj.person
            for fname in ['personal_name_last',
                          'personal_name_first',
                          'personal_name_suffix']:
                repr[fname] = getattr(obj, fname)
        return repr

class CitationSerializer(serializers.HyperlinkedModelSerializer):
    language = LanguageSerializer(many=True, read_only=True)
    attributes = AttributeSerializer(many=True, read_only=True)
    linked_data = LinkedDataSerializer(many=True, read_only=True,
                                       source='linkeddata_entries')
    related_citations = CCRelationSparseSerializer(read_only=True, many=True,
                                                   source='ccrelations')
    related_authorities = ACRelationSparseSerializer(read_only=True, many=True,
                                               source='acrelations')

    class Meta:
        model = Citation
        fields = ('uri', 'url', 'id',
                  'title',
                  'description',
                  'language',
                  'type_controlled',
                  'abstract',
                  'edition_details',
                  'physical_details',
                  'attributes',
                  'linked_data',
                  'related_citations',
                  'related_authorities')

class PartDetailsSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = PartDetails

class AuthorityViewSet(mixins.ListModelMixin,
                       mixins.RetrieveModelMixin,
                       viewsets.GenericViewSet):
    queryset = Authority.objects.all()
    serializer_class = AuthoritySerializer

class UserViewSet(mixins.ListModelMixin,
                  mixins.RetrieveModelMixin,
                  viewsets.GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class CitationViewSet(mixins.ListModelMixin,
                      mixins.RetrieveModelMixin,
                      viewsets.GenericViewSet):
    queryset = Citation.objects.all()
    serializer_class = CitationSerializer

class ACRelationViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = ACRelation.objects.all()
    serializer_class = ACRelationSerializer

class CCRelationViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = CCRelation.objects.all()
    serializer_class = CCRelationSerializer

class AARelationViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = AARelation.objects.all()
    serializer_class = AARelationSerializer

class AttributeTypeViewSet(mixins.ListModelMixin,
                           mixins.RetrieveModelMixin,
                           viewsets.GenericViewSet):
    queryset = AttributeType.objects.all()
    serializer_class = AttributeTypeSerializer

class ContentTypeViewSet(mixins.ListModelMixin,
                         mixins.RetrieveModelMixin,
                         viewsets.GenericViewSet):
    queryset = ContentType.objects.all()
    serializer_class = ContentTypeSerializer

class ValueViewSet(mixins.ListModelMixin,
                   mixins.RetrieveModelMixin,
                   viewsets.GenericViewSet):
    queryset = Value.objects.all()
    serializer_class = ValueSerializer

class LanguageViewSet(mixins.ListModelMixin,
                      mixins.RetrieveModelMixin,
                      viewsets.GenericViewSet):
    queryset = Language.objects.all()
    serializer_class = LanguageSerializer

class AttributeViewSet(mixins.ListModelMixin,
                       mixins.RetrieveModelMixin,
                       viewsets.GenericViewSet):

    queryset = Attribute.objects.all()
    serializer_class = AttributeSerializer

class LinkedDataViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = LinkedData.objects.all()
    serializer_class = LinkedDataSerializer

class LinkedDataTypeViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    queryset = LinkedDataType.objects.all()
    serializer_class = LinkedDataTypeSerializer

class PartDetailsViewSet(mixins.ListModelMixin,
                         mixins.RetrieveModelMixin,
                         viewsets.GenericViewSet):
    queryset = PartDetails.objects.all()
    serializer_class = PartDetailsSerializer

@api_view(('GET',))
def api_root(request, format=None):
    return Response({
        'authority': reverse('authority-list', request=request, format=format),
        'citation': reverse('citation-list', request=request, format=format),
        'acrelation': reverse('acrelation-list', request=request, format=format),
        'ccrelation': reverse('ccrelation-list', request=request, format=format),
        'aarelation': reverse('aarelation-list', request=request, format=format),
        'attribute': reverse('attribute-list', request=request, format=format),
        'linkeddata': reverse('linkeddata-list', request=request, format=format),
    })

def index(request):
    template = loader.get_template('isisdata/index.html')
    context = RequestContext(request, {
        'test': False,
    })
    return HttpResponse(template.render(context))

def index(request, obj_id):
    template = loader.get_template('isisdata/index.html')
    try:
        object = Authority.objects.get(id=obj_id)
    except Authority.DoesNotExist:
        object = None
    if object != None:
        return redirect('authority', authority_id = obj_id)

    return redirect('citation', citation_id = obj_id)

    #context = RequestContext(request, {
    #    'test': False,
    #})
    #return HttpResponse(template.render(context))

def authority(request, authority_id):
    template = loader.get_template('isisdata/authority.html')
    authority = Authority.objects.get(id=authority_id)
    citations_by_list = ACRelation.objects.filter(authority=authority,type_broad_controlled='PR')
    citations_about_list = ACRelation.objects.filter(authority=authority,type_broad_controlled='SC')
    citations_other_list = ACRelation.objects.filter(authority=authority,type_broad_controlled__in=['IH', 'PH'])

    citations_by_paginator = Paginator(citations_by_list, 30)
    citations_about_paginator = Paginator(citations_about_list, 30)
    citations_other_paginator = Paginator(citations_other_list, 30)

    page = request.GET.get('page-about')
    try:
        citations_about = citations_about_paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        citations_about = citations_about_paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        citations_about = citations_about_paginator.page(paginator.num_pages)

    page_other = request.GET.get('page-other')
    try:
        citations_other = citations_other_paginator.page(page_other)
    except PageNotAnInteger:
        citations_other = citations_other_paginator.page(1)
    except EmptyPage:
        citations_other = citations_other_paginator.page(paginator.num_pages)

    page_by = request.GET.get('page-by')
    try:
        citations_by = citations_by_paginator.page(page_other)
    except PageNotAnInteger:
        citations_by = citations_by_paginator.page(1)
    except EmptyPage:
        citations_by = citations_by_paginator.page(paginator.num_pages)

    context = RequestContext(request, {
        'authority_id': authority_id,
        'authority': authority,
        'citations_by': citations_by,
        'citations_about': citations_about,
        'citations_other': citations_other
    })
    return HttpResponse(template.render(context))

def citation(request, citation_id):
    template = loader.get_template('isisdata/citation.html')
    citation = get_object_or_404(Citation, pk=citation_id)
    authors = citation.acrelation_set.filter(type_controlled__in=['AU', 'CO'])
    subjects = citation.acrelation_set.filter(type_controlled__in=['SU'])
    persons = citation.acrelation_set.filter(type_broad_controlled__in=['PR'])
    categories = citation.acrelation_set.filter(type_controlled__in=['CA'])
    time_periods = citation.acrelation_set.filter(type_controlled__in=['TI'])

    properties = citation.acrelation_set.exclude(type_controlled__in=['AU', 'CO', 'SU', 'CA'])
    properties_map = defaultdict(list)
    for prop in properties:
        properties_map[prop.type_controlled] += [prop]

    context = RequestContext(request, {
        'citation_id': citation_id,
        'citation': citation,
        'authors': authors,
        'properties_map': properties,
        'subjects': subjects,
        'persons': persons,
        'categories': categories,
        'time_periods': time_periods,
    })
    return HttpResponse(template.render(context))
<|endoftext|>


<commit_before>from .base import Model
from .fields import TextField
from .session import Session

__all__ = (
    'Model',
    'TextField',
    'Session',
)
<commit_msg>Export the rest of the useful bits from the ODM<commit_after>from .base import Model
from .fields import TextField, JSONField, BaseField
from .session import Session, transaction

__all__ = (
    'Model',
    'TextField',
    'JSONField',
    'BaseField',
    'Session',
    'transaction',
)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

"""
JMDict in SQLite format
"""

# This code is a part of jamdict library: https://github.com/neocl/jamdict
# :copyright: (c) 2016 Le Tuan Anh <tuananh.ke@gmail.com>
# :license: MIT, see LICENSE for more details.

import os
import logging

from puchikarui import Schema
from . import __version__ as JAMDICT_VERSION, __url__ as JAMDICT_URL
from .jmdict import Meta, JMDEntry, EntryInfo, Link, BibInfo, Audit, KanjiForm, KanaForm, Sense, SenseGloss, LSource

# -------------------------------------------------------------------------------
# Configuration
# -------------------------------------------------------------------------------

MY_FOLDER = os.path.dirname(os.path.abspath(__file__))
SCRIPT_FOLDER = os.path.join(MY_FOLDER, 'data')
JMDICT_SETUP_FILE = os.path.join(SCRIPT_FOLDER, 'setup_jmdict.sql')
JMDICT_VERSION = '1.08'
JMDICT_URL = 'http://www.csse.monash.edu.au/~jwb/edict.html'
SETUP_SCRIPT = '''INSERT INTO meta VALUES ('jmdict.version', '{jv}');
INSERT INTO meta VALUES ('jmdict.url', '{ju}');
INSERT INTO meta VALUES ('generator', 'jamdict');
INSERT INTO meta VALUES ('generator_version', '{gv}');
INSERT INTO meta VALUES ('generator_url', '{gu}');'''.format(
    jv=JMDICT_VERSION,
    ju=JMDICT_URL,
    gv=JAMDICT_VERSION,
    gu=JAMDICT_URL
)

def getLogger():
    return logging.getLogger(__name__)

# -------------------------------------------------------------------------------
# Models
# -------------------------------------------------------------------------------

class JMDictSchema(Schema):

    KEY_JMD_VER = "jmdict.version"
    KEY_JMD_URL = "jmdict.url"

    def __init__(self, db_path, *args, **kwargs):
        super().__init__(db_path, *args, **kwargs)
        self.add_script(SETUP_SCRIPT)
        self.add_file(JMDICT_SETUP_FILE)
        # Meta
        self.add_table('meta', ['key', 'value'], proto=Meta).set_id('key')
        self.add_table('Entry', ['idseq'])
        self.add_table('Link', ['ID', 'idseq', 'tag', 'desc', 'uri'])
        self.add_table('Bib', ['ID', 'idseq', 'tag', 'text'])
        self.add_table('Etym', ['idseq', 'text'])
        self.add_table('Audit', ['idseq', 'upd_date', 'upd_detl'])
        # Kanji
        self.add_table('Kanji', ['ID', 'idseq', 'text'])
        self.add_table('KJI', ['kid', 'text'])
        self.add_table('KJP', ['kid', 'text'])
        # Kana
        self.add_table('Kana', ['ID', 'idseq', 'text', 'nokanji'])
        self.add_table('KNI', ['kid', 'text'])
        self.add_table('KNP', ['kid', 'text'])
        self.add_table('KNR', ['kid', 'text'])
        # Senses
        self.add_table('Sense', ['ID', 'idseq'])
        self.add_table('stagk', ['sid', 'text'])
        self.add_table('stagr', ['sid', 'text'])
        self.add_table('pos', ['sid', 'text'])
        self.add_table('xref', ['sid', 'text'])
        self.add_table('antonym', ['sid', 'text'])
        self.add_table('field', ['sid', 'text'])
        self.add_table('misc', ['sid', 'text'])
        self.add_table('SenseInfo', ['sid', 'text'])
        self.add_table('SenseSource', ['sid', 'text', 'lang', 'lstype', 'wasei'])
        self.add_table('dialect', ['sid', 'text'])
        self.add_table('SenseGloss', ['sid', 'lang', 'gend', 'text'])

class JMDictSQLite(JMDictSchema):

    def __init__(self, db_path, *args, **kwargs):
        super().__init__(db_path, *args, **kwargs)

    def update_jmd_meta(self, version, url, ctx=None):
        # create a default context if none was provided
        if ctx is None:
            with self.open(ctx) as ctx:
                return self.update_jmd_meta(version, url, ctx=ctx)
        # else (a context is provided)
        # version
        jv = ctx.meta.by_id(self.KEY_JMD_VER)
        if not jv:
            ctx.meta.insert(self.KEY_JMD_VER, version)
        else:
            jv.value = version
            ctx.meta.save(jv)
        # url
        ju = ctx.meta.by_id(self.KEY_JMD_URL)
        if not ju:
            ctx.meta.insert(self.KEY_JMD_URL, version)
        else:
            ju.value = url
            ctx.meta.save(ju)

    def search(self, query, ctx=None, **kwargs):
        # ensure context
        if ctx is None:
            with self.ctx() as ctx:
                return self.search(query, ctx=ctx)
        _is_wildcard_search = '_' in query or '@' in query or '%' in query
        if _is_wildcard_search:
            where = "idseq IN (SELECT idseq FROM Kanji WHERE text like ?) OR idseq IN (SELECT idseq FROM Kana WHERE text like ?) OR idseq IN (SELECT idseq FROM sense JOIN sensegloss ON sense.ID == sensegloss.sid WHERE text like ?)"
        else:
            where = "idseq IN (SELECT idseq FROM Kanji WHERE text == ?) OR idseq IN (SELECT idseq FROM Kana WHERE text == ?) OR idseq IN (SELECT idseq FROM sense JOIN sensegloss ON sense.ID == sensegloss.sid WHERE text == ?)"
        getLogger().debug(where)
        params = [query, query, query]
        try:
            if query.startswith('id#'):
                query_int = int(query[3:])
                if query_int >= 0:
                    getLogger().debug("Searching by ID: {}".format(query_int))
                    where = "idseq = ?"
                    params = [query_int]
        except Exception:
            pass
        # else (a context is provided)
        eids = self.Entry.select(where, params, ctx=ctx)
        entries = []
        for e in eids:
            entries.append(self.get_entry(e.idseq, ctx=ctx))
        return entries

    def get_entry(self, idseq, ctx=None):
        # ensure context
        if ctx is None:
            with self.ctx() as new_context:
                return self.get_entry(idseq, new_context)
        # else (a context is provided)
        # select entry & info
        entry = JMDEntry(idseq)
        # links, bibs, etym, audit ...
        dblinks = ctx.Link.select('idseq=?', (idseq,))
        dbbibs = ctx.Bib.select('idseq=?', (idseq,))
        dbetym = ctx.Etym.select('idseq=?', (idseq,))
        dbaudit = ctx.Audit.select('idseq=?', (idseq,))
        if dblinks or dbbibs or dbetym or dbaudit:
            entry.info = EntryInfo()
            if dblinks:
                for l in dblinks:
                    entry.info.links.append(Link(l.tag, l.desc, l.uri))
            if dbbibs:
                for b in dbbibs:
                    entry.info.bibinfo.append(BibInfo(b.tag, b.text))
            if dbetym:
                for e in dbetym:
                    entry.info.etym.append(e)
            if dbaudit:
                for a in dbaudit:
                    entry.info.audit.append(Audit(a.upd_date, a.upd_detl))
        # select kanji
        kanjis = ctx.Kanji.select('idseq=?', (idseq,))
        for dbkj in kanjis:
            kj = KanjiForm(dbkj.text)
            kjis = ctx.KJI.select('kid=?', (dbkj.ID,))
            for i in kjis:
                kj.info.append(i.text)
            kjps = ctx.KJP.select('kid=?', (dbkj.ID,))
            for p in kjps:
                kj.pri.append(p.text)
            entry.kanji_forms.append(kj)
        # select kana
        kanas = ctx.Kana.select('idseq=?', (idseq,))
        for dbkn in kanas:
            kn = KanaForm(dbkn.text, dbkn.nokanji)
            knis = ctx.KNI.select('kid=?', (dbkn.ID,))
            for i in knis:
                kn.info.append(i.text)
            knps = ctx.KNP.select('kid=?', (dbkn.ID,))
            for p in knps:
                kn.pri.append(p.text)
            knrs = ctx.KNR.select('kid=?', (dbkn.ID,))
            for r in knrs:
                kn.restr.append(r.text)
            entry.kana_forms.append(kn)
        # select senses
        senses = ctx.Sense.select('idseq=?', (idseq,))
        for dbs in senses:
            s = Sense()
            # stagk
            ks = ctx.stagk.select('sid=?', (dbs.ID,))
            for k in ks:
                s.stagk.append(k.text)
            # stagr
            rs = ctx.stagr.select('sid=?', (dbs.ID,))
            for r in rs:
                s.stagr.append(r.text)
            # pos
            ps = ctx.pos.select('sid=?', (dbs.ID,))
            for p in ps:
                s.pos.append(p.text)
            # xref
            xs = ctx.xref.select('sid=?', (dbs.ID,))
            for x in xs:
                s.xref.append(x.text)
            # antonym
            ans = ctx.antonym.select('sid=?', (dbs.ID,))
            for a in ans:
                s.antonym.append(a.text)
            # field
            fs = ctx.field.select('sid=?', (dbs.ID,))
            for f in fs:
                s.field.append(f.text)
            # misc
            ms = ctx.misc.select('sid=?', (dbs.ID,))
            for m in ms:
                s.misc.append(m.text)
            # SenseInfo
            sis = ctx.SenseInfo.select('sid=?', (dbs.ID,))
            for si in sis:
                s.info.append(si.text)
            # SenseSource
            lss = ctx.SenseSource.select('sid=?', (dbs.ID,))
            for ls in lss:
                s.lsource.append(LSource(ls.lang, ls.lstype, ls.wasei, ls.text))
            # dialect
            ds = ctx.dialect.select('sid=?', (dbs.ID,))
            for d in ds:
                s.dialect.append(d.text)
            # SenseGloss
            gs = ctx.SenseGloss.select('sid=?', (dbs.ID,))
            for g in gs:
                s.gloss.append(SenseGloss(g.lang, g.gend, g.text))
            entry.senses.append(s)
        return entry

    def insert_entries(self, entries, ctx=None):
        # ensure context
        if ctx is None:
            with self.ctx() as new_context:
                return self.insert_entries(entries, ctx=new_context)
        # else
        getLogger().debug("JMdict bulk insert {} entries".format(len(entries)))
        for entry in entries:
            self.insert_entry(entry, ctx)

    def insert_entry(self, entry, ctx=None):
        # ensure context
        if ctx is None:
            with self.ctx() as ctx:
                return self.insert_entry(entry, ctx=ctx)
        # else (a context is provided)
        self.Entry.insert(entry.idseq, ctx=ctx)
        # insert info
        if entry.info:
            # links
            for lnk in entry.info.links:
                ctx.Link.insert(entry.idseq, lnk.tag, lnk.desc, lnk.uri)
            # bibs
            for bib in entry.info.bibinfo:
                ctx.Bib.insert(entry.idseq, bib.tag, bib.text)
            # etym
            for e in entry.info.etym:
                ctx.Etym.insert(entry.idseq, e)
            # audit
            for a in entry.info.audit:
                ctx.Audit.insert(entry.idseq, a.upd_date, a.upd_detl)
        # insert kanji
        for kj in entry.kanji_forms:
            kjid = ctx.Kanji.insert(entry.idseq, kj.text)
            # KJI
            for kji in kj.info:
                ctx.KJI.insert(kjid, kji)
            # KJP
            for kjp in kj.pri:
                ctx.KJP.insert(kjid, kjp)
        # insert kana
        for kn in entry.kana_forms:
            knid = ctx.Kana.insert(entry.idseq, kn.text, kn.nokanji)
            # KNI
            for kni in kn.info:
                ctx.KNI.insert(knid, kni)
            # KNP
            for knp in kn.pri:
                ctx.KNP.insert(knid, knp)
            # KNR
            for knr in kn.restr:
                ctx.KNR.insert(knid, knr)
        # insert senses
        for s in entry.senses:
            sid = ctx.Sense.insert(entry.idseq)
            # stagk
            for sk in s.stagk:
                ctx.stagk.insert(sid, sk)
            # stagr
            for sr in s.stagr:
                ctx.stagr.insert(sid, sr)
            # pos
            for pos in s.pos:
                ctx.pos.insert(sid, pos)
            # xref
            for xr in s.xref:
                ctx.xref.insert(sid, xr)
            # antonym
            for a in s.antonym:
                ctx.antonym.insert(sid, a)
            # field
            for f in s.field:
                ctx.field.insert(sid, f)
            # misc
            for m in s.misc:
                ctx.misc.insert(sid, m)
            # SenseInfo
            for i in s.info:
                ctx.SenseInfo.insert(sid, i)
            # SenseSource
            for l in s.lsource:
                ctx.SenseSource.insert(sid, l.text, l.lang, l.lstype, l.wasei)
            # dialect
            for d in s.dialect:
                ctx.dialect.insert(sid, d)
            # SenseGloss
            for g in s.gloss:
                ctx.SenseGloss.insert(sid, g.lang, g.gend, g.text)
<commit_msg>add all_pos() method and allow to lookup() by pos<commit_after># -*- coding: utf-8 -*-

"""
JMDict in SQLite format
"""

# This code is a part of jamdict library: https://github.com/neocl/jamdict
# :copyright: (c) 2016 Le Tuan Anh <tuananh.ke@gmail.com>
# :license: MIT, see LICENSE for more details.

import os
import logging

from puchikarui import Schema
from . import __version__ as JAMDICT_VERSION, __url__ as JAMDICT_URL
from .jmdict import Meta, JMDEntry, EntryInfo, Link, BibInfo, Audit, KanjiForm, KanaForm, Sense, SenseGloss, LSource

# -------------------------------------------------------------------------------
# Configuration
# -------------------------------------------------------------------------------

MY_FOLDER = os.path.dirname(os.path.abspath(__file__))
SCRIPT_FOLDER = os.path.join(MY_FOLDER, 'data')
JMDICT_SETUP_FILE = os.path.join(SCRIPT_FOLDER, 'setup_jmdict.sql')
JMDICT_VERSION = '1.08'
JMDICT_URL = 'http://www.csse.monash.edu.au/~jwb/edict.html'
SETUP_SCRIPT = '''INSERT INTO meta VALUES ('jmdict.version', '{jv}');
INSERT INTO meta VALUES ('jmdict.url', '{ju}');
INSERT INTO meta VALUES ('generator', 'jamdict');
INSERT INTO meta VALUES ('generator_version', '{gv}');
INSERT INTO meta VALUES ('generator_url', '{gu}');'''.format(
    jv=JMDICT_VERSION,
    ju=JMDICT_URL,
    gv=JAMDICT_VERSION,
    gu=JAMDICT_URL
)

def getLogger():
    return logging.getLogger(__name__)

# -------------------------------------------------------------------------------
# Models
# -------------------------------------------------------------------------------

class JMDictSchema(Schema):

    KEY_JMD_VER = "jmdict.version"
    KEY_JMD_URL = "jmdict.url"

    def __init__(self, db_path, *args, **kwargs):
        super().__init__(db_path, *args, **kwargs)
        self.add_script(SETUP_SCRIPT)
        self.add_file(JMDICT_SETUP_FILE)
        # Meta
        self.add_table('meta', ['key', 'value'], proto=Meta).set_id('key')
        self.add_table('Entry', ['idseq'])
        self.add_table('Link', ['ID', 'idseq', 'tag', 'desc', 'uri'])
        self.add_table('Bib', ['ID', 'idseq', 'tag', 'text'])
        self.add_table('Etym', ['idseq', 'text'])
        self.add_table('Audit', ['idseq', 'upd_date', 'upd_detl'])
        # Kanji
        self.add_table('Kanji', ['ID', 'idseq', 'text'])
        self.add_table('KJI', ['kid', 'text'])
        self.add_table('KJP', ['kid', 'text'])
        # Kana
        self.add_table('Kana', ['ID', 'idseq', 'text', 'nokanji'])
        self.add_table('KNI', ['kid', 'text'])
        self.add_table('KNP', ['kid', 'text'])
        self.add_table('KNR', ['kid', 'text'])
        # Senses
        self.add_table('Sense', ['ID', 'idseq'])
        self.add_table('stagk', ['sid', 'text'])
        self.add_table('stagr', ['sid', 'text'])
        self.add_table('pos', ['sid', 'text'])
        self.add_table('xref', ['sid', 'text'])
        self.add_table('antonym', ['sid', 'text'])
        self.add_table('field', ['sid', 'text'])
        self.add_table('misc', ['sid', 'text'])
        self.add_table('SenseInfo', ['sid', 'text'])
        self.add_table('SenseSource', ['sid', 'text', 'lang', 'lstype', 'wasei'])
        self.add_table('dialect', ['sid', 'text'])
        self.add_table('SenseGloss', ['sid', 'lang', 'gend', 'text'])

class JMDictSQLite(JMDictSchema):

    def __init__(self, db_path, *args, **kwargs):
        super().__init__(db_path, *args, **kwargs)

    def update_jmd_meta(self, version, url, ctx=None):
        # create a default context if none was provided
        if ctx is None:
            with self.open(ctx) as ctx:
                return self.update_jmd_meta(version, url, ctx=ctx)
        # else (a context is provided)
        # version
        jv = ctx.meta.by_id(self.KEY_JMD_VER)
        if not jv:
            ctx.meta.insert(self.KEY_JMD_VER, version)
        else:
            jv.value = version
            ctx.meta.save(jv)
        # url
        ju = ctx.meta.by_id(self.KEY_JMD_URL)
        if not ju:
            ctx.meta.insert(self.KEY_JMD_URL, version)
        else:
            ju.value = url
            ctx.meta.save(ju)

    def all_pos(self, ctx=None):
        if ctx is None:
            return self.all_pos(ctx=self.ctx())
        else:
            return [x['text'] for x in ctx.select("SELECT DISTINCT text FROM pos")]

    def search(self, query, ctx=None, pos=None, **kwargs):
        # ensure context
        if ctx is None:
            with self.ctx() as ctx:
                return self.search(query, ctx=ctx)

        where = []
        params = []
        if query.startswith('id#'):
            query_int = int(query[3:])
            if query_int >= 0:
                getLogger().debug("Searching by ID: {}".format(query_int))
                where.append("idseq = ?")
                params.append(query_int)
        elif query and query != "%":
            _is_wildcard_search = '_' in query or '@' in query or '%' in query
            if _is_wildcard_search:
                where.append("(idseq IN (SELECT idseq FROM Kanji WHERE text like ?) OR idseq IN (SELECT idseq FROM Kana WHERE text like ?) OR idseq IN (SELECT idseq FROM sense JOIN sensegloss ON sense.ID == sensegloss.sid WHERE text like ?))")
            else:
                where.append("(idseq IN (SELECT idseq FROM Kanji WHERE text == ?) OR idseq IN (SELECT idseq FROM Kana WHERE text == ?) OR idseq IN (SELECT idseq FROM sense JOIN sensegloss ON sense.ID == sensegloss.sid WHERE text == ?))")
            params += (query, query, query)
        if pos:
            if isinstance(pos, str):
                getLogger().warning("POS filter should be a collection, not a string")
                pos = [pos]
            # allow to search by POS
            slots = len(pos)
            if where:
                where.append("AND")
            where.append(f"idseq IN (SELECT idseq FROM Sense WHERE ID IN (SELECT sid FROM pos WHERE text IN ({','.join('?' * slots)})))")
            params += pos
        # else (a context is provided)
        logging.getLogger(__name__).debug(f"Search query: {where} -- Params: {params}")
        eids = self.Entry.select(' '.join(where), params, ctx=ctx)
        entries = []
        for e in eids:
            entries.append(self.get_entry(e.idseq, ctx=ctx))
        return entries

    def get_entry(self, idseq, ctx=None):
        # ensure context
        if ctx is None:
            with self.ctx() as new_context:
                return self.get_entry(idseq, new_context)
        # else (a context is provided)
        # select entry & info
        entry = JMDEntry(idseq)
        # links, bibs, etym, audit ...
        dblinks = ctx.Link.select('idseq=?', (idseq,))
        dbbibs = ctx.Bib.select('idseq=?', (idseq,))
        dbetym = ctx.Etym.select('idseq=?', (idseq,))
        dbaudit = ctx.Audit.select('idseq=?', (idseq,))
        if dblinks or dbbibs or dbetym or dbaudit:
            entry.info = EntryInfo()
            if dblinks:
                for l in dblinks:
                    entry.info.links.append(Link(l.tag, l.desc, l.uri))
            if dbbibs:
                for b in dbbibs:
                    entry.info.bibinfo.append(BibInfo(b.tag, b.text))
            if dbetym:
                for e in dbetym:
                    entry.info.etym.append(e)
            if dbaudit:
                for a in dbaudit:
                    entry.info.audit.append(Audit(a.upd_date, a.upd_detl))
        # select kanji
        kanjis = ctx.Kanji.select('idseq=?', (idseq,))
        for dbkj in kanjis:
            kj = KanjiForm(dbkj.text)
            kjis = ctx.KJI.select('kid=?', (dbkj.ID,))
            for i in kjis:
                kj.info.append(i.text)
            kjps = ctx.KJP.select('kid=?', (dbkj.ID,))
            for p in kjps:
                kj.pri.append(p.text)
            entry.kanji_forms.append(kj)
        # select kana
        kanas = ctx.Kana.select('idseq=?', (idseq,))
        for dbkn in kanas:
            kn = KanaForm(dbkn.text, dbkn.nokanji)
            knis = ctx.KNI.select('kid=?', (dbkn.ID,))
            for i in knis:
                kn.info.append(i.text)
            knps = ctx.KNP.select('kid=?', (dbkn.ID,))
            for p in knps:
                kn.pri.append(p.text)
            knrs = ctx.KNR.select('kid=?', (dbkn.ID,))
            for r in knrs:
                kn.restr.append(r.text)
            entry.kana_forms.append(kn)
        # select senses
        senses = ctx.Sense.select('idseq=?', (idseq,))
        for dbs in senses:
            s = Sense()
            # stagk
            ks = ctx.stagk.select('sid=?', (dbs.ID,))
            for k in ks:
                s.stagk.append(k.text)
            # stagr
            rs = ctx.stagr.select('sid=?', (dbs.ID,))
            for r in rs:
                s.stagr.append(r.text)
            # pos
            ps = ctx.pos.select('sid=?', (dbs.ID,))
            for p in ps:
                s.pos.append(p.text)
            # xref
            xs = ctx.xref.select('sid=?', (dbs.ID,))
            for x in xs:
                s.xref.append(x.text)
            # antonym
            ans = ctx.antonym.select('sid=?', (dbs.ID,))
            for a in ans:
                s.antonym.append(a.text)
            # field
            fs = ctx.field.select('sid=?', (dbs.ID,))
            for f in fs:
                s.field.append(f.text)
            # misc
            ms = ctx.misc.select('sid=?', (dbs.ID,))
            for m in ms:
                s.misc.append(m.text)
            # SenseInfo
            sis = ctx.SenseInfo.select('sid=?', (dbs.ID,))
            for si in sis:
                s.info.append(si.text)
            # SenseSource
            lss = ctx.SenseSource.select('sid=?', (dbs.ID,))
            for ls in lss:
                s.lsource.append(LSource(ls.lang, ls.lstype, ls.wasei, ls.text))
            # dialect
            ds = ctx.dialect.select('sid=?', (dbs.ID,))
            for d in ds:
                s.dialect.append(d.text)
            # SenseGloss
            gs = ctx.SenseGloss.select('sid=?', (dbs.ID,))
            for g in gs:
                s.gloss.append(SenseGloss(g.lang, g.gend, g.text))
            entry.senses.append(s)
        return entry

    def insert_entries(self, entries, ctx=None):
        # ensure context
        if ctx is None:
            with self.ctx() as new_context:
                return self.insert_entries(entries, ctx=new_context)
        # else
        getLogger().debug("JMdict bulk insert {} entries".format(len(entries)))
        for entry in entries:
            self.insert_entry(entry, ctx)

    def insert_entry(self, entry, ctx=None):
        # ensure context
        if ctx is None:
            with self.ctx() as ctx:
                return self.insert_entry(entry, ctx=ctx)
        # else (a context is provided)
        self.Entry.insert(entry.idseq, ctx=ctx)
        # insert info
        if entry.info:
            # links
            for lnk in entry.info.links:
                ctx.Link.insert(entry.idseq, lnk.tag, lnk.desc, lnk.uri)
            # bibs
            for bib in entry.info.bibinfo:
                ctx.Bib.insert(entry.idseq, bib.tag, bib.text)
            # etym
            for e in entry.info.etym:
                ctx.Etym.insert(entry.idseq, e)
            # audit
            for a in entry.info.audit:
                ctx.Audit.insert(entry.idseq, a.upd_date, a.upd_detl)
        # insert kanji
        for kj in entry.kanji_forms:
            kjid = ctx.Kanji.insert(entry.idseq, kj.text)
            # KJI
            for kji in kj.info:
                ctx.KJI.insert(kjid, kji)
            # KJP
            for kjp in kj.pri:
                ctx.KJP.insert(kjid, kjp)
        # insert kana
        for kn in entry.kana_forms:
            knid = ctx.Kana.insert(entry.idseq, kn.text, kn.nokanji)
            # KNI
            for kni in kn.info:
                ctx.KNI.insert(knid, kni)
            # KNP
            for knp in kn.pri:
                ctx.KNP.insert(knid, knp)
            # KNR
            for knr in kn.restr:
                ctx.KNR.insert(knid, knr)
        # insert senses
        for s in entry.senses:
            sid = ctx.Sense.insert(entry.idseq)
            # stagk
            for sk in s.stagk:
                ctx.stagk.insert(sid, sk)
            # stagr
            for sr in s.stagr:
                ctx.stagr.insert(sid, sr)
            # pos
            for pos in s.pos:
                ctx.pos.insert(sid, pos)
            # xref
            for xr in s.xref:
                ctx.xref.insert(sid, xr)
            # antonym
            for a in s.antonym:
                ctx.antonym.insert(sid, a)
            # field
            for f in s.field:
                ctx.field.insert(sid, f)
            # misc
            for m in s.misc:
                ctx.misc.insert(sid, m)
            # SenseInfo
            for i in s.info:
                ctx.SenseInfo.insert(sid, i)
            # SenseSource
            for l in s.lsource:
                ctx.SenseSource.insert(sid, l.text, l.lang, l.lstype, l.wasei)
            # dialect
            for d in s.dialect:
                ctx.dialect.insert(sid, d)
            # SenseGloss
            for g in s.gloss:
                ctx.SenseGloss.insert(sid, g.lang, g.gend, g.text)
<|endoftext|>


<commit_before>import ast
import _ast
from jaspyx.ast_util import ast_load, ast_call, ast_store
from jaspyx.visitor import BaseVisitor

class Class(BaseVisitor):
    def visit_ClassDef(self, node):
        if len(node.bases) > 1:
            raise Exception('Multiple inheritance not supported')
        if node.decorator_list:
            raise Exception('Decorators not supported')

        self.visit(ast.FunctionDef(
            node.name,
            ast.arguments([], None, None, []),
            [
                ast.If(
                    ast.UnaryOp(
                        ast.Not(),
                        ast_call(
                            ast_load('isinstance'),
                            ast_load('this'),
                            ast_load('arguments.callee'),
                        )
                    ),
                    [
                        ast.Return(
                            ast_call(
                                ast_load('new'),
                                ast_load('arguments.callee'),
                                ast_load('this'),
                                ast_load('arguments'),
                            )
                        )
                    ],
                    []
                ),
                ast.Assign(
                    [ast_store('this.__class__')],
                    ast_load('arguments.callee')
                ),
                ast.For(
                    ast_store('i'),
                    ast_load('this'),
                    [
                        ast.If(
                            ast.Compare(
                                ast_call(
                                    ast_load('type'),
                                    ast.Subscript(
                                        ast_load('this'),
                                        ast.Index(ast_load('i')),
                                        ast.Load(),
                                    )
                                ),
                                [ast.Is()],
                                [ast.Str('function')]
                            ),
                            [
                                ast.Assign(
                                    [ast.Subscript(
                                        ast_load('this'),
                                        ast.Index(ast_load('i')),
                                        ast.Store(),
                                    )],
                                    ast_call(
                                        ast.Attribute(
                                            ast.Subscript(
                                                ast_load('this'),
                                                ast.Index(ast_load('i')),
                                                ast.Load(),
                                            ),
                                            'bind',
                                            ast.Load(),
                                        ),
                                        ast_load('this'),
                                        ast_load('this'),
                                    )
                                ),
                            ],
                            []
                        )
                    ],
                    []
                ),
                ast.If(
                    ast.Compare(
                        ast_call(
                            ast_load('type'),
                            ast_load('this.__init__'),
                        ),
                        [ast.IsNot()],
                        [ast.Str('undefined')],
                    ),
                    [
                        ast.Expr(
                            ast_call(
                                ast_load('this.__init__.apply'),
                                ast_load('this'),
                                ast_load('arguments'),
                            )
                        ),
                    ],
                    []
                )
            ],
            []
        ))

        if not node.bases:
            self.visit(
                ast.Assign(
                    [ast_store(node.name, 'prototype')],
                    ast.Dict(
                        [
                            ast.Str('constructor'),
                            ast.Str('super')
                        ],
                        [
                            ast_load(node.name),
                            ast.List([ast_load(node.name)], ast.Load())
                        ]
                    )
                )
            )
        else:
            base = node.bases[0]
            tmp = self.stack[-1].scope.alloc_temp()
            self.visit(
                ast.Assign(
                    [ast_store(node.name, 'prototype')],
                    ast_call(
                        ast.FunctionDef(
                            '',
                            ast.arguments([], None, None, []),
                            [
                                ast.Assign(
                                    [ast_store(tmp)],
                                    ast.FunctionDef(
                                        '',
                                        ast.arguments([], None, None, []),
                                        [],
                                        []
                                    )
                                ),
                                ast.Assign(
                                    [ast_store(tmp, 'prototype')],
                                    ast_load(base.id, 'prototype'),
                                ),
                                ast.Return(
                                    ast_call(
                                        ast_load('new'),
                                        ast_load(tmp),
                                    )
                                )
                            ],
                            []
                        ),
                    )
                )
            )
            self.visit(
                ast.Assign(
                    [ast_store(node.name, 'prototype.constructor')],
                    ast_load(node.name)
                )
            )
            self.visit(
                ast.Assign(
                    [ast_store(node.name, 'prototype.super')],
                    ast_call(
                        ast_load(node.name, 'prototype.super.concat'),
                        ast_load(node.name),
                    )
                )
            )

        for stmt in node.body:
            if isinstance(stmt, _ast.FunctionDef):
                self.visit(
                    ast.Assign(
                        [ast_store(node.name, 'prototype', stmt.name)],
                        ast.FunctionDef(
                            '',
                            stmt.args,
                            stmt.body,
                            stmt.decorator_list
                        )
                    )
                )
            elif isinstance(stmt, _ast.Assign):
                targets = []
                for target in stmt.targets:
                    if not isinstance(target, _ast.Name):
                        raise Exception('Indirect assignment not supported in class definition')
                    targets.append(ast_store(node.name, 'prototype', target.id))
                self.visit(ast.Assign(
                    targets,
                    stmt.value
                ))
<commit_msg>Rename super attribute to __mro__.<commit_after>import ast
import _ast
from jaspyx.ast_util import ast_load, ast_call, ast_store
from jaspyx.visitor import BaseVisitor

class Class(BaseVisitor):
    def visit_ClassDef(self, node):
        if len(node.bases) > 1:
            raise Exception('Multiple inheritance not supported')
        if node.decorator_list:
            raise Exception('Decorators not supported')

        self.visit(ast.FunctionDef(
            node.name,
            ast.arguments([], None, None, []),
            [
                ast.If(
                    ast.UnaryOp(
                        ast.Not(),
                        ast_call(
                            ast_load('isinstance'),
                            ast_load('this'),
                            ast_load('arguments.callee'),
                        )
                    ),
                    [
                        ast.Return(
                            ast_call(
                                ast_load('new'),
                                ast_load('arguments.callee'),
                                ast_load('this'),
                                ast_load('arguments'),
                            )
                        )
                    ],
                    []
                ),
                ast.Assign(
                    [ast_store('this.__class__')],
                    ast_load('arguments.callee')
                ),
                ast.For(
                    ast_store('i'),
                    ast_load('this'),
                    [
                        ast.If(
                            ast.Compare(
                                ast_call(
                                    ast_load('type'),
                                    ast.Subscript(
                                        ast_load('this'),
                                        ast.Index(ast_load('i')),
                                        ast.Load(),
                                    )
                                ),
                                [ast.Is()],
                                [ast.Str('function')]
                            ),
                            [
                                ast.Assign(
                                    [ast.Subscript(
                                        ast_load('this'),
                                        ast.Index(ast_load('i')),
                                        ast.Store(),
                                    )],
                                    ast_call(
                                        ast.Attribute(
                                            ast.Subscript(
                                                ast_load('this'),
                                                ast.Index(ast_load('i')),
                                                ast.Load(),
                                            ),
                                            'bind',
                                            ast.Load(),
                                        ),
                                        ast_load('this'),
                                        ast_load('this'),
                                    )
                                ),
                            ],
                            []
                        )
                    ],
                    []
                ),
                ast.If(
                    ast.Compare(
                        ast_call(
                            ast_load('type'),
                            ast_load('this.__init__'),
                        ),
                        [ast.IsNot()],
                        [ast.Str('undefined')],
                    ),
                    [
                        ast.Expr(
                            ast_call(
                                ast_load('this.__init__.apply'),
                                ast_load('this'),
                                ast_load('arguments'),
                            )
                        ),
                    ],
                    []
                )
            ],
            []
        ))

        if not node.bases:
            self.visit(
                ast.Assign(
                    [ast_store(node.name, 'prototype')],
                    ast.Dict(
                        [
                            ast.Str('constructor'),
                            ast.Str('__mro__')
                        ],
                        [
                            ast_load(node.name),
                            ast.List([ast_load(node.name)], ast.Load())
                        ]
                    )
                )
            )
        else:
            base = node.bases[0]
            tmp = self.stack[-1].scope.alloc_temp()
            self.visit(
                ast.Assign(
                    [ast_store(node.name, 'prototype')],
                    ast_call(
                        ast.FunctionDef(
                            '',
                            ast.arguments([], None, None, []),
                            [
                                ast.Assign(
                                    [ast_store(tmp)],
                                    ast.FunctionDef(
                                        '',
                                        ast.arguments([], None, None, []),
                                        [],
                                        []
                                    )
                                ),
                                ast.Assign(
                                    [ast_store(tmp, 'prototype')],
                                    ast_load(base.id, 'prototype'),
                                ),
                                ast.Return(
                                    ast_call(
                                        ast_load('new'),
                                        ast_load(tmp),
                                    )
                                )
                            ],
                            []
                        ),
                    )
                )
            )
            self.visit(
                ast.Assign(
                    [ast_store(node.name, 'prototype.constructor')],
                    ast_load(node.name)
                )
            )
            self.visit(
                ast.Assign(
                    [ast_store(node.name, 'prototype.__mro__')],
                    ast_call(
                        ast_load(node.name, 'prototype.__mro__.concat'),
                        ast_load(node.name),
                    )
                )
            )

        for stmt in node.body:
            if isinstance(stmt, _ast.FunctionDef):
                self.visit(
                    ast.Assign(
                        [ast_store(node.name, 'prototype', stmt.name)],
                        ast.FunctionDef(
                            '',
                            stmt.args,
                            stmt.body,
                            stmt.decorator_list
                        )
                    )
                )
            elif isinstance(stmt, _ast.Assign):
                targets = []
                for target in stmt.targets:
                    if not isinstance(target, _ast.Name):
                        raise Exception('Indirect assignment not supported in class definition')
                    targets.append(ast_store(node.name, 'prototype', target.id))
                self.visit(ast.Assign(
                    targets,
                    stmt.value
                ))
<|endoftext|>


<commit_before>from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from djangocms_misc.alternate_toolbar.cms_toolbars import AlternateBasicToolbar

toolbar_pool.unregister(AlternateBasicToolbar)

@toolbar_pool.register
class CustomToolbar(AlternateBasicToolbar):

    def add_crud_menu_item(self, app, model, menu=None, label=None, view='changelist'):
        if not menu:
            menu = self.admin_menu
        if not label:
            label = model
        if self.request.user.has_perm('{}.view_{}'.format(app, model)):
            menu.add_sideframe_item(
                label,
                url=reverse('admin:{}_{}_{}'.format(app, model, view)),
            )

    def add_more_admin_menu_items(self):

        # misc_menu = self.admin_menu.get_or_create_menu("misc", _("Diverses"),  )

        self.add_crud_menu_item('admin', 'log', label=_('Admin Log'))
        # self.admin_menu.add_sideframe_item(
        #     _('Projects'),
        #     url=admin_reverse('newsevents_event_changelist')
        # )
        # self.admin_menu.add_sideframe_item(
        #     _('Texte'),
        #     url=admin_reverse('textblocks_textblock_changelist')
        # )

<commit_msg>improve improve<commit_after>from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from djangocms_misc.alternate_toolbar.cms_toolbars import AlternateBasicToolbar

toolbar_pool.unregister(AlternateBasicToolbar)

@toolbar_pool.register
class CustomToolbar(AlternateBasicToolbar):

    def add_crud_menu_item(self, app, model, menu=None, label=None, view='changelist'):
        if not menu:
            menu = self.admin_menu
        if not label:
            label = model
        if self.request.user.has_perm('{}.view_{}'.format(app, model)):
            menu.add_sideframe_item(
                label,
                url=reverse('admin:{}_{}_{}'.format(app, model, view)),
            )

    def add_more_admin_menu_items(self):

        # misc_menu = self.admin_menu.get_or_create_menu("misc", _("Diverses"),  )

        self.add_crud_menu_item('textblocks', 'textblock', label=_('Texteblöcke'))
        self.add_crud_menu_item('admin', 'logentry', label=_('Admin Log'))
        # self.admin_menu.add_sideframe_item(
        #     _('Projects'),
        #     url=admin_reverse('newsevents_event_changelist')
        # )
        # self.admin_menu.add_sideframe_item(
        #     _('Texte'),
        #     url=admin_reverse('textblocks_textblock_changelist')
        # )

<|endoftext|>


<commit_before>"""
Usage:

    ./manage.py import_operators < NOC_db.csv
"""

from ..import_from_csv import ImportFromCSVCommand
from ...models import Operator

class Command(ImportFromCSVCommand):
    @staticmethod
    def get_region_id(region_id):
        if region_id in ('ADMIN', 'Admin', 'Taxi', ''):
            return 'GB'
        elif region_id in ('SC', 'YO', 'WA', 'LO'):
            return region_id[0]

        return region_id

    @staticmethod
    def is_rubbish_name(name):
        """Given an OperatorPublicName, return True if it should be
        ignored in favour of the RefNm or OpNm fields
        """
        return (
            name in ('First', 'Arriva', 'Stagecoach') or
            name.startswith('inc.') or
            name.startswith('formerly') or
            name == 'Oakwood Travel' or
            name.isupper()
        )

    @classmethod
    def get_name(cls, row):
        """Given a row dictionary, returns the best-seeming name string"""
        if cls.is_rubbish_name(row['OperatorPublicName']):
            if row['RefNm'] != '':
                return row['RefNm']
            return row['OpNm']
        if row['OperatorPublicName'] != '':
            return row['OperatorPublicName']
        return row['OpNm']

    @classmethod
    def handle_row(cls, row):
        """Given a CSV row (a list), returns an Operator object"""

        operator_id = row['NOCCODE'].replace('=', '')
        if (
                operator_id in ('TVSR', 'HBSY', 'OWML')
                or operator_id == 'FMAN' and row['Duplicate'] != 'OK'
        ):
            return

        name = cls.get_name(row).replace('\'', '\u2019')  # Fancy apostrophe

        mode = row['Mode'].lower()
        if mode == 'airline':
            return
        if mode == 'ct operator':
            mode = 'community transport'
        elif mode == 'drt':
            mode = 'demand responsive transport'

        defaults = {
            'name': name.strip(),
            'vehicle_mode': mode,
            'region_id': cls.get_region_id(row['TLRegOwn']),
        }

        operator = Operator.objects.update_or_create(
            id=operator_id,
            defaults=defaults
        )
        return operator
<commit_msg>Document merging of duplicate Owens and Horseless Carriage Services<commit_after>"""
Usage:

    ./manage.py import_operators < NOC_db.csv
"""

from ..import_from_csv import ImportFromCSVCommand
from ...models import Operator

class Command(ImportFromCSVCommand):
    @staticmethod
    def get_region_id(region_id):
        if region_id in ('ADMIN', 'Admin', 'Taxi', ''):
            return 'GB'
        elif region_id in ('SC', 'YO', 'WA', 'LO'):
            return region_id[0]

        return region_id

    @staticmethod
    def is_rubbish_name(name):
        """Given an OperatorPublicName, return True if it should be
        ignored in favour of the RefNm or OpNm fields
        """
        return (
            name in ('First', 'Arriva', 'Stagecoach') or
            name.startswith('inc.') or
            name.startswith('formerly') or
            name == 'Oakwood Travel' or
            name.isupper()
        )

    @classmethod
    def get_name(cls, row):
        """Given a row dictionary, returns the best-seeming name string"""
        if cls.is_rubbish_name(row['OperatorPublicName']):
            if row['RefNm'] != '':
                return row['RefNm']
            return row['OpNm']
        if row['OperatorPublicName'] != '':
            return row['OperatorPublicName']
        return row['OpNm']

    @classmethod
    def handle_row(cls, row):
        """Given a CSV row (a list), returns an Operator object"""

        operator_id = row['NOCCODE'].replace('=', '')
        # Avoid duplicates, for operators with multiple National Operator Codes
        # (Travelsure, Yorkshire Tiger, Owens, and Horseless Carriage Services)
        # and for operators with multiple different rows for the same NOC
        # (First Manchester)
        if (
                operator_id in ('TVSR', 'HBSY', 'OWML', 'POTD')
                or operator_id == 'FMAN' and row['Duplicate'] != 'OK'
        ):
            return

        name = cls.get_name(row).replace('\'', '\u2019')  # Fancy apostrophe

        mode = row['Mode'].lower()
        if mode == 'airline':
            return
        if mode == 'ct operator':
            mode = 'community transport'
        elif mode == 'drt':
            mode = 'demand responsive transport'

        defaults = {
            'name': name.strip(),
            'vehicle_mode': mode,
            'region_id': cls.get_region_id(row['TLRegOwn']),
        }

        operator = Operator.objects.update_or_create(
            id=operator_id,
            defaults=defaults
        )
        return operator
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    Author Vincent Renaville. Copyright 2013 Camptocamp SA
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{"name": "Switzerland - Printing of dunning BVR",
 "summary": "Print BVR/ESR slip related to credit control",
 "description": """
Printing of dunning BVR
=======================
Add possibility to print BVR/ESR slip of related credit control lines.
The dunning fees are printed on ESR but they will not affect the amount
of move lines

""",
 "version": "1.3.0",
 "author": "Camptocamp",
 "category": "Generic Modules/Others",
 "website": "http://www.camptocamp.com",
 "depends": ["account_credit_control",
             "account_credit_control_dunning_fees",
             "l10n_ch_payment_slip"
             ],
 "data": ["credit_control_printer_view.xml",
          "report.xml"
          ],
 "active": False,
 "installable": True
 }
<commit_msg>Add summary in l10n_ch_credit_control_payment_slip_report<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    Author Vincent Renaville. Copyright 2013 Camptocamp SA
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
<<<<<<< HEAD
{"name": "Switzerland - Printing of dunning BVR",
 "summary": "Print BVR/ESR slip related to credit control",
 "description": """
Printing of dunning BVR
=======================
Add possibility to print BVR/ESR slip of related credit control lines.
The dunning fees are printed on ESR but they will not affect the amount
of move lines
""",
 "version": "1.3.0",
 "author": "Camptocamp",
 "category": "Generic Modules/Others",
 "website": "http://www.camptocamp.com",
 "depends": ["account_credit_control",
             "account_credit_control_dunning_fees",
             "l10n_ch_payment_slip"
             ],
 "data": ["credit_control_printer_view.xml",
          "report.xml"
          ],
 "active": False,
 "installable": True
 }
<|endoftext|>