Last active
December 12, 2015 06:28
-
-
Save diogobaeder/4728918 to your computer and use it in GitHub Desktop.
Refactor the big monster into pieces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create_order(products, user): | |
# Start a connection | |
connection = db_connection() | |
connection.begin_transaction() | |
# Create a mail message | |
mail = mailer.create_message() | |
mail.to = user.email | |
mail.from_ = 'The store' | |
try: | |
item_repository = item_repository_for(connection) | |
order_repository = order_repository_for(connection) | |
payment_repository = payment_repository_for(connection) | |
# Calculate the amount for the total order | |
amount = Decimal('0') | |
for product in products: | |
amount += product.price | |
# Create an order with the data | |
order = order_repository.create() | |
order.amount = amount | |
order.user = user | |
order.date = today() | |
# Create one item for each product | |
for product in products: | |
item = item_repository.create() | |
item.name = product.name | |
item.price = product.price | |
item.date = today() | |
item.order = order | |
item_repository.add(item) | |
# Create a payment | |
payment = payment_repository.create() | |
payment.amount = amount | |
payment.user = user | |
# Authorize the payment in the gateway | |
authorized = payment_gateway.authorize(payment) | |
if not authorized: | |
raise Exception('You cannot buy that!') | |
# Save the payment with the authorization results | |
payment.transaction_id = authorized.transaction_id | |
payment_repository.add(payment) | |
except Exception as e: | |
connection.rollback() | |
mail.message = 'Order failed : %s' % e | |
else: | |
connection.commit() | |
mail.message = 'Order successful!' | |
finally: | |
connection.close() | |
mail.send() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment