Sfoglia il codice sorgente

Merge branch 'dev' of http://git.izouma.com/xiongzhu/art-trade-2 into dev

panhui 2 anni fa
parent
commit
2b24790257

+ 2 - 2
src/main/java/com/izouma/awesomeAdmin/service/SaleBatchService.java

@@ -92,6 +92,7 @@ public class SaleBatchService {
     }
 
     public SaleBatchDto update1(SaleBatchDto record) {
+        List<SalesBatchExtension> extensions = record.getExtensions();
         SaleBatch orig = saleBatchRepo.findById(record.getSaleBatch().getId())
                                       .orElseThrow(new BusinessException(Translator.toLocale("record.not_found")));
         ObjUtils.merge(orig, record.getSaleBatch());
@@ -100,9 +101,8 @@ public class SaleBatchService {
         if (list.size() > 0) {
             extensionRepo.deleteAll(list);
         }
-        List<SalesBatchExtension> extensions = record.getExtensions();
         extensions.forEach(c -> c.setBatchId(orig.getId()));
-        extensionRepo.saveAllAndFlush(list);
+        extensionRepo.saveAll(extensions);
         schedule();
         cacheService.clearBatch();
         return new SaleBatchDto(saleBatch, extensions);

+ 12 - 22
src/main/java/com/izouma/awesomeAdmin/service/VipAsyncService.java

@@ -23,32 +23,22 @@ public class VipAsyncService {
     private final DelegationService delegationService;
     private final UserVipRepo       userVipRepo;
 
-    @Async
     @Transactional
-    public Future<Void> autoTrade(UserVip userVip, Product product) {
+    public void autoTrade(UserVip userVip, Product product) {
         Long userId = userVip.getUserId();
-        try {
-            log.info("🚚 start, userId: {}, productId: {}", userId, product.getId());
-            Order order = orderService.createOrder(userId, product.getId(), null, true);
-            log.info("🚚 create order success, userId: {}, productId: {}, orderId: {}", userId, product.getId(), order.getId());
+        log.info("🚚 start, userId: {}, productId: {}", userId, product.getId());
+        Order order = orderService.createOrder(userId, product.getId(), null, true);
+        log.info("🚚 create order success, userId: {}, productId: {}, orderId: {}", userId, product.getId(), order.getId());
 
-            log.info("🚚 pay start, userId: {}, productId: {}", userId, product.getId());
-            orderService.balancePay(userId, order.getId());
-            log.info("🚚 pay success, userId: {}, productId: {}", userId, product.getId());
+        log.info("🚚 pay start, userId: {}, productId: {}", userId, product.getId());
+        orderService.balancePay(userId, order.getId());
+        log.info("🚚 pay success, userId: {}, productId: {}", userId, product.getId());
 
-            userVipRepo.increaseUsed(userId);
-            log.info("🚚 increase used limit, userId: {}, left: {}", userId, userVip.getDailyLimit() - userVip.getTodayUsed() - 1);
+        userVipRepo.increaseUsed(userId);
+        log.info("🚚 increase used limit, userId: {}, left: {}", userId, userVip.getDailyLimit() - userVip.getTodayUsed() - 1);
 
-            log.info("🚚 pay delegation start, userId: {}, productId: {}", userId, product.getId());
-            delegationService.payDelegationBalance(userId, order.getId());
-            log.info("🚚 pay delegation success, userId: {}, productId: {}", userId, product.getId());
-        } catch (Exception e) {
-            if (e instanceof BusinessException) {
-                log.error("🚚 error, message: {}", e.getMessage());
-            } else {
-                log.error("🚚 error", e);
-            }
-        }
-        return new AsyncResult<>(null);
+        log.info("🚚 pay delegation start, userId: {}, productId: {}", userId, product.getId());
+        delegationService.payDelegationBalance(userId, order.getId());
+        log.info("🚚 pay delegation success, userId: {}, productId: {}", userId, product.getId());
     }
 }

+ 1 - 2
src/main/java/com/izouma/awesomeAdmin/service/VipService.java

@@ -155,9 +155,8 @@ public class VipService {
                     continue;
                 }
                 UserVip chosenVip = vips.get(new Random().nextInt(vips.size()));
-                Future result = vipAsyncService.autoTrade(chosenVip, product);
                 try {
-                    result.get();
+                    vipAsyncService.autoTrade(chosenVip, product);
                 } catch (Exception e) {
                     log.error("🚚 auto trade error", e);
                 }

+ 24 - 3
src/main/java/com/izouma/awesomeAdmin/web/SaleBatchController.java

@@ -18,7 +18,10 @@ import org.springframework.web.bind.annotation.*;
 
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 @RestController
 @RequestMapping("/saleBatch")
@@ -57,8 +60,26 @@ public class SaleBatchController extends BaseController {
 
 
     @PostMapping("/all")
-    public Page<SaleBatch> all() {
-        return new PageImpl<>(saleBatchService.all());
+    public Page<SaleBatchDto> all() {
+        PageImpl<SaleBatch> saleBatches = new PageImpl<>(saleBatchService.all());
+        List<SaleBatch> content = saleBatches.getContent();
+
+        List<SalesBatchExtension> list = extensionRepo.findAll();
+        Map<Long, List<SalesBatchExtension>> map = new HashMap<>();
+        list.forEach(c -> {
+            if (map.containsKey(c.getBatchId())) {
+                map.get(c.getBatchId()).add(c);
+            } else {
+                List<SalesBatchExtension> salesBatchExtensions = new ArrayList<>();
+                salesBatchExtensions.add(c);
+                map.put(c.getBatchId(), salesBatchExtensions);
+            }
+        });
+
+        List<SaleBatchDto> record = new ArrayList<>();
+        content.forEach(c -> record.add(new SaleBatchDto(c, map.get(c.getId()))));
+
+        return new PageImpl<>(record);
     }
 
     /*@GetMapping("/get/{id}")
@@ -84,7 +105,7 @@ public class SaleBatchController extends BaseController {
     @GetMapping("/excel")
     @ResponseBody
     public void excel(HttpServletResponse response) throws IOException {
-        List<SaleBatch> data = all().getContent();
+        List<SaleBatchDto> data = all().getContent();
         ExcelUtils.export(response, data);
     }
 }

+ 2 - 0
src/main/java/com/izouma/awesomeAdmin/web/TelegramBot.java

@@ -5,6 +5,7 @@ import com.izouma.awesomeAdmin.exception.BusinessException;
 import com.izouma.awesomeAdmin.service.TelegramBotConfig;
 import com.izouma.awesomeAdmin.service.UserBalanceService;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
 import org.springframework.boot.context.properties.EnableConfigurationProperties;
 import org.springframework.stereotype.Service;
 import org.telegram.abilitybots.api.bot.AbilityBot;
@@ -28,6 +29,7 @@ import static org.telegram.abilitybots.api.objects.Flag.REPLY;
 @EnableConfigurationProperties(TelegramBotConfig.class)
 @Service
 @Slf4j
+@ConditionalOnProperty(name = "tg-bot.enabled", havingValue = "true")
 public class TelegramBot extends AbilityBot {
 
     private final TelegramBotConfig  config;

+ 1 - 1
src/main/resources/logback-spring.xml

@@ -11,7 +11,7 @@
         <root level="INFO">
             <appender-ref ref="CONSOLE"/>
         </root>
-        <logger name="org.hibernate.SQL" level="DEBUG"/>
+<!--        <logger name="org.hibernate.SQL" level="DEBUG"/>-->
 <!--        <logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE"/>-->
 <!--        <logger name="org.springframework.jdbc.core.JdbcTemplate" level="DEBUG"/>-->
 <!--        <logger name="org.springframework.jdbc.core.StatementCreatorUtils" level="TRACE"/>-->

+ 197 - 0
src/main/vue-admin/src/views/UserVipList.vue

@@ -0,0 +1,197 @@
+<template>
+    <div  class="list-view">
+        <div class="filters-container">
+            <el-input placeholder="输入关键字" v-model="search" clearable
+                      class="filter-item"></el-input>
+            <el-button @click="getData" type="primary" icon="el-icon-search"
+                       class="filter-item">搜索
+            </el-button>
+            <el-button @click="addRow" type="primary" icon="el-icon-plus"
+                       class="filter-item">添加
+            </el-button>
+            <el-button @click="download" type="primary" icon="el-icon-download"
+                       :loading="downloading" class="filter-item">导出EXCEL
+            </el-button>
+        </div>
+        <el-table :data="tableData" row-key="id" ref="table"
+                  header-row-class-name="table-header-row"
+                  header-cell-class-name="table-header-cell"
+                  row-class-name="table-row" cell-class-name="table-cell"
+                  :height="tableHeight">
+            <el-table-column v-if="multipleMode" align="center" type="selection"
+                             width="50">
+            </el-table-column>
+            <el-table-column prop="id" label="ID" width="100">
+            </el-table-column>
+                                <el-table-column prop="userId" label="userId"
+>
+                    </el-table-column>
+                    <el-table-column prop="typeId" label="typeId"
+>
+                    </el-table-column>
+                    <el-table-column prop="startAt" label="购买时间"
+                            :formatter="datetimeFormatter"
+>
+                    </el-table-column>
+                    <el-table-column prop="expireAt" label="过期时间"
+                            :formatter="datetimeFormatter"
+>
+                    </el-table-column>
+                    <el-table-column prop="minPrice" label="购买下区间"
+>
+                    </el-table-column>
+                    <el-table-column prop="maxPrice" label="购买上区间"
+>
+                    </el-table-column>
+                    <el-table-column prop="autoTradeEnabled" label="是否开启自动交易"
+>
+                    </el-table-column>
+                    <el-table-column prop="dailyLimit" label="每天购买次数"
+>
+                    </el-table-column>
+                    <el-table-column prop="todayUsed" label="剩余购买次数"
+>
+                    </el-table-column>
+                    <el-table-column prop="expired" label="是否过期"
+>
+                    </el-table-column>
+                    <el-table-column prop="weight" label="weight"
+>
+                    </el-table-column>
+            <el-table-column
+                    label="操作"
+                    align="center"
+                    fixed="right"
+                    min-width="150">
+                <template slot-scope="{row}">
+                    <el-button @click="editRow(row)" type="primary" size="mini" plain>编辑</el-button>
+                    <el-button @click="deleteRow(row)" type="danger" size="mini" plain>删除</el-button>
+                </template>
+            </el-table-column>
+        </el-table>
+        <div class="pagination-wrapper">
+            <div class="multiple-mode-wrapper">
+                <el-button v-if="!multipleMode"
+                           @click="toggleMultipleMode(true)">批量编辑</el-button>
+                <el-button-group v-else>
+                    <el-button @click="operation1">批量操作1</el-button>
+                    <el-button @click="operation2">批量操作2</el-button>
+                    <el-button @click="toggleMultipleMode(false)">取消</el-button>
+                </el-button-group>
+            </div>
+            <el-pagination background @size-change="onSizeChange"
+                           @current-change="onCurrentChange" :current-page="page"
+                           :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize"
+                           layout="total, sizes, prev, pager, next, jumper"
+                           :total="totalElements">
+            </el-pagination>
+        </div>
+
+    </div>
+</template>
+<script>
+    import { mapState } from "vuex";
+    import pageableTable from "@/mixins/pageableTable";
+
+    export default {
+        name: 'UserVipList',
+        mixins: [pageableTable],
+        created() {
+            this.getData();
+        },
+        data() {
+            return {
+                multipleMode: false,
+                search: "",
+                url: "/userVip/all",
+                downloading: false,
+            }
+        },
+        computed: {
+            selection() {
+                return this.$refs.table.selection.map(i => i.id);
+            }
+        },
+        methods: {
+            beforeGetData() {
+                if (this.search) {
+                    return { search: this.search };
+                }
+            },
+            toggleMultipleMode(multipleMode) {
+                this.multipleMode = multipleMode;
+                if (!multipleMode) {
+                    this.$refs.table.clearSelection();
+                }
+            },
+            addRow() {
+                this.$router.push({
+                    path: "/userVipEdit",
+                    query: {
+                    ...this.$route.query
+                    }
+                });
+            },
+            editRow(row) {
+                this.$router.push({
+                    path: "/userVipEdit",
+                    query: {
+                    id: row.id
+                    }
+                });
+            },
+            download() {
+                this.downloading = true;
+                this.$axios
+                    .get("/userVip/excel", { 
+                        responseType: "blob",
+                        params: { size: 10000 }
+                    })
+                    .then(res => {
+                        console.log(res);
+                        this.downloading = false;
+                        const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
+                        const link = document.createElement("a");
+                        link.href = downloadUrl;
+                        link.setAttribute(
+                            "download",
+                            res.headers["content-disposition"].split("filename=")[1]
+                        );
+                        document.body.appendChild(link);
+                        link.click();
+                        link.remove();
+                    })
+                    .catch(e => {
+                        console.log(e);
+                        this.downloading = false;
+                        this.$message.error(e.error);
+                    });
+            },
+            operation1() {
+                this.$notify({
+                    title: '提示',
+                    message: this.selection
+                });
+            },
+            operation2() {
+                this.$message('操作2');
+            },
+            deleteRow(row) {
+                this.$alert('删除将无法恢复,确认要删除么?', '警告', {type: 'error'}).then(() => {
+                    return this.$http.post(`/userVip/del/${row.id}`)
+                }).then(() => {
+                    this.$message.success('删除成功');
+                    this.getData();
+                }).catch(action => {
+                    if (action === 'cancel') {
+                        this.$message.info('删除取消');
+                    } else {
+                        this.$message.error('删除失败');
+                    }
+                })
+            },
+        }
+    }
+</script>
+<style lang="less" scoped>
+</style>

+ 49 - 0
src/test/java/com/izouma/awesomeAdmin/service/VipAsyncServiceTest.java

@@ -0,0 +1,49 @@
+package com.izouma.awesomeAdmin.service;
+
+import com.izouma.awesomeAdmin.domain.Product;
+import com.izouma.awesomeAdmin.domain.UserVip;
+import com.izouma.awesomeAdmin.repo.ProductRepo;
+import com.izouma.awesomeAdmin.repo.UserVipRepo;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+@ExtendWith(SpringExtension.class)
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+public class VipAsyncServiceTest {
+
+    @Autowired
+    private VipAsyncService vipAsyncService;
+    @Autowired
+    private UserVipRepo     userVipRepo;
+    @Autowired
+    private ProductRepo     productRepo;
+
+    @Test
+    public void autoTrade() throws InterruptedException {
+        Product product = productRepo.findById(58203L).get();
+        Thread t1 = new Thread(() -> {
+            try {
+                vipAsyncService.autoTrade(userVipRepo.findByUserId(11648L), product);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        });
+        t1.start();
+        Thread t2 = new Thread(() -> {
+            try {
+                vipAsyncService.autoTrade(userVipRepo.findByUserId(60798L), product);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        });
+        t2.start();
+
+        t1.join();
+        t2.join();
+    }
+}