def create_customer(self):
        customer = Customers()
        customer.partner_id = self.partner.id
        customer.company_name = self.partner.company_name
        customer.address = self.partner.address_1 + '' + self.partner.address_2
        customer.city = self.partner.city
        customer.state = self.partner.state
        customer.Pincode = self.partner.pin_code
        customer.country = self.partner.state
        customer.pan_number = ''
        customer.deleted = False
        customer.customer_vertical = None
        customer.delivery_sequence = '000'
        customer.save()
        print('Customer %s created' % customer.company_name)

        self.customer = customer
        ''' Creating customer contacts1 '''
        self.create_customer_contacts()
        ''' Creating customer contacts2 '''
        self.create_customer_contacts()
Exemplo n.º 2
0
    def handle(self, *args, **options):
        migration_csvs = os.path.join(settings.BASE_DIR, 'migrations')

        partner_map = {}

        print("Creating Partners...")
        with open(os.path.join(migration_csvs, 'partners.csv'),
                  'r',
                  encoding='latin1') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                if not row[0]:
                    print("Cannot find partner identifier for ", row[0])
                    continue

                partner = Partner()
                partner.company_name = row[3]

                if row[1] == 'Y':
                    partner.status = True
                else:
                    partner.status = False

                if row[28] == 'Y':
                    partner.existing_status = True
                else:
                    partner.existing_status = False
                partner.jba_code = str.strip(row[23])
                partner.credits = row[24]
                partner.address_1 = row[4]
                partner.address_2 = row[5]
                partner.address_3 = row[6]
                partner.city = row[7]
                partner.state = row[8]
                partner.pin_code = row[9]
                partner.partner_type = 'R'
                partner.business_type = 'S'
                partner.focused_customer = ''
                partner.business_type = ''
                partner.interested_workload = ''
                original_date = row[21].split(' ')
                try:
                    val = datetime.datetime.strptime(original_date[0],
                                                     '%m/%d/%y')
                except ValueError:
                    val = datetime.datetime.strptime(original_date[0],
                                                     '%m/%d/%Y')
                partner.created_at = val
                partner.activated_at = val
                for field in partner._meta.fields:
                    if field.name == 'created_at' or field.name == 'activated_at':
                        field.auto_now_add = False
                partner.created_by = 1
                partner.save()
                partner_id = partner.id
                partner_map[row[0].strip()] = partner_id

                c = ContactDetails()
                c.partner = partner
                c.type = 'P'
                c.name = str.format('{} {}', row[10], row[11])
                c.email = row[13]
                c.mobile = row[12]
                c.save()

                contact_types = ['D/O', 'A&O', 'S']
                for type in contact_types:
                    c = ContactDetails()
                    c.partner = partner
                    c.type = type
                    c.name = str.format('{} {}', row[10], row[11])
                    c.email = row[13]
                    c.mobile = row[12]
                    c.save()

        customer_map = {}
        print("Creating Customers...")
        with open(os.path.join(migration_csvs, 'customers.csv'),
                  'r',
                  encoding='latin1') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                customer = Customers()
                if not row[1].strip() in partner_map.keys():
                    import pdb
                    pdb.set_trace()
                    print("Cannot find partner for customer: ", row[1])
                    continue

                customer.partner_id = partner_map[row[1].strip()]
                customer.company_name = row[2]
                customer.address = row[3]
                customer.city = row[6]
                customer.state = row[7]
                customer.country = row[8]
                customer.Pincode = row[9]
                customer.pan_number = row[22]
                customer.deleted = False
                original_date = row[24].split(' ')
                try:
                    val = datetime.datetime.strptime(original_date[0],
                                                     '%m/%d/%y')
                except ValueError:
                    val = datetime.datetime.strptime(original_date[0],
                                                     '%m/%d/%Y')
                customer.created_at = val
                for field in customer._meta.fields:
                    if field.name == 'created_at':
                        field.auto_now_add = False

                customer.save()
                customer_map[row[0]] = customer.id

                customer_contact = CustomerContacts()
                customer_contact.customer = customer
                customer_contact.name = str.format('{} {} {}', row[10],
                                                   row[11], row[12])
                customer_contact.position = row[13]
                customer_contact.email = row[15]
                customer_contact.mobile = row[14]
                customer_contact.save()

                customer_contact2 = CustomerContacts()
                customer_contact2.customer = customer
                customer_contact2.name = str.format('{} {} {}', row[16],
                                                    row[17], row[18])
                customer_contact2.position = row[19]
                customer_contact2.email = row[21]
                customer_contact2.mobile = row[20]
                customer_contact2.save()

        import json
        customer_contents = json.dumps(customer_map)
        f = open('/tmp/customer_map.json', 'w')
        f.write(customer_contents)
        f.close()

        print("Creating Users...")
        with open(os.path.join(migration_csvs, 'users.csv'),
                  'r',
                  encoding='latin1') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                if not row[3].strip() in partner_map.keys():
                    print("Cannot find partner for user: "******"Found Redington user: {}, Please create manually",
                          row[3])
                    continue

                user = RedUser()
                user.username = row[3]
                user.first_name = row[4]
                user.last_name = row[5]
                user.email = row[6]
                user.is_active = True
                user.is_staff = False
                user.save()

                permission_group_name = AppDefaults.get_predefined_roles()

                if Group.objects.filter(
                        name=permission_group_name['Partner']).exists():
                    user.groups = Group.objects.filter(
                        name=permission_group_name['Partner'])
                    user.save()

                PartnerUserDetails.objects.create(
                    user=user,
                    partner=Partner.objects.get(
                        pk=partner_map[row[3].strip()]))

                UserProfile.objects.create(
                    user=user,
                    user_type='P',
                    description=str.format('Partner user for {}', row[3]),
                    created_by=RedUser.objects.get(username='******'),
                    role_id=2)
