Skip to content

Commit

Permalink
Update SalesDAO to include saveAll method for bulk sales insertion
Browse files Browse the repository at this point in the history
  • Loading branch information
tsviz committed May 6, 2024
1 parent c096600 commit 07464e9
Show file tree
Hide file tree
Showing 4 changed files with 132 additions and 4 deletions.
67 changes: 64 additions & 3 deletions src/main/java/net/codejava/AppController.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,18 @@
import org.springframework.dao.DuplicateKeyException;
import java.util.Date;
import javax.servlet.http.HttpSession;
// import java.util.logging.Logger;
// import java.util.logging.Level;
// improt MultipartFile class
import org.springframework.web.multipart.MultipartFile;
// import portMaooing class
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
// bufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
import java.time.ZoneId;

@EnableJpaRepositories(basePackages = "net.codejava")
@Controller
Expand Down Expand Up @@ -207,5 +217,56 @@ public void exportToCSV(HttpServletResponse response) throws IOException {
writer.newLine();
}
writer.flush();
}
}

@PostMapping("/import")
public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
try {
// Parse the file
BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));

// Validate the header
String line = reader.readLine(); // Read the first line
if (line == null || !line.equals("Serial Number,Item Name,Amount,Quantity,Date")) {
throw new IllegalArgumentException("Invalid header. Expected 'Serial Number,Item Name,Amount,Quantity,Date'");
}

// Validate the rest of the file
while ((line = reader.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 5) {
throw new IllegalArgumentException("Invalid line. Each line should contain exactly 5 fields separated by commas.");
}
}

// If the file format is valid, convert it to a list of Sale objects
List<Sale> sales = new ArrayList<>();
reader = new BufferedReader(new InputStreamReader(file.getInputStream())); // Reset the reader
reader.readLine(); // Skip the header
while ((line = reader.readLine()) != null) {
String[] fields = line.split(",");
Sale sale = new Sale();
sale.setSerialNumber(fields[0].trim());
sale.setItem(fields[1].trim());

// Convert LocalDate to Date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(fields[4].trim(), formatter);
Date sqlDate = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
sale.setDate(sqlDate);

sale.setAmount((float) Double.parseDouble(fields[2].trim()));
sale.setQuantity(Integer.parseInt(fields[3].trim()));
sales.add(sale);
}

// If the file format is valid, call the upload method
dao.saveAll(sales);
redirectAttributes.addFlashAttribute("message", "Successfully saved the list of Sale objects to the database");
System.out.println("Successfully saved the list of Sale objects to the database");
} catch (Exception e) {
System.out.println("Error calling dao.saveAll(sales): " + e.getMessage());
}
return "redirect:/";
}
}
19 changes: 19 additions & 0 deletions src/main/java/net/codejava/SalesDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,23 @@ public List<Sale> listAll() {
List<Sale> listSale = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(Sale.class));
return listSale;
}

// save all sales in a list
public void saveAll(List<Sale> sales) {
if (sales == null) {
throw new IllegalArgumentException("List of sales cannot be null");
}

if (jdbcTemplate == null) {
throw new IllegalStateException("JdbcTemplate cannot be null");
}

SimpleJdbcInsert insertActor = new SimpleJdbcInsert(jdbcTemplate);
insertActor.withTableName("sales").usingColumns("serial_number", "item", "quantity", "amount", "date");

for (Sale sale : sales) {
BeanPropertySqlParameterSource param = new BeanPropertySqlParameterSource(sale);
insertActor.execute(param);
}
}
}
3 changes: 3 additions & 0 deletions src/main/java/net/codejava/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.http.HttpMethod;


@EnableWebSecurity
Expand All @@ -24,8 +25,10 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers(HttpMethod.POST, "/import").permitAll()
// .anyRequest().permitAll()
.anyRequest().authenticated()
.and()
Expand Down
47 changes: 46 additions & 1 deletion src/main/resources/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,51 @@
<h1>Inventory Records</h1>
<a href="/new" class="modern-button">Enter New Product</a>
<a href="/export" class="modern-button">Export to CSV</a>
<form id="uploadForm" style="display: none;">
<input type="file" id="csvFile" name="file" accept=".csv">
<button type="submit" id="submitBtn">Submit</button>
</form>
<label for="csvFile" class="modern-button">Import from CSV</label>
<div id="errorMessage" style="color: red;"></div>
<script>
document.getElementById('csvFile').addEventListener('change', function() {
if (this.value) {
document.getElementById('uploadForm').style.display = 'block';
} else {
document.getElementById('uploadForm').style.display = 'none';
}
});

document.getElementById('uploadForm').addEventListener('submit', function(e) {
e.preventDefault();

var formData = new FormData();
formData.append('file', document.getElementById('csvFile').files[0]);

fetch('/import', {
method: 'POST',
body: formData
}).then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
}).then(data => {
console.log('File uploaded successfully: ' + data);
// clear the file input and hide the form
document.getElementById('csvFile').value = '';
document.getElementById('uploadForm').style.display = 'none';

// Wait for 1 second before reloading the page
setTimeout(function() {
location.reload();
}, 1000);
}).catch(error => {
console.error('There has been a problem with your fetch operation: ', error);
document.getElementById('errorMessage').textContent = 'Error: ' + error.message;
});
});
</script>
<br><br>
<div id="searchFeature">
<form action="/search" method="get">
Expand All @@ -67,7 +112,7 @@ <h1>Inventory Records</h1>
</div>
<br />
<form th:action="@{/logout}" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
<!-- <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" /> -->
<input type="submit" value="Logout" />
</form>
<br />
Expand Down

0 comments on commit 07464e9

Please sign in to comment.