def reservations(request): ruslan_user = sso_ruslan_models.get_ruslan_user(request) if ruslan_user: libraries = list(Library.objects.filter(z_service__gt='')) args = [] for library in libraries: args.append({'id': library.id, 'url': RUSLAN_ORDER_URLS['orders'] % ( RUSLAN_USERNAME, RUSLAN_PASSWORD, library.z_service, ruslan_user.username)}) results = ThreadWorker(_get_content, args).do() for result in results: for library in libraries: if hasattr(result, 'value') and library.id == result.value['id']: if 'result' in result.value: library.reservations = _get_orders(result.value['result']) if 'exception' in result.value: if type(result.value['exception']) == socket.timeout: library.error = u'Сервер с заказами недоступен' else: raise result.value['exception'] else: libraries = [] return render(request, 'orders/frontend/reservations.html', { 'libraries': libraries, })
def books_on_hand(request): """ Выданные книги. Отображение списка библиотек и книг, которые были выданы в соответствующих библиотека """ ruslan_user = sso_ruslan_models.get_ruslan_user(request) if ruslan_user: libraries = list(Library.objects.filter(z_service__gt='')) args = [] for library in libraries: args.append({'id': library.id, 'url': RUSLAN_ORDER_URLS['books'] % ( RUSLAN_USERNAME, RUSLAN_PASSWORD, library.z_service, ruslan_user.username)}) results = ThreadWorker(_get_content, args).do() for result in results: for library in libraries: if hasattr(result, 'value') and library.id == result.value['id']: if 'result' in result.value: library.books = _get_books(result.value['result']) if 'exception' in result.value: if type(result.value['exception']) == socket.timeout: library.error = u'Сервер с заказами недоступен' else: raise result.value['exception'] else: libraries = [] return render(request, 'orders/frontend/on_hand.html', { 'libraries': libraries, })
def index(request): # try: # lib_reader = LibReader.objects.get(user=request.user) # except LibReader.DoesNotExist: # lib_reader = None ruslan_user = ruslan_models.get_ruslan_user(request) return render(request, 'personal/frontend/index.html', { 'ruslan_user': ruslan_user })
def make_reservation(request): ruslan_user = get_ruslan_user(request) if not ruslan_user: return api_responses.errors_response(u'Вы не являетесь читателем') if request.method == 'POST': make_reservation_form = forms.MakeReservationForm(request.POST) if make_reservation_form.is_valid(): ncip_message = { "RequestItem": { "UserId": { "AgencyId": { "value": ORG_CODES[make_reservation_form.cleaned_data['org']] }, "UserIdentifierValue": ruslan_user.username }, "BibliographicId": { "BibliographicRecordId": { "BibliographicRecordIdentifier": make_reservation_form.cleaned_data['record_id'], "AgencyId": { "value": ORG_CODES[make_reservation_form.cleaned_data['org']] } } }, "RequestType": { "value": u"Hold", "Scheme": u"http://www.niso.org/ncip/v1_0/imp1/schemes/requesttype/requesttype.scm" }, "RequestScopeType": { "value": u"Bibliographic Item", "Scheme": u"http://www.niso.org/ncip/v1_0/imp1/schemes/requestscopetype/requestscopetype.scm" }, "PickupLocation": { "value": u'%s/%s' % (make_reservation_form.cleaned_data['org'], make_reservation_form.cleaned_data['branch']) } } } response = ruslan_client.send_ncip_message(ncip_message) response_dict = response.json() problem = response_dict.get('RequestItemResponse', {}).get('Problem', {}) if problem: message = u'Ошибка при бронировании' problem_detail = response_dict.get('RequestItemResponse', {}).get('Problem', {}).get('ProblemDetail', ''); if problem_detail.startswith('220'): message = u'Превышен лимит заказов. Посмотреть текущие заказы можно в разделе "Мои заказы"' return api_responses.error_response(api_errors.Error(code='220', message=message)) return api_responses.error_response(api_errors.Error(code='0', message=message)) return api_responses.response({ 'status': 'ok', }) else: return api_responses.error_response(api_errors.FormError.from_form(name='make_reservation_form', django_form=make_reservation_form))
def get_config(request): is_reader = False if get_ruslan_user(request): is_reader = True response = { 'can_order_branches': CAN_ORDER_BRANCHES, 'is_reader': is_reader, 'urls': { 'holdings': reverse('ruslan_cabinet:api:holdings'), 'make_reservation': reverse('ruslan_cabinet:api:make_reservation') } } return api_responses.response(response)
def index(request): # try: # lib_reader = LibReader.objects.get(user=request.user) # except LibReader.DoesNotExist: # lib_reader = None org_id = request.session.get('org_id') current_library = None if org_id: try: current_library = Library.objects.get(id=org_id) except Library.DoesNotExist: pass ruslan_user = ruslan_models.get_ruslan_user(request) return render(request, 'personal/frontend/index.html', { 'ruslan_user': ruslan_user, 'current_library': current_library })
def current_orders(request): ruslan_user = get_ruslan_user(request) errors = [] if not ruslan_user: return HttpResponse(u'Вы не являетесь читателем') ruslan_client = client.HttpClient(API_ADDRESS, API_USERNAME, API_PASSWORD, auto_close=False) orders_response = _get_orders( ruslan_client=ruslan_client, ruslan_user=ruslan_user, database=ORDERS_DB, ) ruslan_client.close_session() return render(request, 'ruslan_cabinet/frontend/orders.html', { 'orders': orders_response['orders'], 'errors': orders_response['errors'] })
def on_hand(request): now = datetime.datetime.now().date() ruslan_user = get_ruslan_user(request) if not ruslan_user: return HttpResponse(u'Вы не являетесь читателем') ruslan_client = client.HttpClient(API_ADDRESS, API_USERNAME, API_PASSWORD, auto_close=False) def make_request(start_record=1, maximum_records=20): return ruslan_client.search( database=ON_HAND_DB, query='@attrset bib-1 @attr 1=100 "%s"' % ruslan_user.username, maximum_records=maximum_records, start_record=start_record, accept='application/json' ) responses = [] per_request = 20 errors = [] orders = [] fine = 0 try: response = make_request(start_record=1, maximum_records=per_request) #print json.dumps(response, ensure_ascii=False) except Exception as e: errors.append(u'Сервер заказов недоступен. Пожалуйста, попробуйте позже.') logger.exception(e) pass if not errors: responses.append(response) while True: next_position = int(response.get('nextRecordPosition', 0)) number_of_records = int(response.get('numberOfRecords', 0)) if next_position and next_position < number_of_records: response = make_request(next_position, maximum_records=per_request) responses.append(response) else: break ruslan_client.close_session() for response in responses: for record in humanize.get_records(response): opac_record = humanize.get_record_content(record) # print json.dumps(opac_record, ensure_ascii=False) grs_record = humanize.grs_to_dict(opac_record['tag']) bib_record = grs_record.get('202', [{}])[0].get('value', {}).get('record', {}) item_place = grs_record.get('148', [{}])[0].get('value', '') record = junimarc.json_schema.record_from_json(bib_record) libcard = junimarc.utils.beautify( unicode(transformers['libcard'](junimarc.ruslan_xml.record_to_xml(record))) ) org = grs_record.get('146', [{}])[0].get('value', '') branch = grs_record.get('147', [{}])[0].get('value', '') get_date_str = grs_record.get('142', [{}])[0].get('value', '') get_date = None if get_date_str: get_date = datetime.datetime.strptime(get_date_str, '%Y%m%d').date() return_date_str = grs_record.get('143', [{}])[0].get('value', '') return_date = None if return_date_str: return_date = datetime.datetime.strptime(return_date_str, '%Y%m%d').date() item_fine = 0 if return_date and return_date < now and item_place not in PLACES_WITHOUT_FINE: item_fine = (now - return_date).days * FINE_PER_DAY if item_fine > MAX_FINE: item_fine = MAX_FINE fine += item_fine out_of_date = False if return_date and return_date < now: out_of_date = True orders.append({ 'libcard': libcard, 'org': org, 'branch': branch, 'item_place': { 'id': item_place, 'title': PLACES.get(item_place, u''), }, 'get_date': get_date, 'return_date': return_date, 'fine': item_fine, 'out_of_date': out_of_date, }) ruslan_client.close_session() return render(request, 'ruslan_cabinet/frontend/on_hand_items.html', { 'orders': orders, 'fine': fine, 'errors': errors })
def remote_return(request): now = datetime.datetime.now().date() ruslan_user = get_ruslan_user(request) if not ruslan_user: return HttpResponse(u'Вы не являетесь читателем') ruslan_client = client.HttpClient(API_ADDRESS, API_USERNAME, API_PASSWORD, auto_close=False) def make_request(start_record=1, maximum_records=20): return ruslan_client.search( database=RCIRC, query='@attrset bib-1 @attr 1=100 "%s"' % ruslan_user.username, maximum_records=maximum_records, start_record=start_record, accept='application/json' ) responses = [] per_request = 20 errors = [] orders = [] fine = 0 try: response = make_request(start_record=1, maximum_records=per_request) #print json.dumps(response, ensure_ascii=False) except Exception as e: errors.append(u'Сервер заказов недоступен. Пожалуйста, попробуйте позже.') logger.exception(e) pass if not errors: responses.append(response) while True: next_position = int(response.get('nextRecordPosition', 0)) number_of_records = int(response.get('numberOfRecords', 0)) if next_position and next_position < number_of_records: response = make_request(next_position, maximum_records=per_request) responses.append(response) else: break ruslan_client.close_session() for response in responses: for record in humanize.get_records(response): opac_record = humanize.get_record_content(record) # print json.dumps(opac_record, ensure_ascii=False) grs_record = grs.Record.from_dict(opac_record) order_id = grs_record.get_field_value('1', '') receipt_date = grs_record.get_field_value('142', '') bib_card = grs_record.get_field_value('144', '') record_id = grs_record.get_field_value('145', '') owner_id = grs_record.get_field_value('146', '') receipter_id = grs_record.get_field_value('410', '') state = REMOTE_STATES.get(grs_record.get_field_value('148', ''), u'неизвестно') owner_sigla = grs_record.get_field_value('147', '') receipter_sigla = grs_record.get_field_value('411', '') owner_org = None try: owner_org = Library.objects.get(code=owner_id) if owner_sigla: owner_org = find_holders(owner_org, owner_sigla) except Library.DoesNotExist: pass receipter_org = None try: receipter_org = Library.objects.get(code=receipter_id) if receipter_sigla: receipter_org = find_holders(receipter_org, receipter_sigla) except Library.DoesNotExist: pass orders.append({ 'order_id': order_id, 'receipt_date': receipt_date, 'bib_card': bib_card, 'record_id': record_id, 'owner_id': owner_id, 'receipter_id': receipter_id, 'state': state, 'owner_org': owner_org, 'receipter_org': receipter_org, }) ruslan_client.close_session() return render(request, 'ruslan_cabinet/frontend/remote_items.html', { 'orders': orders, 'fine': fine, 'errors': errors })
def make_reservation(request): ruslan_user = get_ruslan_user(request) if not ruslan_user: return api_responses.errors_response(u'Вы не являетесь читателем') if request.method == 'POST': make_reservation_form = forms.MakeReservationForm(request.POST) if make_reservation_form.is_valid(): ncip_message = { "RequestItem": { "UserId": { "AgencyId": { "value": ORG_CODES[ make_reservation_form.cleaned_data['org']] }, "UserIdentifierValue": ruslan_user.username }, "BibliographicId": { "BibliographicRecordId": { "BibliographicRecordIdentifier": make_reservation_form.cleaned_data['record_id'], "AgencyId": { "value": ORG_CODES[ make_reservation_form.cleaned_data['org']] } } }, "RequestType": { "value": u"Hold", "Scheme": u"http://www.niso.org/ncip/v1_0/imp1/schemes/requesttype/requesttype.scm" }, "RequestScopeType": { "value": u"Bibliographic Item", "Scheme": u"http://www.niso.org/ncip/v1_0/imp1/schemes/requestscopetype/requestscopetype.scm" }, "PickupLocation": { "value": u'%s/%s' % (make_reservation_form.cleaned_data['org'], make_reservation_form.cleaned_data['branch']) } } } response = ruslan_client.send_ncip_message(ncip_message) response_dict = response.json() problem = response_dict.get('RequestItemResponse', {}).get('Problem', {}) if problem: message = u'Ошибка при бронировании' problem_detail = response_dict.get('RequestItemResponse', {}).get('Problem', {}).get( 'ProblemDetail', '') if problem_detail.startswith('220'): message = u'Превышен лимит заказов. Посмотреть текущие заказы можно в разделе "Мои заказы"' return api_responses.error_response( api_errors.Error(code='220', message=message)) return api_responses.error_response( api_errors.Error(code='0', message=message)) return api_responses.response({ 'status': 'ok', }) else: return api_responses.error_response( api_errors.FormError.from_form( name='make_reservation_form', django_form=make_reservation_form))
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ ap_mac = request.GET.get('ap_mac', '') wifi = request.GET.get('wifi', '') remote_addr = request.META.get('REMOTE_ADDR', '') redirect_to = request.REQUEST.get(redirect_field_name, '') if request.method == "POST": form = authentication_form(data=request.POST) if form.is_valid(): netloc = urlparse.urlparse(redirect_to)[1] # Use default setting if redirect_to is empty if not redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL # Heavier security check -- don't allow redirection to a different # host. elif netloc and netloc != request.get_host(): redirect_to = settings.LOGIN_REDIRECT_URL # Okay, security checks complete. Log the user in. auth_login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() else: return HttpResponse( u'У вас не работают cookies. Пожалуйста, включите их в браузере или очистите кеш браузера.') if request.user.is_authenticated(): if ap_mac: request.session['ap_mac'] = ap_mac library = participants_models.get_org_by_ap_mac(ap_mac) if library: request.session['org_id'] = library.id if wifi: username = form.cleaned_data['username'] suffix = '@tatar.ru' if username.endswith(suffix): username = username.replace(suffix, '') # username = u'EDU\\' + username ruslan_user = get_ruslan_user(request) wifi_username = username wifi_password = form.cleaned_data['password'] if ruslan_user: wifi_username = ruslan_user.username # wifi_password = ruslan_user.password return render(request, 'accounts/frontend/to_wifi.html', { 'username': wifi_username, 'password': wifi_password }) orgs = participants_models.user_organizations(request.user) if orgs: return redirect('http://help.kitap.tatar.ru') return redirect(redirect_to) else: form = authentication_form(request) request.session.set_test_cookie() current_site = get_current_site(request) library = None if ap_mac: library = participants_models.get_org_by_ap_mac(ap_mac) if library: request.session['org_id'] = library.id context = { 'form': form, 'library': library, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, } if extra_context is not None: context.update(extra_context) return render(request, template_name, context, current_app=current_app)
def on_hand(request): now = datetime.datetime.now().date() ruslan_user = get_ruslan_user(request) if not ruslan_user: return HttpResponse(u'Вы не являетесь читателем') ruslan_client = client.HttpClient(API_ADDRESS, API_USERNAME, API_PASSWORD, auto_close=False) def make_request(start_record=1, maximum_records=20): return ruslan_client.search(database=ON_HAND_DB, query='@attrset bib-1 @attr 1=100 "%s"' % ruslan_user.username, maximum_records=maximum_records, start_record=start_record, accept='application/json') responses = [] per_request = 20 errors = [] orders = [] fine = 0 try: response = make_request(start_record=1, maximum_records=per_request) # print json.dumps(response, ensure_ascii=False) except Exception as e: errors.append( u'Сервер заказов недоступен. Пожалуйста, попробуйте позже.') logger.exception(e) pass if not errors: responses.append(response) while True: next_position = int(response.get('nextRecordPosition', 0)) number_of_records = int(response.get('numberOfRecords', 0)) if next_position and next_position < number_of_records: response = make_request(next_position, maximum_records=per_request) responses.append(response) else: break ruslan_client.close_session() for response in responses: for record in humanize.get_records(response): opac_record = humanize.get_record_content(record) # print json.dumps(opac_record, ensure_ascii=False) grs_record = humanize.grs_to_dict(opac_record['tag']) bib_record = grs_record.get('202', [{}])[0].get('value', {}).get('record', {}) item_place = grs_record.get('148', [{}])[0].get('value', '') record = junimarc.json_schema.record_from_json(bib_record) libcard = junimarc.utils.beautify( unicode(transformers['libcard']( junimarc.ruslan_xml.record_to_xml(record)))) org = grs_record.get('146', [{}])[0].get('value', '') branch = grs_record.get('147', [{}])[0].get('value', '') get_date_str = grs_record.get('142', [{}])[0].get('value', '') get_date = None if get_date_str: get_date = datetime.datetime.strptime( get_date_str, '%Y%m%d').date() return_date_str = grs_record.get('143', [{}])[0].get('value', '') return_date = None if return_date_str: return_date = datetime.datetime.strptime( return_date_str, '%Y%m%d').date() item_fine = 0 if return_date and return_date < now and item_place not in PLACES_WITHOUT_FINE: item_fine = (now - return_date).days * FINE_PER_DAY if item_fine > MAX_FINE: item_fine = MAX_FINE fine += item_fine out_of_date = False if return_date and return_date < now: out_of_date = True orders.append({ 'libcard': libcard, 'org': org, 'branch': branch, 'item_place': { 'id': item_place, 'title': PLACES.get(item_place, u''), }, 'get_date': get_date, 'return_date': return_date, 'fine': item_fine, 'out_of_date': out_of_date, }) ruslan_client.close_session() return render(request, 'ruslan_cabinet/frontend/on_hand_items.html', { 'orders': orders, 'fine': fine, 'errors': errors })
def remote_return(request): now = datetime.datetime.now().date() ruslan_user = get_ruslan_user(request) if not ruslan_user: return HttpResponse(u'Вы не являетесь читателем') ruslan_client = client.HttpClient(API_ADDRESS, API_USERNAME, API_PASSWORD, auto_close=False) def make_request(start_record=1, maximum_records=20): return ruslan_client.search(database=RCIRC, query='@attrset bib-1 @attr 1=100 "%s"' % ruslan_user.username, maximum_records=maximum_records, start_record=start_record, accept='application/json') responses = [] per_request = 20 errors = [] orders = [] fine = 0 try: response = make_request(start_record=1, maximum_records=per_request) # print json.dumps(response, ensure_ascii=False) except Exception as e: errors.append( u'Сервер заказов недоступен. Пожалуйста, попробуйте позже.') logger.exception(e) pass if not errors: responses.append(response) while True: next_position = int(response.get('nextRecordPosition', 0)) number_of_records = int(response.get('numberOfRecords', 0)) if next_position and next_position < number_of_records: response = make_request(next_position, maximum_records=per_request) responses.append(response) else: break ruslan_client.close_session() for response in responses: for record in humanize.get_records(response): opac_record = humanize.get_record_content(record) # print json.dumps(opac_record, ensure_ascii=False) grs_record = grs.Record.from_dict(opac_record) order_id = grs_record.get_field_value('1', '') receipt_date = grs_record.get_field_value('142', '') bib_card = grs_record.get_field_value('144', '') record_id = grs_record.get_field_value('145', '') owner_id = grs_record.get_field_value('146', '') receipter_id = grs_record.get_field_value('410', '') state = REMOTE_STATES.get( grs_record.get_field_value('148', ''), u'неизвестно') owner_sigla = grs_record.get_field_value('147', '') receipter_sigla = grs_record.get_field_value('411', '') owner_org = None try: owner_org = Library.objects.get(code=owner_id) if owner_sigla: owner_org = find_holders(owner_org, owner_sigla) except Library.DoesNotExist: pass receipter_org = None try: receipter_org = Library.objects.get(code=receipter_id) if receipter_sigla: receipter_org = find_holders(receipter_org, receipter_sigla) except Library.DoesNotExist: pass orders.append({ 'order_id': order_id, 'receipt_date': receipt_date, 'bib_card': bib_card, 'record_id': record_id, 'owner_id': owner_id, 'receipter_id': receipter_id, 'state': state, 'owner_org': owner_org, 'receipter_org': receipter_org, }) ruslan_client.close_session() return render(request, 'ruslan_cabinet/frontend/remote_items.html', { 'orders': orders, 'fine': fine, 'errors': errors })
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ ap_mac = request.GET.get('ap_mac', '') wifi = request.GET.get('wifi', '') remote_addr = request.META.get('REMOTE_ADDR', '') redirect_to = request.REQUEST.get(redirect_field_name, '') if request.method == "POST": form = authentication_form(data=request.POST) if form.is_valid(): netloc = urlparse.urlparse(redirect_to)[1] # Use default setting if redirect_to is empty if not redirect_to: redirect_to = settings.LOGIN_REDIRECT_URL # Heavier security check -- don't allow redirection to a different # host. elif netloc and netloc != request.get_host(): redirect_to = settings.LOGIN_REDIRECT_URL # Okay, security checks complete. Log the user in. auth_login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() else: return HttpResponse( u'У вас не работают cookies. Пожалуйста, включите их в браузере или очистите кеш браузера.' ) if request.user.is_authenticated(): if ap_mac: request.session['ap_mac'] = ap_mac library = participants_models.get_org_by_ap_mac(ap_mac) if library: request.session['org_id'] = library.id if wifi: username = form.cleaned_data['username'] suffix = '@tatar.ru' if username.endswith(suffix): username = username.replace(suffix, '') # username = u'EDU\\' + username ruslan_user = get_ruslan_user(request) wifi_username = username wifi_password = form.cleaned_data['password'] if ruslan_user: wifi_username = ruslan_user.username # wifi_password = ruslan_user.password return render(request, 'accounts/frontend/to_wifi.html', { 'username': wifi_username, 'password': wifi_password }) orgs = participants_models.user_organizations(request.user) if orgs: return redirect('http://help.kitap.tatar.ru') return redirect(redirect_to) else: form = authentication_form(request) request.session.set_test_cookie() current_site = get_current_site(request) library = None if ap_mac: library = participants_models.get_org_by_ap_mac(ap_mac) if library: request.session['org_id'] = library.id context = { 'form': form, 'library': library, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, } if extra_context is not None: context.update(extra_context) return render(request, template_name, context, current_app=current_app)