示例#1
0
 def form_valid(self, form):
     login           = form.cleaned_data['login']
     password1       = form.cleaned_data['password1']
     first_name      = form.cleaned_data['first_name']
     image           = form.cleaned_data['image']
     new_user = User(
         username=login,
         first_name=first_name,
     )
     new_user.set_password(password1)
     try:
         new_user.full_clean()
     except ValidationError:
         self.set_message(u'Не правильно заполненна форма', True)
         return super(CreateCompanyView, self).form_invalid(form)
     new_user.save()
     new_profile = Profile(
         user=new_user,
         is_company=True,
         is_report=False,
         is_super_user=False,
         image=image,
     )
     new_profile.save()
     new_company = Company(com_user=new_user)
     new_company.save()
     self.set_message(u'Компания успешно добавлена.')
     return super(CreateCompanyView,self).form_valid(form)
示例#2
0
文件: views.py 项目: josben/flo
def newCompany(request):
    if request.method == 'POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            address = form.cleaned_data['address']
            description = form.cleaned_data['description']

            company = Company(name=name,
                         address=address,
                         description=description)
            company.save()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'La empresa %s se creo correctamente' % company.name)
            return HttpResponseRedirect('/staff/only_staff/')
        else:
            messages.add_message(request,
                                 messages.ERROR,
                                 'Los datos que ingreso son incorrectos')
            return render_to_response('company_form.html', {'form': form},
                                      context_instance=RequestContext(request))
    else:
        form = CompanyForm()
        return render_to_response('company_form.html', {'form': form},
                                  context_instance=RequestContext(request))
示例#3
0
 def create(self, validated_data):
     validated_data['industry'] = Industry.objects.get(
         industry_slug=validated_data['industry']['industry_slug'])
     if validated_data.get('gallery'):
         gallery = validated_data.pop('gallery')
     else:
         gallery = []
     if validated_data.get('benefit'):
         benefit = validated_data.pop('benefit')
     else:
         benefit = []
     validated_data['user'] = self.context['request'].user
     validated_data['city'] = City.objects.get(
         city_slug=validated_data['city']['city_slug'])
     validated_data['approved'] = True
     if validated_data.get('location_point'):
         validated_data['location_point'] = Point(
             validated_data.pop('location'))
     company = Company(**validated_data)
     company.save()
     for item in benefit:
         benefit_item = Benefit.objects.get(name=item['name'])
         company.benefit.add(benefit_item)
     for item in gallery:
         item['company'] = company
         gallery_item = Gallery(**item)
         gallery_item.save()
     cache.delete(settings.COMPANY_NAME_LIST)
     return company
示例#4
0
    def setUp(self):
        _company = Company(
            zipcode="79008",
            logo="http://test.test",
            name="testcompany",
            mail="*****@*****.**",
            phone="+380901234567",
        )
        _company.save()
        _project = AdviserProject(
            id_company=_company,
            name="project1",
            description="test",
            project_template="test",
        )
        _project.save()

        self.first = [Player.objects.create(
                    id=1,
                    name="player1",
                    description="player description",
                    mac_address="11:2a:bb:q1:ss:77",
                    status=False,
                    project=_project),
                 Player.objects.create(
                    id=2,
                    name="player2",
                    description="player2 description",
                    mac_address="88:2a:bb:q1:ss:88",
                    status=False,
                    project=_project)
                ]
示例#5
0
 def setUp(self):
     self.company = Company(name='example',
                            created_at=timezone.now(),
                            email='*****@*****.**',
                            website='https://www.example.com',
                            krs_code=1111111111,
                            nip_code=1111111111)
示例#6
0
 def create(self, validated_data):
     if validated_data.get('gallery'):
         gallery = validated_data.pop('gallery')
     else:
         gallery = []
     if len(Company.objects.filter(name=validated_data['name'])) > 0:
         raise CustomException(
             detail=ugettext('Company with this name exists.'))
     try:
         validated_data['city'] = City.objects.get(
             city_slug=validated_data['city']['city_slug'])
     except City.DoesNotExist as e:
         raise CustomException(
             detail=ugettext('City with this name does not exist.'))
     try:
         validated_data['industry'] = Industry.objects.get(
             industry_slug=validated_data['industry']['industry_slug'])
     except Industry.DoesNotExist as e:
         raise CustomException(
             detail=ugettext('Industry with this slug does not exist.'))
     validated_data['user'] = self.context['request'].user
     if validated_data.get('site'):
         validated_data['site'] = self.validate_site(validated_data['site'])
     validated_data['logo'] = self.validate_logo(validated_data['logo'])
     validated_data['approved'] = False
     validated_data['user_generated'] = True
     company = Company(**validated_data)
     company.save()
     for item in gallery:
         item['company'] = company
         gallery_item = Gallery(**item)
         gallery_item.save()
     cache.delete(settings.COMPANY_NAME_LIST)
     return company
示例#7
0
def edit_company(request, company_id=None):
    if company_id:
        company_instance = Company.objects.get(pk=company_id)
        check_manager_permission(company_instance.manager, request.user)
    else:
        company_instance = Company()
    company_form = CompanyForm(instance=company_instance)

    if request.method == 'POST':
        company_form = CompanyForm(request.POST,
                                   instance=company_instance,
                                   files=request.FILES)
        if company_form.is_valid():
            if not company_id:
                try:
                    manager = Manager.objects.get(profile=request.user.profile)
                except Manager.DoesNotExist:
                    manager = Manager(profile=request.user.profile)
                    manager.save()
                company_instance = company_form.save(commit=False)
                company_instance.manager = manager
            company_instance.save()
            return redirect(
                reverse('company-detail', args=(company_instance.id, )))

    return render(request, 'company/company/company_form.html', {
        'company_form': company_form,
        'title': 'Update Company'
    })
