qilikuacha vor 3 Jahren
Ursprung
Commit
29f0e3990e

+ 1 - 1
APITest/constants.py

@@ -1,2 +1,2 @@
-HOST_IP = '8.141.68.219'
+HOST_IP = 'localhost'
 WEBSITE_PREFIX = 'http://%s:8080' % (HOST_IP)

+ 20 - 16
APITest/setup_db.py

@@ -124,11 +124,21 @@ def create_questions(namePrefix='qtest-', number=10, from_file=False):
     if from_file:
         files = os.listdir('./demo-questions/')
         for file_name in files:
-            with open('./demo-questions/' + file_name, encoding="UTF-8") as read_obj:
+            with open('./demo-questions/' + file_name, 'r') as read_obj:
                 print('loading ' + file_name + ' to db')
                 exam_tag = file_name.split('-')[1]
+                tags = []
+                if len(exam_tag) > 0:
+                    if exam_tag == '线路工':
+                        tags.append('XianLuGong')
+                    elif exam_tag == '桥隧工':
+                        tags.append('QiaoSuiGong')
+                    elif exam_tag == '大型线路机械司机':
+                        tags.append('DaXingXianLuJiXieSiJi')
+                    elif exam_tag == '测量工':
+                        tags.append('CeLiangGong')
                 exam_prefix = file_name.split('-')[0]
-                exams = create_exams(namePrefix=exam_prefix + '-' + exam_tag, number=6, tags=[exam_tag])
+                exams = create_exams(namePrefix=exam_prefix + '-' + exam_tag, number=6, tags=tags)
                 csv_reader = reader(read_obj)
                 for row in csv_reader:
                     qNumber = row[0]
@@ -149,16 +159,6 @@ def create_questions(namePrefix='qtest-', number=10, from_file=False):
                     answerAnalysis = row[8]
                     keyword = row[9];
                     level = row[10];
-                    tags = []
-                    if len(row[11]) > 0:
-                        if row[11] == '线路工':
-                            tags.append('XianLuGong')
-                        elif row[11] == '桥隧工':
-                            tags.append('QiaoSuiGong')
-                        elif row[11] == '大型线路机械司机':
-                            tags.append('DaXingXianLuJiXieSiJi')
-                        elif row[11] == '测量工':
-                            tags.append('CeLiangGong')
                     if len(content) == 0 or len(qType) == 0 or len(answers) == 0 or len(finalAnswer) == 0:
                         print('Skip due to required info missing')
                         continue
@@ -181,6 +181,7 @@ def create_questions(namePrefix='qtest-', number=10, from_file=False):
                     }
                     # if random number equals to magic number, then add tag 今日必练
                     if random.randint(0, 100) == 3:
+                        print('going to add tag to question')
                         add_tag(datetime.today().strftime('%Y%m%d'), questionId=_text(resp)['id'])
                     # add newly created question to a random exam
                     add_question_to_exam(random_exam_id, [exam_to_question])
@@ -257,9 +258,6 @@ def create_2_levels_categories(root_level, second_levels):
         children.append(child_id)
     return children
 
-
-
-
 def create_specific_categories():
     categories = []
     resp = show_root_categories()
@@ -280,7 +278,7 @@ def create_specific_categories():
     return categories
 
 def read_material_from_file(file_name):
-    file = open('./demo-materials/' + file_name, encoding="UTF-8")
+    file = open('./demo-materials/' + file_name, 'r')
     file_lines = file.readlines()
     count = 0
     content = ''
@@ -296,6 +294,10 @@ def read_material_from_file(file_name):
         count+=1
     return title, content
 
+def random_pick_tags():
+    tags = ['CeLiangGong', 'DaXingXianLuJiXieSiJi', 'QiaoSuiGong', 'XianLuGong']
+    return tags[random.randint(0, len(tags)-1)]
+
 def create_learning_materials(namePrefix='测试资料-', number=20, from_file=False):
     categories = []
     if not from_file:
@@ -311,10 +313,12 @@ def create_learning_materials(namePrefix='测试资料-', number=20, from_file=F
                 'userId': randomly_pick_user(),
                 'type': 'ARTICLE',
                 'contents': content,
+                'tags': [random_pick_tags()]
             })
             materialId = _text(material)['id']
             # if random number equals to magic number, then add tag 今日必练
             if random.randint(0, 10) == 3:
