def test_ajax(self):
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     assert prefix.description == ''
     prefix_id = prefix.id
     response = self.client.post('/prefixes/ajax/', {
         'pk': prefix_id,
         'value': 'New description'
     })
     assert response.status_code == 200
     assert response.content == b'{"success": true}'
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     assert prefix.description == 'New description'
 def test_next_number_field(self):
     response = self.client.get(self.url)
     assert response.status_code == 200
     self.assertNotContains(response, '<b>53900011</b><span style="color:#F26334">0002</span>7')
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     prefix.starting_from = '5390001100027'
     prefix.save()
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     assert prefix.starting_from == '5390001100027'
     response = self.client.get(self.url)
     assert response.status_code == 200
     self.assertContains(response, '<b>53900011</b><span style="color:#F26334">0002</span>7')
 def test_suspended_prefixes_exist(self):
     response = self.client.get(self.url)
     assert response.status_code == 200
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     prefix.is_suspended = 1
     prefix.save()
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     assert prefix.is_suspended == 1
     response = self.client.get(self.url)
     assert response.status_code == 200
     self.assertContains(response, 'Suspended prefixes')
     self.assertContains(response, '<td>53900011</td>')
Exemple #4
0
    def validate_product_active_prefix(self, prefix_instance):
        available_prefixes = prefix_service.find(user=self.instance,
                                                 is_suspended=False)
        if prefix_instance not in available_prefixes:
            raise serializers.ValidationError(
                _('You can\'t select this prefix.'))

        return prefix_instance
 def test_models_get_active(self):
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     assert not prefix.is_active
     prefix_id = prefix.id
     prefix_organisation = prefix.company_organisation
     active_id = prefix_service.get_active(prefix_organisation)
     assert active_id is None
     prefix_service.make_active(prefix_id)
     active_id = prefix_service.get_active(prefix_organisation)
     assert active_id == prefix_id
Exemple #6
0
def get_range_data(request):
    from services import prefix_service
    prefix = prefix_service.find(user=request.user).first()
    if not prefix:
        return ''
    if prefix.is_upc():
        prfx = prefix.prefix[1:]
    else:
        prfx = prefix.prefix

    products = Product.service.filter(owner=request.user,
                                      gs1_company_prefix=prefix.prefix).all()
    prfxs = prefix.get_available_gtins(products, True)

    #locations = location_service.find(owner=user, gs1_company_prefix=prefix.prefix).all()
    locations = []
    prfxs2 = prefix.get_available_glns(locations, True)

    return prfx, len(products), prfxs, len(locations), prfxs2
Exemple #7
0
    def post(self, request, *args, **kwargs):
        """logs in the user"""
        data = request.data
        # m2m_token = data.get('m2m_token', None)
        # if not check_m2m_token(request.user, m2m_token):
        #     return Response({
        #         'user': '',
        #         'token': ''
        #     })

        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token = AuthToken.objects.create(user)
        login(request, user)  # this sets csrftoken and sessionid cookies

        prefixes = prefix_service.find(user=user).all()
        if len(prefixes) == 1:
            user.profile.product_active_prefix = prefixes[0]
            user.profile.save()

        return Response({'user': UserSerializer(user).data, 'token': token})
 def test_make_active(self):
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     assert not prefix.is_active
     id1 = prefix.id
     prefix = prefix_service.find(prefix='53900012').first()
     assert prefix.prefix == '53900012'
     assert not prefix.is_active
     id2 = prefix.id
     prefix_service.make_active(id1)
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     assert prefix.is_active
     prefix = prefix_service.find(prefix='53900012').first()
     assert prefix.prefix == '53900012'
     assert not prefix.is_active
     prefix_service.make_active(id2)
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     assert not prefix.is_active
     prefix = prefix_service.find(prefix='53900012').first()
     assert prefix.prefix == '53900012'
     assert prefix.is_active
