Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backoffice/Export csv file #706

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions backoffice/modules/order/services/OrderService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,11 @@ export async function getOrderById(id: number) {
if (response.status >= 200 && response.status < 300) return response.json();
return Promise.reject(response);
}

export async function exportCsvFile(params: string) {
const response = await fetch('/api/order/backoffice/orders/csv-export?' + params);
console.log('/api/order/backoffice/orders/csv-export?' + params);

if (response.status >= 200 && response.status < 300) return response;
return Promise.reject(response);
}
110 changes: 101 additions & 9 deletions backoffice/pages/sales/orders/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,23 @@ import ReactPaginate from 'react-paginate';
import moment from 'moment';
import { useForm, SubmitHandler } from 'react-hook-form';
import queryString from 'query-string';
import { getOrders } from 'modules/order/services/OrderService';
import { exportCsvFile, getOrders } from 'modules/order/services/OrderService';
import { OrderSearchForm } from 'modules/order/models/OrderSearchForm';
import { DEFAULT_PAGE_SIZE } from '@constants/Common';
import { Order } from 'modules/order/models/Order';
import OrderSearch from 'modules/order/components/OrderSearch';
import { formatPriceVND } from 'utils/formatPrice';
import Link from 'next/link';
import { toastError, toastSuccess } from '@commonServices/ToastService';

const Orders: NextPage = () => {
const { register, watch, handleSubmit } = useForm<OrderSearchForm>();
const [isLoading, setLoading] = useState(false);

const [orderList, setOrderList] = useState<Order[]>([]);
const [orderIdList, setOrderIdList] = useState<number[]>([]);
const [pageNo, setPageNo] = useState<number>(0);
const [totalPage, setTotalPage] = useState<number>(1);
const [isDelete, setDelete] = useState<boolean>(false);
const orderPageSize = DEFAULT_PAGE_SIZE;

const watchAllFields = watch(); // when pass nothing as argument, you are watching everything
Expand All @@ -33,7 +34,6 @@ const Orders: NextPage = () => {
createdFrom: moment(watchAllFields.createdFrom).format(),
createdTo: moment(watchAllFields.createdTo).format(),
});
console.log(params);

getOrders(params)
.then((res) => {
Expand All @@ -49,7 +49,7 @@ const Orders: NextPage = () => {
setLoading(true);
handleGetOrders();
setLoading(false);
}, [pageNo, isDelete]);
}, [pageNo]);