示例#8
0
    def setUp(self):
        ### USERS ###
        self.password = '******'

        ferromet = User()
        ferromet.username = '******'
        ferromet.first_name = 'FERROMET'
        ferromet.set_password(self.password)
        ferromet.save()

        admin = User()
        admin.username = '******'
        admin.first_name = 'Главный куратор'
        admin.set_password(self.password)
        admin.save()

        ### PROFILES ###

        profile1 = Profile()
        profile1.user = admin
        profile1.is_company = False
        profile1.is_report = True
        profile1.is_super_user = True
        profile1.telefon = '+7 921 622 22 50'
        profile1.save()

        profile2 = Profile()
        profile2.user = ferromet
        profile2.save()

        ### COMPANYS ###

        fer_com = Company()
        fer_com.com_user = ferromet
        fer_com.save()

        ### DEPS ###

        dep1 = Departments()
        dep1.pk = 1
        dep1.company = fer_com
        dep1.name = u'Основной'
        dep1.save()

        ### PC ###

        pc1 = CompanyPC()
        pc1.id = 1
        pc1.company = fer_com
        pc1.departament = dep1
        pc1.pc_nameId = '1'
        pc1.pc_name = 'buh'
        pc1.save()

        ### PC_OPTIONS ###

        option1 = PcOptions()
        option1.id = 1
        option1.name = u'Процессор'
        option1.save()
示例#9
0
 def handle(self, *args, **options):
     data = {}
     try:
         with open('mock_data.json', 'r') as fd:
             data = json.load(fd)
     except (IOError, ValueError) as e:
         print("Error with mock_data.json opening: %s" % e)
     # If file successfully loaded and parsed with json
     if data:
         with transaction.atomic():
             for element in data:
                 company = Company(name=element['name'],
                                   sector=element['sector'],
                                   siren=element['siren'])
                 company.save()
                 for result in element['results']:
                     CompanyResult(ca=result['ca'],
                                   margin=result['margin'],
                                   ebitda=result['ebitda'],
                                   loss=result['loss'],
                                   date=date(year=result['year'],
                                             month=01,
                                             day=01),
                                   company=company).save()
                 print('Company "%s" created.' % company.name)
示例#10
0
    def test_4(self):
        """
        импорт из https://proverkacheka.com/check&p=2

        получить все чеки
            получить последний чек загруденный Робо1
            загружать последоватетно страницы из https://proverkacheka.com/check&p=2 до тех пор пока не найдем на странице последний чек
                загрузить страницу
                вытащить из нее чеки
                    преобразовав чеки в формат для сравнения как текст из QR кода
                        параметров всего 5
                попыиаиься найти нужный чек
                если не нашли загрузить следубщую, ограничимся 100 страницами, но первый раз гораничение в 7000
        сохранить их в репозиторий от имени Робо1
             получить список QR кодов скормить его стандартном мехаизму сохранения чеков у пользователей
        потом возможно использовать их для показа похожих товаров в других магазинах и рекомедации цены
        """

        robo1_employee = Employee(title='robo1', key='robo1_123zxc')
        robo1_employee.save()

        company_family = Company(title='family')
        company_family.save()
        company_family.employees.add(robo1_employee)

        last_fns_cheques = FNSCheque.objects.filter(
            company=company_family).order_by('-id')
        has_last_fns_cheques = False
        if last_fns_cheques:
            has_last_fns_cheques = True
            last_fns_cheque = last_fns_cheques[0]
示例#11
0
    def save(self, validated_data):
        email = validated_data.get('email')
        new_user = User(
            username=email,
            email=email,
            is_active=False,
        )
        new_user.save()

        # Create new salary instance
        new_salary = Salary(user=new_user)
        new_salary.save()

        # Create new adminprofile instance
        new_adminprofile = AdminProfile(user=new_user)
        new_adminprofile.save()

        # Create new company instance and assign admin_profile to new admin_profile, other fields have placeholder values
        new_company = Company(adminprofile=new_adminprofile)
        new_company.save()

        registration = Registration(
            user=new_user,
            code_type='RV',
            profile_type='AP',
        )
        registration.save()

        email = Email(
            to=email,
            subject='Thank you for registering with RazzPay!',
            content=f'Here is your validation code: {registration.code}')
        email.save(request=self.context['request'])
        return new_user
示例#12
0
    def handle(self, *args, **options):

        source_url = 'https://raw.githubusercontent.com/maguowei/Internet-companies-of-China/master/company.csv'
        company_csv_file = os.path.join(os.path.dirname(settings.BASE_DIR), 'data/fake/company.csv')

        stage = dict((y, x) for x, y in Company.STAGE)
        size = dict((y, x) for x, y in Company.SIZE)

        cities = ('北京', '上海', '广州', '深圳', '重庆', '天津', '沈阳', '南京', '武汉', '成都', '大连', '杭州', '青岛', '济南',
                  '厦门', '福州', '西安', '长沙')

        if not os.path.isfile(company_csv_file):
            res = requests.get(source_url)
            with open(company_csv_file, 'w', encoding='utf-8') as f:
                f.write(res.text)

        with open(company_csv_file, encoding='utf-8') as f:
            f_csv = csv.DictReader(f)
            for l in f_csv:
                if l['basic.address'] in cities:
                    if l['basic.process'] == 'B 轮':
                        continue

                    if Company.objects.filter(name=l['name']):
                        continue

                    company = Company(name=l['name'], name_short=l['short_name'][:20], logo=l['logo'], href=l['href'][:100],
                                      address=l['address.0'], stage=stage[l['basic.process']],
                                      size=size[l['basic.number']], city_id=1)
                    company.save()

        self.stdout.write(self.style.SUCCESS('Great! fake data fill succeed'))
