def send_sms_for_dues(request):
    today_weekday = (datetime.date.today().isoweekday() + 1) % 7
    # print(today_weekday)
    # , total_due__gt=0
    all_balance = BuyerSellerAccount.objects.filter(total_due__gt=0)
    for a in all_balance:
        seller_name = a.seller.name
        buyer_name = a.buyer.name
        due = a.total_due
        # print(seller_name)
        # print(buyer_name)
        sms_text = 'Dear %s, you have taka %s due to %s. Please pay the bills as soon as possible. ' \
                   'Thanks for shopping with Hishab Limited.' % (buyer_name, format(due,'.2f'), seller_name)
        print(a.buyer.phone)
        print(sms_text)


        send_sms(sms_text, a.buyer.phone)

    return HttpResponse('got_it', content_type="plain/text")
def send_sms_for_dues(request):
    today_weekday = (datetime.date.today().isoweekday() + 1) % 7
    # print(today_weekday)
    # , total_due__gt=0
    all_balance = BuyerSellerAccount.objects.filter(total_due__gt=0)
    for a in all_balance:
        seller_name = a.seller.name
        buyer_name = a.buyer.name
        due = a.total_due
        # print(seller_name)
        # print(buyer_name)
        sms_text = 'Dear %s, you have taka %s due to %s. Please pay the bills as soon as possible. ' \
                   'Thanks for shopping with Hishab Limited.' % (buyer_name, format(due,'.2f'), seller_name)

        # sms_text = 'Dear %s, Apnar %s taka baki ache %s er kache. Onugroho kore apnar bokea joto druto shomvob porishodh korun.' \
        #            'Hishab Lmd-er shathe kenakata korar jonno dhonnbad.' % (buyer_name, format(due,'.2f'), seller_name)

        print(a.buyer.phone)
        print(sms_text)


        send_sms(sms_text, a.buyer.phone)

    return HttpResponse('got_it', content_type="plain/text")
def get_sms(request):
    get_data = request.GET
    # print(get_data)
    # todo have to change the parameters of get data
    # sender_phone = get_data['From']
    # if sender_phone[0] == '+':
    #     sender_phone = sender_phone[1:]
    #     print(sender_phone)
    sms_body = get_data['Body']
    sms_body_into_array = sms_body.split(' ')
    sender_phone = sms_body_into_array[0]
    print(sender_phone)
    if len(sms_body_into_array) > 3:
        if sender_phone[0] == '+':
            sender_phone = sender_phone[1:]
            print(sender_phone)

        other_party_phone = sms_body_into_array[1]
        print(other_party_phone)
        if other_party_phone[0] == '+':
            other_party_phone = other_party_phone[1:]
            print(other_party_phone)
        amount = 0
        if is_number(sms_body_into_array[2]):
            amount = int(sms_body_into_array[2])
        elif is_float((sms_body_into_array[2])):
            amount = float(sms_body_into_array[2])
        if not Consumer.objects.filter(phone__endswith=sender_phone).exists():
            amount = 0
        if not Consumer.objects.filter(phone__endswith=other_party_phone).exists():
            amount = 0
        if amount > 0:
            if Consumer.objects.filter(phone__endswith=sender_phone).exists():
                sender_object = Consumer.objects.get(phone__endswith=sender_phone)
                if Consumer.objects.filter(phone__endswith=other_party_phone).exists():
                    other_party_object = Consumer.objects.get(phone__endswith=other_party_phone)
                else:
                    if Consumer.objects.filter(name='Unknown ' + sender_object.name).exists():
                        other_party_object = Consumer.objects.get(phone__endswith=other_party_phone)
                    else:
                        subscriber_type = ConsumerType.objects.get(type_name__exact='Buyer')
                        other_party_object = Consumer(name=('Unknown ' + sender_object.name),
                                                      type=subscriber_type,
                                                      phone='',
                                                      gender='None')
                        other_party_object.save()
                if sender_object.type.type_name == 'Buyer':
                    buyer_object = sender_object
                    seller_object = other_party_object
                else:
                    if other_party_object.type.type_name == 'Buyer':
                        buyer_object = other_party_object
                        seller_object = sender_object
                    else:
                        buyer_object = sender_object
                        seller_object = other_party_object
                if BuyerSellerAccount.objects.filter(seller=seller_object, buyer=buyer_object).exists():
                    balance = BuyerSellerAccount.objects.get(seller=seller_object, buyer=buyer_object)
                    # previousDue = balance.total_due
                    balance.total_paid += amount
                    remain_due = balance.total_due - amount
                    balance.total_due = remain_due
                    balance.last_paid_amount = amount
                    balance.save()
                else:
                    remain_due = 0
                    # previousDue = 0
                    balance = BuyerSellerAccount(seller=seller_object,
                                                 buyer=buyer_object,
                                                 total_amount_of_transaction=0,
                                                 total_paid=amount,
                                                 total_due=0,
                                                 last_paid_amount=amount)
                    balance.save()
                new_sms_payment = SMSPayment(buyer=buyer_object,
                                             seller=seller_object,
                                             amount=amount)
                new_sms_payment.save()

                transaction = dueTransaction(seller=seller_object,
                                             buyer=buyer_object,
                                             total_amount=0,
                                             total_paid=amount,
                                             total_due=0)
                transaction.save()
                sms_text = 'You have received taka %s from %s. The remaining due amount is taka %s. Thanks for shopping with Hishab Limited.' %(format(amount,'.2f'), buyer_object.name, format(remain_due, '.2f'))
                send_sms(sms_text, seller_object.phone)
                sms_text = 'You have paid taka %s due to %s. The remaining due amount is taka %s. Thanks for shopping with Hishab Limited.' %(format(amount,'.2f'), seller_object.name, format(remain_due, '.2f'))
                send_sms(sms_text, buyer_object.phone)
            return HttpResponse('got_it', content_type="plain/text")
        else:
            sender_object = Consumer.objects.get(phone__endswith=sender_phone)
            sms_text = 'You have entered wrong input. Please try again with correct information. Thanks for shopping with Hishab Limited.'
            send_sms(sms_text, sender_object.phone)
