Skip to content

Commit

Permalink
Data migration to combined app
Browse files Browse the repository at this point in the history
This is an intermediate version for migrating to the new, combined app.
  • Loading branch information
Kaezon committed May 9, 2016
1 parent 94833b4 commit 9d414f4
Show file tree
Hide file tree
Showing 20 changed files with 291 additions and 0 deletions.
7 changes: 7 additions & 0 deletions EVERoachCoach/settings.py.example
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ INSTALLED_APPS = [
'django.contrib.staticfiles',
'rapid_sales_tool',
'portal',
'orders',
'stock',
]

MIDDLEWARE_CLASSES = [
Expand Down Expand Up @@ -125,6 +127,11 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

# STATIC_ROOT should be set to the directory in which your webserver will be looking for static files.
# i.e. /var/www/example/static/

STATIC_ROOT = ''

STATIC_URL = '/static/'

SERVICE_NAME = os.environ.get('APP_SERVICE_NAME', '')
Expand Down
Empty file added orders/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions orders/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
7 changes: 7 additions & 0 deletions orders/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from __future__ import unicode_literals

from django.apps import AppConfig


class OrdersConfig(AppConfig):
name = 'orders'
13 changes: 13 additions & 0 deletions orders/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.forms import ModelForm, ModelChoiceField
from django.forms.models import inlineformset_factory
from stock.models import StockItem
from .models import *

class AddOrderForm(ModelForm):
class Meta:
model = Order
exclude = ('order_price','is_paid')
def __init__(self, *args, **kwargs):
super(AddOrderForm, self).__init__(*args, **kwargs)
self.fields['item'].queryset = StockItem.objects.all()
self.fields['item'].label_from_instance = lambda obj: "%s" % (obj.item_name)
29 changes: 29 additions & 0 deletions orders/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.3 on 2016-03-27 23:17
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
('stock', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('customer_name', models.CharField(max_length=64)),
('item_quantity', models.PositiveIntegerField()),
('order_price', models.DecimalField(decimal_places=2, max_digits=17)),
('is_paid', models.BooleanField()),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='stock.StockItem')),
],
),
]
Empty file added orders/migrations/__init__.py
Empty file.
11 changes: 11 additions & 0 deletions orders/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from __future__ import unicode_literals

from django.db import models
from stock.models import StockItem

class Order(models.Model):
customer_name = models.CharField(max_length=64)
item = models.ForeignKey(StockItem, on_delete=models.CASCADE)
item_quantity = models.PositiveIntegerField()
order_price = models.DecimalField(max_digits=17, decimal_places=2)
is_paid = models.BooleanField()
3 changes: 3 additions & 0 deletions orders/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
59 changes: 59 additions & 0 deletions orders/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import requests
import json
from decimal import Decimal
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http.response import HttpResponseServerError
from django.template import RequestContext
from django.shortcuts import HttpResponseRedirect, render, get_object_or_404, HttpResponse
from django.forms import modelformset_factory
from .forms import *
from .models import *

def order(request):
orders = Order.objects.filter(is_paid=False)
for item in orders:
item.markup_price = item.order_price + (item.order_price * Decimal(settings.MARKUP_VALUE))
if request.method == 'POST':
form = AddOrderForm(request.POST)
if form.is_valid():
order_instance = form.save(commit=False)
stock_item = order_instance.item
if order_instance.item_quantity <= stock_item.item_count:
order_instance.order_price = order_instance.item_quantity * stock_item.unit_cost
stock_item.item_count -= order_instance.item_quantity
order_instance.is_paid = False
stock_item.save()
form.save()
else:
return HttpResponseServerError(('You cannot order more than is available: {0} units').format(stock_item.item_count))
return HttpResponseRedirect(reverse(order))
else:
addOrderForm = AddOrderForm()
return render(request, 'public/orders.html', {'addOrderForm': addOrderForm, 'orders': orders, 'service_name': settings.SERVICE_NAME}, context_instance=RequestContext(request))

def cancelOrder(request):
if request.method == 'POST':
response = HttpResponse()
order_id = request.POST['order_id']
order = get_object_or_404(Order, pk=order_id)
stock_item = order.item
stock_item.item_count += order.item_quantity
stock_item.save()
order.delete()
response.status_code = 200
return response
else:
Http404("Why are you here?")

def paidOrder(request):
if request.method == 'POST':
response = HttpResponse()
order_id = request.POST['order_id']
order = get_object_or_404(Order, pk=order_id)
order.is_paid = True
order.save()
response.status_code = 200
return response
else:
Http404("Why are you here?")
55 changes: 55 additions & 0 deletions rapid_sales_tool/migrations/0002_upgrade_from_v1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.3 on 2016-05-08 23:02
from __future__ import unicode_literals