示例#13
0
    def setUp(self):
        company = Company(
            id=1,
            zipcode="79008",
            logo="http://test.test",
            name="testcompany",
            mail="*****@*****.**",
            phone="+380901234567",
        )
        company.save()

        project = AdviserProject(
            id=1,
            id_company=company,
            name="project1",
            description="test",
            project_template="test",
        )
        project.save()

        Player.objects.create(id=1,
                              name="player1",
                              description="player description",
                              mac_address="11:2a:bb:q1:ss:77",
                              status=False,
                              project=project)

        Player.objects.create(id=2,
                              name="player2",
                              description="player description",
                              mac_address="22:21:dd:ac:ff:22",
                              status=False)

        self.client = Client()
示例#14
0
    def post(self, request, format=None):
        serializer = serializers.CompanyCreateUpdateSerializer(
            data=request.data)
        if serializer.is_valid():
            user_id = request.user.id
            company_instance = Company()
            company_instance.company_name = serializer.data.get(
                "company_name", "")
            # company_instance.u_by =user_id
            # company_instance.is_active = "y"
            # company_instance.is_deleted = "n"
            company_instance.save()

            return_arr = {}
            return_arr['code'] = 200
            return_arr['success'] = 'true'
            return_arr['message'] = 'valid'
            return HttpResponse(json.dumps(return_arr),
                                status=return_arr['code'])

        return_arr = {}
        return_arr['code'] = 602
        return_arr['success'] = 'false'
        return_arr['message'] = 'Error in saving data'
        return HttpResponse(json.dumps(return_arr), status=return_arr['code'])
示例#15
0
def get_or_create_company(name):
    cd = get_company_detail(name)
    if cd is None:
        company_title = name
    else:
        company_title = cd['name']
    jc = Company.objects.all().filter(company__iexact=company_title)
    if jc.count() == 0:
        # if company doesnt exist save it
        if cd is None:
            jc = Company(company=name, domain=None)
        else:
            jc = Company(company=cd['name'], domain=cd['domain'])
            jc.save()
            if 'logo' in cd and cd['logo'] is not None and cd['logo'] is not '':
                try:
                    urlretrieve(cd['logo'], filename=cd['logo'].split('/')[-1])
                    file = open(cd['logo'].split('/')[-1], 'rb')
                    filename = "%s.%s" % (uuid.uuid4(), 'jpg')
                    jc.logo.save(filename, File(file), save=True)
                    jc.save()
                    os.remove(cd['logo'].split('/')[-1])
                except FileNotFoundError as err:
                    pass  # something wrong with local path
                except HTTPError as err:
                    pass  # something wrong with url
        jc.save()
    else:
        jc = jc[0]
    if jc.location_address is None:
        fetch_company_location(name)
    return jc
 def handle(self, *args, **options):
     print('Recalculating product query count')
     Product.recalculate_query_count()
     print('Recalculating product ai pics count')
     Product.recalculate_ai_pics_count()
     print('Recalculating company query count')
     Company.recalculate_query_count()
     print('Finished recalculating query count')
示例#17
0
 def post(self, request, *args, **kwargs):
     company_index = request.POST.get('company_index')
     company_name = request.POST.get('company_name')
     company_address = request.POST.get('company_address')
     new_company = Company(company_index=int(company_index),
                           company_name=company_name,
                           company_address=company_address)
     new_company.save()
     return redirect('/company/company/')
示例#18
0
def update_company_from_krs(product, company):
    try:
        krs = KrsClient()
        if company.name:
            companies = krs.get_companies_by_name(company.name)
        elif company.nip:
            companies = krs.get_companies_by_nip(company.nip)
        else:
            return False
        if companies.__len__() == 1:
            company.official_name = companies[0]['nazwa']
            company.common_name = companies[0]['nazwa_skrocona']
            company.address = companies[0]['adres']
            company.nip = companies[0]['nip']
            company.plRegistered = 100
            company.sources = "Dane z KRS|%s" % companies[0]['url']

            Company.save(
                company,
                commit_desc="Dane firmy pobrane "
                "automatycznie poprzez API "
                "mojepanstwo.pl ({})".format(companies[0]['url']),
            )

            shareholders = shareholders_to_str(krs, companies[0]['id'], '')
            if shareholders:
                create_bot_report(
                    product,
                    'Wspólnicy spółki {}:\n{}'.format(company.name,
                                                      shareholders))
            return True

        elif companies.__len__() > 0:
            description = '{} - ta firma może być jedną z następujących:\n\n'.format(
                company.name)

            for i in range(0, min(companies.__len__(), 10)):
                description += ('Nazwa: {}\n' + 'Skrót: {}\n' + 'NIP:   {}\n' +
                                'Adres: \n{}\n' + 'Url:   {}\n').format(
                                    companies[i]['nazwa'],
                                    companies[i]['nazwa_skrocona'],
                                    companies[i]['nip'],
                                    companies[i]['adres'],
                                    companies[i]['url'],
                                )
                shareholders = shareholders_to_str(krs, companies[i]['id'], '')
                if shareholders:
                    description += 'Wspólnicy:\n{}'.format(shareholders)
                description += '\n'

            create_bot_report(product, description)

    except (mojepanstwo_api.CompanyNotFound, mojepanstwo_api.ConnectionError,
            mojepanstwo_api.ApiError):
        pass

    return False