def save_registration_voice(request):
    file_data = request.FILES
    get_data = request.GET
    print(get_data)
    print(file_data)
    if 'level' in get_data:
        if get_data['level'] == '1':
            phone = get_data['session.callerid']
            caller_type = get_data['caller_type']
            # print('upto here')
            # print(get_data)
            if 'session.calledid' in get_data:
                calledNumber = get_data['session.calledid']
                # print(calledNumber[-4:])
                if calledNumber[-4:] == '0010':
                    phone = '880' + phone[-10:]
                    # print('bangladesh')
                elif calledNumber[-4:] == '4436':
                    # print('singapore')
                    phone = '65' + phone[-8:]
            tracking_id = get_data['tracking_id']
            # print(phone)
            # now = ''.join(x for x in str(datetime.datetime.now()) if x.isdigit())
            # tracking_id += now[2:14]
            new_voice_reg = VoiceReg(caller=phone,
                                     caller_type=caller_type,
                                     tracking_id=tracking_id)
            new_voice_reg.save()
            if get_data['caller_type'] == 'Shop' or get_data['caller_type'] == 'Distributor':
                shop = True
            else:
                shop = False
            print(tracking_id)
            send_sms('There is a new registration. Please transcribe!', '8801753248170')
            return render(request, 'IVR/registration_2.xml', {'shop': shop, 'tracking_id': tracking_id},  content_type='application/xml')
        elif get_data['level'] == '2':
            print("here")
            tracking_id = get_data['tracking_id']
            new_voice_reg = VoiceReg.objects.get(tracking_id=tracking_id)
            new_voice_reg.registration_voice_name = file_data['rec2']
            new_voice_reg.save()
            # new_voice_regname = new_voice_reg.registration_voice_name
            # print(new_voice_regname)
            tempname = str(new_voice_reg.registration_voice_name)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            if new_voice_reg.caller_type == 'Shop' or new_voice_reg.caller_type == 'Distributor':
                shop = True
            else:
                shop = False

            return render(request, 'IVR/registration_3.xml', {'tracking_id': tracking_id, 'shop': shop},  content_type='application/xml')
        elif get_data['level'] == '3':
            tracking_id = get_data['tracking_id']
            new_voice_reg = VoiceReg.objects.get(tracking_id=tracking_id)
            new_voice_reg.registration_voice_address = file_data['rec3']
            new_voice_reg.save()
            tempname = str(new_voice_reg.registration_voice_address)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            if new_voice_reg.caller_type == 'Shop' or new_voice_reg.caller_type == 'Distributor':
                return render(request, 'IVR/registration_5.xml', {'tracking_id': tracking_id},  content_type='application/xml')
            else:
                return render(request, 'IVR/registration_4.xml', {'tracking_id': tracking_id},  content_type='application/xml')
        elif get_data['level'] == '4':
            tracking_id = get_data['tracking_id']
            new_voice_reg = VoiceReg.objects.get(tracking_id=tracking_id)
            new_voice_reg.registration_voice_age = file_data['rec4']
            new_voice_reg.save()
            tempname = str(new_voice_reg.registration_voice_age)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            return render(request, 'IVR/registration_5.xml', {'tracking_id': tracking_id},  content_type='application/xml')
        elif get_data['level'] == '5':
            tracking_id = get_data['tracking_id']
            new_voice_reg = VoiceReg.objects.get(tracking_id=tracking_id)
            new_voice_reg.registration_voice_intro = file_data['rec5']
            new_voice_reg.save()
            tempname = str(new_voice_reg.registration_voice_intro)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            return render(request, 'IVR/end.xml', content_type='application/xml')
    else:
        return render(request, 'IVR/end.xml', content_type='application/xml')