Exemple #9
0
def prefixes_list(request):
    current_user = request.user
    company_organisation = users_service.get_company_organisation(current_user)

    prefixes = prefix_service.all()
    susp_prefixes = prefix_service.find(
        company_organisation=company_organisation, is_suspended=True).all()
    '''
    prefixes = prefix_service.find_all().all()
    result = db.session.query('prefix', 'products'). \
        from_statement(text("select products.gs1_company_prefix as prefix, 
                                    count(*) as products
                             from products
                             where owner_id=%s
                             group by products.gs1_company_prefix" % current_user.id)).all()

    result_locations = db.session.query('prefix', 'locations'). \
        from_statement(text("select locations.gs1_company_prefix as prefix, 
                                    count(*) as locations
                             from locations
                             where owner_id=%s
                             group by locations.gs1_company_prefix" % current_user.id)).all()

    # set products count
    for prefix in prefixes:
        for row in result:
            if prefix.prefix == row[0]:
                setattr(prefix, 'products', row[1])

    # set locations count
    for prefix in prefixes:
        for row in result_locations:
            if prefix.prefix == row[0]:
                setattr(prefix, 'locations', row[1])
    '''

    if request.method == 'POST':
        form = PrefixActionForm(request.POST)
        form.fields['select_prefix'].choices = [(str(p.id), p.prefix)
                                                for p in prefixes]
        if form.is_valid():
            try:
                int_prefix_id = int(form.data['select_prefix'])
            except (ValueError, TypeError):
                flash(request, 'Your selections were not valid!', 'danger')
            else:
                prefix = prefix_service.get(int_prefix_id)
                if not prefix:
                    raise Http404('Prefix not found')

                if prefix.is_special == 'READ-ONLY' and form.data[
                        'prefix_action'] != 'set_this':
                    flash(request,
                          'Read-only prefix, please contact GS1 helpdesk.',
                          'danger')
                else:
                    prefix_service.make_active(prefix.id)

                    prefix_action = form.data['prefix_action']
                    # Enter a new product in selected range
                    if prefix_action == 'new_product':
                        return redirect(
                            reverse('user:products.add_product') + '?prefix=' +
                            str(prefix.prefix))

                    # Set selected range as active and go to My Products
                    elif prefix_action == 'set_this':
                        return redirect(reverse('user:products.products_list'))

                    # Set starting GTIN in selected range manually
                    elif prefix_action == 'starting_gtin':
                        return redirect(
                            reverse('prefixes:prefixes_set_starting',
                                    args=(prefix.id, )))

                    # Set starting GTIN to first available number
                    elif prefix_action == 'first_available':
                        try:
                            prefix.make_starting_from()
                        except Exception as e:
                            return render(request,
                                          'prefixes/prefix_exhausted.html', {
                                              'current_user': current_user,
                                              'prefix': prefix
                                          })
                        prefix_service.save(prefix)
                        flash(
                            request, 'Starting gtin has been set to GTIN-%s' %
                            prefix.starting_from, 'success')
                        return redirect(reverse('prefixes:prefixes_list'))

                    # new location
                    elif prefix_action == 'new_gln':
                        return redirect(
                            reverse('user:locations.add_location') +
                            '?prefix=' + str(prefix.prefix))

                    elif prefix_action == 'first_available_gln':
                        pass
                        '''
                        try:
                            prefix.make_starting_from_gln()
                        except Exception,e:
                            return render_template('prefixes/prefix_exhausted.html', prefix=prefix)
                        prefix_service.save(prefix)
                        return redirect(url_for('.prefixes_list'))
                        '''

                    # Export available GTINs in this range
                    elif prefix_action == 'export_available':
                        try:
                            products = (Product.objects.filter(
                                owner=current_user).filter(
                                    gs1_company_prefix=prefix.prefix).order_by(
                                        'gtin'))
                            prfxs = prefix.get_available_gtins(products)
                            if len(prfxs) > 0:
                                tfile = tempfile.NamedTemporaryFile(
                                    suffix='.xlsx')
                                zfile = tempfile.NamedTemporaryFile(
                                    suffix='.zip')

                                file_xlsx = load_workbook(
                                    settings.PREFIXES_EXCEL_TEMPLATE)
                                ws = file_xlsx.active
                                for index, prfx in enumerate(prfxs):
                                    _ = ws.cell(column=2,
                                                row=index + 5,
                                                value=prfx)
                                file_xlsx.save(filename=tfile.name)

                                with ZipFile(zfile.name, "w") as z:
                                    export_filename = "export_%s_available.xlsx" % (
                                        prefix.prefix, )
                                    attachment_filename = "export_%s_available.%s" % (
                                        prefix.prefix, 'zip')
                                    z.write(tfile.name, export_filename)

                                send_file = open(zfile.name, 'rb')
                                response = HttpResponse(
                                    send_file, content_type='application/zip')
                                response[
                                    'Content-Disposition'] = 'attachment; filename=%s' % attachment_filename
                                return response
                            else:
                                flash(
                                    request,
                                    'There are no available GTIN numbers for current active prefix',
                                    'danger')
                        except Exception as e:
                            flash(request, 'Error: %s' % str(e), 'danger')
        else:
            flash(request, 'You must choose a prefix and an action!', 'danger')

    form = PrefixActionForm()
    form.fields['select_prefix'].choices = [(str(p.id), p.prefix)
                                            for p in prefixes]
    try:
        selected_prefix = int(request.POST['select_prefix'])
        prefix_service.make_active(selected_prefix)
    except:
        selected_prefix = prefix_service.get_active(company_organisation)

    config = {'GS1_GLN_CAPABILITY': settings.GS1_GLN_CAPABILITY}

    context = {
        'current_user': current_user,
        'config': config,
        'prefixes': prefixes,
        'susp_prefixes': susp_prefixes,
        'flashed_messages': flash_get_messages(request),
        'selected_prefix': selected_prefix
    }
    return render(request, 'prefixes/prefixes_list.html', context)