示例#19
0
    def setUp(self):
        """ company initialization with proper arguments """

        self.company = Company(name='example',
                               created_at=timezone.now(),
                               email='*****@*****.**',
                               website='https://www.example.com',
                               krs_code=1111111111,
                               nip_code=1111111111)
示例#20
0
def update_company_from_krs(product, company):
    try:
        krs = KrsClient()
        if company.name:
            companies = krs.get_companies_by_name(company.name)
        elif company.nip:
            companies = krs.get_companies_by_nip(company.nip)
        else:
            return False
        if companies.__len__() == 1:
            company.official_name = companies[0]['nazwa']
            company.common_name = companies[0]['nazwa_skrocona']
            company.address = companies[0]['adres']
            company.nip = companies[0]['nip']
            company.plRegistered = 100
            company.sources = u"Dane z KRS|%s" % companies[0]['url']

            Company.save(company, commit_desc="Dane firmy pobrane "
                                              "automatycznie poprzez API "
                                              "mojepanstwo.pl ({})"
                         .format(companies[0]['url']))

            shareholders = shareholders_to_str(krs, companies[0]['id'], '')
            if shareholders:
                create_bot_report(product, u'Wspólnicy spółki {}:\n{}'.
                                  format(company.name, shareholders))
            return True

        elif companies.__len__() > 0:
            description = u'{} - ta firma może być jedną z następujących:\n\n' \
                .format(company.name)

            for i in range(0, min(companies.__len__(), 10)):
                description += \
                    (u'Nazwa: {}\n' +
                     u'Skrót: {}\n' +
                     u'NIP:   {}\n' +
                     u'Adres: \n{}\n' +
                     u'Url:   {}\n').format(companies[i]['nazwa'],
                                            companies[i]['nazwa_skrocona'],
                                            companies[i]['nip'],
                                            companies[i]['adres'],
                                            companies[i]['url'])
                shareholders = shareholders_to_str(krs, companies[i]['id'], '')
                if shareholders:
                    description += u'Wspólnicy:\n{}'.format(shareholders)
                description += '\n'

            create_bot_report(product, description)

    except (mojepanstwo_api.CompanyNotFound, mojepanstwo_api.ConnectionError,
            mojepanstwo_api.ApiError):
        pass

    return False
示例#21
0
文件: views.py 项目: lhalam/itaplay
 def get(self, request):
     """
     Handling GET method.
     :param request: Request to View.
     :return: HttpResponse with company fields and values by id_company of user which is logined.
     If user is superuser returns all companies with their fields and values.
     """
     if request.user.is_superuser:
         company = [model_to_dict(company) for company in Company.get_company()]
         return HttpResponse(json.dumps(company))
     user = request.user.adviseruser
     company = [model_to_dict(company) for company in Company.filter_company(user.id_company.id)]
     return HttpResponse(json.dumps(company))
示例#22
0
    def test_delete_company(self):
        Company.objects.create(
            id=3,
            zipcode="379007",
            logo="332132",
            name="testcompany3",
            mail="[email protected]",
            address="testaddress3",
            phone="+3809012345673",
        )

        self.assertEqual(len(Company.get_company()), 3)
        Company().delete_company(3)
        self.assertEqual(len(Company.get_company()), 2)
示例#23
0
 def post(self, request):
     """
     Handling POST method.
     :param request: Request to View.
     :return: HttpResponse with code 201 if company is added or
     HttpResponseBadRequest if request contain incorrect data or user is not superuser.
     """
     company = Company()
     data = json.loads(request.body)
     company_form = CompanyForm(data)
     if not company_form.is_valid():
         return HttpResponseBadRequest(str(company_form.errors))
     company.set_company(data)
     return HttpResponse(status=201)
示例#24
0
文件: views.py 项目: lhalam/itaplay
 def post(self, request):
     """
     Handling POST method.
     :param request: Request to View.
     :return: HttpResponse with code 201 if company is added or
     HttpResponseBadRequest if request contain incorrect data or user is not superuser.
     """
     company = Company()
     data = json.loads(request.body)
     company_form = CompanyForm(data)
     if not company_form.is_valid():
         return HttpResponseBadRequest(str(company_form.errors))
     company.set_company(data) 
     return HttpResponse(status=201)
示例#25
0
 def test_delete_company(self):
     Company.objects.create(
         id=3,
         zipcode="379007",
         logo="332132",
         name="testcompany3",
         mail="[email protected]",
         address= "testaddress3",
         phone="+3809012345673",
     )
     
     self.assertEqual(len(Company.get_company()), 3)
     Company().delete_company(3)
     self.assertEqual(len(Company.get_company()), 2)
示例#26
0
 def list(self, request, *args, **kwargs):
     company_instance = Company.get_company()
     if company_instance is None:
         return super().list(request, *args, **kwargs)
     else:
         serializer = self.serializer_class(company_instance)
         return Response(serializer.data)