def save_record_voice(request):
    file_data = request.FILES
    get_data = request.GET
    print request.GET
    print request.FILES
    if 'session.callerid' in get_data:
        phone = get_data['session.callerid'][3:]
    else:
        phone = 'unknown'
    if 'tid' in get_data:
        tracking_id = get_data['tid']
    else:
        tracking_id = '0000'
    tempname=''

    if get_data['level'] == '1':
        if get_data['part'] == '1':
            # tracking_id = phone[-4:]

            now = ''.join(x for x in str(datetime.datetime.now()) if x.isdigit())
            tracking_id = tracking_id
            caller_object = Consumer.objects.get(phone__endswith=phone)
            # save_record = None
            save_record = VoiceRecord(caller=caller_object,
                                      level1_voice_part1=file_data['rec1'],
                                      call_tracking_id=tracking_id,
                                      purpose=caller_object.type.type_name,
                                      level=get_data['level'])
            save_record.save()
            tempname = str(save_record.level1_voice_part1)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            print(filename)
            print(filenamenew)
            send_sms('There is a new transaction. Please transcribe!', '8801753248170')
            # if get_data['purpose'] == 'Sell':
            #     sell = True
            # else:
            #     sell = False
            return render(request, 'IVR/level1_part2.xml',
                          {'caller': phone,   'tid': tracking_id},
                          content_type='application/xml')

        elif get_data['part'] == '2':
            save_record = VoiceRecord.objects.get(call_tracking_id__exact=tracking_id)
            save_record.level1_voice_part2 = file_data['rec2']
            save_record.save()
            tempname = str(save_record.level1_voice_part2)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            # if get_data['purpose'] == 'Sell':
            #     sell = True
            # else:
            #     sell = False
            return render(request, 'IVR/level1_part3.xml',
                          {'caller': phone,  'tid': tracking_id},
                          content_type='application/xml')
        elif get_data['part'] == '3':
            save_record = VoiceRecord.objects.get(call_tracking_id__exact=tracking_id)
            save_record.level1_voice_part3 = file_data['rec3']
            save_record.save()
            tempname = str(save_record.level1_voice_part3)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            return render(request, 'IVR/end.xml', content_type='application/xml')
    elif get_data['level'] == '2':
        if get_data['part'] == '1':

            tracking_id = phone[-4:]
            now = ''.join(x for x in str(datetime.datetime.now()) if x.isdigit())
            tracking_id += now[2:14]
            caller_object = Consumer.objects.get(phone__endswith=phone)
            save_record = VoiceRecord(caller=caller_object,
                                      level1_voice_part1=file_data['rec41'],
                                      call_tracking_id=tracking_id,
                                      purpose=get_data['purpose'],
                                      level=get_data['level'])
            save_record.save()
            tempname = str(save_record.level1_voice_part1)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            if get_data['purpose'] == 'Sell':
                sell = True
            else:
                sell = False
            return render(request, 'IVR/level2p2.xml',
                          {'caller': phone, 'purpose': get_data['purpose'], 'sell': sell, 'tid': tracking_id},
                          content_type='application/xml')

        elif get_data['part'] == '2':
            save_record = VoiceRecord.objects.get(call_tracking_id__exact=tracking_id)
            save_record.level1_voice_part2 = file_data['rec42']
            save_record.save()
            tempname = str(save_record.level1_voice_part2)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            if get_data['purpose'] == 'Sell':
                sell = True
            else:
                sell = False
            return render(request, 'IVR/level2p3.xml',
                          {'caller': phone, 'purpose': get_data['purpose'], 'sell': sell, 'tid': tracking_id},
                          content_type='application/xml')
        elif get_data['part'] == '3':
            save_record = VoiceRecord.objects.get(call_tracking_id__exact=tracking_id)
            save_record.level1_voice_part3 = file_data['rec43']
            save_record.save()
            tempname = str(save_record.level1_voice_part3)
            filename = '/home/exor/web/static/media/' + tempname
            filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
            # shutil.copy2(filename, filenamenew)
            return render(request, 'IVR/end.xml', content_type='application/xml')
    elif get_data['level'] == '3':
        # tracking_id = phone[-4:]
        now = ''.join(x for x in str(datetime.datetime.now()) if x.isdigit())
        tracking_id = tracking_id
        caller_object = Consumer.objects.get(phone__endswith=phone)
        save_record = VoiceRecord(caller=caller_object,
                                  level3=file_data['rec5'],
                                  level1_voice_part1=file_data['rec5'],
                                  call_tracking_id=tracking_id,
                                  purpose=caller_object.type.type_name,
                                  level=get_data['level'])
        save_record.save()
        tempname = str(save_record.level3)
        filename = '/home/exor/web/static/media/' + tempname
        filenamenew = '/home/exor/web/static/media/' + tempname[:-3] + 'wav'
        # shutil.copy2(filename, filenamenew)
        send_sms('There is a new transaction. Please transcribe!', '8801753248170')
        return render(request, 'IVR/end.xml', content_type='application/xml')
    else:
        return render(request, 'IVR/base.xml', content_type='application/xml')