def account_create_or_update(request):
    if request.method == 'POST':
        form = AccountCreateOrUpdateForm(request.POST)
        if form.is_valid():
            try:
                # core data
                email = form.data.get('email')
                company_name = form.data.get('company_name')
                try:
                    member_organisation = MemberOrganisation.objects.get(
                        slug=form.cleaned_data.get('member_organisation'))
                except MemberOrganisation.DoesNotExist:
                    member_organisation = None

                # get company
                company_organisation, company_organisation_created = CompanyOrganisation.objects.get_or_create(
                    uuid=form.data.get('uuid'),
                    member_organisation=member_organisation)

                # update company name if any
                if company_name:
                    company_organisation.company = company_name
                    company_organisation.save()

                auth_user, auth_user_created = users_service.get_or_create(
                    email=email,
                    defaults={
                        'username': email,
                        'customer_role': 'gs1ie',
                        'member_organisation': member_organisation,
                        'company_organisation': company_organisation
                    })

                auth_user.save()

                company_organisation = users_service.get_company_organisation(
                    auth_user)

                # user, user_created = users_service.get_or_create(email=email,
                #                                                  defaults={
                #                                                      'username': email,
                #                                                      'customer_role': 'gs1ie',
                #                                                      'organisation': organisation
                #                                                  })

            except Exception as e:
                return jsonify(success=False, message=str(e))

            log_message = 'logging in: ' + str(auth_user.email) + '::' + str(
                company_organisation.company)
            log_extra = {
                'user': auth_user.email,
                'company': company_organisation.company,
                'ip_address': request.environ.get('REMOTE_ADDR')
            }
            logging.getLogger().info(log_message, extra=log_extra)
            logging.getLogger('audit').info(log_message, extra=log_extra)

            # if user's organisation has prefix override, use it
            # if not use prefixes provided by the form
            if not company_organisation.prefix_override:
                form_prefix = form.data.get('company_prefix', '')
            else:
                form_prefix = company_organisation.prefix_override
            form_prefixes = form_prefix.split(',')

            prefixes = prefix_service.find(
                company_organisation=company_organisation,
                member_organisation=member_organisation).all()
            prefixes_list = [p.prefix for p in prefixes]

            # set gln to be first prefix
            if len(prefixes_list) > 0:
                first_prefix = prefixes_list[0]
                derived_gln = normalize("EAN13", first_prefix)
                company_organisation.gln = derived_gln
                company_organisation.save()

            for prfx in form_prefixes:
                if not re.match(settings.GS1_PREFIX_START_REGEX,
                                prfx[:3]) or len(prfx) < 6:
                    if prfx.find(
                            '20'
                    ) == 0:  # we will not complain about variable weight
                        continue
                    else:
                        return jsonify(success=False,
                                       message='Invalid prefix %s' % prfx)
                if prfx not in prefixes_list:
                    try:
                        prefix = prefix_service.create(
                            prefix=prfx,
                            company_organisation=company_organisation,
                            member_organisation=member_organisation)
                    except IntegrityError:
                        return jsonify(
                            success=False,
                            message=
                            'Prefix %s has been allocated for another user' %
                            prfx)
                    try:
                        prefix.make_starting_from()
                    except:
                        prefix.starting_from = None
                    prefix_service.save(prefix)
                else:
                    i = prefixes_list.index(prfx)
                    if prefixes[i].is_suspended:
                        prefixes[i].is_suspended = False
                        prefix_service.save(prefixes[i])

            for prfx in prefixes_list:
                if prfx not in form_prefixes:
                    prefix = prefix_service.find(
                        company_organisation=company_organisation,
                        member_organisation=member_organisation,
                        prefix=prfx).first()
                    prefix.is_suspended = True
                    prefix.is_active = False
                    prefix_service.save(prefix)

            # Check active prefix and set accordingly
            try:
                prefix_service.find(company_organisation=company_organisation,
                                    member_organisation=member_organisation,
                                    is_active=True,
                                    is_suspended=False).first()
            except ObjectDoesNotExist:
                prefix = prefix_service.find(
                    company_organisation=company_organisation,
                    member_organisation=member_organisation,
                    is_active=False,
                    is_suspended=False).order_by('prefix').first()
                if not prefix:
                    return jsonify(success=False,
                                   message='No working prefix found')
                prefix.is_active = True
                prefix_service.save(prefix)
            except MultipleObjectsReturned:
                prefixes = prefix_service.find(
                    company_organisation=company_organisation,
                    member_organisation=member_organisation,
                    is_active=True,
                    is_suspended=False).order_by('prefix').all()
                for prefix in prefixes:
                    prefix.is_active = False
                    prefix_service.save(prefix)
                prefix = prefixes[0]
                prefix.is_active = True
                prefix_service.save(prefix)

            serializer = URLSafeTimedSerializer(settings.SECRET_KEY)
            token = serializer.dumps(
                [auth_user.email, company_organisation.uuid])
            logging.getLogger().debug('Created token: %s' % token)
            return redirect('/API/v1/auth/%s/' % token)
    else:
        form = AccountCreateOrUpdateForm()

    current_user = request.user
    context = {'current_user': current_user, 'active_page': '', 'form': form}
    return render(request, 'gs1ie/AccountCreateOrUpdate.html', context)