示例#27
0
def run():
    base_path = './data/'
    file_list = os.listdir(base_path)
    company_name_set = set()
    existed_company_name_set = Company.objects.all().values_list('name', flat=True)
    existed_company_name_set = set(existed_company_name_set)

    for filename in file_list:
        full_path = base_path + filename

        with open(full_path, 'r') as file:
            file_data = file.read()
            file_data = file_data.replace(' ', '').replace('\n', '')
            file_data = json.loads(file_data)
            for data in file_data:
                if data.get('company_info'):
                    company_name_set.add(data.get('company_info'))

    new_create_company_name_set = company_name_set - existed_company_name_set
    new_company_list = list()
    for name in new_create_company_name_set:
        new_company_list.append(Company(name=name))

    print('即将创建{}条数据'.format(len(new_company_list)))
    save = input('是否保存y/n: ')
    if save == 'y':
        Company.objects.bulk_create(new_company_list, batch_size=1000)
        print('创建成功')
    else:
        print('什么也没有执行')
示例#28
0
文件: views.py 项目: lhalam/itaplay
 def get(self, request, company_id):
     """
     Handling GET method.
     :args
         request: Request to View.
         company_id: id of company to be returned.
     :return: HttpResponse with company fields and values by id.
     If user is not superuser and tries to get acces into foreign company
     returns HttpResponseBadRequest with 'Permission denied' massage.
     """
     company_id = int(company_id)
     if (not request.user.is_superuser) and (company_id != 
                                             request.user.adviseruser.id_company.id):
         return HttpResponseBadRequest("Permission denied")
     data = {"company" : model_to_dict(Company.get_company(company_id)),
             "users" : Company.get_company(company_id).get_users()}
     return HttpResponse(json.dumps(data))
示例#29
0
    def test_11(self):
        company_family = Company(title='family')
        company_family.save()

        tests = [
            '20201216T1818 29.00 9280440301295284 236 3107860384',
            #'2020.12.16 18:18:01 29.00 9280440301295284 236 3107860384',
            '2020.12.16 18:18 29.00 9280440301295284 236 3107860384',
            '18:18 2020.12.16 29.00 9280440301295284 236 3107860384',
            '18:18 16.12.2020 29.00 9280440301295284 236 3107860384',
            '18:18 2020.12.16 29.00 9280440301295284 236 3107860384',
        ]
        chat_id = '383332826'

        for test in tests:
            message = test
            Telegram.process_message(company_family, chat_id, message)
示例#30
0
def public_profile_software():
    company = Company(**default_public_profile_data)
    company.number = '0123456C'
    company.is_published = True
    company.sectors = ['SOFTWARE_AND_COMPUTER_SERVICES']
    company.save()
    return company
示例#31
0
def public_profile_cars():
    company = Company(**default_public_profile_data)
    company.number = '0123456D'
    company.is_published = True
    company.sectors = ['AUTOMOTIVE']
    company.save()
    return company
示例#32
0
def public_profile_smart_cars():
    company = Company(**default_public_profile_data)
    company.number = '0123456E'
    company.is_published = True
    company.sectors = ['SOFTWARE_AND_COMPUTER_SERVICES', 'AUTOMOTIVE']
    company.save()
    return company
示例#33
0
def signup(request):
    #user validation start
    if request.user.is_authenticated:
        if request.user.user_type == 1:
            return redirect("/university/home")
        elif request.user.user_type == 2:
            return redirect("/company/home")
    #user validation end
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            if user.user_type == 1:
                university = University(name=user.fullname, admin=user)
                university.save()
            else:
                company = Company(name=user.fullname, admin=user)
                company.save()
            curren_site = get_current_site(request)
            subject = "Activate your Career Bridge account"

            message = render_to_string(
                'auth/activate.html', {
                    'user': user,
                    'domain': curren_site,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': generate_token.make_token(user)
                })

            email = EmailMessage(subject, message, settings.EMAIL_HOST_USER,
                                 [user.email])
            email.send(fail_silently=False)

            context = {
                "isSignedUp": True,
                "name": form.cleaned_data['fullname']
            }
            return render(request, 'login.html', context)
        else:
            context = {"form": form}
            return render(request, 'signup.html', context)

    form = RegisterForm()
    context = {"form": form}
    return render(request, 'signup.html', context)
示例#34
0
    def test_7(self):
        """
	1. создать чек на основе строки полученой из QR кода
	2. обновить данные в чеке из проверка чеков ком 
	"""

        company_family = Company(title='family')
        company_family.save()

        qr_text = 't=20200524T125600&s=849.33&fn=9285000100127361&i=115180&fp=1513716805&n=1'

        fns_cheque = FNSCheque.create_fns_cheque_from_qr_text(
            qr_text, company_family)
        fns_cheque.save()

        self.assertEqual('', fns_cheque.fns_userInn)
        self.assertEqual(
            '',
            FNSCheque.objects.get(
                fns_fiscalDocumentNumber='115180').fns_userInn)

        fns_cheque_json = ImportProverkachekaComFormatLikeFNS.get_fns_cheque_by_qr_params(
            '', qr_text)

        self.assertTrue(
            FNSCheque.has_cheque_with_fiscal_params(
                company_family,
                fns_cheque_json["document"]["receipt"]["fiscalDocumentNumber"],
                fns_cheque_json["document"]["receipt"]["fiscalDriveNumber"],
                fns_cheque_json["document"]["receipt"]["fiscalSign"],
                fns_cheque_json["document"]["receipt"]["dateTime"],
                fns_cheque_json["document"]["receipt"].get(
                    "totalSum", 'Error')))
        self.assertTrue(
            FNSCheque.has_cheque_with_fns_cheque_json(company_family,
                                                      fns_cheque_json))

        #FNSCheque.update_cheque_from_json(fns_cheque, fns_cheque_json)
        fns_cheque.update_cheque_from_json(fns_cheque_json)

        self.assertEqual(u'5258056945', fns_cheque.fns_userInn)
        self.assertEqual(
            u'5258056945',
            FNSCheque.objects.get(
                fns_fiscalDocumentNumber='115180').fns_userInn)