def add_transaction(request):
    post_data = request.POST
    print(post_data)
    response = 'not_ok'
    if 'csrfmiddlewaretoken' in post_data:
        if 'call_id' in post_data and 'caller_id' in post_data and 'otherParty' in post_data:
            call_id = post_data['call_id']
            call_object = VoiceRecord.objects.get(pk=call_id)
            caller_id = post_data['caller_id']
            caller_object = Consumer.objects.get(pk=caller_id)
            other_party = post_data['otherParty']
            if post_data['distributorTransaction'] == '0':
                if other_party == '0':
                    if Consumer.objects.filter(name=('Unknown ' + caller_object.name)).exists():
                        other_party_object = Consumer.objects.get(name=('Unknown' + caller_object.name))
                    else:
                        subscriber_type = ConsumerType.objects.get(type_name__exact='Buyer')
                        other_party_object = Consumer(name=('Unknown ' + caller_object.name),
                                                      type=subscriber_type,
                                                      phone='',
                                                      gender='None')
                        other_party_object.save()

                elif is_number(other_party) and not other_party == '0':
                    other_party_object = Consumer.objects.get(pk=other_party)
                else:
                    if Consumer.objects.filter(name=('Unknown' + caller_object.name)).exists():
                        other_party_object = Consumer.objects.get(name=('Unknown' + caller_object.name))
                    else:
                        subscriber_type = ConsumerType.objects.get(type_name__exact='Buyer')
                        other_party_object = Consumer(name=('Unknown' + caller_object.name),
                                                      type=subscriber_type,
                                                      phone='',
                                                      gender='None')
                        other_party_object.save()

            else:
                if Consumer.objects.filter(name=('Distributor' + caller_object.name)).exists():
                    other_party_object = Consumer.objects.get(name=('Distributor' + caller_object.name))
                else:
                    subscriber_type = ConsumerType.objects.get(type_name__exact='Distributor')
                    other_party_object = Consumer(name=('Distributor' + caller_object.name),
                                                  type=subscriber_type,
                                                  phone='',
                                                  gender='None')
                    other_party_object.save()

            if caller_object.type.type_name == 'Buyer':
                buyer_object = caller_object
                seller_object = other_party_object
            elif caller_object.type.type_name == 'Distributor' or caller_object.type.type_name == 'SR':
                buyer_object = other_party_object
                seller_object = caller_object
            else:
                if other_party_object.type.type_name == 'Buyer':
                    buyer_object = other_party_object
                    seller_object = caller_object
                elif other_party_object.type.type_name == 'Distributor' or other_party_object.type.type_name == 'SR':
                    buyer_object = caller_object
                    seller_object = other_party_object
                else:
                    buyer_object = caller_object
                    seller_object = other_party_object
            # balance Update done here
            if BuyerSellerAccount.objects.filter(seller=seller_object, buyer=buyer_object).exists():
                balance = BuyerSellerAccount.objects.get(seller=seller_object, buyer=buyer_object)
                balance.total_amount_of_transaction += float(post_data['transactionTotal'])
                balance.total_paid += float(post_data['transactionPaid'])
                balance.total_due += float(post_data['transactionDue'])
                balance.last_paid_amount = float(post_data['transactionPaid'])
                balance.save()
            else:
                balance = BuyerSellerAccount(seller=seller_object,
                                             buyer=buyer_object,
                                             total_amount_of_transaction=float(post_data['transactionTotal']),
                                             total_paid=float(post_data['transactionPaid']),
                                             total_due=float(post_data['transactionDue']),
                                             last_paid_amount=float(post_data['transactionPaid']))
                balance.save()
            # transaction added here
            transcriber = request.session['user']
            if Transcriber.objects.filter(name=transcriber).exists():
                transcriber_object = Transcriber.objects.get(name=transcriber)
            else:
                transcriber_object = Transcriber(name=transcriber)
                transcriber_object.save()

            transaction = Transaction(seller=seller_object,
                                      buyer=buyer_object,
                                      total_amount=float(post_data['transactionTotal']),
                                      total_paid=float(post_data['transactionPaid']),
                                      total_due=float(post_data['transactionDue']),
                                      transcriber=transcriber_object,
                                      callID=call_object)
            transaction.save()
            tr = transaction.id
            print(transaction.id)
            # product transaction added here
            product_string = post_data['transactionProducts']
            product_string = product_string.strip(';')
            product_array = product_string.split(';')
            # this section covers fraud detection

            if float(post_data['transactionDue']) > 0:
                if buyer_object.type.type_name == 'Buyer':
                    if BuyerSellerAccount.objects.filter(buyer=buyer_object).exists():
                        fraud = False
                        for transaction in BuyerSellerAccount.objects.filter(buyer=buyer_object):
                            if transaction.total_due > 200 and not transaction.seller == seller_object:
                                fraud = True
                                break
                        if fraud:
                            fraud_text = '%s has more than taka 200.00 due already in other shop.' \
                                         'Be careful while trading with this person. Thanks for shopping with Hishab Limited' % buyer_object.name
                            print(fraud_text)
                            phone_number_to_send_sms = seller_object.phone
                            send_sms(fraud_text, phone_number_to_send_sms)
            count = 0
            # finding the shop and transaction with buyer or distributor
            is_shop = False
            if buyer_object.type.type_name == 'Seller':
                is_shop = True
                shop = buyer_object
                transaction_with = seller_object.type.type_name
            elif seller_object.type.type_name == 'Seller':
                is_shop = True
                shop = seller_object
                transaction_with = buyer_object.type.type_name
            number_of_products = len(product_array)

            sms_text_products = ''
            while count < len(product_array):
                new_product = product_array[count]
                product_breakdown = new_product.split('-')
                product_name = product_breakdown[0]
                product_object = Product.objects.get(name=product_name)
                product_quantity = product_breakdown[1]
                product_price = float(product_breakdown[2])
                # sms_text_products = product_name + ' ' +
                if is_shop:
                    if Inventory.objects.filter(shop=shop, product=product_object).exists():
                        inventory = Inventory.objects.get(shop=shop, product=product_object)
                        if transaction_with == 'Buyer':
                            inventory.left -= float(product_quantity)
                            inventory.save()
                        elif transaction_with == 'Distributor' or transaction_with == 'SR':
                            inventory.left += float(product_quantity)
                            inventory.save()
                    else:
                        if transaction_with == 'Buyer':
                            left = 0
                            inventory = Inventory(shop=shop,
                                                  product=product_object,
                                                  unit=product_object.retail_unit,
                                                  left=left)
                            inventory.save()
                        elif transaction_with == 'Distributor' or transaction_with == 'SR':
                            left = float(product_quantity)
                            inventory = Inventory(shop=shop,
                                                  product=product_object,
                                                  unit=product_object.retail_unit,
                                                  left=left)
                            inventory.save()
                    # list of sold product is added here
                    if ProductInventory.objects.filter(product=product_object).exists():
                        pro_inventory = ProductInventory.objects.get(product=product_object)
                        if transaction_with == 'Buyer':
                            pro_inventory.sold += float(product_quantity)
                        elif transaction_with == 'Distributor' or transaction_with == 'SR':
                            pro_inventory.sold += float(product_quantity)
                        pro_inventory.save()
                    else:
                        if transaction_with == 'Buyer':
                            sold = float(product_quantity)
                        elif transaction_with == 'Distributor' or transaction_with == 'SR':
                            sold = float(product_quantity)
                        pro_inventory = ProductInventory(product=product_object,
                                                         unit=product_object.retail_unit,
                                                         sold=sold)
                        pro_inventory.save()
                    # list of profit per shop in per product

                    if transaction_with == 'Buyer':
                        if ProductBuySellProfitInventory.objects.filter(product=product_object).exists():
                            buying_price_for_this_transaction = ProductBuySellProfitInventory.objects.get(product=product_object).buying_price
                        else:
                            new_added = ProductBuySellProfitInventory(product=product_object)
                            new_added.save()
                            buying_price_for_this_transaction = new_added.buying_price

                        profit_of_this_product = product_price - buying_price_for_this_transaction
                        new_transcriber_transcription_for_this_product = BuySellProfitInventoryIndividual(shop=shop,
                                                                                                          product=product_object,
                                                                                                          unit=product_object.retail_unit,
                                                                                                          buying_price=buying_price_for_this_transaction,
                                                                                                          selling_price=product_price, profit=profit_of_this_product)
                        new_transcriber_transcription_for_this_product.save()

                    if BuySellProfitInventory.objects.filter(shop=shop, product=product_object).exists():
                        buy_sell_profit = BuySellProfitInventory.objects.get(shop=shop, product=product_object)
                        if transaction_with == 'Buyer':
                            if buy_sell_profit.selling_price == 0:
                                buy_sell_profit.selling_price = product_price
                            else:
                                buy_sell_profit.selling_price = (buy_sell_profit.selling_price + product_price) / 2
                        elif transaction_with == 'Distributor' or transaction_with == 'SR':
                            if buy_sell_profit.buying_price == 0:
                                buy_sell_profit.buying_price = (product_price)
                            else:
                                buy_sell_profit.buying_price = ((buy_sell_profit.buying_price +
                                                                 (product_price)) / 2)
                        buy_sell_profit.profit = buy_sell_profit.selling_price - buy_sell_profit.buying_price
                        buy_sell_profit.save()
                    else:
                        if transaction_with == 'Buyer':
                            buy_sell_profit = BuySellProfitInventory(shop=shop,
                                                                     product=product_object,
                                                                     unit=product_object.retail_unit,
                                                                     selling_price=product_price)
                        elif transaction_with == 'Distributor' or transaction_with == 'SR':
                            buy_sell_profit = BuySellProfitInventory(shop=shop,
                                                                     product=product_object,
                                                                     unit=product_object.retail_unit,
                                                                     buying_price=(product_price))
                        buy_sell_profit.profit = buy_sell_profit.selling_price - buy_sell_profit.buying_price
                        buy_sell_profit.save()

                    # list of profit per product

                    if ProductBuySellProfitInventory.objects.filter(product=product_object).exists():
                        product_buy_sell_profit = ProductBuySellProfitInventory.objects.get(product=product_object)
                        if transaction_with == 'Buyer':
                            if product_buy_sell_profit.selling_price == 0:
                                product_buy_sell_profit.selling_price = product_price
                            else:
                                product_buy_sell_profit.selling_price = (product_buy_sell_profit.selling_price + product_price) / 2
                            product_buy_sell_profit.total_sold += float(product_quantity)
                        elif transaction_with == 'Distributor' or transaction_with == 'SR':
                            if product_buy_sell_profit.buying_price == 0:
                                product_buy_sell_profit.buying_price = (product_price)
                            else:
                                product_buy_sell_profit.buying_price = ((product_buy_sell_profit.buying_price +
                                                                         (product_price)) / 2)
                        product_buy_sell_profit.profit = product_buy_sell_profit.selling_price - product_buy_sell_profit.buying_price
                        product_buy_sell_profit.q_profit = product_buy_sell_profit.profit * product_buy_sell_profit.total_sold
                        product_buy_sell_profit.save()
                    else:
                        if transaction_with == 'Buyer':
                            product_buy_sell_profit = ProductBuySellProfitInventory(product=product_object,
                                                                                    unit=product_object.retail_unit,
                                                                                    selling_price=product_price,
                                                                                    total_sold=float(product_quantity))
                        elif transaction_with == 'Distributor' or transaction_with == 'SR':
                            product_buy_sell_profit = ProductBuySellProfitInventory(product=product_object,
                                                                                    unit=product_object.retail_unit,
                                                                                    buying_price=(product_price))
                        profit_here = product_buy_sell_profit.selling_price - product_buy_sell_profit.buying_price
                        product_buy_sell_profit.profit = profit_here
                        product_buy_sell_profit.q_profit = profit_here * product_buy_sell_profit.total_sold
                        product_buy_sell_profit.save()

                if buyer_object.type.type_name == 'Distributor' or seller_object.type.type_name == 'Distributor' or buyer_object.type.type_name == 'SR' or seller_object.type.type_name == 'SR':
                    product_unit = product_object.retail_unit
                else:
                    product_unit = product_object.retail_unit
                # product_quantity = float(product_quantity)
                print(product_object)
                print(product_unit)
                print(product_price)
                print(product_quantity)
                if float(product_quantity)>0:
                    sms_text_products += product_name + ' ' + str(round(float(product_quantity),2)) + ' ' + product_unit + ' price: taka ' + str(format((float(product_price)*float(product_quantity)),'.2f')) + ','
                    print(sms_text_products)
                else:
                    sms_text_products += ''
                # transaction =
                tr_object = Transaction.objects.get(pk=tr)
                product_transaction = ProductsInTransaction(TID=tr_object,
                                                            product=product_object,
                                                            unit=product_unit,
                                                            price_per_unit=product_price,
                                                            quantity=product_quantity)

                product_transaction.save()
                count += 1
            sms_text_products = sms_text_products[:-1]
            sms_text_seller = seller_object.name
            sms_text_buyer = buyer_object.name
            sms_text_id = tr
            date = datetime.date.today()
            sms_total_bill = post_data['transactionTotal']
            sms_total_paid = post_data['transactionPaid']
            sms_total_due = post_data['transactionDue']
            buyer_sms = '%s, you have purchased %s ' \
                        'from %s.' \
                        ' Total bill : taka %s, Paid : taka %s, Due : taka %s.' \
                        ' Thanks for shopping with Hishab Limited ' % (sms_text_buyer,
                                                                       sms_text_products, sms_text_seller,
                                                                       format(float(sms_total_bill),'.2f'),
                                                                       format(float(sms_total_bill)-float(sms_total_due),'.2f'),
                                                                       format(float(sms_total_due),'.2f'))
            seller_sms = '%s, you have sold %s ' \
                         'to %s.' \
                         ' Total bill : taka %s, Paid : taka %s,Due : taka %s.' \
                         ' Thanks for shopping with Hishab Limited ' % (sms_text_seller,
                                                                        sms_text_products, sms_text_buyer,
                                                                        format(float(sms_total_bill),'.2f'),
                                                                        format(float(sms_total_bill)-float(sms_total_due),'.2f'),
                                                                        format(float(sms_total_due),'.2f'))
            # caller scoring update !
            send_sms(buyer_sms, buyer_object.phone)
            send_sms(seller_sms, seller_object.phone)
            caller_object.total_successful_call += 1
            caller_object.save()
            call_object.transcribed = True
            call_object.save()
            # add transcriber info here
            transcriber = request.session['user']
            if Transcriber.objects.filter(name=transcriber).exists():
                transcriber_object = Transcriber.objects.get(name=transcriber)
            else:
                transcriber_object = Transcriber(name=transcriber)
                transcriber_object.save()
            new_transcriber_transcription = TranscriberInTranscription(name=transcriber_object,
                                                                       callID=call_object,
                                                                       number_of_products=number_of_products,
                                                                       time_taken=post_data['timetaken'])
            new_transcriber_transcription.save()

            response = 'ok'

    return HttpResponse(response)
