ajax_lexeme_view.py 18.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
#-*- coding:utf-8 -*-

import json
from django.contrib.auth.models import User
from django.core.cache import cache
from django.db.models import Max
from dictionary.ajax_jqgrid import JqGridQuery
from dictionary.ajax_lexeme_jqgrid import cache_key, get_pk_list
from dictionary.models import Lexeme, LexemeInflectionPattern, PartOfSpeech, \
  Pattern, InflectionCharacteristic, Vocabulary, LexemeAssociation, Qualifier, \
  prepare_table, ClassificationValue, CrossReference, TableTemplate, get_root, \
  InputLexeme, set_vocabulary, CrossReferenceType, filter_visible, \
  editable_vocabularies, visible_qualifiers, LexemeAttribute, LexemeAttributeValue
from dictionary.forms import LexemeEditForm, LIPEditForm, ClassificationForm, \
  CrossReferenceForm, ActionFieldForm, ACTION_FIELDS, LexemeOpenAttributeForm, \
  LexemeClosedAttributeForm, LexemeMultipleAttributeForm
from common.decorators import render, ajax, AjaxError
from common.util import error_messages

@render('inflection_tables.html')
@ajax(method='get', encode_result=False)
def get_inflection_tables(request, variant, id):
  lexeme = Lexeme.all_objects.get(pk=id) # może być nowy
  if not lexeme.perm(request.user, 'view'):
    raise AjaxError('access denied')
  qualifiers = visible_qualifiers(request.user)
  tables = lexeme.inflection_tables(variant, qualifiers=qualifiers)
  return {'tables': tables}

@render('inflection_table.html')
@ajax(method='get', encode_result=False)
def table_preview(request, id, pattern, inflection_characteristic, lip_id,
                  entry=None, pos=None):
  lexeme = Lexeme.all_objects.get(pk=id)
  if not lexeme.perm(request.user, 'view'):
    raise AjaxError('access denied')
  if entry is None:
    entry = lexeme.entry
  if pos is None:
    pos = lexeme.part_of_speech.symbol
  try:
    pattern = Pattern.objects.get(name=pattern)
    inflection_characteristic = InflectionCharacteristic.objects.get(
      pk=inflection_characteristic)
    if lip_id.startswith('lip_add'):
      lip = LexemeInflectionPattern(lexeme=lexeme, index=0)
    else:
      lip = LexemeInflectionPattern.objects.get(pk=int(lip_id[3:]))
    lip.pattern = pattern
    lip.inflection_characteristic = inflection_characteristic
    lip.root = get_root(entry, pos, pattern, inflection_characteristic)
    qualifiers = visible_qualifiers(request.user)
    table = lip.inflection_table('0', separated=True, qualifiers=qualifiers,
                                 edit_view=True)
    prepare_table(table)
  except Pattern.DoesNotExist:
    table = None
  except TableTemplate.DoesNotExist:
    table = None
  return {'table': table}

@render()
@ajax(method='get', encode_result=False)
def odm_forms(request, id):
  to_return = {}
  l = Lexeme.all_objects.get(pk=id)
  if not l.perm(request.user, 'view'):
    raise AjaxError('access denied')
  odm_lexemes = []
  for l in InputLexeme.objects.filter(entry=l.entry):
    odm_lexemes.append(list(l.inputform_set.values_list('form', flat=True)))
  to_return['odm_lexemes'] = odm_lexemes
  return to_return

def attribute_forms(l):
  for attr, v in l.attributes_values():
    if not attr.closed:
      form_class = LexemeOpenAttributeForm
    elif not attr.multiple:
      form_class = LexemeClosedAttributeForm
    else:
      form_class = LexemeMultipleAttributeForm
    prefix = 'attr%s' % attr.pk
    yield form_class(attribute=attr, initial_value=v, prefix=prefix)