示例#35
0
    def create_company(self, user_id, bigcompany_id, name, logo):
        """
        创建公司
        by:尚宗凯 at:2015-06-11
		完善测试
		by:尚宗凯 at:2015-07-02
        """
        resonse = self.client.post('/cp/create_company', {"bigcompany_id":bigcompany_id, "name":name, "logo":logo})
        bigcompany_id = bigcompany_id
        name = name
        logo = logo
        expired_date = ""
        if expired_date:
            expired_date = datetime.datetime.strptime(expired_date, "%Y-%m-%d")
        else:
            expired_date = datetime.datetime.now().date() + datetime.timedelta(days=7)
        c = Company()
        c.bigcompany_id = bigcompany_id
        c.name = str(name)
        c.expired_date = expired_date
        if logo:
            c.logo = logo
        c.save()
        CompanyColumn.init_company_column(c)
        self.assertEqual(200, resonse.status_code, u'')
示例#36
0
 def test_set_company_create(self):
     admin = AdviserUser.objects.get(id=1)
     data = {
         "id": 3,
         "zipcode": "379007",
         "logo": "32132",
         "name": "testcompany3",
         "mail": "[email protected]",
         "address": "testaddress3",
         "phone": "+380951234567",
         "administrator": admin,
     }
     Company().set_company(data)
     company = Company.get_company(3)
     self.assertEqual(company.name, "testcompany3")
     self.assertEqual(company.mail, "[email protected]")
     self.assertEqual(company.phone, "+380951234567")
     self.assertEqual(company.zipcode, "379007")
示例#37
0
 def get(self, request):
     """
     Handling GET method.
     :param request: Request to View.
     :return: HttpResponse with company fields and values by id_company of user which is logined.
     If user is superuser returns all companies with their fields and values.
     """
     if request.user.is_superuser:
         company = [
             model_to_dict(company) for company in Company.get_company()
         ]
         return HttpResponse(json.dumps(company))
     user = request.user.adviseruser
     company = [
         model_to_dict(company)
         for company in Company.filter_company(user.id_company.id)
     ]
     return HttpResponse(json.dumps(company))
示例#38
0
    def register(self, request, form):
        username = form.cleaned_data['email']
        password = form.cleaned_data['password']
        zipcode = form.cleaned_data['zipCode']
        phone = form.cleaned_data['phone']
        size = form.cleaned_data['size']
        name = form.cleaned_data['name']

        User.objects.create_user(username, email=username, password=password)
        new_user = authenticate(
			username=username,
			password=password
		)
        login(request, new_user)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)

        Company.register_company(new_user, name, zipCode=zipcode, phone=phone, size=size)
        return new_user
示例#39
0
    def generate_link(self):
        """Function that generates user invitation link

        Returns :
            str :user invitation link
        """
        u_id = uuid.uuid4().hex  # u_id stores random generated hash
        AdviserInvitations.create(email=self.email,
                                  id_company=Company.get_company(self.company_id),
                                  verification_code=u_id,
                                  creation_time=timezone.now())
        return EMAIL_SETTINGS['URL_REGISTRATION'] + u_id
示例#40
0
 def test_set_company_update(self):
     admin = AdviserUser.objects.get(id=1)
     data = {
                "id" : 1,
                 "zipcode" : "379007",
                 "logo" : "32132",
                 "name" : "testcompany1",
                 "mail" : "[email protected]",
                 "address" : "testaddress1",
                 "phone" : "+380951234567",   
                 "administrator" : admin,
             }
     
     company = Company.get_company(1)
     company.set_company(data)
     company = Company.get_company(1)
     self.assertEqual(company.name, "testcompany1")
     self.assertEqual(company.mail, "[email protected]")
     self.assertEqual(company.phone, "+380951234567")
     self.assertEqual(company.zipcode, "379007")
     self.assertEqual(company.administrator, admin)
示例#41
0
文件: views.py 项目: lhalam/itaplay
 def put(self, request, company_id):
     """
     Handling put method.
     :args
         request: Request to View.
         company_id: id of company to be updated.
     :return: HttpResponse with code 201 if company is updated or
     HttpResponseBadRequest if request contain incorrect data also if user is not superuser .
     """
     if (not request.user.is_superuser) and (Company.get_company(company_id).administrator != 
                                             request.user.adviseruser):
         return HttpResponseBadRequest("Permission denied")
     data = json.loads(request.body)
     if data.get("administrator"):
         data["administrator"] = AdviserUser.objects.get(id=data.get("administrator").get("id"))
     company = Company.get_company(data["id"])
     company_form = CompanyForm(data, company)
     if not company_form.is_valid():
         return HttpResponseBadRequest(str(company_form.errors))
     company.set_company(data)
     return HttpResponse(status=201)