useEffect(() => {
setLoading(true);
Expand All @@ -64,6 +64,62 @@ const Orders: NextPage = () => {
const handlePageChange = ({ selected }: any) => {
setPageNo(selected);
};

const handleExportCsv = (idList: number[] | null) => {
const params = idList
? queryString.stringify({
orderIdList: idList,
})
: queryString.stringify({
orderIdList: orderIdList,
});
exportCsvFile(params)
.then((res) => {
const downloadLink = document.createElement('a');
downloadLink.href = res.url; // URL of the file

// Simulate a click event to trigger the download
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);

toastSuccess('Export CSV successfully!');
})
.catch((ex) => {
toastError('Export CSV failed!');
console.log(ex);
});
};

const handleClickCheckbox = (value: number) => {
const isExist = orderIdList.includes(value);

console.log('checked', value, isExist);

if (isExist) {
setOrderIdList(orderIdList.filter((id) => id !== value));
} else {
setOrderIdList([...orderIdList, value]);
}
};

const handleClickCheckAll = (e: any) => {
const { checked } = e.target;
const newOrderIdList = checked
? orderList
.filter((order) => typeof order.id === 'number') // Filter out undefined values
.map((order) => order.id as number)
: [];

setOrderIdList(newOrderIdList);

//set all checkbox to checked
const checkboxes = document.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
checkboxes.forEach((checkbox) => {
checkbox.checked = checked;
});
};

if (isLoading) return <p>Loading...</p>;
return (
<>
Expand All @@ -72,9 +128,37 @@ const Orders: NextPage = () => {
<h2 className="text-danger font-weight-bold mb-3">Order Management</h2>
</div>
<div className="col-md-6 text-right">
<button type="button" className="btn btn-success me-2">
<i className="fa fa-download me-2" aria-hidden="true"></i> Export
</button>
<div className="btn-group me-2">
<button type="button" className="btn btn-success">
<i className="fa fa-download" aria-hidden="true"></i> Export
</button>
<button type="button" className="btn btn-success " data-bs-toggle="dropdown">
<i className="fa fa-caret-down" aria-hidden="true"></i>
</button>
<ul className="dropdown-menu">
<li>
<a
className="dropdown-item"
href="#"
onClick={() => {
handleExportCsv(
orderList
.filter((order) => typeof order.id === 'number') // Filter out undefined values
.map((order) => order.id as number)
);
}}
>
Export to Excel (all found)
</a>
</li>
<li>
<a className="dropdown-item" href="#" onClick={() => handleExportCsv(null)}>
Export to Excel (selected)
</a>
</li>
</ul>
</div>

<button type="button" className="btn btn-warning me-2">
<i className="fa fa-upload me-2" aria-hidden="true"></i> Import
</button>
Expand Down Expand Up @@ -118,7 +202,14 @@ const Orders: NextPage = () => {
<thead>
<tr>
<th className="d-flex justify-content-center">
<input className="form-check-input" type="checkbox" value="" id="checkAll" />
<input
className="form-check-input"
type="checkbox"
checked={orderIdList.length === orderList?.length}
id="checkAll"
onClick={(Event) => handleClickCheckAll(Event)}
disabled={orderList === undefined || orderList == null}
/>
</th>
<th>Order Id</th>
<th>Order status</th>
Expand All @@ -138,7 +229,8 @@ const Orders: NextPage = () => {
<input
className="form-check-input mb-3"
type="checkbox"
value=""
onChange={(e) => handleClickCheckbox(Number(e.target.value))}
value={order.id}
id={`selectOrder${order.id}`}
/>
</td>
Expand Down
6 changes: 6 additions & 0 deletions order/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@
<artifactId>keycloak-spring-security-adapter</artifactId>
<version>${keycloak-spring-security-adapter.version}</version>
</dependency>

<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.7.1</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
Expand Down
2 changes: 0 additions & 2 deletions order/src/main/java/com/yas/order/OrderApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}


@Bean
public ZipkinSpanExporter zipkinSpanExporter() {
return ZipkinSpanExporter.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.yas.order.model.enumeration.EOrderStatus;
import com.yas.order.service.OrderService;
import com.yas.order.viewmodel.order.*;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
Expand Down Expand Up @@ -41,6 +42,12 @@ public ResponseEntity<OrderVm> getOrderWithItemsById(@PathVariable long id) {
return ResponseEntity.ok(orderService.getOrderWithItemsById(id));
}

@GetMapping("/backoffice/orders/csv-export")
public void exportCSVFile(HttpServletResponse response,
@RequestParam List<Long> orderIdList) {
orderService.exportCSVFile(response, orderIdList);
}

@GetMapping("/backoffice/orders")
public ResponseEntity<OrderListVm> getOrders(
@RequestParam(value = "createdFrom", defaultValue = "#{new java.util.Date(1970-01-01)}", required = false)
Expand Down
20 changes: 20 additions & 0 deletions order/src/main/java/com/yas/order/exception/InternalException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.yas.order.exception;

import com.yas.order.utils.MessagesUtils;

public class InternalException extends RuntimeException {
private String message;

public InternalException(String errorCode, Object... var2) {
this.message = MessagesUtils.getMessage(errorCode, var2);
}

@Override
public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,5 @@ Page<Order> findOrderByWithMulCriteria(
@Param("createdTo") ZonedDateTime createdTo,
Pageable pageable);

List<Order> findByIdIn(List<Long> idList);
}
33 changes: 30 additions & 3 deletions order/src/main/java/com/yas/order/service/OrderService.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.yas.order.service;

import com.yas.order.exception.InternalException;
import com.yas.order.exception.NotFoundException;
import com.yas.order.model.Checkout;
import com.yas.order.model.Order;
import com.yas.order.model.OrderAddress;
import com.yas.order.model.OrderItem;
Expand All @@ -16,12 +16,13 @@
import com.yas.order.viewmodel.order.*;
import com.yas.order.viewmodel.orderaddress.OrderAddressPostVm;
import com.yas.order.viewmodel.product.ProductVariationVM;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
Expand All @@ -30,6 +31,10 @@
import java.util.*;
import java.util.stream.Collectors;

import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;

@Slf4j
@Service
@Transactional
Expand Down Expand Up @@ -164,7 +169,7 @@ public OrderListVm getAllOrder(ZonedDateTime createdFrom,
createdFrom,
createdTo,
pageable);
if(orderPage.isEmpty())
if (orderPage.isEmpty())
return new OrderListVm(null, 0, 0);

List<OrderBriefVm> orderVms = orderPage.getContent()
Expand Down Expand Up @@ -198,4 +203,26 @@ public List<OrderGetVm> getMyOrders(String productName, EOrderStatus orderStatus
List<Order> orders = orderRepository.findMyOrders(userId, productName, orderStatus);
return orders.stream().map(OrderGetVm::fromModel).toList();
}

public void exportCSVFile(HttpServletResponse response, List<Long> orderIdList) {
//set file name and content type
String filename = "Orders-data.csv";

response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
response.setCharacterEncoding("UTF-8");
//create a csv writer
try {
StatefulBeanToCsv<OrderCsvExportVm> writer = new StatefulBeanToCsvBuilder<OrderCsvExportVm>(response.getWriter())
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withOrderedResults(true)
.build();
//write all orders data to csv file
writer.write(orderRepository.findByIdIn(orderIdList).stream().map(OrderCsvExportVm::fromModel).toList());
} catch (Exception ex) {
throw new InternalException(ex.getMessage());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might lost the stack trace of the origin Exception here, can we remove the try/catch here or throw exception more properly

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll alter it when i'm available, Thanks for your comment.

}
}
}
Loading