Exemple #11
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            member_organisation = MemberOrganisation.objects.get(
                slug=request.data['member_organisation'])
        except:
            return Response({'data': 'Unknown member_organisation'},
                            status=status.HTTP_400_BAD_REQUEST)
        if member_organisation.login_api_auth_only:
            try:
                company_organisation, auth_user = self.perform_login(
                    serializer)
            except Exception:
                return Response({'data': 'Unknown user'},
                                status=status.HTTP_400_BAD_REQUEST)
        else:
            company_organisation, auth_user = self.perform_create(serializer)

        member_organisation = auth_user.profile.member_organisation

        self.push_info_to_logger(auth_user, company_organisation)

        if member_organisation.login_api_secure:
            try:
                token_user = request._auth.user
                assert token_user.profile.member_organisation == auth_user.profile.member_organisation
            except AssertionError as e:
                return Response({'data': 'm2m token mismatch'},
                                status=status.HTTP_400_BAD_REQUEST)

        # return if we are in read-only mode
        if member_organisation.login_api_auth_only:
            return Response(get_api_auth(auth_user.email),
                            status=status.HTTP_200_OK)

        # if user's organisation has prefix override, use it
        # if not use prefixes provided by the form
        if not company_organisation.prefix_override:
            form_prefix = serializer.validated_data.get('company_prefix', None)
        else:
            form_prefix = company_organisation.prefix_override
        if form_prefix is not None:
            form_prefixes = form_prefix.split(',')
        else:
            form_prefixes = []

        prefixes = prefix_service.find(user=auth_user).all()
        prefixes_list = [v for v in prefixes.values_list('prefix', flat=True)]

        # set gln to be first prefix
        if len(prefixes_list) > 0:
            first_prefix = prefixes_list[0]
            derived_gln = normalize("EAN13", first_prefix)
            company_organisation.gln = derived_gln

        # if we are in read-write copy country from MO to the company
        self.set_country_and_save(company_organisation, member_organisation)

        for prfx in form_prefixes:
            if not re.match(member_organisation.gs1_prefix_regex,
                            prfx[:3]) or len(prfx) < 6:
                if prfx.find(
                        '20'
                ) == 0:  # we will not complain about variable weight
                    continue
                else:
                    return Response(status=400, data=f'Invalid prefix {prfx}')

            if prfx not in prefixes_list:
                try:
                    prefix = prefix_service.create(user=auth_user, prefix=prfx)
                except IntegrityError:
                    return Response(
                        status=400,
                        data=
                        f'Prefix {prfx} has been allocated for another user')
                try:
                    prefix.make_starting_from()
                except:
                    prefix.starting_from = None
                prefix_service.save(user=auth_user, prefix=prefix)
            else:
                i = prefixes_list.index(prfx)
                if prefixes[i].is_suspended:
                    prefixes[i].is_suspended = False
                    prefix_service.save(prefixes[i])

        for prfx in prefixes_list:
            if prfx not in form_prefixes:
                prefix = prefix_service.find(user=auth_user,
                                             prefix=prfx).first()
                prefix.is_suspended = True
                prefix_service.save(prefix)

        # Check active prefix and set accordingly
        user_active_prefix = auth_user.profile.product_active_prefix
        if not user_active_prefix:
            prefix = prefix_service.find(
                user=auth_user, is_suspended=False).order_by('prefix').first()

            if prefix:
                prefix_service.make_active(user=auth_user,
                                           prefix=prefix.prefix)
                prefix_service.save(prefix)
            # else:
            #     return Response(status=400, data='No working prefix found')

        return Response(get_api_auth(auth_user.email),
                        status=status.HTTP_201_CREATED)