示例#42
0
    def setUp(self):
        company = Company(
            id=1,
            zipcode="79008",
            logo="http://test.test",
            name="testcompany",
            mail="*****@*****.**",
            phone="+380901234567",
        )
        company.save()

        project = AdviserProject(
            id=1,
            id_company=company,
            name="project1",
            description="test",
            project_template="test",
        )
        project.save()

        Player.objects.create(
            id=1,
            name="player1",
            description="player description",
            mac_address="11:2a:bb:q1:ss:77",
            status=False,
            project=project  
        )

        Player.objects.create(
            id=2,
            name="player2",
            description="player description",
            mac_address="22:21:dd:ac:ff:22",
            status=False
        )

        self.client = Client()
示例#43
0
    def setUp(self):
        _company = Company(
            id=1,
            zipcode="79008",
            logo="http://test.test",
            name="testcompany",
            mail="*****@*****.**",
            phone="+380901234567",
        )
        _company.save()
        _project = AdviserProject(
            id=1,
            id_company=_company,
            name="project1",
            description="test",
            project_template="test",
            )
        _project.save()

        self.first = [Player.objects.create(
            id=1,
            name="player1",
            description="player description",
            mac_address="11:2a:bb:q1:ss:77",
            status=False,
            project=_project),
                Player.objects.create(
            id=2,
            name="player2",
            description="player2 description",
            mac_address="88:2a:bb:q1:ss:88",
            status=True,
            project=_project)
        ]

        self.client = Client()
        self.client.login(username="******", password="******")
示例#44
0
def new(request, pk):

    company = Company.goof(pk=pk)

    if request.method == "POST":
        pos = Position(company=company)
        form = PositionForm(request.POST, instance=pos)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect(company.get_edit_url() )
    else:
        form = PositionForm()

    return {'company': company, 'form': form}
示例#45
0
 def test_get_company_by_id(self):
     company = Company.get_company(1)
     company_id_1 = Company.objects.get(id=1)
     self.assertEqual(company, company_id_1)
示例#46
0
    def setUp(self):
        
        User.objects.create(
            username="******",
            is_superuser=True,
            email="*****@*****.**",
            id=1
        )

        User.objects.create(
            username="******",
            is_superuser=False,
            email="*****@*****.**",
            id=2
        )

        User.objects.create(
            username="******",
            is_superuser=False,
            email="*****@*****.**",
            id=3
        )

        User.objects.create(
            username="******",
            is_superuser=False,
            email="*****@*****.**",
            id=4
        )

        user = User.objects.get(id=1)
        user.set_password("password")
        user.save()

        user = User.objects.get(id=2)
        user.set_password("password")
        user.save()

        user = User.objects.get(id=3)
        user.set_password("password")
        user.save()

        user = User.objects.get(id=4)
        user.set_password("password")
        user.save()
        
        Company.objects.create(
            id=1,
            zipcode="79008",
            logo="http://test.test",
            name="testcompany",
            mail="*****@*****.**",
            address= "testaddress",
            phone="+380901234567",      
        )

        Company.objects.create(
            id=2,
            zipcode="794508",
            logo="http://test2.test",
            name="testcompany2",
            mail="*****@*****.**",
            address= "testaddress2",
            phone="+380901234677",
        )

        AdviserUser.objects.create(
            user=User.objects.get(id=2),
            id_company=Company.objects.get(id=1),
            id=1
        )
        
        AdviserUser.objects.create(
            user=User.objects.get(id=3),
            id_company=Company.objects.get(id=1),
            id=2
        )    
        
        AdviserUser.objects.create(
            user=User.objects.get(id=4),
            id_company=Company.objects.get(id=2),
            id=3
        )    
        
        company = Company.get_company(1)
        company.administrator = AdviserUser.objects.get(id=1)
        company.save()

        self.client = Client()
        self.client.login(username="******", password="******")
示例#47
0
	def test_CreateCompany(self):
		company = Company(
			name = "TEST_COMPANY_001"
		)
		company_key = company.put()
		self.assertEquals(company_key.get().name, "TEST_COMPANY_001")
 def handle(self, *args, **options):
     print "Recalculating product query count"
     Product.recalculate_query_count()
     print "Recalculating company query count"
     Company.recalculate_query_count()
     print "Finished recalculating query count"
示例#49
0
    def setUp(self):
        ### USERS ###
        self.password = '******'

        ferromet = User()
        ferromet.username = '******'
        ferromet.first_name = 'FERROMET'
        ferromet.set_password(self.password)
        ferromet.save()

        admin = User()
        admin.username = '******'
        admin.first_name = 'Главный куратор'
        admin.set_password(self.password)
        admin.save()

        ### PROFILES ###

        profile1 = Profile()
        profile1.user = admin
        profile1.is_company = False
        profile1.is_report = True
        profile1.is_super_user = True
        profile1.telefon = '+7 921 622 22 50'
        profile1.save()

        profile2 = Profile()
        profile2.user = ferromet
        profile2.save()

        ### COMPANYS ###


        fer_com = Company()
        fer_com.com_user = ferromet
        fer_com.save()


        ### DEPS ###

        dep1 = Departments()
        dep1.pk = 1
        dep1.company = fer_com
        dep1.name = u'Основной'
        dep1.save()

        ### PC ###

        pc1 = CompanyPC()
        pc1.id = 1
        pc1.company = fer_com
        pc1.departament = dep1
        pc1.pc_nameId = '1'
        pc1.pc_name = 'buh'
        pc1.save()

        ### PC_OPTIONS ###

        option1 = PcOptions()
        option1.id = 1
        option1.name = u'Процессор'
        option1.save()