+                print('going to add tag to material')
                 add_tag(datetime.today().strftime('%Y%m%d'), materialId=materialId)
             materials.append(materialId)
             random_category = categories[random.randint(0, len(categories)-1)]

+ 28 - 4
src/main/java/com/jtxt/demo/controller/CategoryController.java

@@ -1,19 +1,22 @@
 package com.jtxt.demo.controller;
 
-import com.jtxt.demo.model.LearningMaterial;
-import com.jtxt.demo.model.MaterialCategory;
-import com.jtxt.demo.model.Question;
-import com.jtxt.demo.model.QuestionCategory;
+import com.jtxt.demo.model.*;
 import com.jtxt.demo.repository.CategoryRepository;
 import com.jtxt.demo.repository.CategoryToMaterialRepository;
 import com.jtxt.demo.service.CategoryService;
+import com.jtxt.demo.service.LearningMaterialService;
 import com.jtxt.demo.service.QuestionCategoryService;
+import com.jtxt.demo.service.TagToResourcesService;
+import com.jtxt.demo.util.Utils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
 
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
+import java.util.stream.Collectors;
 
 @RestController
 public class CategoryController {
@@ -25,12 +28,33 @@ public class CategoryController {
     private CategoryToMaterialRepository categoryToMaterialRepository;
     @Autowired
     private CategoryRepository categoryRepository;
+    @Autowired
+    private TagToResourcesService tagToResourcesService;
+    @Autowired
+    private LearningMaterialService learningMaterialService;
 
     @GetMapping("/categories")
     public ResponseEntity<?> showCategoryRootLevel() {
         return new ResponseEntity<>(categoryService.getRootMaterialCategories(), HttpStatus.OK);
     }
 
+    @GetMapping("/newsfeed")
+    public ResponseEntity<?> showNewsFeed() {
+        TagToResources resources = tagToResourcesService.findResourcesByTag(Utils.getTodayTag());
+        if (resources == null) {
+            // 今日必读为空,返回昨日必读
+            resources = tagToResourcesService.findResourcesByTag(Utils.getYesterdayTag());
+            if (resources == null) {
+                // 如果也为空的话,则返回空
+                return new ResponseEntity<>(Collections.emptyList(), HttpStatus.OK);
+            }
+        }
+        List<LearningMaterial> materials = resources.getMaterials().stream()
+                .map(id -> learningMaterialService.getMaterialById(id))
+                .collect(Collectors.toList());
+        return new ResponseEntity<>(materials, HttpStatus.OK);
+    }
+
     @GetMapping("/q-categories")
     public ResponseEntity<?> showQuestionCategoryRootLevel() {
         return new ResponseEntity<>(questionCategoryService.getRootQuestionCategories(), HttpStatus.OK);

+ 2 - 2
src/main/java/com/jtxt/demo/controller/TagController.java

@@ -41,7 +41,7 @@ public class TagController {
                                        @RequestParam(value = "material", required = false) String materialId,
                                        @RequestParam(value = "question", required = false) String questionId,
                                        @RequestParam(value = "exam", required = false) String examId) {
-        if (materialId == null && questionId == null) {
+        if (materialId == null && questionId == null && examId == null) {
             return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
         }
         if (materialId != null) {
@@ -63,7 +63,7 @@ public class TagController {
             if (exam == null) {
                 return new ResponseEntity<>(HttpStatus.NOT_FOUND);
             }
-
+            tagToResourcesService.addExamToTag(tag, examId);
         }
         return new ResponseEntity<>(HttpStatus.OK);
     }

+ 1 - 1
src/main/java/com/jtxt/demo/repository/PointsHistoryRepository.java

@@ -11,5 +11,5 @@ import java.util.List;
 public interface PointsHistoryRepository extends MongoRepository<PointsHistory, String> {
     List<PointsHistory> findAllByUserId(String userId);
     List<PointsHistory> findAllByUserIdAndCreatedTimeBetween(String userId, LocalDateTime start, LocalDateTime end);
-    PointsHistory findOneByUserIdAndEventOrderByCreatedTimeDesc(String userId, Event event);
+    PointsHistory findFirstByUserIdAndEventOrderByCreatedTimeDesc(String userId, Event event);
 }

+ 1 - 1
src/main/java/com/jtxt/demo/service/ExamServiceImpl.java

@@ -162,7 +162,7 @@ public class ExamServiceImpl implements ExamService {
         while (questionList.size() < number) {
             // 需要再随机选出问题补足number个问题
             String randomId = typeResources.get((int) (Math.random() * typeResources.size()));
-            if (questionList.contains(randomId)) questionList.add(randomId);
+            if (!questionList.contains(randomId)) questionList.add(randomId);
         }
         return questionList;
     }

+ 1 - 1
src/main/java/com/jtxt/demo/service/PointsHistoryServiceImpl.java

@@ -44,6 +44,6 @@ public class PointsHistoryServiceImpl implements PointsHistoryService {
 
     @Override
     public PointsHistory findLatestPointsHistoryByUserAndEvent(String userName, Event event) {
-        return pointsHistoryRepository.findOneByUserIdAndEventOrderByCreatedTimeDesc(userName, event);
+        return pointsHistoryRepository.findFirstByUserIdAndEventOrderByCreatedTimeDesc(userName, event);
     }
 }

+ 6 - 10
src/main/java/com/jtxt/demo/service/TagToResourcesServiceImpl.java

@@ -9,6 +9,7 @@ import org.springframework.stereotype.Service;
 
 import java.time.LocalDate;
 import java.time.format.DateTimeFormatter;
+import java.util.Optional;
 
 import static com.jtxt.demo.util.Utils.CHINA_ZONE;
 
@@ -29,8 +30,9 @@ public class TagToResourcesServiceImpl implements TagToResourcesService {
         if (!isValidTag(tag)) return null;
         TagToResources rst;
         if (tagCache.get(tag) == null) {
-            rst = tagToResourcesRepository.findByName(tag);
-            if (rst == null) return null;
+            Optional<TagToResources> resourcesOpt = tagToResourcesRepository.findById(tag);
+            if (resourcesOpt.isEmpty()) return null;
+            rst = resourcesOpt.get();
             tagCache.add(tag, rst);
         } else {
             rst = tagCache.get(tag);
@@ -123,16 +125,10 @@ public class TagToResourcesServiceImpl implements TagToResourcesService {
     }
 
     private boolean isValidTag(String tag) {
-        try {
-            int dateInt = Integer.parseInt(tag);
-            if (tag.length() != 8) return false;
-            int todayInt = Integer.parseInt(Utils.getTodayTag());
-            if (dateInt > todayInt + 1000) return false; // 最多可设置未来1000天的每日必读必练
-            if (dateInt < todayInt - 1) return false;
-            return true;
-        } catch (NumberFormatException nfe) {
+        if (!tag.matches("\\d+")) {
             // 但凡不是全部数字,一律判断为合法tag
             return true;
         }
+        return Utils.isValidDateTag(tag);
     }
 }

+ 28 - 0
src/main/java/com/jtxt/demo/util/Utils.java

@@ -1,9 +1,13 @@
 package com.jtxt.demo.util;
 
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
 import java.time.LocalDate;
 import java.time.ZoneId;
 import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
 import java.time.temporal.WeekFields;
+import java.util.Date;
 import java.util.Locale;
 
 public class Utils {
@@ -13,6 +17,30 @@ public class Utils {
         LocalDate localDate = LocalDate.now(CHINA_ZONE);
         return dtf.format(localDate);
     }
+
+    public static String getYesterdayTag() {
+        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMdd");
+        LocalDate localDate = LocalDate.now(CHINA_ZONE).minusDays(1);
+        return dtf.format(localDate);
+    }
+
+    public static boolean isValidDateTag(String tag) {
+        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMdd");
+        try {
+            LocalDate dateTag = LocalDate.parse(tag, dtf);
+            LocalDate today = LocalDate.now(CHINA_ZONE);
+
+            //calculating number of days in between
+            long noOfDaysBetween = ChronoUnit.DAYS.between(dateTag, today);
+            if (dateTag.isBefore(today) && noOfDaysBetween > 1) {
+                return false;
+            }
+        } catch (Exception e) {
+            return false;
+        }
+        return true;
+    }
+
     // return "2021Week2" to indicate that the second week of 2021.
     public static String getWeekTag() {
         return getYear() + "Week" + getWeekNum();