Exemple #12
0
    def handle(self, *args, **options):
        """
        python manage.py load_company_user deployment/deployment-v1-2018-03/mo_users.json
        :return:
        """
        filename = options['filename']

        try:
            with open(filename) as json_data:
                data = json.load(json_data)
        except Exception as e:
            print(
                '\n**************\nUnable to load json file. {0}. \n\n\nException message: '
                .format(filename), e.message)
        else:

            companies_data = data.get('companies')
            if companies_data:
                for company_data in companies_data:

                    if not 'uuid' in company_data:
                        continue
                    try:
                        # expected value: email, company_name, member_organization, uuid, company_prefix
                        email = company_data.get('email')
                        company_name = company_data.get('company_name')
                        try:
                            member_organisation = MemberOrganisation.objects.get(
                                slug=company_data.get('role'))
                        except MemberOrganisation.DoesNotExist:
                            member_organisation = None

                        # get company
                        company_organisation, company_organisation_created = CompanyOrganisation.objects.get_or_create(
                            uuid=company_data.get('uuid'),
                            defaults={
                                'member_organisation': member_organisation,
                                'name': company_data.get('name')
                            })
                        #print("Company  Created:- " if company_organisation_created else "Company Updated:- ",
                        #      u' '.join(
                        #          [company_organisation.uuid]).encode('utf-8').strip())

                        # update company name if any
                        if company_name:
                            company_organisation.company = company_name
                            company_organisation.save()

                        auth_user, auth_user_created = users_service.get_or_create(
                            email=email,
                            defaults={
                                'username': email,
                                'member_organisation': member_organisation,
                                'company_organisation': company_organisation
                            })

                        auth_user.save()
                        # print('Create New User:- ' if auth_user_created else 'Updated User:- ', auth_user.email)
                        company_organisation = users_service.get_company_organisation(
                            auth_user)

                    except Exception as e:
                        print(company_data)
                        print(str(e))
                        continue

                    log_message = 'logging in: ' + str(
                        auth_user.email) + '::' + str(
                            company_organisation.company)
                    log_extra = {
                        'user': auth_user.email,
                        'company': company_organisation.company
                    }
                    logging.getLogger().info(log_message, extra=log_extra)
                    logging.getLogger('audit').info(log_message,
                                                    extra=log_extra)

                    # if user's organisation has prefix override, use it
                    # if not use prefixes provided by the form
                    if company_organisation.prefix_override:
                        form_prefix = company_organisation.prefix_override
                        form_prefixes = form_prefix.split(',')
                    else:
                        form_prefixes = company_data.get('prefixes')

                    prefixes = prefix_service.find(user=auth_user).all()
                    prefixes_list = [p.prefix for p in prefixes]

                    # set gln to be first prefix
                    if len(prefixes_list) > 0:
                        first_prefix = prefixes_list[0]
                        derived_gln = normalize("EAN13", first_prefix)
                        company_organisation.gln = derived_gln
                        company_organisation.save()

                    for prfx in form_prefixes:
                        # if not re.match(settings.GS1_PREFIX_START_REGEX, prfx[:3]) or len(prfx) < 6:
                        #     if prfx.find('20') == 0:  # we will not complain about variable weight
                        #         continue
                        #     else:
                        #         return jsonify(success=False, message='Invalid prefix %s' % prfx)
                        if prfx not in prefixes_list:
                            try:
                                prefix = prefix_service.create(user=auth_user,
                                                               prefix=prfx)
                            except IntegrityError:
                                print(
                                    '\n\n*** ERROR:  Prefix {0} has been allocated for another user\n\n'
                                    .format(prfx))
                                continue
                            try:
                                prefix.make_starting_from()
                            except:
                                prefix.starting_from = None
                            prefix_service.save(prefix)
                        else:
                            i = prefixes_list.index(prfx)
                            if prefixes[i].is_suspended:
                                prefixes[i].is_suspended = False
                                prefix_service.save(prefixes[i])

                    for prfx in prefixes_list:
                        if prfx not in form_prefixes:
                            prefix = prefix_service.find(user=auth_user,
                                                         prefix=prfx).first()
                            prefix.is_suspended = True
                            prefix_service.save(prefix)

                    # Check active prefix and set accordingly
                    user_active_prefix = auth_user.profile.product_active_prefix
                    if not user_active_prefix:
                        prefix = prefix_service.find(
                            user=auth_user,
                            is_suspended=False).order_by('prefix').first()

                        if prefix:
                            prefix_service.make_active(user=auth_user,
                                                       prefix=prefix.prefix)
                            prefix_service.save(prefix)
                        else:
                            print('\n\nERROR: No working prefix found\n\n')
                            continue

                    serializer = URLSafeTimedSerializer(settings.SECRET_KEY)
                    token = serializer.dumps(
                        [auth_user.email, company_organisation.uuid])
                    logging.getLogger().debug('Created token: %s' % token)
 def test_models_make_starting_from(self):
     prefix = prefix_service.find(prefix='53900011').first()
     assert prefix.prefix == '53900011'
     prefix.make_starting_from()
     assert prefix.starting_from == '5390001100003'