@render()
@ajax(method='get', encode_result=False)
def lexeme_edit_form(request, id):
  to_return = {}
  l = Lexeme.all_objects.get(pk=id) # bo może być świeżo utworzony
  if not l.perm(request.user, 'view'):
    raise AjaxError('access denied')
  editable = l.perm(request.user, 'change')
  to_return['editable'] = editable
  owner = l.owner_vocabulary

  to_return['attribute_forms'] = attribute_forms(l)

  editable_vocabs = editable_vocabularies(request.user)
  ro_owner = owner not in editable_vocabs
  to_return['multiple_editable'] = editable and editable_vocabs.count() > 1
  if ro_owner:
    # nie pokazujemy wszystkich, tylko te z właściciela
    ro_qualifiers = l.qualifiers.filter(vocabulary=owner)
  else:
    ro_qualifiers = []
  to_return['owner'] = owner
  ro_vocabularies = l.visible_vocabularies(request.user).exclude(
    pk=owner.pk).exclude(pk__in=editable_vocabs)
  to_return['ro_vocabularies'] = ro_vocabularies
  to_return['ro_qualifiers'] = ro_qualifiers

  to_return['form'] = LexemeEditForm(
    instance=l, editable=editable, user=request.user)
  to_return['id'] = l.pk
  to_return['part_of_speech'] = l.part_of_speech.symbol
  to_return['classification_forms'] = make_classification_forms(
    l, owner, editable)

  lips = l.lexemeinflectionpattern_set.all()
  to_return['lip_forms'] = [
    (LIPEditForm(
      lexeme=l, part_of_speech=l.part_of_speech, instance=lip,
      prefix='lip' + str(lip.pk), user=request.user, editable=editable),
     lip.qualifiers.filter(vocabulary=owner) if ro_owner else [])
    for lip in lips]
  crs = l.refs_to.order_by('type__index')
  to_return['cross_references'] = crs
  return to_return

def make_classification_forms(lexeme, vocabulary=None, editable=True):
  if not vocabulary:
    vocabulary = lexeme.owner_vocabulary
  classifications = vocabulary.classifications.all()
  classification_forms = []
  for c in classifications:
    values = lexeme.classification_values(c)
    classification_forms.append(
      ClassificationForm(
        classification=c, values=values, prefix='cl' + str(c.pk),
        editable=editable))
  return classification_forms

@render()
@ajax(method='get', encode_result=False)
def classification_forms(request, lexeme_id, vocab_id):
  l = Lexeme.objects.get(pk=lexeme_id)
  if vocab_id:
    vocab = Vocabulary.objects.get(pk=vocab_id)
  else:
    vocab = None
  forms = make_classification_forms(l, vocab)
  return {'forms': forms}

@render('lexeme_edit_form_row.html')
@ajax(method='get', encode_result=False)
def new_lip_edit_row(request, id, pos_id):
  l = Lexeme.all_objects.get(pk=id)
  if not l.perm(request.user, 'change'):
    raise AjaxError('access denied')
  if not pos_id:
    raise AjaxError(u'Nieokreślona część mowy.')
  pos = PartOfSpeech.objects.get(pk=pos_id)
  lip_form = LIPEditForm(
    lexeme=l, part_of_speech=pos, prefix='lip_add_NUM', user=request.user)
  return {'lip_form': lip_form, 'editable': True}

@render('cross_reference_row.html')
@ajax(method='get', encode_result=False)
def new_cross_reference_row(request, id, pos_id):
  l = Lexeme.objects.get(pk=id)
  if not l.perm(request.user, 'change'):
    raise AjaxError('access denied')
  pos = PartOfSpeech.objects.get(pk=pos_id)
  cr_form = CrossReferenceForm(lexeme=l, pos=pos, prefix='cr_add_NUM')
  return {'cr_form': cr_form, 'editable': True}

