Skip to content

Commit

Permalink
views
Browse files Browse the repository at this point in the history
  • Loading branch information
annagav committed Jan 16, 2025
1 parent d1bca0d commit d543e76
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 75 deletions.
4 changes: 2 additions & 2 deletions ecommerce/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
CheckoutApiViewSet,
CheckoutCallbackView,
CheckoutInterstitialView,
AddProductToCartView,
CheckoutProductView,
DiscountViewSet,
NestedDiscountProductViewSet,
NestedDiscountRedemptionViewSet,
Expand Down Expand Up @@ -102,6 +102,6 @@ class SimpleRouterWithNesting(NestedRouterMixin, SimpleRouter):
CheckoutCallbackView.as_view(),
name="checkout-result-callback",
),
re_path(r"^cart/add", AddProductToCartView.as_view(), name="checkout-product"),
re_path(r"^cart/add", CheckoutProductView.as_view(), name="checkout-product"),
re_path(r"^int_admin/refund", AdminRefundOrderView.as_view(), name="refund-order"),
]
89 changes: 49 additions & 40 deletions ecommerce/views/v0/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,54 @@ def redeem_discount(self, request):
}
)

@action(
detail=False,
methods=["post"],
name="Add To Cart",
url_name="add_to_cart",
)
def add_to_cart(self, request):
"""Add product to the cart"""
with transaction.atomic():
basket, _ = Basket.objects.select_for_update().get_or_create(
user=self.request.user
)
basket.basket_items.all().delete()
BasketDiscount.objects.filter(redeemed_basket=basket).delete()

# Incoming product ids from internal checkout
all_product_ids = self.request.POST.getlist("product_id")

# If the request is from an external source we would have course_id as query param
# Note that course_id passed in param corresponds to course run's courseware_id on mitxonline
course_run_ids = self.request.POST.getlist("course_run_id")
course_ids = self.request.POST.getlist("course_id")
program_ids = self.request.POST.getlist("program_id")

all_product_ids.extend(
list(
CourseRun.objects.filter(
Q(courseware_id__in=course_run_ids)
| Q(courseware_id__in=course_ids)
).values_list("products__id", flat=True)
)
)
all_product_ids.extend(
list(
ProgramRun.objects.filter(program__id__in=program_ids).values_list(
"products__id", flat=True
)
)
)
for product in Product.objects.filter(id__in=all_product_ids):
BasketItem.objects.create(basket=basket, product=product)

return Response(
{
"message": "Product added to cart",
}
)

@action(
detail=False, methods=["post"], name="Start Checkout", url_name="start_checkout"
)
Expand Down Expand Up @@ -661,48 +709,9 @@ def post(self, request, *args, **kwargs): # noqa: ARG002
return Response(status=status.HTTP_200_OK)


class AddProductToCartView(APIView):
class CheckoutProductView(APIView):
"""View to add products to the cart"""

def post(self, request, *args, **kwargs):
"""Add product to the cart"""
with transaction.atomic():
basket, _ = Basket.objects.select_for_update().get_or_create(
user=self.request.user
)
basket.basket_items.all().delete()
BasketDiscount.objects.filter(redeemed_basket=basket).delete()

# Incoming product ids from internal checkout
all_product_ids = self.request.POST.getlist("product_id")

# If the request is from an external source we would have course_id as query param
# Note that course_id passed in param corresponds to course run's courseware_id on mitxonline
course_run_ids = self.request.POST.getlist("course_run_id")
course_ids = self.request.POST.getlist("course_id")
program_ids = self.request.POST.getlist("program_id")

all_product_ids.extend(
list(
CourseRun.objects.filter(
Q(courseware_id__in=course_run_ids)
| Q(courseware_id__in=course_ids)
).values_list("products__id", flat=True)
)
)
all_product_ids.extend(
list(
ProgramRun.objects.filter(program__id__in=program_ids).values_list(
"products__id", flat=True
)
)
)
for product in Product.objects.filter(id__in=all_product_ids):
BasketItem.objects.create(basket=basket, product=product)

return HttpResponseRedirect(request.headers["Referer"])


def get_redirect_url(self, *args, **kwargs):
"""Populate the basket before redirecting"""
with transaction.atomic():
Expand Down
38 changes: 19 additions & 19 deletions frontend/public/src/components/CourseProductDetailEnroll.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@ import { getCookie } from "../lib/api"
import users, { currentUserSelector } from "../lib/queries/users"
import {
enrollmentMutation,
deactivateEnrollmentMutation, cartMutation
deactivateEnrollmentMutation,
} from "../lib/queries/enrollment"
import AddlProfileFieldsForm from "./forms/AddlProfileFieldsForm"
import CourseInfoBox from "./CourseInfoBox"

