Пример #1
0
class YourTestClass(TestCase):
    def setUp(self):
        self.stock = Stock(stock_name='testStock', stock_price=2, stock_sold=0)
        self.stock.save()
        self.shareQuantity = 5

        self.user = User(username='******', password='******')
        self.user.save()
        self.user = User.objects.get(username='******')
        self.userund = UserFund(user=self.user, fund=1000)

        Trading_Account.objects.create(user_id=self.user,
                                       trading_name='testTrade')
        self.trading = Trading_Account.objects.get(user_id=self.user)

    def testBuyShareOnFunds(self):
        self.user.userfund.fund -= self.stock.stock_price * self.shareQuantity
        self.assertTrue(self.user.userfund.fund, 10)

    def testBuySharesOnSharesAmount(self):
        shares = Shares(shares_amount=10)
        self.stock.stock_sold -= self.shareQuantity
        self.assertTrue(self.stock.stock_sold, 5)

    def testSellSharesOnStockSold(self):
        self.stock.stock_sold += self.shareQuantity
        self.assertTrue(self.stock.stock_sold, 5)

    def testSellSharesOnSharesAmount(self):
        shares = Shares(shares_amount=self.shareQuantity)
        self.stock.stock_sold += shares.shares_amount
        self.assertTrue(self.stock.stock_sold, 5)
Пример #2
0
def stock_enter(request):
    """

    Function to read the CSV files and enter the data to the database. The csv module is used for this purpose.
    The 'resources' folder is scanned for the CSV files. All the files found from there are listed in the terminal, and they are read and stored one by one.

    :return: HttpResponse containing a message saying either all entries have been added, or no CSV files found in the resources folder to add

    """
    mypath = join(os.getcwd(), 'stock/resources')  # path to the 'resources' folder
    print '\nLooking for .CSV files in %s' % mypath
    files = [ f for f in listdir(mypath) if isfile(join(mypath,f)) and f.endswith('.CSV') ]  # list of CSV files found, if any
    if not files:  # no CSV files present in the resources folder
        return HttpResponse('No ".CSV" files are placed in the resources folder. Could not add data.')  # display error message
    else:  # CSV files found
        print '\nThe following %s .CSV files have been found in %s -' % (len(files), mypath)
        for count, f in enumerate(files):
            print 'File (%s/%s): %s' %(count + 1, len(files), f)
        stock_list = Stock.objects.all()
        for filename in files:  # iterating through the list of CSV filenames found
            # calculating the date by reading the filename (present in ddmmyy format by default)
            day, month, year = filename.split('.CSV')[0][2:4], filename.split('.CSV')[0][4:6], filename.split('.CSV')[0][6:]
            if len(year) == 2:
                year = '20' + year  # if year is of 2 digits, add '20' to its beginning
            print '\nEntering data from file (%s/%s) %s' % (files.index(filename) + 1, len(files), filename)
            with open(join(mypath, filename)) as csvfile:  # open the file
                spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')  # read the contents
                for count, row in enumerate(spamreader):
                    row_entry_list = ', '.join(row).split(', ')  # list of all the elements in the current row separated by comma
                    if count > 0:  # the current row is not the field-name row
                        # save the entry to database
                        q = Stock(SC_CODE = row_entry_list[0], SC_NAME = row_entry_list[1], SC_GROUP = row_entry_list[2], SC_TYPE = row_entry_list[3], OPEN = float(row_entry_list[4]), HIGH = float(row_entry_list[5]), LOW = float(row_entry_list[6]), CLOSE = float(row_entry_list[7]), LAST = float(row_entry_list[8]), PREVCLOSE = float(row_entry_list[9]), NO_TRADES = float(row_entry_list[10]), NO_OF_SHRS = float(row_entry_list[11]), NET_TURNOV = float(row_entry_list[12]), DATE = datetime.date(int(year), int(month), int(day)))
                        q.save()
                        print "Saving entry from file %s/%s with id %s, SC_NAME %s" % (files.index(filename) + 1, len(files), q.id, q.SC_NAME)
        return HttpResponse('All the entries have been successfully added. Call the "stock" method to view the current database.')
Пример #3
0
def register(request):
    stock = Stock.objects.filter(symbol=request.POST['symbol'])
    if not stock:
        stock = Stock(symbol=request.POST['symbol'], name=request.POST['name'])
        stock.save()
        subprocess.Popen(['java', '-jar', '/Users/shijieru/Desktop/updateDB.jar'])
    return HttpResponseRedirect(reverse('index'))
Пример #4
0
def register(request):
    stock = Stock.objects.filter(symbol=request.POST['symbol'])
    if not stock:
        stock = Stock(symbol=request.POST['symbol'], name=request.POST['name'])
        stock.save()
        subprocess.Popen(
            ['java', '-jar', '/Users/shijieru/Desktop/updateDB.jar'])
    return HttpResponseRedirect(reverse('index'))
Пример #5
0
def create_stock_data():
    stock_list = business()
    for stock in stock_list:
        new_stock = Stock()
        new_stock.business = stock['business']
        new_stock.code = stock['code']
        new_stock.title = stock['title']
        new_stock.graph_url()
        new_stock.stock_reset()
        new_stock.save()
Пример #6
0
 def get(self, request):
     stocks = ts.get_stock_basics()
     for code in stocks.index:
         print not Stock.objects.filter(code=code).exists()
         print Stock.objects.filter(code=code).exists()
         if not Stock.objects.filter(code=code).exists():
             stock = Stock()
             stock.code = code
             stock.save()
     return HttpResponse(json.dumps({"status": "success"}),
                         content_type="application/json")
Пример #7
0
 def new(self, barcode=""):
     if len(barcode) == 0:
         barcode = self.scan()
     if self.getProduit(barcode) == None:
         name = raw_input("Entrez le nom du produit: ")
         price = raw_input("Entrez le prix: ")
         quantity = raw_input("Entrez la quantité: ")
         p = Product(barcode=barcode, name=name, price=price)
         p.save()
         s = Stock(produit=p, quantite=quantity)
         s.save()
     else:
         p = Product.objects.get(barcode=barcode)
         name = raw_input("Entrez le nouveau nom du produit: ")
         price = raw_input("Entrez le nouveau prix: ")
         quantity = raw_input("Entrez la quantitée supplémentaire: ")
         p.name = name
         p.price = price
         p.save()
         s = Stock.objects.get(produit=p)
         s.quantite += int(quantity)
         s.save()
Пример #8
0
class BookStockOnPositionBase(ABC, LoginRequiredMixin, View):
    __metaclass__ = ABCMeta

    template_name = "rebook/book_stock_on_position.html"

    def __init__(self, **kwargs):
        self.position = None
        self.stock = None
        self.destination_stock = None
        self.form = None
        super().__init__(**kwargs)

    @abstractmethod
    def pre_dispatch(self):
        pass

    def dispatch(self, request, *args, **kwargs):
        self.pre_dispatch()
        self.position = self.request.GET.get("position", "") or ""
        self.form = self.get_form()

        if self.position == "":
            return render(request, self.template_name, self.get_context())

        if self.form.is_valid() is True:
            self.rebook_stock_to_destination()
        else:
            return render(request, self.template_name, self.get_context())
        return super().dispatch(request, *args, **kwargs)

    def rebook_stock_to_destination(self):
        rebook_amount = self.form.cleaned_data.get("amount")

        self.destination_stock = Stock.objects.filter(
            lagerplatz=self.position, sku_instance=self.stock.sku_instance)

        if self.destination_stock.count() > 0:
            self.destination_stock = self.destination_stock.first()
        else:
            self.destination_stock = None

        if self.destination_stock is None:
            self.destination_stock = Stock(
                lagerplatz=self.position,
                sku_instance=self.stock.sku_instance,
                sku=self.stock.sku_instance.sku)

        if self.destination_stock is not None:
            if self.destination_stock.bestand is None:
                self.destination_stock.bestand = rebook_amount
            else:
                self.destination_stock.bestand += rebook_amount

        self.destination_stock.save()
        self.pre_rebook_stock_to_destination(
            self.destination_stock, self.destination_stock.sku_instance,
            self.destination_stock.lagerplatz)

        if rebook_amount > 0:
            if self.stock.bestand - rebook_amount >= 0:
                self.destination_stock.save()
                if self.stock.bestand - rebook_amount == 0:
                    self.stock.delete()
                else:
                    self.stock.bestand -= rebook_amount
                    self.stock.save()

    def pre_rebook_stock_to_destination(self, destination_stock,
                                        destination_sku, destination_position):
        pass

    def get_form(self):
        if self.request.method == "POST":
            self.form = BookStockOnPositionForm(data=self.request.POST,
                                                stock=self.stock)
        else:
            self.form = BookStockOnPositionForm(stock=self.stock)
        return self.form

    def get(self, request, *args, **kwargs):
        context = self.get_context()
        return render(request, self.template_name, context)

    def get_context(self):
        return {
            "title": "Auf Position einbuchen",
            "stock": self.stock,
            "position": self.position,
            "form": self.form
        }

    def post(self, request, *args, **kwargs):
        return HttpResponseRedirect(reverse_lazy("stock:list"))