def add_subscriber(request):
    post_data = request.POST
    print(post_data)
    if 'csrfmiddlewaretoken' in post_data:
        name = post_data['name']
        phone = post_data['phone']
        add_notification = True
        if is_bangladeshi_number(phone) or is_japanese_number(phone):
            if Consumer.objects.filter(name__exact=name).exists():
                notification = 'This name ' + name + ' is already taken'
            else:
                if Consumer.objects.filter(phone__exact=phone).exists():
                    notification = 'This number ' + phone + ' is already taken'
                else:
                    child = 0
                    if 'child' in post_data:

                        child = post_data['child']
                    gender = 'None'
                    if 'gender' in post_data:
                        if not post_data['gender'] == 'Not Defined':
                            gender = post_data['gender']
                    age = 0
                    if 'age' in post_data:
                        if is_number(post_data['age']):
                            age = int(post_data['age'])
                        if is_float(post_data['age']):
                            age = float(post_data['age'])
                    married = False
                    if 'married' in post_data:
                        if post_data['married'] == 'Married':
                            married = True
                    address = ''
                    if 'address' in post_data:
                        address = post_data['address']
                    subscriber_type = ConsumerType.objects.get(type_name__exact='SR')
                    if 'type' in post_data:
                        subscriber_type = ConsumerType.objects.get(type_name__exact=post_data['type'])

                    email = ''
                    if 'email' in post_data:
                        email = post_data['email']

                    new_consumer = Consumer(name=name,
                                            type=subscriber_type,
                                            phone=phone,
                                            address=address,
                                            email=email,
                                            number_of_child=child,
                                            gender=gender,
                                            age=age,
                                            married=married)
                    new_consumer.save()
                    print(phone[-9:])
                    print(post_data['child'])
                    user = User.objects.create_user(phone[-9:], phone[-9:]+'@sense.ai',
                                                    post_data['child'])
                    user.save()
                    transcriber_name = request.session['user']
                    if ACL.objects.filter(loginID=transcriber_name).exists():
                        login_user = ACL.objects.get(loginID=transcriber_name)
                        if login_user.loginUser.type.type_name == 'Distributor':
                            add_new_subscriber = ACL(loginUser=new_consumer,
                                                     distUser=login_user.loginUser,
                                                     loginID=phone[-9:])
                            add_new_subscriber.save()
                    else:
                        add_new_subscriber = ACL(loginUser=new_consumer,
                                                 loginID=phone[-9:])
                        add_new_subscriber.save()
                    notification = 'Transcriber Successfully Added.'
                    # add_to_transcriber = Transcriber(name=post_data['username'])
                    # add_to_transcriber.save()
                    welcome_sms = 'Thanks for connecting with hishab Limited. Use %s as username and %s as password while logging in to app.hishab.co . For more info go to www.hishab.co .' % (phone, child)
                    send_sms(welcome_sms, phone)
                    notification = 'New User ' + name + ' was added successfully'
        else:
            notification = 'Invalid Phone Number : ' + phone
    else:
        add_notification = False
        notification = ''
    all_subscriber = Consumer.objects.all()
    type_of_subscriber = ConsumerType.objects.all()
    transcriber_name = request.session['user']
    shop_consumer = ConsumerType.objects.get(type_name='Seller')
    all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
    all_user_for_base = Consumer.objects.all()
    shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
    all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
    res = render(request, 'pages/add_subscriber.html', {'subscribers': all_subscriber, 'types': type_of_subscriber,
                                                        'notification': notification,
                                                        'shop_list_base': all_shop_for_base,
                                                        'all_consumer_for_base' :all_consumer_for_base,
                                                        'all_user_for_base': all_user_for_base,
                                                        'transcriber_name': transcriber_name,
                                                        'add_notification': add_notification})

    res['Access-Control-Allow-Origin'] = "*"
    res['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept"
    res['Access-Control-Allow-Methods'] = "PUT, GET, POST, DELETE, OPTIONS"

    return res
def add_subscriber_outside(request):
    print('here')
    post_data = request.POST
    print(post_data)
    name = post_data['name']
    phone = post_data['phone']
    if phone[0] == ' ':
        phone = phone[1:]
    # # todo error handeling in jS with error text

    add_notification = True

    if Consumer.objects.filter(name__exact=name).exists():
        notification = 'This name ' + name + ' is already taken'
        res = HttpResponse('error')
    else:
        if Consumer.objects.filter(phone__exact=phone).exists():
            notification = 'This number ' + phone + ' is already taken'
            res = HttpResponse('error')
        else:
            child = 0
            if 'child' in post_data:
               child = post_data['child']
            gender = 'None'
            if 'gender' in post_data:
                if not post_data['gender'] == 'Not Defined':
                    gender = post_data['gender']
            age = 0
            if 'age' in post_data:
                if is_number(post_data['age']):
                    age = int(post_data['age'])
                if is_float(post_data['age']):
                    age = float(post_data['age'])
            married = False
            if 'married' in post_data:
                if post_data['married'] == 'Married':
                    married = True
            address = ''
            if 'address' in post_data:
                address = post_data['address']
            subscriber_type = ConsumerType.objects.get(type_name__exact='Buyer')
            if 'type' in post_data:
                subscriber_type = ConsumerType.objects.get(type_name__exact=post_data['type'])
            email = ''
            if 'email' in post_data:
                email = post_data['email']

            new_consumer = Consumer(name=name,
                                    type=subscriber_type,
                                    phone=phone,
                                    address=address,
                                    email=email,
                                    number_of_child=child,
                                    gender=gender,
                                    age=age,
                                    married=married)
            new_consumer.save()
            print(phone[-9:])
            print(post_data['child'])
            user = User.objects.create_user(phone[-9:], phone[-9:]+'@sense.ai',
                                            post_data['child'])
            user.save()
            add_new_subscriber = ACL(loginUser=new_consumer,
                                     loginID=phone[-9:])
            add_new_subscriber.save()
            welcome_sms = 'Thanks for connecting with hishab Limited. Use %s as username and %s as password while logging in to app.hishab.co . For more info go to www.hishab.co .' % (phone, child)
            if 'record_id' in post_data:
                if not post_data['record_id'] == '':
                    call_record = VoiceReg.objects.get(pk=post_data['record_id'])
                    call_record.completed = True
                    call_record.save()
            if 'introduced_by' in post_data:
                if not post_data['introduced_by'] == '':
                    introduced_by = post_data['introduced_by']
                    introduced_by_object = Consumer.objects.get(pk=int(introduced_by))
                    new_dependency = Connectivity(user=new_consumer, introduced_by=introduced_by_object)
                    new_dependency.save()
            notification = 'New User ' + name + ' was added successfully'
            # welcome_sms = 'Thanks for connecting with Hishab Limited. For more info go to www.hishab.co .'
            send_sms(welcome_sms, phone)
            res = HttpResponse(new_consumer.id)



    all_subscriber = Consumer.objects.all()
    type_of_subscriber = ConsumerType.objects.all()
    shop_consumer = ConsumerType.objects.get(type_name='Seller')
    all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
    all_user_for_base = Consumer.objects.all()

    res['Access-Control-Allow-Origin'] = "*"
    res['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept"
    res['Access-Control-Allow-Methods'] = "PUT, GET, POST, DELETE, OPTIONS"
    return res