示例#50
0
def run():

    mypass = u'user12345'

    admin = User.objects.get(pk=1)
    admin.first_name = u'Главный куратор'
    admin.save()
    admin_profile = Profile(user=admin, is_company=False, is_report=True, is_super_user=True, telefon = '+1222333')
    admin_profile.save()


    alexandrov = User(username = u'alexandrov', first_name = u'Михаил', last_name = u'Александров' )
    alexandrov.set_password(mypass)
    alexandrov.email = '*****@*****.**'
    alexandrov.save()

    alexandrov_profile = Profile(user=alexandrov, is_report = True, is_company=False, telefon='+7-911-234-44-55')
    alexandrov_profile.save()


    ivanov = User(username = u'ivanov', first_name = u'Сергей', last_name = u'Иванов' )
    ivanov.set_password(mypass)
    ivanov.save()


    ivanov_profile = Profile(user=ivanov, is_company=False, telefon ='+7-921-355-34-34')
    ivanov_profile.save()

    petrov = User(username = u'petrov', first_name = u'Павел', last_name = u'Петров' )
    petrov.set_password(mypass)
    petrov.save()

    petrov_profile = Profile(user=petrov, is_company=False, telefon= '+7-904-122-12-12')
    petrov_profile.save()


    maslov = User(username= '******', first_name = u'Алексей', last_name = u'Маслов')
    maslov.set_password('megapass123')
    maslov.save()

    maslov_profile = Profile(user=maslov, is_company=False, telefon='+7-812-211-44-44')
    maslov_profile.save()







    usersList = [ alexandrov, ivanov, petrov, maslov]

    ferromet = User(username = u'ferromet', first_name = u'ООО ФЕРРОМЕТ')
    ferromet.set_password(mypass)
    ferromet.save()

    intersteel = User(username = u'intersteel', first_name = u'ООО ИНТЕРСТАЛЬ' )
    intersteel.set_password(mypass)
    intersteel.save()

    rbk = User(username = u'rbk', first_name = u'ООО РБК' )
    rbk.set_password(mypass)
    rbk.save()

    sevsap = User(username = u'sevzap', first_name = u'ООО СЕВЗАП')
    sevsap.set_password(mypass)
    sevsap.save()

    test = User(username='******', first_name = u'ООО Приборы')
    test.set_password('test12345')
    test.save()

    Profile(user=ferromet).save()
    Profile(user=intersteel).save()
    Profile(user=rbk).save()
    Profile(user=sevsap).save()
    Profile(user=test).save()



    companyUserList = [ferromet, intersteel, rbk, sevsap, test]


    com_ferromet = Company( com_user = ferromet)
    com_ferromet.save()

    com_interseel = Company( com_user = intersteel)
    com_interseel.save()

    com_rbk = Company( com_user = rbk)
    com_rbk.save()

    com_sevsap = Company( com_user = sevsap)
    com_sevsap.save()

    com_test = Company(com_user = test)
    com_test.save()


    main_dep = Departments(name = u'Основной', company=com_ferromet)
    main_dep.save()
    buh_dep = Departments(name = u'Бухгалтерия', company=com_ferromet)
    buh_dep.save()
    dir_dep = Departments(name = u'Директорат', company=com_ferromet)
    dir_dep.save()
    fin_dep = Departments(name = u'Финансисты', company=com_ferromet)
    fin_dep.save()


    dep_list = [
        main_dep,
        buh_dep,
        dir_dep,
        fin_dep,
    ]

    companyList = [
        com_ferromet,
        com_interseel,
        com_rbk,
        com_sevsap,
        com_test
    ]


    alfavitList = ['a', 'b', 'z', 'r', 'e', 'y', 't', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'j', 'o', 'p', 'm']



    kurator = Posts(name=u'Куратор', decription=u'По главным вопросам')
    kurator.save()

    gelezo = Posts(name=u'Железо', decription=u'По вопросам железа')
    gelezo.save()

    admin1c = Posts(name=u'1с', decription=u'По вопросам 1c')
    admin1c.save()

    access = Posts(name=u'Аксес', decription=u'По вопросам Access')
    access.save()



    postsList = [kurator, gelezo, admin1c, access]

    for i in range(0,20):
        CompanyAdmins(username=usersList[randrange(0, len(usersList))], company=companyList[randrange(0,len(companyList))], post=postsList[randrange(0, len(postsList))]).save()

    CompanyAdmins(username=alexandrov, company = com_ferromet, post = kurator).save()


    proccesor   = PcOptions(name = u'Процессор')
    proccesor.save()
    video       = PcOptions(name = u'Видеокарта')
    video.save()
    hard        = PcOptions(name = u'Жесткий диск')
    hard.save()





    host_names_list = ['server', 'buh', 'manager', 'mail', 'secretary']
示例#51
0
 def test_get_company_by_wromg_id(self):
     company = Company.get_company(4)
     self.assertEqual(company, None)    
示例#52
0
 def test_get_company(self):
     companies = Company.get_company()
     company1 = Company.objects.get(id=1)
     company2 = Company.objects.get(id=2)
     self.assertEqual(companies[0], company1)
     self.assertEqual(companies[1], company2)