@ajax(method='post')
def update_lexeme(request, form_data, mask=''):
  form_dict = dict((x['name'], x['value']) for x in form_data)
  l = Lexeme.all_objects.get(pk=form_dict['id'])
  if not l.perm(request.user, 'view'):
    raise AjaxError('access denied')
  owner = l.owner_vocabulary
  created = l.entry == ''
  if not l.perm(request.user, 'change'):
    return update_lexeme_qualifiers(
      l, request.user, form_dict, form_data)
  form = LexemeEditForm(data=form_dict, instance=l, user=request.user)
  if form.is_valid():
    l = form.save()
    l.responsible = request.user
    l.deleted = False
    l.fix_homonym_number()
    l.save()
  else:
    raise AjaxError(error_messages(form))

  for vocab in editable_vocabularies(request.user):
    if vocab != owner:
      set_vocabulary(l, vocab, vocab in form.cleaned_data['vocabularies'])
  new_owner = form.cleaned_data.get('new_owner')
  if new_owner and new_owner != owner:
    l.change_owner(new_owner)
    l.save()
  for qualifier in form.fields['qualifiers'].queryset:
    qualifier.set_for(l, qualifier in form.cleaned_data['qualifiers'])

  classifications = l.owner_vocabulary.classifications.all()
  for c in classifications:
    classification_form = ClassificationForm(
      data=form_dict, classification=c, prefix='cl' + str(c.pk))
    if classification_form.is_valid():
      cvs = ClassificationValue.objects.filter(
        pk__in=classification_form.cleaned_data['values'])
      l_cvs = l.classification_values(c)
      for cv in l_cvs:
        if cv.pk not in classification_form.cleaned_data['values']:
          cv.lexemes.remove(l) #add
      for cv in cvs:
        if cv not in l_cvs:
          cv.lexemes.add(l) #add
    else:
      raise AjaxError(error_messages(classification_form))
  for cv in l.classificationvalue_set.all():
    if cv.classification not in classifications:
      cv.lexemes.remove(l) #add

  for prefix in form_dict['deleted']:
    pk = int(prefix[3:])
    LexemeInflectionPattern.objects.get(pk=pk).delete()
  for cr_pk in form_dict['deleted_cr']:
    CrossReference.objects.get(pk=cr_pk).delete()
  submitted_lips = []
  submitted_crs = []
  submitted_attrs = []
  for pair in form_data:
    # może (?) się psuć, jeśli jest zły charfl
    name = pair['name']
    prefix = name.split('-')[0]
    print name, name.startswith('lip')
    if name.startswith('lip') and prefix not in submitted_lips:
      submitted_lips.append(prefix)
      if prefix.startswith('lip_add'):
        lip = LexemeInflectionPattern()
        lip.lexeme = l
      else:
        pk = int(prefix[3:])
        lip = LexemeInflectionPattern.objects.get(pk=pk)
      form_dict[prefix + '-qualifiers'] = get_list(
        form_data, prefix + '-qualifiers')
      lip_form = LIPEditForm(
        lexeme=l, part_of_speech=l.part_of_speech, data=form_dict, prefix=prefix,
        instance=lip, user=request.user, index=len(submitted_lips))
      if lip_form.is_valid():
        lip = lip_form.save()
        lip.root = l.get_root(lip.pattern, lip.inflection_characteristic)
        if lip.root is None:
          raise AjaxError(u'Niepasujące zakończenie formy podstawowej.')
        for qualifier in lip_form.fields['qualifiers'].queryset:
          qualifier.set_for(
            lip, qualifier in lip_form.cleaned_data['qualifiers'])
        lip.save()
      else:
        raise AjaxError(error_messages(lip_form))
    if name.startswith('cr_add') and prefix not in submitted_crs:
      submitted_crs.append(prefix)
      cr_form = CrossReferenceForm(data=form_dict, prefix=prefix)
      if cr_form.is_valid():
        cr_form.save()
      else:
        raise AjaxError(error_messages(cr_form))
    # TODO trzeba porównywać z poprzednią wartością
    # i jeśli się różni to do usuwać ze starej i dodawać do nowej
    if name.startswith('attr') and prefix not in submitted_attrs:
      submitted_attrs.append(prefix)
      attr_id = prefix[len('attr'):]
      attr = LexemeAttribute.objects.get(pk=attr_id)
      attr_values = attr.values.filter(lexemes=l)
      if not attr.multiple:
        assert len(attr_values) <= 1
        if not attr.closed:
          attr_form = LexemeOpenAttributeForm(
            attribute=attr, data=form_dict, prefix=prefix)
        else:
          attr_form = LexemeClosedAttributeForm(
            attribute=attr, data=form_dict, prefix=prefix)
        if attr_form.is_valid():
          if not attr.closed:
            value = attr_form.cleaned_data['value']
            av = LexemeAttributeValue.objects.get_or_create(
              attribute=attr, value=value)
          else:
            av = attr_form.cleaned_data['value']
          if not attr_values or attr_values.get() != av:
            for av1 in attr_values:
              av1.lexemes.remove(l) #add
            av.lexemes.add(l)
      else:
        # TODO
        pass
  if len(submitted_lips) == 0 and l.status != 'cand':
    raise AjaxError(u'Wybierz odmianę lub ustaw status "kandydat".')
  l.refresh_forms()
  if created:
    sort_rules = json.loads(request.session['sort_rules'])
    filters = json.loads(request.session['filters'])
    query = JqGridQuery(
      filters=filters, sort_rules=sort_rules, mask=mask, user=request.user)
    key = cache_key(query)
    pk_list = cache.get(key)
    if pk_list:
      pk_list = [l.pk] + pk_list
      cache.set(key, pk_list)
  return {}