import type { User } from "../flow/authTypes"
import type { Product } from "../flow/cartTypes"
import { addUserNotification } from "../actions"
import { applyCartMutation } from "../lib/queries/cart"

type Props = {
courseId: ?string,
Expand All @@ -50,7 +52,7 @@ type Props = {
addProductToBasket: (user: number, productId: number) => Promise<any>,
currentUser: User,
createEnrollment: (runId: number) => Promise<any>,
addToCart: (productId: number) => Promise<any>,
addToCart: (productId: string) => Promise<any>,
deactivateEnrollment: (runId: number) => Promise<any>,
updateAddlFields: (currentUser: User) => Promise<any>,
forceRequest: () => any
Expand Down Expand Up @@ -97,14 +99,15 @@ export class CourseProductDetailEnroll extends React.Component<
})
}

async onAddToCartClick(productId: number) {
const {addToCart} = this.props

const addToCartResponse = await addToCart(productId)
async onAddToCartClick() {
const { addToCart } = this.props
const addToCartResponse = await addToCart(1)
if (isSuccessResponse(addToCartResponse)) {
this.setState({
addedToCartDialogVisibility: true
})
} else {
console.log(addToCartResponse)
}
}

Expand Down Expand Up @@ -279,7 +282,6 @@ export class CourseProductDetailEnroll extends React.Component<
renderUpgradeEnrollmentDialog() {
const {courses, currentUser } = this.props
const courseRuns = courses && courses[0] ? courses[0].courseruns : null
const csrfToken = getCookie("csrftoken")
const enrollableCourseRuns = courseRuns ?
courseRuns.filter(
(run: EnrollmentFlaggedCourseRun) => run.is_enrollable
Expand Down Expand Up @@ -372,17 +374,17 @@ export class CourseProductDetailEnroll extends React.Component<
}`}
>
<div className="certificate-pricing-logo">
<img src="/static/images/certificates/certificate-logo.svg" />
<img src="/static/images/certificates/certificate-logo.svg"/>
</div>
<p>
<strong> Certificate track: </strong>
<span id="certificate-price-info">
{product &&
run.is_upgradable &&
formatLocalePrice(getFlexiblePriceForProduct(product))}
run.is_upgradable &&
formatLocalePrice(getFlexiblePriceForProduct(product))}
</span>
<>
<br />
<br/>
{canUpgrade ? (
<>
<span className="text-danger">
Expand All @@ -393,7 +395,7 @@ export class CourseProductDetailEnroll extends React.Component<
</>
) : (
<strong id="certificate-price-info">
not available
not available
</strong>
)}
</>
Expand All @@ -402,9 +404,7 @@ export class CourseProductDetailEnroll extends React.Component<
<div className="col-md-6 col-sm-12 pr-0">
<div className={`text-center ${newCartDesign ? "new-design" : ""}`}>
<button
onClick={() => {
this.onAddToCartClick((product && product.id) || "")
}}
onClick={this.onAddToCartClick}
type="button"
className="btn btn-upgrade btn-gradient-red-to-blue"
disabled={!canUpgrade}
Expand Down Expand Up @@ -602,9 +602,8 @@ const createEnrollment = (run: EnrollmentFlaggedCourseRun) =>
mutateAsync(enrollmentMutation(run.id))


const addToCart = (productId: number) => {
mutateAsync(cartMutation(productId))
console.log("Hello")
const addToCart = (productId: string) => {
mutateAsync(applyCartMutation(productId))
}

const deactivateEnrollment = (run: number) =>
Expand Down Expand Up @@ -640,7 +639,8 @@ const mapDispatchToProps = {
createEnrollment,
addToCart,
deactivateEnrollment,
updateAddlFields
updateAddlFields,
addUserNotification
}

export default compose(
Expand Down
12 changes: 12 additions & 0 deletions frontend/public/src/lib/queries/cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,15 @@ export const orderReceiptQuery = (orderId: number) => ({
discounts: nextState
}
})

export const applyCartMutation = (productId: string) => ({
url: `/api/checkout/add_to_cart/`,
body: {
product_id: productId,
},
options: {
...getCsrfOptions(),
method: "POST"
},
update: {},
})
14 changes: 0 additions & 14 deletions frontend/public/src/lib/queries/enrollment.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,17 +187,3 @@ export const enrollmentMutation = (runId: number) => ({
},
update: {}
})

export const cartMutation = (productId: number) => ({
url: `/cart/add/`,
body: {
product_id: `${productId}`,
},
update: {
basket: nextState
},
options: {
...getCsrfOptions(),
method: "POST"
},
})

0 comments on commit d543e76

Please sign in to comment.