Exemplo n.º 3
0
    def handle(self, *args, **options):
        migration_csvs = os.path.join(settings.BASE_DIR, 'migrations')

        existing_azure_accounts = os.path.join(migration_csvs,
                                               'existing_azure_accounts.csv')
        customers = json.load(open('/tmp/customer_map.json', 'r'))

        m = MicrosoftBase()
        headers = m.getAccessHeaders()

        with open(existing_azure_accounts, 'r', encoding='latin1') as csvfile:
            for row in list(csv.reader(csvfile)):
                print("Processing: %s" % (row[5]))
                customer_id = row[13]
                reference_number = None
                if not customer_id:
                    # insert into customers, cloudaccounts
                    customer = Customers()
                    partner = Partner.objects.filter(jba_code=row[11].strip())
                    if not partner:
                        print("Cannot find partner: %s" % (row[11]))
                        continue
                    else:
                        partner = partner[0]

                    customer.partner = partner
                    customer.company_name = row[5]
                    customer.address = row[5]
                    customer.save()

                    customer_contact1 = CustomerContacts()
                    customer_contact1.customer = customer
                    customer_contact1.name = ''
                    customer_contact1.save()

                    customer_contact2 = CustomerContacts()
                    customer_contact2.customer = customer
                    customer_contact2.name = ''
                    customer_contact2.save()
                    customer_id = customer.id
                elif not customer_id in customers:
                    print("Cannot find customers: %s" % (customer_id))
                    continue
                else:
                    customer = Customers.objects.get(pk=customers[customer_id])

                partner = PartnerUserDetails.objects.filter(
                    partner=customer.partner)
                orders = Orders()
                if not row[14]:
                    orders.order_number = generate_order_number()
                else:
                    orders.order_number = row[14]
                orders.status = 6
                orders.customer = customer
                orders.partner = customer.partner
                orders.vendor = VendorDetails.objects.get(pk=3)
                orders.total_cost = 0
                orders.created_by = partner[0].user
                orders.created_at = datetime.datetime.now()
                orders.modified_by = partner[0].user
                orders.billing_type = 'annually'
                orders.billing_completed = 0
                orders.save()
                reference_number = orders.id

                order_items = OrderItems()
                order_items.order = orders
                order_items.product = Products.objects.get(
                    product_sku_code='MS-AZR-0145P')
                order_items.quantity = 1
                order_items.discount = 0
                order_items.price_per_unit = 0
                order_items.cost = 0
                order_items.created_by = partner[0].user
                order_items.created_at = datetime.datetime.now()
                order_items.modified_by = partner[0].user
                order_items.save()

                cloud_account = CloudAccounts.objects.filter(
                    customer=customer,
                    type='MS',
                    vendor=VendorDetails.objects.get(pk=3))
                if not cloud_account.exists():
                    cloud_account = CloudAccounts()
                    cloud_account.customer = customer
                    cloud_account.vendor = VendorDetails.objects.get(pk=3)
                    cloud_account.type = 'MS'
                    cloud_account.active = True
                    partner = PartnerUserDetails.objects.filter(
                        partner=customer.partner)
                    cloud_account.created_by = partner[0].user
                    cloud_account.created_at = datetime.datetime.now()
                    cloud_account.modified_by = partner[0].user
                    discount = 10

                    reference_number = orders.order_number
                    if row[8]:
                        discount = row[8]
                    cloud_account.details = {
                        'active': True,
                        'tenant_id': row[16],
                        'domain_name': row[17],
                        'discount_status': 'Approved',
                        'standard_discount': discount,
                        'allow_order': 'Yes',
                        'reference_number': reference_number
                    }
                    cloud_account.save()

                # Insert into Subscriptions
                url = str.format(
                    'https://api.partnercenter.microsoft.com/v1/customers/{}/subscriptions/{}',
                    row[16], row[15])

                subscriptions_out = requests.get(url, headers=headers)

                if subscriptions_out.status_code == 401:
                    # Reprocess
                    m = MicrosoftBase()
                    headers = m.getAccessHeaders()
                    subscriptions_out = requests.get(url, headers=headers)

                if subscriptions_out.status_code == 200:
                    subscriptions = json.loads(
                        codecs.decode(subscriptions_out.content, 'utf-8-sig'))

                    # Insert into Subscription
                    subscription = Subscriptions()
                    subscription.customer = customer
                    subscription.order = orders
                    subscription.product = Products.objects.get(
                        product_sku_code='MS-AZR-0145P')
                    subscription.subscription = subscriptions['id']
                    subscription.creation_date = parse_datetime(
                        subscriptions['creationDate'])
                    subscription.ms_order_id = subscriptions['orderId']
                    subscription.name = subscriptions['offerName']
                    subscription.quantity = subscriptions['quantity']
                    subscription.unit_type = subscriptions['unitType']
                    subscription.effective_start_date = parse_datetime(
                        subscriptions['effectiveStartDate'])
                    subscription.commitment_end_date = parse_datetime(
                        subscriptions['commitmentEndDate'])
                    subscription.auto_renew_enabled = subscriptions[
                        'autoRenewEnabled']
                    subscription.status = subscriptions['status']
                    subscription.is_trial = subscriptions['isTrial']
                    subscription.billing_type = subscriptions['billingType']
                    subscription.billing_cycle = subscriptions['billingCycle']
                    subscription.contract_type = subscriptions['contractType']
                    subscription.save()
Exemplo n.º 4
0
    def create(self, request, *args, **kwargs):
        data = request.data
        tenant_id = None
        is_valid_domain = None
        if 'logo' in request.FILES:
            logo = request.FILES['logo']
            customer_data = json.loads(data['data'])
        else:
            logo = None
            customer_data = json.loads(data['data'])

        # initial_partner_obj = InitialPartner.objects.filter(id=1)

        customer_obj = Customers()
        if logo != None:
            customer_obj.logo = logo

        if not request.user.is_superuser:
            if request.user.profile.user_type == 'P':
                customer_data['partner_id'] = request.user.partner.first(
                ).partner.id

        if 'cloud_account' in customer_data.keys():
            cloud_account = customer_data['cloud_account']
            if cloud_account['type'] == 'MS':
                domain = cloud_account['details']['domain_name']
                if domain and domain != '':
                    ms_api = MicrosoftApi()
                    domain_exist = ms_api.check_domain_exists(domain)
                    if not domain_exist:
                        return Response('Invalid_domain')
                    else:
                        customer_info = ms_api.get_customer_from_domain(domain)
                        if 'companyProfile' in customer_info:
                            tenant_id = customer_info['companyProfile'][
                                'tenantId']
                            is_valid_domain = True

        customer_obj.company_name = customer_data['company_name']
        customer_obj.address = customer_data['address']
        customer_obj.city = customer_data['city']
        customer_obj.state = customer_data['state']
        customer_obj.Pincode = customer_data['postcode']
        customer_obj.country = customer_data['country']
        customer_obj.pan_number = customer_data['pan_number']
        customer_obj.customer_vertical = customer_data['customer_vertical'][0][
            'id']
        customer_obj.delivery_sequence = customer_data['delivery_sequence']
        customer_obj.segment = customer_data['segment'][0]['id']
        if 'partner_id' in customer_data:
            partnerId = customer_data['partner_id']
            customer_obj.partner_id = partnerId
        customer_obj.save()

        try:
            # Inserting primary contact details of Customer
            self.saveContactDetails(customer_data['primary_contact'],
                                    customer_obj.id)
        except Exception:
            return Response(Exception)

        try:
            # Inserting secondary contact details of Customer
            self.saveContactDetails(customer_data['secondary_contact'],
                                    customer_obj.id)
        except Exception:
            return Response(Exception)
        """ Validating and Storing customer's cloud account requirements """
        if 'cloud_account' in customer_data.keys():
            try:
                cloud_account_data = customer_data['cloud_account']
                if tenant_id is not None:
                    cloud_account_data['details']['tenant_id'] = tenant_id
                    cloud_account_data['details']['active'] = is_valid_domain
                    if is_valid_domain:
                        cloud_account_data['active'] = True
                cloud_account_data['customer'] = customer_obj.id
                cloud_account_serializer = CloudAccountsSerializer(
                    data=cloud_account_data, context={'request': request})
                cloud_account_serializer.is_valid(raise_exception=True)
                cloud_account_serializer.save()
            except Exception:
                customer_obj.delete()
                return Response(Exception)

            if cloud_account['type'] == 'MS':
                domain = cloud_account_data['details']['domain_name']
                if tenant_id is None and domain != '':
                    data['customer'] = customer_obj.id
                    CloudAccountsViewSet.store_ms_domain(
                        data, domain, cloud_account_serializer.data['id'])

        return Response(customer_obj.id)