Exemple #14
0
def account_create_or_update(request):

    auth_only = False

    if request.method == 'POST':
        form = AccountCreateOrUpdateForm(request.POST)
        if form.is_valid():
            try:
                if not request.user.is_anonymous:
                    m2m_token = form.cleaned_data.get('m2m_token', '')
                    if not check_m2m_token(request.user, m2m_token):
                        return redirect(reverse('BCM:login'))

                try:
                    member_organisation = MemberOrganisation.objects.get(
                        slug=form.cleaned_data.get('member_organisation'))
                except MemberOrganisation.DoesNotExist:
                    member_organisation = None

                # core data
                email = form.cleaned_data.get('email')
                company_name = form.cleaned_data.get('company_name')

                # get company
                company_organisation, company_organisation_created = CompanyOrganisation.objects.get_or_create(
                    uuid=form.data.get('uuid'),
                    member_organisation=member_organisation)

                # update company name if any
                if company_name:
                    company_organisation.company = company_name
                    company_organisation.name = company_name
                    company_organisation.save()

                auth_user, auth_user_created = users_service.get_or_create(
                    email=email,
                    defaults={
                        'username': email,
                        'customer_role': 'gs1ie',
                        'member_organisation': member_organisation,
                        'company_organisation': company_organisation
                    })

                auth_user.save()

                company_organisation = users_service.get_company_organisation(
                    auth_user)
            except Exception as e:
                return jsonify(success=False, message=str(e))

            log_message = 'logging in: ' + str(auth_user.email) + '::' + str(
                company_organisation.company)
            log_extra = {
                'user': auth_user.email,
                'company': company_organisation.company,
                'ip_address': request.environ.get('REMOTE_ADDR')
            }
            logging.getLogger().info(log_message, extra=log_extra)
            logging.getLogger('audit').info(log_message, extra=log_extra)

            if form.data.get('company_prefix', '') == 13 * '0':
                auth_only = True

            if not auth_only:
                # if user's organisation has prefix override, use it
                # if not use prefixes provided by the form
                if not company_organisation.prefix_override:
                    form_prefix = form.data.get('company_prefix', '')
                else:
                    form_prefix = company_organisation.prefix_override
                form_prefixes = form_prefix.split(',')

                prefixes = prefix_service.find(user=auth_user).all()
                prefixes_list = list(prefixes.values_list('prefix', flat=True))

                # set gln to be first prefix
                if len(prefixes_list) > 0:
                    first_prefix = prefixes_list[0]
                    derived_gln = normalize("EAN13", first_prefix)
                    company_organisation.gln = derived_gln
                    company_organisation.save()

                for prfx in form_prefixes:
                    if not re.match(member_organisation.gs1_prefix_regex,
                                    prfx[:3]) or len(prfx) < 6:
                        if prfx.find(
                                '20'
                        ) == 0:  # we will not complain about variable weight
                            continue
                        else:
                            return jsonify(success=False,
                                           message='Invalid prefix %s' % prfx)
                    if prfx not in prefixes_list:
                        try:
                            prefix = prefix_service.create(
                                user=auth_user,
                                prefix=prfx,
                                status_id=Prefix.ACTIVE)
                        except IntegrityError:
                            return jsonify(
                                success=False,
                                message=
                                'Prefix %s has been allocated for another user'
                                % prfx)
                        try:
                            prefix.make_starting_from()
                        except:
                            prefix.starting_from = None
                        prefix_service.save(user=auth_user, prefix=prefix)
                    else:
                        i = prefixes_list.index(prfx)
                        if prefixes[i].is_suspended:
                            prefixes[i].is_suspended = False
                            prefix_service.save(prefixes[i])

                for prfx in prefixes_list:
                    if prfx not in form_prefixes:
                        prefix = prefix_service.find(user=auth_user,
                                                     prefix=prfx).first()
                        prefix.is_suspended = True
                        # prefix.is_active = False
                        prefix_service.save(prefix)

                # Check active prefix and set accordingly
                user_active_prefix = auth_user.profile.product_active_prefix
                if not user_active_prefix:
                    prefix = prefix_service.find(
                        user=auth_user,
                        is_suspended=False).order_by('prefix').first()

                    if prefix:
                        prefix_service.make_active(user=auth_user,
                                                   prefix=prefix.prefix)
                        prefix_service.save(prefix)
                    else:
                        return jsonify(success=False,
                                       message='No working prefix found')

            return redirect(get_api_auth(auth_user.email))
    else:
        form = AccountCreateOrUpdateForm()

    try:
        m2m_token_set = request.user.auth_token_set.all()
        m2m_token = m2m_token_set[0].digest
    except Exception:
        m2m_token = ''

    context = {
        'current_user': request.user,
        'm2m_token': m2m_token,
        'active_page': '',
        'form': form
    }
    return render(request, 'activate/AccountCreateOrUpdate.html', context)