def update_lexeme_qualifiers(lexeme, user, form_dict, form_data):
  owner = lexeme.owner_vocabulary
  editable_vocabs = editable_vocabularies(user).exclude(pk=owner.pk)
  l_editable_vocabs = lexeme.editable_vocabularies(user)
  qualifiers = Qualifier.objects.filter(vocabulary__in=l_editable_vocabs)
  for qualifier in qualifiers:
    qualifier.set_for(
      lexeme, unicode(qualifier.pk) in form_dict['qualifiers'])
  for vocab in editable_vocabs:
    set_vocabulary(lexeme, vocab, vocab.pk in form_dict['vocabularies'])
  submitted_lips = []
  for pair in form_data:
    name = pair['name']
    prefix = name.split('-')[0]
    if name.startswith('lip') and prefix not in submitted_lips:
      submitted_lips.append(prefix)
      pk = int(prefix[3:])
      lip = LexemeInflectionPattern.objects.get(pk=pk)
      lip_qualifiers = get_list(form_data, prefix + '-qualifiers')
      for qualifier in qualifiers:
        qualifier.set_for(lip, unicode(qualifier.pk) in lip_qualifiers)
  return {}

def get_list(form_data, name):
  return [pair['value'] for pair in form_data if pair['name'] == name]

@ajax(method='post')
def delete_lexeme(request, id):
  id = int(id)
  l = Lexeme.objects.get(pk=id)
  if not l.perm(request.user, 'change'):
    raise AjaxError('access denied')
  l.deleted = True
  l.save()
  key_list = cache.get('key_list', [])
  for key in key_list:
    pk_list = cache.get(key)
    if pk_list and id in pk_list:
      pk_list.remove(id)
      cache.set(key, pk_list)
  return {}

@ajax(method='get')
def check_pos(request, pos_id, ic_id):
  ic = InflectionCharacteristic.objects.get(pk=ic_id)
  if InflectionCharacteristic.objects.filter(
       entry=ic.entry, part_of_speech__pk=pos_id):
    return {'answer': 'yes'}
  else:
    return {'answer': 'no'}

@ajax(method='get')
def check_pattern(request, pattern_name, ic_id):
  lips = LexemeInflectionPattern.objects.filter(
    inflection_characteristic__pk=ic_id, pattern__name=pattern_name)
  lips = lips.exclude(lexeme__status='cand')
  if lips.exists():
    return {'answer': 'yes'}
  else:
    return {'answer': 'no'}

@ajax(method='get')
def get_ics(request, pos_id):
  return {'ics': list(InflectionCharacteristic.objects.filter(
                        part_of_speech__pk=pos_id).values_list('pk', 'entry'))}

START_ID = 1000000

@ajax(method='post')
def create_lexeme(request, vocab_id):
  owner = Vocabulary.objects.get(pk=vocab_id)
  if request.user not in owner.all_editors():
    raise AjaxError('access denied')
  next_id = Lexeme.all_objects.filter(
    pk__gte=START_ID).aggregate(Max('id'))['id__max']
  next_id = next_id + 1 if next_id else START_ID
  l = Lexeme()
  l.id = next_id
  l.homonym_number = 1 # zanim zostanie faktycznie stworzony
  l.part_of_speech = PartOfSpeech.objects.get(symbol='subst')
  l.owner_vocabulary = owner
  l.status = 'cand'
  l.responsible = request.user
  l.deleted = True # proste i genialne!
  l.save()
  LexemeAssociation.objects.create(lexeme=l, vocabulary=owner)
  return {'id': l.id}

