Skip to content

Commit

Permalink
Исправила расчет рейтинга при повтороной отправке записи истории
Browse files Browse the repository at this point in the history
  • Loading branch information
foxstrot committed May 4, 2017
1 parent d43a81f commit 596ffa8
Show file tree
Hide file tree
Showing 15 changed files with 94 additions and 52 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ Web API v4
### Регистрация нового устройства
##### GET /v4/devices/{deviceId}/{deviceName}/registerdevice
* `{deviceId}` - UUID устройства
* `{deviceName}` - название устройства (может отсутсвтваовать)
* `{deviceName}` - название устройства (может отсутствовать)
##### HttpStatus
* `200, "OK"` – если все ок
* `400, "Bad Request"` - Если пользователь ввел некорректные данные
Expand Down
6 changes: 5 additions & 1 deletion v3/src/main/java/ownradio/domain/UsersRating.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ public class UsersRating{
// @Temporal(TemporalType.TIMESTAMP)
private String recupdated;

@DateTimeFormat(pattern = "dd-MM-yyyy'T'H:m:s")
//@Temporal(TemporalType.TIMESTAMP)
private String lastactive;

private BigInteger owntracks;

private BigInteger lasttracks;
private BigInteger downloadtracks;
}
3 changes: 3 additions & 0 deletions v3/src/main/java/ownradio/repository/UserRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,7 @@ public interface UserRepository extends JpaRepository<User, UUID> {

@Query(value = "select * from getusersrating(?1)", nativeQuery = true)
List<Object[]> getUsersRating(Integer countRows);

@Query(value = "select * from getlastusers(?1)", nativeQuery = true)
List<Object[]> getLastUsers(Integer countRows);
}
2 changes: 1 addition & 1 deletion v3/src/main/java/ownradio/service/HistoryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@
* @author Alpenov Tanat
*/
public interface HistoryService {
void save(History history);
void save(History history, Boolean isNewHistoryRec);
History getById(UUID uuid);
}
1 change: 1 addition & 0 deletions v3/src/main/java/ownradio/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ public interface UserService {

List<UsersRating> getUsersRating(Integer countRows);

List<UsersRating> getLastUsers(Integer countRows);
}
43 changes: 22 additions & 21 deletions v3/src/main/java/ownradio/service/impl/HistoryServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,30 @@ public History getById(UUID uuid) {

@Transactional
@Override
public void save(History history) {
public void save(History history, Boolean isNewHistoryRec) {
historyRepository.saveAndFlush(history);

Rating rating = ratingRepository.findByUserAndTrack(history.getDevice().getUser(), history.getTrack());
if(rating != null) {
int ratingsum = rating.getRatingsum() + history.getIsListen();
rating.setLastlisten(history.getLastListen());
rating.setRatingsum(ratingsum);
ratingRepository.saveAndFlush(rating);
}
else {
rating = new Rating();
rating.setUser(history.getDevice().getUser());
rating.setTrack(history.getTrack());
rating.setLastlisten(history.getLastListen());
rating.setRatingsum(history.getIsListen());
ratingRepository.saveAndFlush(rating);
}

try {
ratioRepository.updateRatios(history.getDevice().getRecid());
}catch (Exception ex){
ex.printStackTrace();
if(isNewHistoryRec) {
Rating rating = ratingRepository.findByUserAndTrack(history.getDevice().getUser(), history.getTrack());
if (rating != null) {
int ratingsum = rating.getRatingsum() + history.getIsListen();
rating.setLastlisten(history.getLastListen());
rating.setRatingsum(ratingsum);
ratingRepository.saveAndFlush(rating);
} else {
rating = new Rating();
rating.setUser(history.getDevice().getUser());
rating.setTrack(history.getTrack());
rating.setLastlisten(history.getLastListen());
rating.setRatingsum(history.getIsListen());
ratingRepository.saveAndFlush(rating);
}

try {
ratioRepository.updateRatios(history.getDevice().getRecid());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
26 changes: 25 additions & 1 deletion v3/src/main/java/ownradio/service/impl/UserServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ownradio.domain.Device;
import ownradio.domain.User;
import ownradio.domain.UsersRating;
import ownradio.repository.UserRepository;
Expand Down Expand Up @@ -41,7 +42,7 @@ public List<UsersRating> getUsersRating(Integer countRows) {
userRating.setRecname((String) objects.get(i)[2]);
userRating.setRecupdated((String) objects.get(i)[3]);
userRating.setOwntracks((BigInteger) objects.get(i)[4]);
userRating.setLasttracks((BigInteger) objects.get(i)[5]);
userRating.setDownloadtracks((BigInteger) objects.get(i)[5]);

usersRating.add(userRating);
}
Expand All @@ -50,4 +51,27 @@ public List<UsersRating> getUsersRating(Integer countRows) {
}
return usersRating;
}


@Override
public List<UsersRating> getLastUsers(Integer countRows){
List<UsersRating> lastUsers = new ArrayList<UsersRating>();
List<Object[]> objects = userRepository.getLastUsers(countRows);
if (objects != null) {
for (int i = 0; i < objects.size(); i++) {
UsersRating lastUser = new UsersRating();
lastUser.setUserid(UUID.fromString((String) objects.get(i)[0]));
lastUser.setReccreated((String) objects.get(i)[1]);
lastUser.setLastactive((String) objects.get(i)[2]);
lastUser.setRecname((String) objects.get(i)[3]);
lastUser.setRecupdated((String) objects.get(i)[4]);
lastUser.setOwntracks((BigInteger) objects.get(i)[5]);
lastUser.setDownloadtracks((BigInteger) objects.get(i)[6]);
lastUsers.add(lastUser);
}
} else {
return null;
}
return lastUsers;
}
}
1 change: 0 additions & 1 deletion v3/src/main/java/ownradio/util/IdOrGenerate.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
*/

public class IdOrGenerate extends UUIDGenerator {
//private static final Logger log = Logger.getLogger(UseIdOrGenerate.class.getName());

@Override
public UUID generate(SessionImplementor session, Object obj) throws HibernateException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public ResponseEntity save(@PathVariable UUID deviceId, @PathVariable UUID track
history.setTrack(track);
history.setDevice(device);

historyService.save(history);
historyService.save(history, true);

return new ResponseEntity(history, HttpStatus.OK);
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ private ResponseEntity getResponseEntity(@PathVariable UUID deviceId, @PathVaria
history.setTrack(track);
history.setDevice(device);

historyService.save(history);
historyService.save(history, true);
log.info("Save history, rating and update ratios");
return new ResponseEntity(HttpStatus.OK);
} catch (Exception e) {
Expand Down
6 changes: 3 additions & 3 deletions v3/src/main/java/ownradio/web/rest/v4/HistoryController.java
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ private ResponseEntity getResponseEntity(@PathVariable UUID deviceId, @PathVaria
if(historyTemp != null){
historyTemp.setCountsend(((historyTemp.getCountsend()==null?0:historyTemp.getCountsend())) + 1);
// historyTemp.setComment(historyTemp.getComment() + (new Date()).toString() + "; ");
historyService.save(historyTemp);
historyService.save(historyTemp, false);
return new ResponseEntity(HttpStatus.ALREADY_REPORTED);
} else {
historyTemp = new History();
Expand All @@ -108,13 +108,13 @@ private ResponseEntity getResponseEntity(@PathVariable UUID deviceId, @PathVaria
historyTemp.setCountsend(1);
historyTemp.setIsListen(history.getIsListen());
historyTemp.setLastListen(history.getLastListen());
historyService.save(historyTemp);
historyService.save(historyTemp, true);
}
} else {
history.setTrack(track);
history.setDevice(device);
history.setCountsend(1);
historyService.save(history);
historyService.save(history, true);
}
log.info("Save history, rating and update ratios");
//}
Expand Down
10 changes: 10 additions & 0 deletions v3/src/main/java/ownradio/web/rest/v4/StatisticsController.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,5 +95,15 @@ public ResponseEntity<?> getLastDevices() {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

@RequestMapping(value = "/getlastusers/{countUsers}", method = RequestMethod.GET)
public ResponseEntity<?> getLastUsers(@PathVariable Integer countUsers) {
try{
List<UsersRating> lastActiveDevices = userService.getLastUsers(countUsers);
return new ResponseEntity<>(lastActiveDevices, HttpStatus.OK);
}catch (Exception ex){
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}

3 changes: 2 additions & 1 deletion v3/src/main/resources/application-prod.properties
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ logging.level.ownradio=info
logging.level.org.springframework=warn
logging.level.org.hibernate=warn
#server.port = 9090
spring.datasource.schema=classpath:/data/postgresql/schema.sql
#There is switch on file with sql scripts for auto create stored procedures
#spring.datasource.schema=classpath:/data/postgresql/schema.sql
#spring.datasource.data=classpath:/data/postgresql/data.sql
36 changes: 17 additions & 19 deletions v3/src/main/resources/data/postgresql/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,8 @@ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION calculateratios()
RETURNS boolean AS
'
-- Функция рассчитывает таблицу коэффициентов схожести интересов для пар пользователей
DECLARE
-- объявляем курсор и запрос для него
-- объявляем курсор и запрос для него
curs1 CURSOR FOR SELECT * FROM(
-- рассчитываем матрицу коэффициентов схожести интересов для каждой пары пользователей
SELECT r.userid as userid01, r2.userid as userid02, SUM(r.ratingsum * r2.ratingsum) as s
Expand Down Expand Up @@ -331,27 +330,25 @@ BEGIN
IF NOT FOUND THEN EXIT; -- если данных нет - выходим
END IF;
-- если для данной пары пользователей уже записан коэффициент - пропускаем, иначе - записываем во временную таблицу
IF NOT EXISTS (SELECT * FROM temp_ratio WHERE userid1 = cuser2 AND userid2 = cuser1 OR userid1 = cuser1 AND userid2 = cuser2) THEN
INSERT INTO temp_ratio(userid1, userid2, ratio)
INSERT INTO temp_ratio(userid1, userid2, ratio)
VALUES (cuser1, cuser2, cratio);
END IF;
END LOOP;
CLOSE curs1; -- закрываем курсор
-- обновляем имеющиеся коэффициенты в таблице ratios
UPDATE ratios SET ratio = temp_ratio.ratio, recupdated = now() FROM temp_ratio
WHERE (ratios.userid1 = temp_ratio.userid1 AND ratios.userid2 = temp_ratio.userid2)
OR (ratios.userid1 = temp_ratio.userid2 AND ratios.userid2 = temp_ratio.userid1);
WHERE ratios.userid1 = temp_ratio.userid1 AND ratios.userid2 = temp_ratio.userid2;
INSERT INTO ratios (userid1, userid2, ratio, reccreated)
(SELECT temp_ratio.userid1,temp_ratio.userid2, temp_ratio.ratio, now()
FROM temp_ratio
LEFT OUTER JOIN ratios ON
temp_ratio.userid1 = ratios.userid1 AND temp_ratio.userid2 = ratios.userid2
WHERE ratios.userid1 IS NULL OR ratios.userid2 IS NULL
);
-- если в ratios меньше пар пользователей, чем во временной таблице - вставляем недостающие записи
IF (SELECT COUNT(*) FROM ratios WHERE userid1 = i_userid or userid2 = i_userid) < (SELECT COUNT(*) FROM temp_ratio) THEN
INSERT INTO ratios (userid1, userid2, ratio, reccreated)
(SELECT tr.userid1, tr.userid2, tr.ratio, now() FROM temp_ratio AS tr
LEFT OUTER JOIN ratios AS rr ON tr.userid1 = rr.userid1 AND tr.userid2 = rr.userid2 OR tr.userid1 = rr.userid2 AND tr.userid2 = rr.userid1
WHERE rr.userid1 IS NULL OR rr.userid2 IS NULL
);
END IF;
RETURN TRUE;
END;
'
Expand Down Expand Up @@ -578,7 +575,7 @@ BEGIN
IF i_count < 0 THEN
i_count = null;
END IF;
RETURN QUERY SELECT CAST((res1.recid) AS CHARACTER VARYING), CAST((res1.reccreated) AS CHARACTER VARYING), res1.recname, CAST((res1.recupdated) AS CHARACTER VARYING), res1.owntracks, COUNT(res2.userid) AS lasttracks
RETURN QUERY SELECT CAST((res1.recid) AS CHARACTER VARYING), CAST((res1.reccreated) AS CHARACTER VARYING), res1.recname, CAST((res1.recupdated) AS CHARACTER VARYING), res1.owntracks, COUNT(res2.userid) AS downloadtracks
FROM
(SELECT u.recid, u.reccreated, u.recname, u.recupdated, COUNT(r.recid) AS owntracks
FROM users u
Expand All @@ -589,7 +586,7 @@ FROM
ON dev.recid= d.deviceid AND d.reccreated > localtimestamp - INTERVAL ''1 day'') res2
ON res2.userid = res1.recid
GROUP BY res1.recid, res1.reccreated, res1.recname, res1.recupdated, res1.owntracks
ORDER BY lasttracks DESC, owntracks DESC
ORDER BY downloadtracks DESC, owntracks DESC
LIMIT i_count;
END;
Expand Down Expand Up @@ -924,6 +921,7 @@ LANGUAGE plpgsql;



DROP FUNCTION getnexttrack_v2(uuid);

CREATE OR REPLACE FUNCTION getnexttrack_v2(IN i_deviceid uuid)
RETURNS TABLE(track character varying, method integer, useridrecommended character varying, txtrecommendedinfo character varying, timeexecute character varying) AS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Mockito.doThrow;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
Expand Down Expand Up @@ -94,7 +95,7 @@ public void saveStatusIsInternalServerError() throws Exception {
given(this.trackService.getById(TRACK_UUID)).willReturn(track);
given(this.deviceService.getById(DEVICE_UUID)).willReturn(device);

doThrow(RuntimeException.class).when(this.historyService).save(any(History.class));
doThrow(RuntimeException.class).when(this.historyService).save(any(History.class), anyBoolean());

JSONObject obj = new JSONObject();
obj.put("lastListen", "2016-11-28T12:34:56");
Expand Down

0 comments on commit 596ffa8

Please sign in to comment.