Пример #9
0
class BookProductInPosition(View):
    template_name = "online/refill_order/book_product_in_position.html"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.product, self.state, self.position, self.form, self.refill_order = None, None, None, None, None
        self.bookin_amount, self.booked_in_amount, self.booked_out_amount = 0, 0, 0
        self.stock = None

    def dispatch(self, request, *args, **kwargs):
        self.product = Product.objects.get(pk=self.kwargs.get("product_pk"))
        self.position = Position.objects.get(pk=self.kwargs.get("position_pk"))
        self.state = self.kwargs.get("state")
        self.form = self.get_form()
        self.refill_order = request.user.refillorder_set.filter(
            Q(Q(booked_out=None) | Q(booked_in=None))
            & Q(user=self.request.user)).first()
        self.bookin_amount = self.get_bookin_amount()
        self.booked_in_amount = self.get_booked_in_amount()
        self.booked_out_amount = self.get_booked_out_amount()
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, self.get_context())

    def get_context(self):
        context = {
            "title": "Artikel in Lagerposition einbuchen",
            "product": self.product,
            "position": self.position,
            "form": self.form,
            "refill_order": self.refill_order,
            "state": self.state
        }
        return context

    def get_form(self):
        if self.request.method == "POST":
            return BookinForm(data=self.request.POST)
        else:
            return BookinForm()

    def post(self, request, *args, **kwargs):
        self.validate_booked_in_amount_is_greater_than_booked_out()
        self.validate_booked_in_amount_not_exceeding_outbooked_amount()
        if self.form.is_valid() is True:
            self.bookin_product_on_position()
            self.create_refill_order_inbook_stock()
            return HttpResponseRedirect(
                reverse_lazy("online:products_for_bookin"))
        else:
            return render(request, self.template_name, self.get_context())

    def bookin_product_on_position(self):
        query_condition = Q(
            Q(product=self.product,
              lagerplatz__iexact=self.position.name,
              zustand=self.state)
            | (Q(ean_vollstaendig=self.product.ean,
                 lagerplatz__iexact=self.position.name,
                 zustand=self.state)))
        self.stock = Stock.objects.filter(query_condition).first()
        print(f"bbaba: {self.position.name} - {self.stock}")
        if self.stock is None:
            self.stock = Stock(ean_vollstaendig=self.product.ean,
                               zustand=self.state,
                               lagerplatz=self.position.name,
                               product=self.product)
        print(f"GUTE FRAGE : {self.bookin_amount} - {self.stock.bestand}")

        print(f"bbaba2: {self.position.name} - {self.stock.lagerplatz}")

        if self.stock.bestand is not None:
            self.stock.bestand += self.bookin_amount
        else:
            self.stock.bestand = self.bookin_amount
        self.stock.save()

    def create_refill_order_inbook_stock(self):
        RefillOrderInbookStock.objects.create(refill_order=self.refill_order,
                                              product=self.product,
                                              amount=self.bookin_amount,
                                              position=self.position.name,
                                              booked_in=True,
                                              stock=self.stock,
                                              state=self.state)

    def get_bookin_amount(self):
        if self.form.is_valid() is True:
            self.bookin_amount = self.form.cleaned_data.get("bookin_amount")
        return self.bookin_amount

    def get_booked_in_amount(self):
        booked_in_sum = 0
        for inbook_stock in self.refill_order.refillorderinbookstock_set.filter(
                product=self.product):
            booked_in_sum += inbook_stock.amount
        return booked_in_sum

    def get_booked_out_amount(self):
        booked_out_amount = 0
        for outbook_stock in self.refill_order.refillorderoutbookstock_set.filter(
                product_mission__sku__product=self.product):
            booked_out_amount += outbook_stock.amount
        return booked_out_amount

    def validate_booked_in_amount_not_exceeding_outbooked_amount(self):
        booked_in_sum = self.get_booked_in_amount()

        if self.booked_out_amount - (self.booked_in_amount +
                                     self.bookin_amount) < 0:
            self.form.add_error(
                "bookin_amount", f"Sie dürfen maximal noch "
                f"{self.booked_out_amount-self.booked_in_amount}x den Artikel "
                f"einbuchen")

    def validate_booked_in_amount_is_greater_than_booked_out(self):
        self.booked_out_amount = self.get_booked_out_amount()
        if self.form.is_valid() is True:
            if self.bookin_amount + self.booked_in_amount > self.booked_out_amount:
                self.form.add_error(
                    "bookin_amount",
                    f"Sie dürfen nicht mehr einbuchen als ausgebucht wurde ")
                self.form.add_error(
                    "bookin_amount",
                    f"Sie haben den Artikel {self.booked_out_amount}x ausgebucht"
                )
        rowValues = []
        col_value = []
        for col in range(s.ncols):
            value  = (s.cell(row,col).value)
            rowValues.append(value)
        print rowValues

        stkObj=Stock()
        stkObj.type=str(rowValues[0])
        stkObj.company_Name=str(rowValues[0])
        # stkObj.supply_Place=str(rowValues[1])
        # stkObj.bill_No=str(rowValues[1])
        # stkObj.bill_Date=str(rowValues[1])
        # stkObj.bill_Rec_Date=str(rowValues[1])
        # stkObj.bill_Amount=str(rowValues[1])
        # stkObj.lr_No=str(rowValues[1])
        # stkObj.lr_Date=str(rowValues[1])
        # stkObj.cases=str(rowValues[1])
        # stkObj.carriers_Name=str(rowValues[1])
        # stkObj.permit_No=str(rowValues[1])
        # stkObj.doc_Month=str(rowValues[1])
        # stkObj.F_C_O=str(rowValues[1])
        # stkObj.date=str(rowValues[1])
        # stkObj.qrt=str(rowValues[1])
        # stkObj.year=str(rowValues[1])
        # stkObj.remarks=str(rowValues[1])
        # stkObj.commodity=str(rowValues[1])
        stkObj.save()