@ajax(method='get', login_required=True)
def homonym_count(request, entry, lexeme_id):
  lexemes = Lexeme.objects.filter(entry=entry).exclude(pk=lexeme_id)
  lexemes = filter_visible(lexemes, request.user)
  return {'count': lexemes.count()}

@ajax(method='get', login_required=True)
def cr_homonyms(request, entry, cr_type):
  cr_type = CrossReferenceType.objects.get(pk=cr_type)
  lexemes = Lexeme.objects.filter(entry=entry, part_of_speech=cr_type.to_pos)
  lexemes_data = [
    {
      'homonym_number': l.homonym_number,
      'lip_data': l.lip_data(),
    } for l in lexemes.order_by('homonym_number')
  ]
  return {'lexemes': lexemes_data}


@render()
@ajax(method='get', login_required=True, encode_result=False)
def new_action_row(request):
  form = ActionFieldForm(prefix='action_NUM')
  return {'form': form}

@ajax(method='get', login_required=True)
def dynamic_action_fields(request, field_name):
  action_form, value_form = dict(ACTION_FIELDS)[field_name][1:3]
  return {
    'action': action_form()['action'].as_widget(),
    'value': value_form(request)['value'].as_widget(),
  }

@ajax(method='post', login_required=True)
def execute_group_actions(request, actions, filters):
  if not request.user.has_perm('dictionary.change_lexeme'):
    raise AjaxError('access denied')
  if isinstance(filters, basestring):
    filters = json.loads(filters)
  query = JqGridQuery(
    filters=filters, sort_rules=[], mask='', user=request.user)
  pk_list = get_pk_list(query)
  lexemes = Lexeme.objects.filter(pk__in=pk_list)
  for l in lexemes:
    for action in actions:
      field = action['field']
      if field == 'status':
        # action['type'] == 'set'
        l.status = action['value']
      elif field == 'using_vocabulary':
        vocab = Vocabulary.objects.get(pk=action['value'])
        if action['type'] == 'add':
          set_vocabulary(l, vocab, True)
        else: # 'remove'
          if vocab != l.owner_vocabulary:
            set_vocabulary(l, vocab, False)
      else: # field == 'lexeme_qualifier'
        qual = Qualifier.objects.get(pk=action['value'])
        # a co jeśli koliduje z innym?
        if action['type'] == 'add':
          l.qualifiers.add(qual) #add
        else:
          l.qualifiers.remove(qual) #add
    l.save()
  print repr(actions), repr(filters)
  return {}


@ajax(method='post')
def save_columns(request, col_model, col_names, remap):
  request.session['colModel'] = col_model
  request.session['colNames'] = col_names
  request.session['remap'] = remap
  return {}


@ajax(method='post')
def add_vocabulary(request, name):
  if not request.user.has_perm('dictionary.manage_vocabulary'):
    raise AjaxError('access denied')
  vocab = Vocabulary.objects.create(id=name)
  vocab.managers.add(request.user) #add
  return {}

@ajax(method='get')
def vocabulary_privileges(request, name):
  if not request.user.has_perm('dictionary.manage_vocabulary'):
    raise AjaxError('access denied')
  vocab = Vocabulary.objects.get(id=name)
  return {
    'managers': list(vocab.all_managers().values_list('pk', flat=True)),
    'viewers': list(vocab.all_viewers().values_list('pk', flat=True)),
    'editors': list(vocab.editors.values_list('pk', flat=True)),
  }

@ajax(method='post')
def set_vocabulary_privilege(request, name, id, type, set):
  if not request.user.has_perm('dictionary.manage_vocabulary'):
    raise AjaxError('access denied')
  vocab = Vocabulary.objects.get(id=name)
  user = User.objects.get(pk=id)
  if type == 'view':
    related_manager = vocab.viewers
  elif type == 'change':
    related_manager = vocab.editors
  else: # type == 'manage'
    related_manager = vocab.managers
  if set:
    related_manager.add(user) #add
  else:
    related_manager.remove(user) #add
  return {}