from django.apps import apps as global_apps
from django.db import migrations

def migrate_stock(apps, schema_editor):
try:
old_stock = apps.get_model("stock", "StockItem")
except LookupError:
print("The Stock app is not installed. Skipping migration step.")
return

new_stock = apps.get_model("rapid_sales_tool", "StockItem")
new_stock.objects.bulk_create([
new_stock(pk = old_object.pk,
item_name = old_object.item_name,
item_count = old_object.item_count,
unit_cost = old_object.unit_cost)
for old_object in old_stock.objects.all()])

def migrate_orders(apps, schema_editor):
try:
old_orders = apps.get_model("orders", "Order")
except LookupError:
print("The Orders app is not installed. Skipping migration step.")
return

new_stock = apps.get_model("rapid_sales_tool", "StockItem")
new_orders = apps.get_model("rapid_sales_tool", "Order")
new_orders.objects.bulk_create([
new_orders(pk = old_object.pk,
customer_name = old_object.customer_name,
item = new_stock(pk=old_object.item.pk),
item_quantity = old_object.item_quantity,
order_price = old_object.order_price,
is_paid = old_object.is_paid)
for old_object in old_orders.objects.all()])

class Migration(migrations.Migration):

dependencies = [
('rapid_sales_tool', '0001_initial'),
]

operations = [
migrations.RunPython(migrate_stock, migrations.RunPython.noop),
migrations.RunPython(migrate_orders, migrations.RunPython.noop),
]

if global_apps.is_installed('orders'):
dependencies.append(('orders', '0001_initial'))
if global_apps.is_installed('stock'):
dependencies.append(('stock', '0001_initial'))
Empty file added stock/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions stock/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
7 changes: 7 additions & 0 deletions stock/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from __future__ import unicode_literals

from django.apps import AppConfig


class StockConfig(AppConfig):
name = 'stock'
13 changes: 13 additions & 0 deletions stock/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django import forms
from django.forms import ModelForm
from .models import StockItem

class AddItemForm(ModelForm):
class Meta:
model = StockItem
fields = '__all__'

class AddStockForm(ModelForm):
class Meta:
model = StockItem
fields = ['item_count','unit_cost']
25 changes: 25 additions & 0 deletions stock/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.3 on 2016-03-27 23:17
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='StockItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('item_name', models.CharField(max_length=255)),
('item_count', models.PositiveIntegerField()),
('unit_cost', models.DecimalField(decimal_places=2, max_digits=17)),
],
),
]
Empty file added stock/migrations/__init__.py
Empty file.
8 changes: 8 additions & 0 deletions stock/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from __future__ import unicode_literals

from django.db import models

class StockItem(models.Model):
item_name = models.CharField(max_length=255)
item_count = models.PositiveIntegerField()
unit_cost = models.DecimalField(max_digits=17, decimal_places=2)
3 changes: 3 additions & 0 deletions stock/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
45 changes: 45 additions & 0 deletions stock/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import requests
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.shortcuts import HttpResponseRedirect, render, get_object_or_404, HttpResponse
from .forms import *
from .models import *

def stock(request):
items = StockItem.objects.all()
if request.method == 'POST':
form = AddItemForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse(stock))
else:
addItemForm = AddItemForm()
addStockForm = AddStockForm()
return render(request, 'public/stock.html', {'addItemForm': addItemForm, 'addStockForm': addStockForm, 'items': items, 'service_name': settings.SERVICE_NAME}, context_instance=RequestContext(request))

def editStock(request, stock_id):
stock_item = get_object_or_404(StockItem, pk=stock_id)
item_instance = get_object_or_404(StockItem, pk=stock_id)
if request.method == 'POST':
form = AddStockForm(request.POST, instance=item_instance)
if form.is_valid():
item_count = form.instance.item_count + stock_item.item_count
unit_cost = ((form.instance.item_count * form.instance.unit_cost) + (stock_item.item_count * stock_item.unit_cost)) / item_count
form.instance.item_count = item_count
form.instance.unit_cost = unit_cost
form.save()
return HttpResponseRedirect(reverse(stock))
else:
raise Http404("Stock item does not exist")

def deleteStock(request):
if request.method == 'POST':
response = HttpResponse()
item_id = request.POST['item_id']
stock_item = get_object_or_404(StockItem, pk=item_id)
stock_item.delete()
response.status_code = 200
return response
else:
Http404("Why are you here?")

0 comments on commit 9d414f4

Please sign in to comment.